clang API Documentation

TreeTransform.h
Go to the documentation of this file.
00001 //===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //===----------------------------------------------------------------------===//
00008 //
00009 //  This file implements a semantic tree transformation that takes a given
00010 //  AST and rebuilds it, possibly transforming some nodes in the process.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
00015 #define LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
00016 
00017 #include "TypeLocBuilder.h"
00018 #include "clang/AST/Decl.h"
00019 #include "clang/AST/DeclObjC.h"
00020 #include "clang/AST/DeclTemplate.h"
00021 #include "clang/AST/Expr.h"
00022 #include "clang/AST/ExprCXX.h"
00023 #include "clang/AST/ExprObjC.h"
00024 #include "clang/AST/Stmt.h"
00025 #include "clang/AST/StmtCXX.h"
00026 #include "clang/AST/StmtObjC.h"
00027 #include "clang/AST/StmtOpenMP.h"
00028 #include "clang/Sema/Designator.h"
00029 #include "clang/Sema/Lookup.h"
00030 #include "clang/Sema/Ownership.h"
00031 #include "clang/Sema/ParsedTemplate.h"
00032 #include "clang/Sema/ScopeInfo.h"
00033 #include "clang/Sema/SemaDiagnostic.h"
00034 #include "clang/Sema/SemaInternal.h"
00035 #include "llvm/ADT/ArrayRef.h"
00036 #include "llvm/Support/ErrorHandling.h"
00037 #include <algorithm>
00038 
00039 namespace clang {
00040 using namespace sema;
00041 
00042 /// \brief A semantic tree transformation that allows one to transform one
00043 /// abstract syntax tree into another.
00044 ///
00045 /// A new tree transformation is defined by creating a new subclass \c X of
00046 /// \c TreeTransform<X> and then overriding certain operations to provide
00047 /// behavior specific to that transformation. For example, template
00048 /// instantiation is implemented as a tree transformation where the
00049 /// transformation of TemplateTypeParmType nodes involves substituting the
00050 /// template arguments for their corresponding template parameters; a similar
00051 /// transformation is performed for non-type template parameters and
00052 /// template template parameters.
00053 ///
00054 /// This tree-transformation template uses static polymorphism to allow
00055 /// subclasses to customize any of its operations. Thus, a subclass can
00056 /// override any of the transformation or rebuild operators by providing an
00057 /// operation with the same signature as the default implementation. The
00058 /// overridding function should not be virtual.
00059 ///
00060 /// Semantic tree transformations are split into two stages, either of which
00061 /// can be replaced by a subclass. The "transform" step transforms an AST node
00062 /// or the parts of an AST node using the various transformation functions,
00063 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
00064 /// node of the appropriate kind from the pieces. The default transformation
00065 /// routines recursively transform the operands to composite AST nodes (e.g.,
00066 /// the pointee type of a PointerType node) and, if any of those operand nodes
00067 /// were changed by the transformation, invokes the rebuild operation to create
00068 /// a new AST node.
00069 ///
00070 /// Subclasses can customize the transformation at various levels. The
00071 /// most coarse-grained transformations involve replacing TransformType(),
00072 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
00073 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
00074 /// new implementations.
00075 ///
00076 /// For more fine-grained transformations, subclasses can replace any of the
00077 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
00078 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
00079 /// replacing TransformTemplateTypeParmType() allows template instantiation
00080 /// to substitute template arguments for their corresponding template
00081 /// parameters. Additionally, subclasses can override the \c RebuildXXX
00082 /// functions to control how AST nodes are rebuilt when their operands change.
00083 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
00084 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
00085 /// be able to use more efficient rebuild steps.
00086 ///
00087 /// There are a handful of other functions that can be overridden, allowing one
00088 /// to avoid traversing nodes that don't need any transformation
00089 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
00090 /// operands have not changed (\c AlwaysRebuild()), and customize the
00091 /// default locations and entity names used for type-checking
00092 /// (\c getBaseLocation(), \c getBaseEntity()).
00093 template<typename Derived>
00094 class TreeTransform {
00095   /// \brief Private RAII object that helps us forget and then re-remember
00096   /// the template argument corresponding to a partially-substituted parameter
00097   /// pack.
00098   class ForgetPartiallySubstitutedPackRAII {
00099     Derived &Self;
00100     TemplateArgument Old;
00101 
00102   public:
00103     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
00104       Old = Self.ForgetPartiallySubstitutedPack();
00105     }
00106 
00107     ~ForgetPartiallySubstitutedPackRAII() {
00108       Self.RememberPartiallySubstitutedPack(Old);
00109     }
00110   };
00111 
00112 protected:
00113   Sema &SemaRef;
00114 
00115   /// \brief The set of local declarations that have been transformed, for
00116   /// cases where we are forced to build new declarations within the transformer
00117   /// rather than in the subclass (e.g., lambda closure types).
00118   llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
00119 
00120 public:
00121   /// \brief Initializes a new tree transformer.
00122   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
00123 
00124   /// \brief Retrieves a reference to the derived class.
00125   Derived &getDerived() { return static_cast<Derived&>(*this); }
00126 
00127   /// \brief Retrieves a reference to the derived class.
00128   const Derived &getDerived() const {
00129     return static_cast<const Derived&>(*this);
00130   }
00131 
00132   static inline ExprResult Owned(Expr *E) { return E; }
00133   static inline StmtResult Owned(Stmt *S) { return S; }
00134 
00135   /// \brief Retrieves a reference to the semantic analysis object used for
00136   /// this tree transform.
00137   Sema &getSema() const { return SemaRef; }
00138 
00139   /// \brief Whether the transformation should always rebuild AST nodes, even
00140   /// if none of the children have changed.
00141   ///
00142   /// Subclasses may override this function to specify when the transformation
00143   /// should rebuild all AST nodes.
00144   ///
00145   /// We must always rebuild all AST nodes when performing variadic template
00146   /// pack expansion, in order to avoid violating the AST invariant that each
00147   /// statement node appears at most once in its containing declaration.
00148   bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
00149 
00150   /// \brief Returns the location of the entity being transformed, if that
00151   /// information was not available elsewhere in the AST.
00152   ///
00153   /// By default, returns no source-location information. Subclasses can
00154   /// provide an alternative implementation that provides better location
00155   /// information.
00156   SourceLocation getBaseLocation() { return SourceLocation(); }
00157 
00158   /// \brief Returns the name of the entity being transformed, if that
00159   /// information was not available elsewhere in the AST.
00160   ///
00161   /// By default, returns an empty name. Subclasses can provide an alternative
00162   /// implementation with a more precise name.
00163   DeclarationName getBaseEntity() { return DeclarationName(); }
00164 
00165   /// \brief Sets the "base" location and entity when that
00166   /// information is known based on another transformation.
00167   ///
00168   /// By default, the source location and entity are ignored. Subclasses can
00169   /// override this function to provide a customized implementation.
00170   void setBase(SourceLocation Loc, DeclarationName Entity) { }
00171 
00172   /// \brief RAII object that temporarily sets the base location and entity
00173   /// used for reporting diagnostics in types.
00174   class TemporaryBase {
00175     TreeTransform &Self;
00176     SourceLocation OldLocation;
00177     DeclarationName OldEntity;
00178 
00179   public:
00180     TemporaryBase(TreeTransform &Self, SourceLocation Location,
00181                   DeclarationName Entity) : Self(Self) {
00182       OldLocation = Self.getDerived().getBaseLocation();
00183       OldEntity = Self.getDerived().getBaseEntity();
00184 
00185       if (Location.isValid())
00186         Self.getDerived().setBase(Location, Entity);
00187     }
00188 
00189     ~TemporaryBase() {
00190       Self.getDerived().setBase(OldLocation, OldEntity);
00191     }
00192   };
00193 
00194   /// \brief Determine whether the given type \p T has already been
00195   /// transformed.
00196   ///
00197   /// Subclasses can provide an alternative implementation of this routine
00198   /// to short-circuit evaluation when it is known that a given type will
00199   /// not change. For example, template instantiation need not traverse
00200   /// non-dependent types.
00201   bool AlreadyTransformed(QualType T) {
00202     return T.isNull();
00203   }
00204 
00205   /// \brief Determine whether the given call argument should be dropped, e.g.,
00206   /// because it is a default argument.
00207   ///
00208   /// Subclasses can provide an alternative implementation of this routine to
00209   /// determine which kinds of call arguments get dropped. By default,
00210   /// CXXDefaultArgument nodes are dropped (prior to transformation).
00211   bool DropCallArgument(Expr *E) {
00212     return E->isDefaultArgument();
00213   }
00214 
00215   /// \brief Determine whether we should expand a pack expansion with the
00216   /// given set of parameter packs into separate arguments by repeatedly
00217   /// transforming the pattern.
00218   ///
00219   /// By default, the transformer never tries to expand pack expansions.
00220   /// Subclasses can override this routine to provide different behavior.
00221   ///
00222   /// \param EllipsisLoc The location of the ellipsis that identifies the
00223   /// pack expansion.
00224   ///
00225   /// \param PatternRange The source range that covers the entire pattern of
00226   /// the pack expansion.
00227   ///
00228   /// \param Unexpanded The set of unexpanded parameter packs within the
00229   /// pattern.
00230   ///
00231   /// \param ShouldExpand Will be set to \c true if the transformer should
00232   /// expand the corresponding pack expansions into separate arguments. When
00233   /// set, \c NumExpansions must also be set.
00234   ///
00235   /// \param RetainExpansion Whether the caller should add an unexpanded
00236   /// pack expansion after all of the expanded arguments. This is used
00237   /// when extending explicitly-specified template argument packs per
00238   /// C++0x [temp.arg.explicit]p9.
00239   ///
00240   /// \param NumExpansions The number of separate arguments that will be in
00241   /// the expanded form of the corresponding pack expansion. This is both an
00242   /// input and an output parameter, which can be set by the caller if the
00243   /// number of expansions is known a priori (e.g., due to a prior substitution)
00244   /// and will be set by the callee when the number of expansions is known.
00245   /// The callee must set this value when \c ShouldExpand is \c true; it may
00246   /// set this value in other cases.
00247   ///
00248   /// \returns true if an error occurred (e.g., because the parameter packs
00249   /// are to be instantiated with arguments of different lengths), false
00250   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
00251   /// must be set.
00252   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
00253                                SourceRange PatternRange,
00254                                ArrayRef<UnexpandedParameterPack> Unexpanded,
00255                                bool &ShouldExpand,
00256                                bool &RetainExpansion,
00257                                Optional<unsigned> &NumExpansions) {
00258     ShouldExpand = false;
00259     return false;
00260   }
00261 
00262   /// \brief "Forget" about the partially-substituted pack template argument,
00263   /// when performing an instantiation that must preserve the parameter pack
00264   /// use.
00265   ///
00266   /// This routine is meant to be overridden by the template instantiator.
00267   TemplateArgument ForgetPartiallySubstitutedPack() {
00268     return TemplateArgument();
00269   }
00270 
00271   /// \brief "Remember" the partially-substituted pack template argument
00272   /// after performing an instantiation that must preserve the parameter pack
00273   /// use.
00274   ///
00275   /// This routine is meant to be overridden by the template instantiator.
00276   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
00277 
00278   /// \brief Note to the derived class when a function parameter pack is
00279   /// being expanded.
00280   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
00281 
00282   /// \brief Transforms the given type into another type.
00283   ///
00284   /// By default, this routine transforms a type by creating a
00285   /// TypeSourceInfo for it and delegating to the appropriate
00286   /// function.  This is expensive, but we don't mind, because
00287   /// this method is deprecated anyway;  all users should be
00288   /// switched to storing TypeSourceInfos.
00289   ///
00290   /// \returns the transformed type.
00291   QualType TransformType(QualType T);
00292 
00293   /// \brief Transforms the given type-with-location into a new
00294   /// type-with-location.
00295   ///
00296   /// By default, this routine transforms a type by delegating to the
00297   /// appropriate TransformXXXType to build a new type.  Subclasses
00298   /// may override this function (to take over all type
00299   /// transformations) or some set of the TransformXXXType functions
00300   /// to alter the transformation.
00301   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
00302 
00303   /// \brief Transform the given type-with-location into a new
00304   /// type, collecting location information in the given builder
00305   /// as necessary.
00306   ///
00307   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
00308 
00309   /// \brief Transform the given statement.
00310   ///
00311   /// By default, this routine transforms a statement by delegating to the
00312   /// appropriate TransformXXXStmt function to transform a specific kind of
00313   /// statement or the TransformExpr() function to transform an expression.
00314   /// Subclasses may override this function to transform statements using some
00315   /// other mechanism.
00316   ///
00317   /// \returns the transformed statement.
00318   StmtResult TransformStmt(Stmt *S);
00319 
00320   /// \brief Transform the given statement.
00321   ///
00322   /// By default, this routine transforms a statement by delegating to the
00323   /// appropriate TransformOMPXXXClause function to transform a specific kind
00324   /// of clause. Subclasses may override this function to transform statements
00325   /// using some other mechanism.
00326   ///
00327   /// \returns the transformed OpenMP clause.
00328   OMPClause *TransformOMPClause(OMPClause *S);
00329 
00330   /// \brief Transform the given attribute.
00331   ///
00332   /// By default, this routine transforms a statement by delegating to the
00333   /// appropriate TransformXXXAttr function to transform a specific kind
00334   /// of attribute. Subclasses may override this function to transform
00335   /// attributed statements using some other mechanism.
00336   ///
00337   /// \returns the transformed attribute
00338   const Attr *TransformAttr(const Attr *S);
00339 
00340 /// \brief Transform the specified attribute.
00341 ///
00342 /// Subclasses should override the transformation of attributes with a pragma
00343 /// spelling to transform expressions stored within the attribute.
00344 ///
00345 /// \returns the transformed attribute.
00346 #define ATTR(X)
00347 #define PRAGMA_SPELLING_ATTR(X)                                                \
00348   const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
00349 #include "clang/Basic/AttrList.inc"
00350 
00351   /// \brief Transform the given expression.
00352   ///
00353   /// By default, this routine transforms an expression by delegating to the
00354   /// appropriate TransformXXXExpr function to build a new expression.
00355   /// Subclasses may override this function to transform expressions using some
00356   /// other mechanism.
00357   ///
00358   /// \returns the transformed expression.
00359   ExprResult TransformExpr(Expr *E);
00360 
00361   /// \brief Transform the given initializer.
00362   ///
00363   /// By default, this routine transforms an initializer by stripping off the
00364   /// semantic nodes added by initialization, then passing the result to
00365   /// TransformExpr or TransformExprs.
00366   ///
00367   /// \returns the transformed initializer.
00368   ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
00369 
00370   /// \brief Transform the given list of expressions.
00371   ///
00372   /// This routine transforms a list of expressions by invoking
00373   /// \c TransformExpr() for each subexpression. However, it also provides
00374   /// support for variadic templates by expanding any pack expansions (if the
00375   /// derived class permits such expansion) along the way. When pack expansions
00376   /// are present, the number of outputs may not equal the number of inputs.
00377   ///
00378   /// \param Inputs The set of expressions to be transformed.
00379   ///
00380   /// \param NumInputs The number of expressions in \c Inputs.
00381   ///
00382   /// \param IsCall If \c true, then this transform is being performed on
00383   /// function-call arguments, and any arguments that should be dropped, will
00384   /// be.
00385   ///
00386   /// \param Outputs The transformed input expressions will be added to this
00387   /// vector.
00388   ///
00389   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
00390   /// due to transformation.
00391   ///
00392   /// \returns true if an error occurred, false otherwise.
00393   bool TransformExprs(Expr **Inputs, unsigned NumInputs, bool IsCall,
00394                       SmallVectorImpl<Expr *> &Outputs,
00395                       bool *ArgChanged = nullptr);
00396 
00397   /// \brief Transform the given declaration, which is referenced from a type
00398   /// or expression.
00399   ///
00400   /// By default, acts as the identity function on declarations, unless the
00401   /// transformer has had to transform the declaration itself. Subclasses
00402   /// may override this function to provide alternate behavior.
00403   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
00404     llvm::DenseMap<Decl *, Decl *>::iterator Known
00405       = TransformedLocalDecls.find(D);
00406     if (Known != TransformedLocalDecls.end())
00407       return Known->second;
00408 
00409     return D;
00410   }
00411 
00412   /// \brief Transform the attributes associated with the given declaration and
00413   /// place them on the new declaration.
00414   ///
00415   /// By default, this operation does nothing. Subclasses may override this
00416   /// behavior to transform attributes.
00417   void transformAttrs(Decl *Old, Decl *New) { }
00418 
00419   /// \brief Note that a local declaration has been transformed by this
00420   /// transformer.
00421   ///
00422   /// Local declarations are typically transformed via a call to
00423   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
00424   /// the transformer itself has to transform the declarations. This routine
00425   /// can be overridden by a subclass that keeps track of such mappings.
00426   void transformedLocalDecl(Decl *Old, Decl *New) {
00427     TransformedLocalDecls[Old] = New;
00428   }
00429 
00430   /// \brief Transform the definition of the given declaration.
00431   ///
00432   /// By default, invokes TransformDecl() to transform the declaration.
00433   /// Subclasses may override this function to provide alternate behavior.
00434   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
00435     return getDerived().TransformDecl(Loc, D);
00436   }
00437 
00438   /// \brief Transform the given declaration, which was the first part of a
00439   /// nested-name-specifier in a member access expression.
00440   ///
00441   /// This specific declaration transformation only applies to the first
00442   /// identifier in a nested-name-specifier of a member access expression, e.g.,
00443   /// the \c T in \c x->T::member
00444   ///
00445   /// By default, invokes TransformDecl() to transform the declaration.
00446   /// Subclasses may override this function to provide alternate behavior.
00447   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
00448     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
00449   }
00450 
00451   /// \brief Transform the given nested-name-specifier with source-location
00452   /// information.
00453   ///
00454   /// By default, transforms all of the types and declarations within the
00455   /// nested-name-specifier. Subclasses may override this function to provide
00456   /// alternate behavior.
00457   NestedNameSpecifierLoc
00458   TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
00459                                   QualType ObjectType = QualType(),
00460                                   NamedDecl *FirstQualifierInScope = nullptr);
00461 
00462   /// \brief Transform the given declaration name.
00463   ///
00464   /// By default, transforms the types of conversion function, constructor,
00465   /// and destructor names and then (if needed) rebuilds the declaration name.
00466   /// Identifiers and selectors are returned unmodified. Sublcasses may
00467   /// override this function to provide alternate behavior.
00468   DeclarationNameInfo
00469   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
00470 
00471   /// \brief Transform the given template name.
00472   ///
00473   /// \param SS The nested-name-specifier that qualifies the template
00474   /// name. This nested-name-specifier must already have been transformed.
00475   ///
00476   /// \param Name The template name to transform.
00477   ///
00478   /// \param NameLoc The source location of the template name.
00479   ///
00480   /// \param ObjectType If we're translating a template name within a member
00481   /// access expression, this is the type of the object whose member template
00482   /// is being referenced.
00483   ///
00484   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
00485   /// also refers to a name within the current (lexical) scope, this is the
00486   /// declaration it refers to.
00487   ///
00488   /// By default, transforms the template name by transforming the declarations
00489   /// and nested-name-specifiers that occur within the template name.
00490   /// Subclasses may override this function to provide alternate behavior.
00491   TemplateName
00492   TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
00493                         SourceLocation NameLoc,
00494                         QualType ObjectType = QualType(),
00495                         NamedDecl *FirstQualifierInScope = nullptr);
00496 
00497   /// \brief Transform the given template argument.
00498   ///
00499   /// By default, this operation transforms the type, expression, or
00500   /// declaration stored within the template argument and constructs a
00501   /// new template argument from the transformed result. Subclasses may
00502   /// override this function to provide alternate behavior.
00503   ///
00504   /// Returns true if there was an error.
00505   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
00506                                  TemplateArgumentLoc &Output);
00507 
00508   /// \brief Transform the given set of template arguments.
00509   ///
00510   /// By default, this operation transforms all of the template arguments
00511   /// in the input set using \c TransformTemplateArgument(), and appends
00512   /// the transformed arguments to the output list.
00513   ///
00514   /// Note that this overload of \c TransformTemplateArguments() is merely
00515   /// a convenience function. Subclasses that wish to override this behavior
00516   /// should override the iterator-based member template version.
00517   ///
00518   /// \param Inputs The set of template arguments to be transformed.
00519   ///
00520   /// \param NumInputs The number of template arguments in \p Inputs.
00521   ///
00522   /// \param Outputs The set of transformed template arguments output by this
00523   /// routine.
00524   ///
00525   /// Returns true if an error occurred.
00526   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
00527                                   unsigned NumInputs,
00528                                   TemplateArgumentListInfo &Outputs) {
00529     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs);
00530   }
00531 
00532   /// \brief Transform the given set of template arguments.
00533   ///
00534   /// By default, this operation transforms all of the template arguments
00535   /// in the input set using \c TransformTemplateArgument(), and appends
00536   /// the transformed arguments to the output list.
00537   ///
00538   /// \param First An iterator to the first template argument.
00539   ///
00540   /// \param Last An iterator one step past the last template argument.
00541   ///
00542   /// \param Outputs The set of transformed template arguments output by this
00543   /// routine.
00544   ///
00545   /// Returns true if an error occurred.
00546   template<typename InputIterator>
00547   bool TransformTemplateArguments(InputIterator First,
00548                                   InputIterator Last,
00549                                   TemplateArgumentListInfo &Outputs);
00550 
00551   /// \brief Fakes up a TemplateArgumentLoc for a given TemplateArgument.
00552   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
00553                                  TemplateArgumentLoc &ArgLoc);
00554 
00555   /// \brief Fakes up a TypeSourceInfo for a type.
00556   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
00557     return SemaRef.Context.getTrivialTypeSourceInfo(T,
00558                        getDerived().getBaseLocation());
00559   }
00560 
00561 #define ABSTRACT_TYPELOC(CLASS, PARENT)
00562 #define TYPELOC(CLASS, PARENT)                                   \
00563   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
00564 #include "clang/AST/TypeLocNodes.def"
00565 
00566   template<typename Fn>
00567   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
00568                                       FunctionProtoTypeLoc TL,
00569                                       CXXRecordDecl *ThisContext,
00570                                       unsigned ThisTypeQuals,
00571                                       Fn TransformExceptionSpec);
00572 
00573   bool TransformExceptionSpec(SourceLocation Loc,
00574                               FunctionProtoType::ExceptionSpecInfo &ESI,
00575                               SmallVectorImpl<QualType> &Exceptions,
00576                               bool &Changed);
00577 
00578   StmtResult TransformSEHHandler(Stmt *Handler);
00579 
00580   QualType
00581   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
00582                                       TemplateSpecializationTypeLoc TL,
00583                                       TemplateName Template);
00584 
00585   QualType
00586   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
00587                                       DependentTemplateSpecializationTypeLoc TL,
00588                                                TemplateName Template,
00589                                                CXXScopeSpec &SS);
00590 
00591   QualType TransformDependentTemplateSpecializationType(
00592       TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
00593       NestedNameSpecifierLoc QualifierLoc);
00594 
00595   /// \brief Transforms the parameters of a function type into the
00596   /// given vectors.
00597   ///
00598   /// The result vectors should be kept in sync; null entries in the
00599   /// variables vector are acceptable.
00600   ///
00601   /// Return true on error.
00602   bool TransformFunctionTypeParams(SourceLocation Loc,
00603                                    ParmVarDecl **Params, unsigned NumParams,
00604                                    const QualType *ParamTypes,
00605                                    SmallVectorImpl<QualType> &PTypes,
00606                                    SmallVectorImpl<ParmVarDecl*> *PVars);
00607 
00608   /// \brief Transforms a single function-type parameter.  Return null
00609   /// on error.
00610   ///
00611   /// \param indexAdjustment - A number to add to the parameter's
00612   ///   scope index;  can be negative
00613   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
00614                                           int indexAdjustment,
00615                                           Optional<unsigned> NumExpansions,
00616                                           bool ExpectParameterPack);
00617 
00618   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
00619 
00620   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
00621   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
00622   
00623   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
00624   /// \brief Transform the captures and body of a lambda expression.
00625   ExprResult TransformLambdaScope(LambdaExpr *E, CXXMethodDecl *CallOperator, 
00626        ArrayRef<InitCaptureInfoTy> InitCaptureExprsAndTypes);
00627 
00628   TemplateParameterList *TransformTemplateParameterList(
00629         TemplateParameterList *TPL) {
00630     return TPL;
00631   }
00632 
00633   ExprResult TransformAddressOfOperand(Expr *E);
00634 
00635   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
00636                                                 bool IsAddressOfOperand,
00637                                                 TypeSourceInfo **RecoveryTSI);
00638 
00639   ExprResult TransformParenDependentScopeDeclRefExpr(
00640       ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
00641       TypeSourceInfo **RecoveryTSI);
00642 
00643   StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
00644 
00645 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
00646 // amount of stack usage with clang.
00647 #define STMT(Node, Parent)                        \
00648   LLVM_ATTRIBUTE_NOINLINE \
00649   StmtResult Transform##Node(Node *S);
00650 #define EXPR(Node, Parent)                        \
00651   LLVM_ATTRIBUTE_NOINLINE \
00652   ExprResult Transform##Node(Node *E);
00653 #define ABSTRACT_STMT(Stmt)
00654 #include "clang/AST/StmtNodes.inc"
00655 
00656 #define OPENMP_CLAUSE(Name, Class)                        \
00657   LLVM_ATTRIBUTE_NOINLINE \
00658   OMPClause *Transform ## Class(Class *S);
00659 #include "clang/Basic/OpenMPKinds.def"
00660 
00661   /// \brief Build a new pointer type given its pointee type.
00662   ///
00663   /// By default, performs semantic analysis when building the pointer type.
00664   /// Subclasses may override this routine to provide different behavior.
00665   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
00666 
00667   /// \brief Build a new block pointer type given its pointee type.
00668   ///
00669   /// By default, performs semantic analysis when building the block pointer
00670   /// type. Subclasses may override this routine to provide different behavior.
00671   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
00672 
00673   /// \brief Build a new reference type given the type it references.
00674   ///
00675   /// By default, performs semantic analysis when building the
00676   /// reference type. Subclasses may override this routine to provide
00677   /// different behavior.
00678   ///
00679   /// \param LValue whether the type was written with an lvalue sigil
00680   /// or an rvalue sigil.
00681   QualType RebuildReferenceType(QualType ReferentType,
00682                                 bool LValue,
00683                                 SourceLocation Sigil);
00684 
00685   /// \brief Build a new member pointer type given the pointee type and the
00686   /// class type it refers into.
00687   ///
00688   /// By default, performs semantic analysis when building the member pointer
00689   /// type. Subclasses may override this routine to provide different behavior.
00690   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
00691                                     SourceLocation Sigil);
00692 
00693   /// \brief Build a new array type given the element type, size
00694   /// modifier, size of the array (if known), size expression, and index type
00695   /// qualifiers.
00696   ///
00697   /// By default, performs semantic analysis when building the array type.
00698   /// Subclasses may override this routine to provide different behavior.
00699   /// Also by default, all of the other Rebuild*Array
00700   QualType RebuildArrayType(QualType ElementType,
00701                             ArrayType::ArraySizeModifier SizeMod,
00702                             const llvm::APInt *Size,
00703                             Expr *SizeExpr,
00704                             unsigned IndexTypeQuals,
00705                             SourceRange BracketsRange);
00706 
00707   /// \brief Build a new constant array type given the element type, size
00708   /// modifier, (known) size of the array, and index type qualifiers.
00709   ///
00710   /// By default, performs semantic analysis when building the array type.
00711   /// Subclasses may override this routine to provide different behavior.
00712   QualType RebuildConstantArrayType(QualType ElementType,
00713                                     ArrayType::ArraySizeModifier SizeMod,
00714                                     const llvm::APInt &Size,
00715                                     unsigned IndexTypeQuals,
00716                                     SourceRange BracketsRange);
00717 
00718   /// \brief Build a new incomplete array type given the element type, size
00719   /// modifier, and index type qualifiers.
00720   ///
00721   /// By default, performs semantic analysis when building the array type.
00722   /// Subclasses may override this routine to provide different behavior.
00723   QualType RebuildIncompleteArrayType(QualType ElementType,
00724                                       ArrayType::ArraySizeModifier SizeMod,
00725                                       unsigned IndexTypeQuals,
00726                                       SourceRange BracketsRange);
00727 
00728   /// \brief Build a new variable-length array type given the element type,
00729   /// size modifier, size expression, and index type qualifiers.
00730   ///
00731   /// By default, performs semantic analysis when building the array type.
00732   /// Subclasses may override this routine to provide different behavior.
00733   QualType RebuildVariableArrayType(QualType ElementType,
00734                                     ArrayType::ArraySizeModifier SizeMod,
00735                                     Expr *SizeExpr,
00736                                     unsigned IndexTypeQuals,
00737                                     SourceRange BracketsRange);
00738 
00739   /// \brief Build a new dependent-sized array type given the element type,
00740   /// size modifier, size expression, and index type qualifiers.
00741   ///
00742   /// By default, performs semantic analysis when building the array type.
00743   /// Subclasses may override this routine to provide different behavior.
00744   QualType RebuildDependentSizedArrayType(QualType ElementType,
00745                                           ArrayType::ArraySizeModifier SizeMod,
00746                                           Expr *SizeExpr,
00747                                           unsigned IndexTypeQuals,
00748                                           SourceRange BracketsRange);
00749 
00750   /// \brief Build a new vector type given the element type and
00751   /// number of elements.
00752   ///
00753   /// By default, performs semantic analysis when building the vector type.
00754   /// Subclasses may override this routine to provide different behavior.
00755   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
00756                              VectorType::VectorKind VecKind);
00757 
00758   /// \brief Build a new extended vector type given the element type and
00759   /// number of elements.
00760   ///
00761   /// By default, performs semantic analysis when building the vector type.
00762   /// Subclasses may override this routine to provide different behavior.
00763   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
00764                                 SourceLocation AttributeLoc);
00765 
00766   /// \brief Build a new potentially dependently-sized extended vector type
00767   /// given the element type and number of elements.
00768   ///
00769   /// By default, performs semantic analysis when building the vector type.
00770   /// Subclasses may override this routine to provide different behavior.
00771   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
00772                                               Expr *SizeExpr,
00773                                               SourceLocation AttributeLoc);
00774 
00775   /// \brief Build a new function type.
00776   ///
00777   /// By default, performs semantic analysis when building the function type.
00778   /// Subclasses may override this routine to provide different behavior.
00779   QualType RebuildFunctionProtoType(QualType T,
00780                                     MutableArrayRef<QualType> ParamTypes,
00781                                     const FunctionProtoType::ExtProtoInfo &EPI);
00782 
00783   /// \brief Build a new unprototyped function type.
00784   QualType RebuildFunctionNoProtoType(QualType ResultType);
00785 
00786   /// \brief Rebuild an unresolved typename type, given the decl that
00787   /// the UnresolvedUsingTypenameDecl was transformed to.
00788   QualType RebuildUnresolvedUsingType(Decl *D);
00789 
00790   /// \brief Build a new typedef type.
00791   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
00792     return SemaRef.Context.getTypeDeclType(Typedef);
00793   }
00794 
00795   /// \brief Build a new class/struct/union type.
00796   QualType RebuildRecordType(RecordDecl *Record) {
00797     return SemaRef.Context.getTypeDeclType(Record);
00798   }
00799 
00800   /// \brief Build a new Enum type.
00801   QualType RebuildEnumType(EnumDecl *Enum) {
00802     return SemaRef.Context.getTypeDeclType(Enum);
00803   }
00804 
00805   /// \brief Build a new typeof(expr) type.
00806   ///
00807   /// By default, performs semantic analysis when building the typeof type.
00808   /// Subclasses may override this routine to provide different behavior.
00809   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
00810 
00811   /// \brief Build a new typeof(type) type.
00812   ///
00813   /// By default, builds a new TypeOfType with the given underlying type.
00814   QualType RebuildTypeOfType(QualType Underlying);
00815 
00816   /// \brief Build a new unary transform type.
00817   QualType RebuildUnaryTransformType(QualType BaseType,
00818                                      UnaryTransformType::UTTKind UKind,
00819                                      SourceLocation Loc);
00820 
00821   /// \brief Build a new C++11 decltype type.
00822   ///
00823   /// By default, performs semantic analysis when building the decltype type.
00824   /// Subclasses may override this routine to provide different behavior.
00825   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
00826 
00827   /// \brief Build a new C++11 auto type.
00828   ///
00829   /// By default, builds a new AutoType with the given deduced type.
00830   QualType RebuildAutoType(QualType Deduced, bool IsDecltypeAuto) {
00831     // Note, IsDependent is always false here: we implicitly convert an 'auto'
00832     // which has been deduced to a dependent type into an undeduced 'auto', so
00833     // that we'll retry deduction after the transformation.
00834     return SemaRef.Context.getAutoType(Deduced, IsDecltypeAuto, 
00835                                        /*IsDependent*/ false);
00836   }
00837 
00838   /// \brief Build a new template specialization type.
00839   ///
00840   /// By default, performs semantic analysis when building the template
00841   /// specialization type. Subclasses may override this routine to provide
00842   /// different behavior.
00843   QualType RebuildTemplateSpecializationType(TemplateName Template,
00844                                              SourceLocation TemplateLoc,
00845                                              TemplateArgumentListInfo &Args);
00846 
00847   /// \brief Build a new parenthesized type.
00848   ///
00849   /// By default, builds a new ParenType type from the inner type.
00850   /// Subclasses may override this routine to provide different behavior.
00851   QualType RebuildParenType(QualType InnerType) {
00852     return SemaRef.Context.getParenType(InnerType);
00853   }
00854 
00855   /// \brief Build a new qualified name type.
00856   ///
00857   /// By default, builds a new ElaboratedType type from the keyword,
00858   /// the nested-name-specifier and the named type.
00859   /// Subclasses may override this routine to provide different behavior.
00860   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
00861                                  ElaboratedTypeKeyword Keyword,
00862                                  NestedNameSpecifierLoc QualifierLoc,
00863                                  QualType Named) {
00864     return SemaRef.Context.getElaboratedType(Keyword,
00865                                          QualifierLoc.getNestedNameSpecifier(),
00866                                              Named);
00867   }
00868 
00869   /// \brief Build a new typename type that refers to a template-id.
00870   ///
00871   /// By default, builds a new DependentNameType type from the
00872   /// nested-name-specifier and the given type. Subclasses may override
00873   /// this routine to provide different behavior.
00874   QualType RebuildDependentTemplateSpecializationType(
00875                                           ElaboratedTypeKeyword Keyword,
00876                                           NestedNameSpecifierLoc QualifierLoc,
00877                                           const IdentifierInfo *Name,
00878                                           SourceLocation NameLoc,
00879                                           TemplateArgumentListInfo &Args) {
00880     // Rebuild the template name.
00881     // TODO: avoid TemplateName abstraction
00882     CXXScopeSpec SS;
00883     SS.Adopt(QualifierLoc);
00884     TemplateName InstName
00885       = getDerived().RebuildTemplateName(SS, *Name, NameLoc, QualType(),
00886                                          nullptr);
00887 
00888     if (InstName.isNull())
00889       return QualType();
00890 
00891     // If it's still dependent, make a dependent specialization.
00892     if (InstName.getAsDependentTemplateName())
00893       return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
00894                                           QualifierLoc.getNestedNameSpecifier(),
00895                                                                     Name,
00896                                                                     Args);
00897 
00898     // Otherwise, make an elaborated type wrapping a non-dependent
00899     // specialization.
00900     QualType T =
00901     getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
00902     if (T.isNull()) return QualType();
00903 
00904     if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
00905       return T;
00906 
00907     return SemaRef.Context.getElaboratedType(Keyword,
00908                                        QualifierLoc.getNestedNameSpecifier(),
00909                                              T);
00910   }
00911 
00912   /// \brief Build a new typename type that refers to an identifier.
00913   ///
00914   /// By default, performs semantic analysis when building the typename type
00915   /// (or elaborated type). Subclasses may override this routine to provide
00916   /// different behavior.
00917   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
00918                                     SourceLocation KeywordLoc,
00919                                     NestedNameSpecifierLoc QualifierLoc,
00920                                     const IdentifierInfo *Id,
00921                                     SourceLocation IdLoc) {
00922     CXXScopeSpec SS;
00923     SS.Adopt(QualifierLoc);
00924 
00925     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
00926       // If the name is still dependent, just build a new dependent name type.
00927       if (!SemaRef.computeDeclContext(SS))
00928         return SemaRef.Context.getDependentNameType(Keyword,
00929                                           QualifierLoc.getNestedNameSpecifier(),
00930                                                     Id);
00931     }
00932 
00933     if (Keyword == ETK_None || Keyword == ETK_Typename)
00934       return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
00935                                        *Id, IdLoc);
00936 
00937     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
00938 
00939     // We had a dependent elaborated-type-specifier that has been transformed
00940     // into a non-dependent elaborated-type-specifier. Find the tag we're
00941     // referring to.
00942     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
00943     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
00944     if (!DC)
00945       return QualType();
00946 
00947     if (SemaRef.RequireCompleteDeclContext(SS, DC))
00948       return QualType();
00949 
00950     TagDecl *Tag = nullptr;
00951     SemaRef.LookupQualifiedName(Result, DC);
00952     switch (Result.getResultKind()) {
00953       case LookupResult::NotFound:
00954       case LookupResult::NotFoundInCurrentInstantiation:
00955         break;
00956 
00957       case LookupResult::Found:
00958         Tag = Result.getAsSingle<TagDecl>();
00959         break;
00960 
00961       case LookupResult::FoundOverloaded:
00962       case LookupResult::FoundUnresolvedValue:
00963         llvm_unreachable("Tag lookup cannot find non-tags");
00964 
00965       case LookupResult::Ambiguous:
00966         // Let the LookupResult structure handle ambiguities.
00967         return QualType();
00968     }
00969 
00970     if (!Tag) {
00971       // Check where the name exists but isn't a tag type and use that to emit
00972       // better diagnostics.
00973       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
00974       SemaRef.LookupQualifiedName(Result, DC);
00975       switch (Result.getResultKind()) {
00976         case LookupResult::Found:
00977         case LookupResult::FoundOverloaded:
00978         case LookupResult::FoundUnresolvedValue: {
00979           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
00980           unsigned Kind = 0;
00981           if (isa<TypedefDecl>(SomeDecl)) Kind = 1;
00982           else if (isa<TypeAliasDecl>(SomeDecl)) Kind = 2;
00983           else if (isa<ClassTemplateDecl>(SomeDecl)) Kind = 3;
00984           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << Kind;
00985           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
00986           break;
00987         }
00988         default:
00989           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
00990               << Kind << Id << DC << QualifierLoc.getSourceRange();
00991           break;
00992       }
00993       return QualType();
00994     }
00995 
00996     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
00997                                               IdLoc, *Id)) {
00998       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
00999       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
01000       return QualType();
01001     }
01002 
01003     // Build the elaborated-type-specifier type.
01004     QualType T = SemaRef.Context.getTypeDeclType(Tag);
01005     return SemaRef.Context.getElaboratedType(Keyword,
01006                                          QualifierLoc.getNestedNameSpecifier(),
01007                                              T);
01008   }
01009 
01010   /// \brief Build a new pack expansion type.
01011   ///
01012   /// By default, builds a new PackExpansionType type from the given pattern.
01013   /// Subclasses may override this routine to provide different behavior.
01014   QualType RebuildPackExpansionType(QualType Pattern,
01015                                     SourceRange PatternRange,
01016                                     SourceLocation EllipsisLoc,
01017                                     Optional<unsigned> NumExpansions) {
01018     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
01019                                         NumExpansions);
01020   }
01021 
01022   /// \brief Build a new atomic type given its value type.
01023   ///
01024   /// By default, performs semantic analysis when building the atomic type.
01025   /// Subclasses may override this routine to provide different behavior.
01026   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
01027 
01028   /// \brief Build a new template name given a nested name specifier, a flag
01029   /// indicating whether the "template" keyword was provided, and the template
01030   /// that the template name refers to.
01031   ///
01032   /// By default, builds the new template name directly. Subclasses may override
01033   /// this routine to provide different behavior.
01034   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
01035                                    bool TemplateKW,
01036                                    TemplateDecl *Template);
01037 
01038   /// \brief Build a new template name given a nested name specifier and the
01039   /// name that is referred to as a template.
01040   ///
01041   /// By default, performs semantic analysis to determine whether the name can
01042   /// be resolved to a specific template, then builds the appropriate kind of
01043   /// template name. Subclasses may override this routine to provide different
01044   /// behavior.
01045   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
01046                                    const IdentifierInfo &Name,
01047                                    SourceLocation NameLoc,
01048                                    QualType ObjectType,
01049                                    NamedDecl *FirstQualifierInScope);
01050 
01051   /// \brief Build a new template name given a nested name specifier and the
01052   /// overloaded operator name that is referred to as a template.
01053   ///
01054   /// By default, performs semantic analysis to determine whether the name can
01055   /// be resolved to a specific template, then builds the appropriate kind of
01056   /// template name. Subclasses may override this routine to provide different
01057   /// behavior.
01058   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
01059                                    OverloadedOperatorKind Operator,
01060                                    SourceLocation NameLoc,
01061                                    QualType ObjectType);
01062 
01063   /// \brief Build a new template name given a template template parameter pack
01064   /// and the
01065   ///
01066   /// By default, performs semantic analysis to determine whether the name can
01067   /// be resolved to a specific template, then builds the appropriate kind of
01068   /// template name. Subclasses may override this routine to provide different
01069   /// behavior.
01070   TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
01071                                    const TemplateArgument &ArgPack) {
01072     return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
01073   }
01074 
01075   /// \brief Build a new compound statement.
01076   ///
01077   /// By default, performs semantic analysis to build the new statement.
01078   /// Subclasses may override this routine to provide different behavior.
01079   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
01080                                        MultiStmtArg Statements,
01081                                        SourceLocation RBraceLoc,
01082                                        bool IsStmtExpr) {
01083     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
01084                                        IsStmtExpr);
01085   }
01086 
01087   /// \brief Build a new case statement.
01088   ///
01089   /// By default, performs semantic analysis to build the new statement.
01090   /// Subclasses may override this routine to provide different behavior.
01091   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
01092                                    Expr *LHS,
01093                                    SourceLocation EllipsisLoc,
01094                                    Expr *RHS,
01095                                    SourceLocation ColonLoc) {
01096     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
01097                                    ColonLoc);
01098   }
01099 
01100   /// \brief Attach the body to a new case statement.
01101   ///
01102   /// By default, performs semantic analysis to build the new statement.
01103   /// Subclasses may override this routine to provide different behavior.
01104   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
01105     getSema().ActOnCaseStmtBody(S, Body);
01106     return S;
01107   }
01108 
01109   /// \brief Build a new default statement.
01110   ///
01111   /// By default, performs semantic analysis to build the new statement.
01112   /// Subclasses may override this routine to provide different behavior.
01113   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
01114                                       SourceLocation ColonLoc,
01115                                       Stmt *SubStmt) {
01116     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
01117                                       /*CurScope=*/nullptr);
01118   }
01119 
01120   /// \brief Build a new label statement.
01121   ///
01122   /// By default, performs semantic analysis to build the new statement.
01123   /// Subclasses may override this routine to provide different behavior.
01124   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
01125                               SourceLocation ColonLoc, Stmt *SubStmt) {
01126     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
01127   }
01128 
01129   /// \brief Build a new label statement.
01130   ///
01131   /// By default, performs semantic analysis to build the new statement.
01132   /// Subclasses may override this routine to provide different behavior.
01133   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
01134                                    ArrayRef<const Attr*> Attrs,
01135                                    Stmt *SubStmt) {
01136     return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
01137   }
01138 
01139   /// \brief Build a new "if" statement.
01140   ///
01141   /// By default, performs semantic analysis to build the new statement.
01142   /// Subclasses may override this routine to provide different behavior.
01143   StmtResult RebuildIfStmt(SourceLocation IfLoc, Sema::FullExprArg Cond,
01144                            VarDecl *CondVar, Stmt *Then,
01145                            SourceLocation ElseLoc, Stmt *Else) {
01146     return getSema().ActOnIfStmt(IfLoc, Cond, CondVar, Then, ElseLoc, Else);
01147   }
01148 
01149   /// \brief Start building a new switch statement.
01150   ///
01151   /// By default, performs semantic analysis to build the new statement.
01152   /// Subclasses may override this routine to provide different behavior.
01153   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
01154                                     Expr *Cond, VarDecl *CondVar) {
01155     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Cond,
01156                                             CondVar);
01157   }
01158 
01159   /// \brief Attach the body to the switch statement.
01160   ///
01161   /// By default, performs semantic analysis to build the new statement.
01162   /// Subclasses may override this routine to provide different behavior.
01163   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
01164                                    Stmt *Switch, Stmt *Body) {
01165     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
01166   }
01167 
01168   /// \brief Build a new while statement.
01169   ///
01170   /// By default, performs semantic analysis to build the new statement.
01171   /// Subclasses may override this routine to provide different behavior.
01172   StmtResult RebuildWhileStmt(SourceLocation WhileLoc, Sema::FullExprArg Cond,
01173                               VarDecl *CondVar, Stmt *Body) {
01174     return getSema().ActOnWhileStmt(WhileLoc, Cond, CondVar, Body);
01175   }
01176 
01177   /// \brief Build a new do-while statement.
01178   ///
01179   /// By default, performs semantic analysis to build the new statement.
01180   /// Subclasses may override this routine to provide different behavior.
01181   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
01182                            SourceLocation WhileLoc, SourceLocation LParenLoc,
01183                            Expr *Cond, SourceLocation RParenLoc) {
01184     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
01185                                  Cond, RParenLoc);
01186   }
01187 
01188   /// \brief Build a new for statement.
01189   ///
01190   /// By default, performs semantic analysis to build the new statement.
01191   /// Subclasses may override this routine to provide different behavior.
01192   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
01193                             Stmt *Init, Sema::FullExprArg Cond,
01194                             VarDecl *CondVar, Sema::FullExprArg Inc,
01195                             SourceLocation RParenLoc, Stmt *Body) {
01196     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
01197                                   CondVar, Inc, RParenLoc, Body);
01198   }
01199 
01200   /// \brief Build a new goto statement.
01201   ///
01202   /// By default, performs semantic analysis to build the new statement.
01203   /// Subclasses may override this routine to provide different behavior.
01204   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
01205                              LabelDecl *Label) {
01206     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
01207   }
01208 
01209   /// \brief Build a new indirect goto statement.
01210   ///
01211   /// By default, performs semantic analysis to build the new statement.
01212   /// Subclasses may override this routine to provide different behavior.
01213   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
01214                                      SourceLocation StarLoc,
01215                                      Expr *Target) {
01216     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
01217   }
01218 
01219   /// \brief Build a new return statement.
01220   ///
01221   /// By default, performs semantic analysis to build the new statement.
01222   /// Subclasses may override this routine to provide different behavior.
01223   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
01224     return getSema().BuildReturnStmt(ReturnLoc, Result);
01225   }
01226 
01227   /// \brief Build a new declaration statement.
01228   ///
01229   /// By default, performs semantic analysis to build the new statement.
01230   /// Subclasses may override this routine to provide different behavior.
01231   StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
01232                              SourceLocation StartLoc, SourceLocation EndLoc) {
01233     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
01234     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
01235   }
01236 
01237   /// \brief Build a new inline asm statement.
01238   ///
01239   /// By default, performs semantic analysis to build the new statement.
01240   /// Subclasses may override this routine to provide different behavior.
01241   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
01242                                bool IsVolatile, unsigned NumOutputs,
01243                                unsigned NumInputs, IdentifierInfo **Names,
01244                                MultiExprArg Constraints, MultiExprArg Exprs,
01245                                Expr *AsmString, MultiExprArg Clobbers,
01246                                SourceLocation RParenLoc) {
01247     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
01248                                      NumInputs, Names, Constraints, Exprs,
01249                                      AsmString, Clobbers, RParenLoc);
01250   }
01251 
01252   /// \brief Build a new MS style inline asm statement.
01253   ///
01254   /// By default, performs semantic analysis to build the new statement.
01255   /// Subclasses may override this routine to provide different behavior.
01256   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
01257                               ArrayRef<Token> AsmToks,
01258                               StringRef AsmString,
01259                               unsigned NumOutputs, unsigned NumInputs,
01260                               ArrayRef<StringRef> Constraints,
01261                               ArrayRef<StringRef> Clobbers,
01262                               ArrayRef<Expr*> Exprs,
01263                               SourceLocation EndLoc) {
01264     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
01265                                     NumOutputs, NumInputs,
01266                                     Constraints, Clobbers, Exprs, EndLoc);
01267   }
01268 
01269   /// \brief Build a new Objective-C \@try statement.
01270   ///
01271   /// By default, performs semantic analysis to build the new statement.
01272   /// Subclasses may override this routine to provide different behavior.
01273   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
01274                                         Stmt *TryBody,
01275                                         MultiStmtArg CatchStmts,
01276                                         Stmt *Finally) {
01277     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
01278                                         Finally);
01279   }
01280 
01281   /// \brief Rebuild an Objective-C exception declaration.
01282   ///
01283   /// By default, performs semantic analysis to build the new declaration.
01284   /// Subclasses may override this routine to provide different behavior.
01285   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
01286                                     TypeSourceInfo *TInfo, QualType T) {
01287     return getSema().BuildObjCExceptionDecl(TInfo, T,
01288                                             ExceptionDecl->getInnerLocStart(),
01289                                             ExceptionDecl->getLocation(),
01290                                             ExceptionDecl->getIdentifier());
01291   }
01292 
01293   /// \brief Build a new Objective-C \@catch statement.
01294   ///
01295   /// By default, performs semantic analysis to build the new statement.
01296   /// Subclasses may override this routine to provide different behavior.
01297   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
01298                                           SourceLocation RParenLoc,
01299                                           VarDecl *Var,
01300                                           Stmt *Body) {
01301     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
01302                                           Var, Body);
01303   }
01304 
01305   /// \brief Build a new Objective-C \@finally statement.
01306   ///
01307   /// By default, performs semantic analysis to build the new statement.
01308   /// Subclasses may override this routine to provide different behavior.
01309   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
01310                                             Stmt *Body) {
01311     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
01312   }
01313 
01314   /// \brief Build a new Objective-C \@throw statement.
01315   ///
01316   /// By default, performs semantic analysis to build the new statement.
01317   /// Subclasses may override this routine to provide different behavior.
01318   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
01319                                           Expr *Operand) {
01320     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
01321   }
01322 
01323   /// \brief Build a new OpenMP executable directive.
01324   ///
01325   /// By default, performs semantic analysis to build the new statement.
01326   /// Subclasses may override this routine to provide different behavior.
01327   StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
01328                                            DeclarationNameInfo DirName,
01329                                            ArrayRef<OMPClause *> Clauses,
01330                                            Stmt *AStmt, SourceLocation StartLoc,
01331                                            SourceLocation EndLoc) {
01332     return getSema().ActOnOpenMPExecutableDirective(Kind, DirName, Clauses,
01333                                                     AStmt, StartLoc, EndLoc);
01334   }
01335 
01336   /// \brief Build a new OpenMP 'if' clause.
01337   ///
01338   /// By default, performs semantic analysis to build the new OpenMP clause.
01339   /// Subclasses may override this routine to provide different behavior.
01340   OMPClause *RebuildOMPIfClause(Expr *Condition,
01341                                 SourceLocation StartLoc,
01342                                 SourceLocation LParenLoc,
01343                                 SourceLocation EndLoc) {
01344     return getSema().ActOnOpenMPIfClause(Condition, StartLoc,
01345                                          LParenLoc, EndLoc);
01346   }
01347 
01348   /// \brief Build a new OpenMP 'final' clause.
01349   ///
01350   /// By default, performs semantic analysis to build the new OpenMP clause.
01351   /// Subclasses may override this routine to provide different behavior.
01352   OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
01353                                    SourceLocation LParenLoc,
01354                                    SourceLocation EndLoc) {
01355     return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
01356                                             EndLoc);
01357   }
01358 
01359   /// \brief Build a new OpenMP 'num_threads' clause.
01360   ///
01361   /// By default, performs semantic analysis to build the new OpenMP clause.
01362   /// Subclasses may override this routine to provide different behavior.
01363   OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
01364                                         SourceLocation StartLoc,
01365                                         SourceLocation LParenLoc,
01366                                         SourceLocation EndLoc) {
01367     return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
01368                                                  LParenLoc, EndLoc);
01369   }
01370 
01371   /// \brief Build a new OpenMP 'safelen' clause.
01372   ///
01373   /// By default, performs semantic analysis to build the new OpenMP clause.
01374   /// Subclasses may override this routine to provide different behavior.
01375   OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
01376                                      SourceLocation LParenLoc,
01377                                      SourceLocation EndLoc) {
01378     return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
01379   }
01380 
01381   /// \brief Build a new OpenMP 'collapse' clause.
01382   ///
01383   /// By default, performs semantic analysis to build the new OpenMP clause.
01384   /// Subclasses may override this routine to provide different behavior.
01385   OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
01386                                       SourceLocation LParenLoc,
01387                                       SourceLocation EndLoc) {
01388     return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
01389                                                EndLoc);
01390   }
01391 
01392   /// \brief Build a new OpenMP 'default' clause.
01393   ///
01394   /// By default, performs semantic analysis to build the new OpenMP clause.
01395   /// Subclasses may override this routine to provide different behavior.
01396   OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
01397                                      SourceLocation KindKwLoc,
01398                                      SourceLocation StartLoc,
01399                                      SourceLocation LParenLoc,
01400                                      SourceLocation EndLoc) {
01401     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
01402                                               StartLoc, LParenLoc, EndLoc);
01403   }
01404 
01405   /// \brief Build a new OpenMP 'proc_bind' clause.
01406   ///
01407   /// By default, performs semantic analysis to build the new OpenMP clause.
01408   /// Subclasses may override this routine to provide different behavior.
01409   OMPClause *RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,
01410                                       SourceLocation KindKwLoc,
01411                                       SourceLocation StartLoc,
01412                                       SourceLocation LParenLoc,
01413                                       SourceLocation EndLoc) {
01414     return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
01415                                                StartLoc, LParenLoc, EndLoc);
01416   }
01417 
01418   /// \brief Build a new OpenMP 'schedule' clause.
01419   ///
01420   /// By default, performs semantic analysis to build the new OpenMP clause.
01421   /// Subclasses may override this routine to provide different behavior.
01422   OMPClause *RebuildOMPScheduleClause(OpenMPScheduleClauseKind Kind,
01423                                       Expr *ChunkSize,
01424                                       SourceLocation StartLoc,
01425                                       SourceLocation LParenLoc,
01426                                       SourceLocation KindLoc,
01427                                       SourceLocation CommaLoc,
01428                                       SourceLocation EndLoc) {
01429     return getSema().ActOnOpenMPScheduleClause(
01430         Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
01431   }
01432 
01433   /// \brief Build a new OpenMP 'private' clause.
01434   ///
01435   /// By default, performs semantic analysis to build the new OpenMP clause.
01436   /// Subclasses may override this routine to provide different behavior.
01437   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
01438                                      SourceLocation StartLoc,
01439                                      SourceLocation LParenLoc,
01440                                      SourceLocation EndLoc) {
01441     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
01442                                               EndLoc);
01443   }
01444 
01445   /// \brief Build a new OpenMP 'firstprivate' clause.
01446   ///
01447   /// By default, performs semantic analysis to build the new OpenMP clause.
01448   /// Subclasses may override this routine to provide different behavior.
01449   OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
01450                                           SourceLocation StartLoc,
01451                                           SourceLocation LParenLoc,
01452                                           SourceLocation EndLoc) {
01453     return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
01454                                                    EndLoc);
01455   }
01456 
01457   /// \brief Build a new OpenMP 'lastprivate' clause.
01458   ///
01459   /// By default, performs semantic analysis to build the new OpenMP clause.
01460   /// Subclasses may override this routine to provide different behavior.
01461   OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
01462                                          SourceLocation StartLoc,
01463                                          SourceLocation LParenLoc,
01464                                          SourceLocation EndLoc) {
01465     return getSema().ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc,
01466                                                   EndLoc);
01467   }
01468 
01469   /// \brief Build a new OpenMP 'shared' clause.
01470   ///
01471   /// By default, performs semantic analysis to build the new OpenMP clause.
01472   /// Subclasses may override this routine to provide different behavior.
01473   OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
01474                                     SourceLocation StartLoc,
01475                                     SourceLocation LParenLoc,
01476                                     SourceLocation EndLoc) {
01477     return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
01478                                              EndLoc);
01479   }
01480 
01481   /// \brief Build a new OpenMP 'reduction' clause.
01482   ///
01483   /// By default, performs semantic analysis to build the new statement.
01484   /// Subclasses may override this routine to provide different behavior.
01485   OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
01486                                        SourceLocation StartLoc,
01487                                        SourceLocation LParenLoc,
01488                                        SourceLocation ColonLoc,
01489                                        SourceLocation EndLoc,
01490                                        CXXScopeSpec &ReductionIdScopeSpec,
01491                                        const DeclarationNameInfo &ReductionId) {
01492     return getSema().ActOnOpenMPReductionClause(
01493         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
01494         ReductionId);
01495   }
01496 
01497   /// \brief Build a new OpenMP 'linear' clause.
01498   ///
01499   /// By default, performs semantic analysis to build the new OpenMP clause.
01500   /// Subclasses may override this routine to provide different behavior.
01501   OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
01502                                     SourceLocation StartLoc,
01503                                     SourceLocation LParenLoc,
01504                                     SourceLocation ColonLoc,
01505                                     SourceLocation EndLoc) {
01506     return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
01507                                              ColonLoc, EndLoc);
01508   }
01509 
01510   /// \brief Build a new OpenMP 'aligned' clause.
01511   ///
01512   /// By default, performs semantic analysis to build the new OpenMP clause.
01513   /// Subclasses may override this routine to provide different behavior.
01514   OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
01515                                      SourceLocation StartLoc,
01516                                      SourceLocation LParenLoc,
01517                                      SourceLocation ColonLoc,
01518                                      SourceLocation EndLoc) {
01519     return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
01520                                               LParenLoc, ColonLoc, EndLoc);
01521   }
01522 
01523   /// \brief Build a new OpenMP 'copyin' clause.
01524   ///
01525   /// By default, performs semantic analysis to build the new OpenMP clause.
01526   /// Subclasses may override this routine to provide different behavior.
01527   OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
01528                                     SourceLocation StartLoc,
01529                                     SourceLocation LParenLoc,
01530                                     SourceLocation EndLoc) {
01531     return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
01532                                              EndLoc);
01533   }
01534 
01535   /// \brief Build a new OpenMP 'copyprivate' clause.
01536   ///
01537   /// By default, performs semantic analysis to build the new OpenMP clause.
01538   /// Subclasses may override this routine to provide different behavior.
01539   OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
01540                                          SourceLocation StartLoc,
01541                                          SourceLocation LParenLoc,
01542                                          SourceLocation EndLoc) {
01543     return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
01544                                                   EndLoc);
01545   }
01546 
01547   /// \brief Build a new OpenMP 'flush' pseudo clause.
01548   ///
01549   /// By default, performs semantic analysis to build the new OpenMP clause.
01550   /// Subclasses may override this routine to provide different behavior.
01551   OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
01552                                    SourceLocation StartLoc,
01553                                    SourceLocation LParenLoc,
01554                                    SourceLocation EndLoc) {
01555     return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
01556                                             EndLoc);
01557   }
01558 
01559   /// \brief Rebuild the operand to an Objective-C \@synchronized statement.
01560   ///
01561   /// By default, performs semantic analysis to build the new statement.
01562   /// Subclasses may override this routine to provide different behavior.
01563   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
01564                                               Expr *object) {
01565     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
01566   }
01567 
01568   /// \brief Build a new Objective-C \@synchronized statement.
01569   ///
01570   /// By default, performs semantic analysis to build the new statement.
01571   /// Subclasses may override this routine to provide different behavior.
01572   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
01573                                            Expr *Object, Stmt *Body) {
01574     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
01575   }
01576 
01577   /// \brief Build a new Objective-C \@autoreleasepool statement.
01578   ///
01579   /// By default, performs semantic analysis to build the new statement.
01580   /// Subclasses may override this routine to provide different behavior.
01581   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
01582                                             Stmt *Body) {
01583     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
01584   }
01585 
01586   /// \brief Build a new Objective-C fast enumeration statement.
01587   ///
01588   /// By default, performs semantic analysis to build the new statement.
01589   /// Subclasses may override this routine to provide different behavior.
01590   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
01591                                           Stmt *Element,
01592                                           Expr *Collection,
01593                                           SourceLocation RParenLoc,
01594                                           Stmt *Body) {
01595     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
01596                                                 Element,
01597                                                 Collection,
01598                                                 RParenLoc);
01599     if (ForEachStmt.isInvalid())
01600       return StmtError();
01601 
01602     return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
01603   }
01604 
01605   /// \brief Build a new C++ exception declaration.
01606   ///
01607   /// By default, performs semantic analysis to build the new decaration.
01608   /// Subclasses may override this routine to provide different behavior.
01609   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
01610                                 TypeSourceInfo *Declarator,
01611                                 SourceLocation StartLoc,
01612                                 SourceLocation IdLoc,
01613                                 IdentifierInfo *Id) {
01614     VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
01615                                                        StartLoc, IdLoc, Id);
01616     if (Var)
01617       getSema().CurContext->addDecl(Var);
01618     return Var;
01619   }
01620 
01621   /// \brief Build a new C++ catch statement.
01622   ///
01623   /// By default, performs semantic analysis to build the new statement.
01624   /// Subclasses may override this routine to provide different behavior.
01625   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
01626                                  VarDecl *ExceptionDecl,
01627                                  Stmt *Handler) {
01628     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
01629                                                       Handler));
01630   }
01631 
01632   /// \brief Build a new C++ try statement.
01633   ///
01634   /// By default, performs semantic analysis to build the new statement.
01635   /// Subclasses may override this routine to provide different behavior.
01636   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
01637                                ArrayRef<Stmt *> Handlers) {
01638     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
01639   }
01640 
01641   /// \brief Build a new C++0x range-based for statement.
01642   ///
01643   /// By default, performs semantic analysis to build the new statement.
01644   /// Subclasses may override this routine to provide different behavior.
01645   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
01646                                     SourceLocation ColonLoc,
01647                                     Stmt *Range, Stmt *BeginEnd,
01648                                     Expr *Cond, Expr *Inc,
01649                                     Stmt *LoopVar,
01650                                     SourceLocation RParenLoc) {
01651     // If we've just learned that the range is actually an Objective-C
01652     // collection, treat this as an Objective-C fast enumeration loop.
01653     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
01654       if (RangeStmt->isSingleDecl()) {
01655         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
01656           if (RangeVar->isInvalidDecl())
01657             return StmtError();
01658 
01659           Expr *RangeExpr = RangeVar->getInit();
01660           if (!RangeExpr->isTypeDependent() &&
01661               RangeExpr->getType()->isObjCObjectPointerType())
01662             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar, RangeExpr,
01663                                                         RParenLoc);
01664         }
01665       }
01666     }
01667 
01668     return getSema().BuildCXXForRangeStmt(ForLoc, ColonLoc, Range, BeginEnd,
01669                                           Cond, Inc, LoopVar, RParenLoc,
01670                                           Sema::BFRK_Rebuild);
01671   }
01672 
01673   /// \brief Build a new C++0x range-based for statement.
01674   ///
01675   /// By default, performs semantic analysis to build the new statement.
01676   /// Subclasses may override this routine to provide different behavior.
01677   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
01678                                           bool IsIfExists,
01679                                           NestedNameSpecifierLoc QualifierLoc,
01680                                           DeclarationNameInfo NameInfo,
01681                                           Stmt *Nested) {
01682     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
01683                                                 QualifierLoc, NameInfo, Nested);
01684   }
01685 
01686   /// \brief Attach body to a C++0x range-based for statement.
01687   ///
01688   /// By default, performs semantic analysis to finish the new statement.
01689   /// Subclasses may override this routine to provide different behavior.
01690   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
01691     return getSema().FinishCXXForRangeStmt(ForRange, Body);
01692   }
01693 
01694   StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
01695                                Stmt *TryBlock, Stmt *Handler) {
01696     return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
01697   }
01698 
01699   StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
01700                                   Stmt *Block) {
01701     return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
01702   }
01703 
01704   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
01705     return getSema().ActOnSEHFinallyBlock(Loc, Block);
01706   }
01707 
01708   /// \brief Build a new predefined expression.
01709   ///
01710   /// By default, performs semantic analysis to build the new expression.
01711   /// Subclasses may override this routine to provide different behavior.
01712   ExprResult RebuildPredefinedExpr(SourceLocation Loc,
01713                                    PredefinedExpr::IdentType IT) {
01714     return getSema().BuildPredefinedExpr(Loc, IT);
01715   }
01716 
01717   /// \brief Build a new expression that references a declaration.
01718   ///
01719   /// By default, performs semantic analysis to build the new expression.
01720   /// Subclasses may override this routine to provide different behavior.
01721   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
01722                                         LookupResult &R,
01723                                         bool RequiresADL) {
01724     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
01725   }
01726 
01727 
01728   /// \brief Build a new expression that references a declaration.
01729   ///
01730   /// By default, performs semantic analysis to build the new expression.
01731   /// Subclasses may override this routine to provide different behavior.
01732   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
01733                                 ValueDecl *VD,
01734                                 const DeclarationNameInfo &NameInfo,
01735                                 TemplateArgumentListInfo *TemplateArgs) {
01736     CXXScopeSpec SS;
01737     SS.Adopt(QualifierLoc);
01738 
01739     // FIXME: loses template args.
01740 
01741     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
01742   }
01743 
01744   /// \brief Build a new expression in parentheses.
01745   ///
01746   /// By default, performs semantic analysis to build the new expression.
01747   /// Subclasses may override this routine to provide different behavior.
01748   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
01749                                     SourceLocation RParen) {
01750     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
01751   }
01752 
01753   /// \brief Build a new pseudo-destructor expression.
01754   ///
01755   /// By default, performs semantic analysis to build the new expression.
01756   /// Subclasses may override this routine to provide different behavior.
01757   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
01758                                             SourceLocation OperatorLoc,
01759                                             bool isArrow,
01760                                             CXXScopeSpec &SS,
01761                                             TypeSourceInfo *ScopeType,
01762                                             SourceLocation CCLoc,
01763                                             SourceLocation TildeLoc,
01764                                         PseudoDestructorTypeStorage Destroyed);
01765 
01766   /// \brief Build a new unary operator expression.
01767   ///
01768   /// By default, performs semantic analysis to build the new expression.
01769   /// Subclasses may override this routine to provide different behavior.
01770   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
01771                                         UnaryOperatorKind Opc,
01772                                         Expr *SubExpr) {
01773     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
01774   }
01775 
01776   /// \brief Build a new builtin offsetof expression.
01777   ///
01778   /// By default, performs semantic analysis to build the new expression.
01779   /// Subclasses may override this routine to provide different behavior.
01780   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
01781                                        TypeSourceInfo *Type,
01782                                        Sema::OffsetOfComponent *Components,
01783                                        unsigned NumComponents,
01784                                        SourceLocation RParenLoc) {
01785     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
01786                                           NumComponents, RParenLoc);
01787   }
01788 
01789   /// \brief Build a new sizeof, alignof or vec_step expression with a
01790   /// type argument.
01791   ///
01792   /// By default, performs semantic analysis to build the new expression.
01793   /// Subclasses may override this routine to provide different behavior.
01794   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
01795                                          SourceLocation OpLoc,
01796                                          UnaryExprOrTypeTrait ExprKind,
01797                                          SourceRange R) {
01798     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
01799   }
01800 
01801   /// \brief Build a new sizeof, alignof or vec step expression with an
01802   /// expression argument.
01803   ///
01804   /// By default, performs semantic analysis to build the new expression.
01805   /// Subclasses may override this routine to provide different behavior.
01806   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
01807                                          UnaryExprOrTypeTrait ExprKind,
01808                                          SourceRange R) {
01809     ExprResult Result
01810       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
01811     if (Result.isInvalid())
01812       return ExprError();
01813 
01814     return Result;
01815   }
01816 
01817   /// \brief Build a new array subscript expression.
01818   ///
01819   /// By default, performs semantic analysis to build the new expression.
01820   /// Subclasses may override this routine to provide different behavior.
01821   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
01822                                              SourceLocation LBracketLoc,
01823                                              Expr *RHS,
01824                                              SourceLocation RBracketLoc) {
01825     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
01826                                              LBracketLoc, RHS,
01827                                              RBracketLoc);
01828   }
01829 
01830   /// \brief Build a new call expression.
01831   ///
01832   /// By default, performs semantic analysis to build the new expression.
01833   /// Subclasses may override this routine to provide different behavior.
01834   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
01835                                    MultiExprArg Args,
01836                                    SourceLocation RParenLoc,
01837                                    Expr *ExecConfig = nullptr) {
01838     return getSema().ActOnCallExpr(/*Scope=*/nullptr, Callee, LParenLoc,
01839                                    Args, RParenLoc, ExecConfig);
01840   }
01841 
01842   /// \brief Build a new member access expression.
01843   ///
01844   /// By default, performs semantic analysis to build the new expression.
01845   /// Subclasses may override this routine to provide different behavior.
01846   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
01847                                bool isArrow,
01848                                NestedNameSpecifierLoc QualifierLoc,
01849                                SourceLocation TemplateKWLoc,
01850                                const DeclarationNameInfo &MemberNameInfo,
01851                                ValueDecl *Member,
01852                                NamedDecl *FoundDecl,
01853                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
01854                                NamedDecl *FirstQualifierInScope) {
01855     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
01856                                                                       isArrow);
01857     if (!Member->getDeclName()) {
01858       // We have a reference to an unnamed field.  This is always the
01859       // base of an anonymous struct/union member access, i.e. the
01860       // field is always of record type.
01861       assert(!QualifierLoc && "Can't have an unnamed field with a qualifier!");
01862       assert(Member->getType()->isRecordType() &&
01863              "unnamed member not of record type?");
01864 
01865       BaseResult =
01866         getSema().PerformObjectMemberConversion(BaseResult.get(),
01867                                                 QualifierLoc.getNestedNameSpecifier(),
01868                                                 FoundDecl, Member);
01869       if (BaseResult.isInvalid())
01870         return ExprError();
01871       Base = BaseResult.get();
01872       ExprValueKind VK = isArrow ? VK_LValue : Base->getValueKind();
01873       MemberExpr *ME =
01874         new (getSema().Context) MemberExpr(Base, isArrow,
01875                                            Member, MemberNameInfo,
01876                                            cast<FieldDecl>(Member)->getType(),
01877                                            VK, OK_Ordinary);
01878       return ME;
01879     }
01880 
01881     CXXScopeSpec SS;
01882     SS.Adopt(QualifierLoc);
01883 
01884     Base = BaseResult.get();
01885     QualType BaseType = Base->getType();
01886 
01887     // FIXME: this involves duplicating earlier analysis in a lot of
01888     // cases; we should avoid this when possible.
01889     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
01890     R.addDecl(FoundDecl);
01891     R.resolveKind();
01892 
01893     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
01894                                               SS, TemplateKWLoc,
01895                                               FirstQualifierInScope,
01896                                               R, ExplicitTemplateArgs);
01897   }
01898 
01899   /// \brief Build a new binary operator expression.
01900   ///
01901   /// By default, performs semantic analysis to build the new expression.
01902   /// Subclasses may override this routine to provide different behavior.
01903   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
01904                                          BinaryOperatorKind Opc,
01905                                          Expr *LHS, Expr *RHS) {
01906     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
01907   }
01908 
01909   /// \brief Build a new conditional operator expression.
01910   ///
01911   /// By default, performs semantic analysis to build the new expression.
01912   /// Subclasses may override this routine to provide different behavior.
01913   ExprResult RebuildConditionalOperator(Expr *Cond,
01914                                         SourceLocation QuestionLoc,
01915                                         Expr *LHS,
01916                                         SourceLocation ColonLoc,
01917                                         Expr *RHS) {
01918     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
01919                                         LHS, RHS);
01920   }
01921 
01922   /// \brief Build a new C-style cast expression.
01923   ///
01924   /// By default, performs semantic analysis to build the new expression.
01925   /// Subclasses may override this routine to provide different behavior.
01926   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
01927                                          TypeSourceInfo *TInfo,
01928                                          SourceLocation RParenLoc,
01929                                          Expr *SubExpr) {
01930     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
01931                                          SubExpr);
01932   }
01933 
01934   /// \brief Build a new compound literal expression.
01935   ///
01936   /// By default, performs semantic analysis to build the new expression.
01937   /// Subclasses may override this routine to provide different behavior.
01938   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
01939                                               TypeSourceInfo *TInfo,
01940                                               SourceLocation RParenLoc,
01941                                               Expr *Init) {
01942     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
01943                                               Init);
01944   }
01945 
01946   /// \brief Build a new extended vector element access expression.
01947   ///
01948   /// By default, performs semantic analysis to build the new expression.
01949   /// Subclasses may override this routine to provide different behavior.
01950   ExprResult RebuildExtVectorElementExpr(Expr *Base,
01951                                                SourceLocation OpLoc,
01952                                                SourceLocation AccessorLoc,
01953                                                IdentifierInfo &Accessor) {
01954 
01955     CXXScopeSpec SS;
01956     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
01957     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
01958                                               OpLoc, /*IsArrow*/ false,
01959                                               SS, SourceLocation(),
01960                                               /*FirstQualifierInScope*/ nullptr,
01961                                               NameInfo,
01962                                               /* TemplateArgs */ nullptr);
01963   }
01964 
01965   /// \brief Build a new initializer list expression.
01966   ///
01967   /// By default, performs semantic analysis to build the new expression.
01968   /// Subclasses may override this routine to provide different behavior.
01969   ExprResult RebuildInitList(SourceLocation LBraceLoc,
01970                              MultiExprArg Inits,
01971                              SourceLocation RBraceLoc,
01972                              QualType ResultTy) {
01973     ExprResult Result
01974       = SemaRef.ActOnInitList(LBraceLoc, Inits, RBraceLoc);
01975     if (Result.isInvalid() || ResultTy->isDependentType())
01976       return Result;
01977 
01978     // Patch in the result type we were given, which may have been computed
01979     // when the initial InitListExpr was built.
01980     InitListExpr *ILE = cast<InitListExpr>((Expr *)Result.get());
01981     ILE->setType(ResultTy);
01982     return Result;
01983   }
01984 
01985   /// \brief Build a new designated initializer expression.
01986   ///
01987   /// By default, performs semantic analysis to build the new expression.
01988   /// Subclasses may override this routine to provide different behavior.
01989   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
01990                                              MultiExprArg ArrayExprs,
01991                                              SourceLocation EqualOrColonLoc,
01992                                              bool GNUSyntax,
01993                                              Expr *Init) {
01994     ExprResult Result
01995       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
01996                                            Init);
01997     if (Result.isInvalid())
01998       return ExprError();
01999 
02000     return Result;
02001   }
02002 
02003   /// \brief Build a new value-initialized expression.
02004   ///
02005   /// By default, builds the implicit value initialization without performing
02006   /// any semantic analysis. Subclasses may override this routine to provide
02007   /// different behavior.
02008   ExprResult RebuildImplicitValueInitExpr(QualType T) {
02009     return new (SemaRef.Context) ImplicitValueInitExpr(T);
02010   }
02011 
02012   /// \brief Build a new \c va_arg expression.
02013   ///
02014   /// By default, performs semantic analysis to build the new expression.
02015   /// Subclasses may override this routine to provide different behavior.
02016   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
02017                                     Expr *SubExpr, TypeSourceInfo *TInfo,
02018                                     SourceLocation RParenLoc) {
02019     return getSema().BuildVAArgExpr(BuiltinLoc,
02020                                     SubExpr, TInfo,
02021                                     RParenLoc);
02022   }
02023 
02024   /// \brief Build a new expression list in parentheses.
02025   ///
02026   /// By default, performs semantic analysis to build the new expression.
02027   /// Subclasses may override this routine to provide different behavior.
02028   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
02029                                   MultiExprArg SubExprs,
02030                                   SourceLocation RParenLoc) {
02031     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
02032   }
02033 
02034   /// \brief Build a new address-of-label expression.
02035   ///
02036   /// By default, performs semantic analysis, using the name of the label
02037   /// rather than attempting to map the label statement itself.
02038   /// Subclasses may override this routine to provide different behavior.
02039   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
02040                                   SourceLocation LabelLoc, LabelDecl *Label) {
02041     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
02042   }
02043 
02044   /// \brief Build a new GNU statement expression.
02045   ///
02046   /// By default, performs semantic analysis to build the new expression.
02047   /// Subclasses may override this routine to provide different behavior.
02048   ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
02049                                    Stmt *SubStmt,
02050                                    SourceLocation RParenLoc) {
02051     return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
02052   }
02053 
02054   /// \brief Build a new __builtin_choose_expr expression.
02055   ///
02056   /// By default, performs semantic analysis to build the new expression.
02057   /// Subclasses may override this routine to provide different behavior.
02058   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
02059                                      Expr *Cond, Expr *LHS, Expr *RHS,
02060                                      SourceLocation RParenLoc) {
02061     return SemaRef.ActOnChooseExpr(BuiltinLoc,
02062                                    Cond, LHS, RHS,
02063                                    RParenLoc);
02064   }
02065 
02066   /// \brief Build a new generic selection expression.
02067   ///
02068   /// By default, performs semantic analysis to build the new expression.
02069   /// Subclasses may override this routine to provide different behavior.
02070   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
02071                                          SourceLocation DefaultLoc,
02072                                          SourceLocation RParenLoc,
02073                                          Expr *ControllingExpr,
02074                                          ArrayRef<TypeSourceInfo *> Types,
02075                                          ArrayRef<Expr *> Exprs) {
02076     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
02077                                                 ControllingExpr, Types, Exprs);
02078   }
02079 
02080   /// \brief Build a new overloaded operator call expression.
02081   ///
02082   /// By default, performs semantic analysis to build the new expression.
02083   /// The semantic analysis provides the behavior of template instantiation,
02084   /// copying with transformations that turn what looks like an overloaded
02085   /// operator call into a use of a builtin operator, performing
02086   /// argument-dependent lookup, etc. Subclasses may override this routine to
02087   /// provide different behavior.
02088   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
02089                                               SourceLocation OpLoc,
02090                                               Expr *Callee,
02091                                               Expr *First,
02092                                               Expr *Second);
02093 
02094   /// \brief Build a new C++ "named" cast expression, such as static_cast or
02095   /// reinterpret_cast.
02096   ///
02097   /// By default, this routine dispatches to one of the more-specific routines
02098   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
02099   /// Subclasses may override this routine to provide different behavior.
02100   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
02101                                            Stmt::StmtClass Class,
02102                                            SourceLocation LAngleLoc,
02103                                            TypeSourceInfo *TInfo,
02104                                            SourceLocation RAngleLoc,
02105                                            SourceLocation LParenLoc,
02106                                            Expr *SubExpr,
02107                                            SourceLocation RParenLoc) {
02108     switch (Class) {
02109     case Stmt::CXXStaticCastExprClass:
02110       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
02111                                                    RAngleLoc, LParenLoc,
02112                                                    SubExpr, RParenLoc);
02113 
02114     case Stmt::CXXDynamicCastExprClass:
02115       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
02116                                                     RAngleLoc, LParenLoc,
02117                                                     SubExpr, RParenLoc);
02118 
02119     case Stmt::CXXReinterpretCastExprClass:
02120       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
02121                                                         RAngleLoc, LParenLoc,
02122                                                         SubExpr,
02123                                                         RParenLoc);
02124 
02125     case Stmt::CXXConstCastExprClass:
02126       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
02127                                                    RAngleLoc, LParenLoc,
02128                                                    SubExpr, RParenLoc);
02129 
02130     default:
02131       llvm_unreachable("Invalid C++ named cast");
02132     }
02133   }
02134 
02135   /// \brief Build a new C++ static_cast expression.
02136   ///
02137   /// By default, performs semantic analysis to build the new expression.
02138   /// Subclasses may override this routine to provide different behavior.
02139   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
02140                                             SourceLocation LAngleLoc,
02141                                             TypeSourceInfo *TInfo,
02142                                             SourceLocation RAngleLoc,
02143                                             SourceLocation LParenLoc,
02144                                             Expr *SubExpr,
02145                                             SourceLocation RParenLoc) {
02146     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
02147                                        TInfo, SubExpr,
02148                                        SourceRange(LAngleLoc, RAngleLoc),
02149                                        SourceRange(LParenLoc, RParenLoc));
02150   }
02151 
02152   /// \brief Build a new C++ dynamic_cast expression.
02153   ///
02154   /// By default, performs semantic analysis to build the new expression.
02155   /// Subclasses may override this routine to provide different behavior.
02156   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
02157                                              SourceLocation LAngleLoc,
02158                                              TypeSourceInfo *TInfo,
02159                                              SourceLocation RAngleLoc,
02160                                              SourceLocation LParenLoc,
02161                                              Expr *SubExpr,
02162                                              SourceLocation RParenLoc) {
02163     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
02164                                        TInfo, SubExpr,
02165                                        SourceRange(LAngleLoc, RAngleLoc),
02166                                        SourceRange(LParenLoc, RParenLoc));
02167   }
02168 
02169   /// \brief Build a new C++ reinterpret_cast expression.
02170   ///
02171   /// By default, performs semantic analysis to build the new expression.
02172   /// Subclasses may override this routine to provide different behavior.
02173   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
02174                                                  SourceLocation LAngleLoc,
02175                                                  TypeSourceInfo *TInfo,
02176                                                  SourceLocation RAngleLoc,
02177                                                  SourceLocation LParenLoc,
02178                                                  Expr *SubExpr,
02179                                                  SourceLocation RParenLoc) {
02180     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
02181                                        TInfo, SubExpr,
02182                                        SourceRange(LAngleLoc, RAngleLoc),
02183                                        SourceRange(LParenLoc, RParenLoc));
02184   }
02185 
02186   /// \brief Build a new C++ const_cast expression.
02187   ///
02188   /// By default, performs semantic analysis to build the new expression.
02189   /// Subclasses may override this routine to provide different behavior.
02190   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
02191                                            SourceLocation LAngleLoc,
02192                                            TypeSourceInfo *TInfo,
02193                                            SourceLocation RAngleLoc,
02194                                            SourceLocation LParenLoc,
02195                                            Expr *SubExpr,
02196                                            SourceLocation RParenLoc) {
02197     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
02198                                        TInfo, SubExpr,
02199                                        SourceRange(LAngleLoc, RAngleLoc),
02200                                        SourceRange(LParenLoc, RParenLoc));
02201   }
02202 
02203   /// \brief Build a new C++ functional-style cast expression.
02204   ///
02205   /// By default, performs semantic analysis to build the new expression.
02206   /// Subclasses may override this routine to provide different behavior.
02207   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
02208                                           SourceLocation LParenLoc,
02209                                           Expr *Sub,
02210                                           SourceLocation RParenLoc) {
02211     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
02212                                                MultiExprArg(&Sub, 1),
02213                                                RParenLoc);
02214   }
02215 
02216   /// \brief Build a new C++ typeid(type) expression.
02217   ///
02218   /// By default, performs semantic analysis to build the new expression.
02219   /// Subclasses may override this routine to provide different behavior.
02220   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
02221                                         SourceLocation TypeidLoc,
02222                                         TypeSourceInfo *Operand,
02223                                         SourceLocation RParenLoc) {
02224     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
02225                                     RParenLoc);
02226   }
02227 
02228 
02229   /// \brief Build a new C++ typeid(expr) expression.
02230   ///
02231   /// By default, performs semantic analysis to build the new expression.
02232   /// Subclasses may override this routine to provide different behavior.
02233   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
02234                                         SourceLocation TypeidLoc,
02235                                         Expr *Operand,
02236                                         SourceLocation RParenLoc) {
02237     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
02238                                     RParenLoc);
02239   }
02240 
02241   /// \brief Build a new C++ __uuidof(type) expression.
02242   ///
02243   /// By default, performs semantic analysis to build the new expression.
02244   /// Subclasses may override this routine to provide different behavior.
02245   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
02246                                         SourceLocation TypeidLoc,
02247                                         TypeSourceInfo *Operand,
02248                                         SourceLocation RParenLoc) {
02249     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
02250                                     RParenLoc);
02251   }
02252 
02253   /// \brief Build a new C++ __uuidof(expr) expression.
02254   ///
02255   /// By default, performs semantic analysis to build the new expression.
02256   /// Subclasses may override this routine to provide different behavior.
02257   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
02258                                         SourceLocation TypeidLoc,
02259                                         Expr *Operand,
02260                                         SourceLocation RParenLoc) {
02261     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
02262                                     RParenLoc);
02263   }
02264 
02265   /// \brief Build a new C++ "this" expression.
02266   ///
02267   /// By default, builds a new "this" expression without performing any
02268   /// semantic analysis. Subclasses may override this routine to provide
02269   /// different behavior.
02270   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
02271                                 QualType ThisType,
02272                                 bool isImplicit) {
02273     getSema().CheckCXXThisCapture(ThisLoc);
02274     return new (getSema().Context) CXXThisExpr(ThisLoc, ThisType, isImplicit);
02275   }
02276 
02277   /// \brief Build a new C++ throw expression.
02278   ///
02279   /// By default, performs semantic analysis to build the new expression.
02280   /// Subclasses may override this routine to provide different behavior.
02281   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
02282                                  bool IsThrownVariableInScope) {
02283     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
02284   }
02285 
02286   /// \brief Build a new C++ default-argument expression.
02287   ///
02288   /// By default, builds a new default-argument expression, which does not
02289   /// require any semantic analysis. Subclasses may override this routine to
02290   /// provide different behavior.
02291   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc,
02292                                             ParmVarDecl *Param) {
02293     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param);
02294   }
02295 
02296   /// \brief Build a new C++11 default-initialization expression.
02297   ///
02298   /// By default, builds a new default field initialization expression, which
02299   /// does not require any semantic analysis. Subclasses may override this
02300   /// routine to provide different behavior.
02301   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
02302                                        FieldDecl *Field) {
02303     return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field);
02304   }
02305 
02306   /// \brief Build a new C++ zero-initialization expression.
02307   ///
02308   /// By default, performs semantic analysis to build the new expression.
02309   /// Subclasses may override this routine to provide different behavior.
02310   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
02311                                            SourceLocation LParenLoc,
02312                                            SourceLocation RParenLoc) {
02313     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc,
02314                                                None, RParenLoc);
02315   }
02316 
02317   /// \brief Build a new C++ "new" expression.
02318   ///
02319   /// By default, performs semantic analysis to build the new expression.
02320   /// Subclasses may override this routine to provide different behavior.
02321   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
02322                                bool UseGlobal,
02323                                SourceLocation PlacementLParen,
02324                                MultiExprArg PlacementArgs,
02325                                SourceLocation PlacementRParen,
02326                                SourceRange TypeIdParens,
02327                                QualType AllocatedType,
02328                                TypeSourceInfo *AllocatedTypeInfo,
02329                                Expr *ArraySize,
02330                                SourceRange DirectInitRange,
02331                                Expr *Initializer) {
02332     return getSema().BuildCXXNew(StartLoc, UseGlobal,
02333                                  PlacementLParen,
02334                                  PlacementArgs,
02335                                  PlacementRParen,
02336                                  TypeIdParens,
02337                                  AllocatedType,
02338                                  AllocatedTypeInfo,
02339                                  ArraySize,
02340                                  DirectInitRange,
02341                                  Initializer);
02342   }
02343 
02344   /// \brief Build a new C++ "delete" expression.
02345   ///
02346   /// By default, performs semantic analysis to build the new expression.
02347   /// Subclasses may override this routine to provide different behavior.
02348   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
02349                                         bool IsGlobalDelete,
02350                                         bool IsArrayForm,
02351                                         Expr *Operand) {
02352     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
02353                                     Operand);
02354   }
02355 
02356   /// \brief Build a new type trait expression.
02357   ///
02358   /// By default, performs semantic analysis to build the new expression.
02359   /// Subclasses may override this routine to provide different behavior.
02360   ExprResult RebuildTypeTrait(TypeTrait Trait,
02361                               SourceLocation StartLoc,
02362                               ArrayRef<TypeSourceInfo *> Args,
02363                               SourceLocation RParenLoc) {
02364     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
02365   }
02366 
02367   /// \brief Build a new array type trait expression.
02368   ///
02369   /// By default, performs semantic analysis to build the new expression.
02370   /// Subclasses may override this routine to provide different behavior.
02371   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
02372                                    SourceLocation StartLoc,
02373                                    TypeSourceInfo *TSInfo,
02374                                    Expr *DimExpr,
02375                                    SourceLocation RParenLoc) {
02376     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
02377   }
02378 
02379   /// \brief Build a new expression trait expression.
02380   ///
02381   /// By default, performs semantic analysis to build the new expression.
02382   /// Subclasses may override this routine to provide different behavior.
02383   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
02384                                    SourceLocation StartLoc,
02385                                    Expr *Queried,
02386                                    SourceLocation RParenLoc) {
02387     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
02388   }
02389 
02390   /// \brief Build a new (previously unresolved) declaration reference
02391   /// expression.
02392   ///
02393   /// By default, performs semantic analysis to build the new expression.
02394   /// Subclasses may override this routine to provide different behavior.
02395   ExprResult RebuildDependentScopeDeclRefExpr(
02396                                           NestedNameSpecifierLoc QualifierLoc,
02397                                           SourceLocation TemplateKWLoc,
02398                                        const DeclarationNameInfo &NameInfo,
02399                               const TemplateArgumentListInfo *TemplateArgs,
02400                                           bool IsAddressOfOperand,
02401                                           TypeSourceInfo **RecoveryTSI) {
02402     CXXScopeSpec SS;
02403     SS.Adopt(QualifierLoc);
02404 
02405     if (TemplateArgs || TemplateKWLoc.isValid())
02406       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
02407                                                     TemplateArgs);
02408 
02409     return getSema().BuildQualifiedDeclarationNameExpr(
02410         SS, NameInfo, IsAddressOfOperand, RecoveryTSI);
02411   }
02412 
02413   /// \brief Build a new template-id expression.
02414   ///
02415   /// By default, performs semantic analysis to build the new expression.
02416   /// Subclasses may override this routine to provide different behavior.
02417   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
02418                                    SourceLocation TemplateKWLoc,
02419                                    LookupResult &R,
02420                                    bool RequiresADL,
02421                               const TemplateArgumentListInfo *TemplateArgs) {
02422     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
02423                                          TemplateArgs);
02424   }
02425 
02426   /// \brief Build a new object-construction expression.
02427   ///
02428   /// By default, performs semantic analysis to build the new expression.
02429   /// Subclasses may override this routine to provide different behavior.
02430   ExprResult RebuildCXXConstructExpr(QualType T,
02431                                      SourceLocation Loc,
02432                                      CXXConstructorDecl *Constructor,
02433                                      bool IsElidable,
02434                                      MultiExprArg Args,
02435                                      bool HadMultipleCandidates,
02436                                      bool ListInitialization,
02437                                      bool StdInitListInitialization,
02438                                      bool RequiresZeroInit,
02439                              CXXConstructExpr::ConstructionKind ConstructKind,
02440                                      SourceRange ParenRange) {
02441     SmallVector<Expr*, 8> ConvertedArgs;
02442     if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
02443                                           ConvertedArgs))
02444       return ExprError();
02445 
02446     return getSema().BuildCXXConstructExpr(Loc, T, Constructor, IsElidable,
02447                                            ConvertedArgs,
02448                                            HadMultipleCandidates,
02449                                            ListInitialization,
02450                                            StdInitListInitialization,
02451                                            RequiresZeroInit, ConstructKind,
02452                                            ParenRange);
02453   }
02454 
02455   /// \brief Build a new object-construction expression.
02456   ///
02457   /// By default, performs semantic analysis to build the new expression.
02458   /// Subclasses may override this routine to provide different behavior.
02459   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
02460                                            SourceLocation LParenLoc,
02461                                            MultiExprArg Args,
02462                                            SourceLocation RParenLoc) {
02463     return getSema().BuildCXXTypeConstructExpr(TSInfo,
02464                                                LParenLoc,
02465                                                Args,
02466                                                RParenLoc);
02467   }
02468 
02469   /// \brief Build a new object-construction expression.
02470   ///
02471   /// By default, performs semantic analysis to build the new expression.
02472   /// Subclasses may override this routine to provide different behavior.
02473   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
02474                                                SourceLocation LParenLoc,
02475                                                MultiExprArg Args,
02476                                                SourceLocation RParenLoc) {
02477     return getSema().BuildCXXTypeConstructExpr(TSInfo,
02478                                                LParenLoc,
02479                                                Args,
02480                                                RParenLoc);
02481   }
02482 
02483   /// \brief Build a new member reference expression.
02484   ///
02485   /// By default, performs semantic analysis to build the new expression.
02486   /// Subclasses may override this routine to provide different behavior.
02487   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
02488                                                 QualType BaseType,
02489                                                 bool IsArrow,
02490                                                 SourceLocation OperatorLoc,
02491                                           NestedNameSpecifierLoc QualifierLoc,
02492                                                 SourceLocation TemplateKWLoc,
02493                                             NamedDecl *FirstQualifierInScope,
02494                                    const DeclarationNameInfo &MemberNameInfo,
02495                               const TemplateArgumentListInfo *TemplateArgs) {
02496     CXXScopeSpec SS;
02497     SS.Adopt(QualifierLoc);
02498 
02499     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
02500                                             OperatorLoc, IsArrow,
02501                                             SS, TemplateKWLoc,
02502                                             FirstQualifierInScope,
02503                                             MemberNameInfo,
02504                                             TemplateArgs);
02505   }
02506 
02507   /// \brief Build a new member reference expression.
02508   ///
02509   /// By default, performs semantic analysis to build the new expression.
02510   /// Subclasses may override this routine to provide different behavior.
02511   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
02512                                          SourceLocation OperatorLoc,
02513                                          bool IsArrow,
02514                                          NestedNameSpecifierLoc QualifierLoc,
02515                                          SourceLocation TemplateKWLoc,
02516                                          NamedDecl *FirstQualifierInScope,
02517                                          LookupResult &R,
02518                                 const TemplateArgumentListInfo *TemplateArgs) {
02519     CXXScopeSpec SS;
02520     SS.Adopt(QualifierLoc);
02521 
02522     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
02523                                             OperatorLoc, IsArrow,
02524                                             SS, TemplateKWLoc,
02525                                             FirstQualifierInScope,
02526                                             R, TemplateArgs);
02527   }
02528 
02529   /// \brief Build a new noexcept expression.
02530   ///
02531   /// By default, performs semantic analysis to build the new expression.
02532   /// Subclasses may override this routine to provide different behavior.
02533   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
02534     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
02535   }
02536 
02537   /// \brief Build a new expression to compute the length of a parameter pack.
02538   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
02539                                    SourceLocation PackLoc,
02540                                    SourceLocation RParenLoc,
02541                                    Optional<unsigned> Length) {
02542     if (Length)
02543       return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
02544                                                   OperatorLoc, Pack, PackLoc,
02545                                                   RParenLoc, *Length);
02546 
02547     return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
02548                                                 OperatorLoc, Pack, PackLoc,
02549                                                 RParenLoc);
02550   }
02551 
02552   /// \brief Build a new Objective-C boxed expression.
02553   ///
02554   /// By default, performs semantic analysis to build the new expression.
02555   /// Subclasses may override this routine to provide different behavior.
02556   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
02557     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
02558   }
02559 
02560   /// \brief Build a new Objective-C array literal.
02561   ///
02562   /// By default, performs semantic analysis to build the new expression.
02563   /// Subclasses may override this routine to provide different behavior.
02564   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
02565                                      Expr **Elements, unsigned NumElements) {
02566     return getSema().BuildObjCArrayLiteral(Range,
02567                                            MultiExprArg(Elements, NumElements));
02568   }
02569 
02570   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
02571                                          Expr *Base, Expr *Key,
02572                                          ObjCMethodDecl *getterMethod,
02573                                          ObjCMethodDecl *setterMethod) {
02574     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
02575                                                    getterMethod, setterMethod);
02576   }
02577 
02578   /// \brief Build a new Objective-C dictionary literal.
02579   ///
02580   /// By default, performs semantic analysis to build the new expression.
02581   /// Subclasses may override this routine to provide different behavior.
02582   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
02583                                           ObjCDictionaryElement *Elements,
02584                                           unsigned NumElements) {
02585     return getSema().BuildObjCDictionaryLiteral(Range, Elements, NumElements);
02586   }
02587 
02588   /// \brief Build a new Objective-C \@encode expression.
02589   ///
02590   /// By default, performs semantic analysis to build the new expression.
02591   /// Subclasses may override this routine to provide different behavior.
02592   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
02593                                          TypeSourceInfo *EncodeTypeInfo,
02594                                          SourceLocation RParenLoc) {
02595     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
02596   }
02597 
02598   /// \brief Build a new Objective-C class message.
02599   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
02600                                           Selector Sel,
02601                                           ArrayRef<SourceLocation> SelectorLocs,
02602                                           ObjCMethodDecl *Method,
02603                                           SourceLocation LBracLoc,
02604                                           MultiExprArg Args,
02605                                           SourceLocation RBracLoc) {
02606     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
02607                                      ReceiverTypeInfo->getType(),
02608                                      /*SuperLoc=*/SourceLocation(),
02609                                      Sel, Method, LBracLoc, SelectorLocs,
02610                                      RBracLoc, Args);
02611   }
02612 
02613   /// \brief Build a new Objective-C instance message.
02614   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
02615                                           Selector Sel,
02616                                           ArrayRef<SourceLocation> SelectorLocs,
02617                                           ObjCMethodDecl *Method,
02618                                           SourceLocation LBracLoc,
02619                                           MultiExprArg Args,
02620                                           SourceLocation RBracLoc) {
02621     return SemaRef.BuildInstanceMessage(Receiver,
02622                                         Receiver->getType(),
02623                                         /*SuperLoc=*/SourceLocation(),
02624                                         Sel, Method, LBracLoc, SelectorLocs,
02625                                         RBracLoc, Args);
02626   }
02627 
02628   /// \brief Build a new Objective-C ivar reference expression.
02629   ///
02630   /// By default, performs semantic analysis to build the new expression.
02631   /// Subclasses may override this routine to provide different behavior.
02632   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
02633                                           SourceLocation IvarLoc,
02634                                           bool IsArrow, bool IsFreeIvar) {
02635     // FIXME: We lose track of the IsFreeIvar bit.
02636     CXXScopeSpec SS;
02637     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
02638     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
02639                                               /*FIXME:*/IvarLoc, IsArrow,
02640                                               SS, SourceLocation(),
02641                                               /*FirstQualifierInScope=*/nullptr,
02642                                               NameInfo,
02643                                               /*TemplateArgs=*/nullptr);
02644   }
02645 
02646   /// \brief Build a new Objective-C property reference expression.
02647   ///
02648   /// By default, performs semantic analysis to build the new expression.
02649   /// Subclasses may override this routine to provide different behavior.
02650   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
02651                                         ObjCPropertyDecl *Property,
02652                                         SourceLocation PropertyLoc) {
02653     CXXScopeSpec SS;
02654     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
02655     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
02656                                               /*FIXME:*/PropertyLoc,
02657                                               /*IsArrow=*/false,
02658                                               SS, SourceLocation(),
02659                                               /*FirstQualifierInScope=*/nullptr,
02660                                               NameInfo,
02661                                               /*TemplateArgs=*/nullptr);
02662   }
02663 
02664   /// \brief Build a new Objective-C property reference expression.
02665   ///
02666   /// By default, performs semantic analysis to build the new expression.
02667   /// Subclasses may override this routine to provide different behavior.
02668   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
02669                                         ObjCMethodDecl *Getter,
02670                                         ObjCMethodDecl *Setter,
02671                                         SourceLocation PropertyLoc) {
02672     // Since these expressions can only be value-dependent, we do not
02673     // need to perform semantic analysis again.
02674     return Owned(
02675       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
02676                                                   VK_LValue, OK_ObjCProperty,
02677                                                   PropertyLoc, Base));
02678   }
02679 
02680   /// \brief Build a new Objective-C "isa" expression.
02681   ///
02682   /// By default, performs semantic analysis to build the new expression.
02683   /// Subclasses may override this routine to provide different behavior.
02684   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
02685                                 SourceLocation OpLoc, bool IsArrow) {
02686     CXXScopeSpec SS;
02687     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
02688     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
02689                                               OpLoc, IsArrow,
02690                                               SS, SourceLocation(),
02691                                               /*FirstQualifierInScope=*/nullptr,
02692                                               NameInfo,
02693                                               /*TemplateArgs=*/nullptr);
02694   }
02695 
02696   /// \brief Build a new shuffle vector expression.
02697   ///
02698   /// By default, performs semantic analysis to build the new expression.
02699   /// Subclasses may override this routine to provide different behavior.
02700   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
02701                                       MultiExprArg SubExprs,
02702                                       SourceLocation RParenLoc) {
02703     // Find the declaration for __builtin_shufflevector
02704     const IdentifierInfo &Name
02705       = SemaRef.Context.Idents.get("__builtin_shufflevector");
02706     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
02707     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
02708     assert(!Lookup.empty() && "No __builtin_shufflevector?");
02709 
02710     // Build a reference to the __builtin_shufflevector builtin
02711     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
02712     Expr *Callee = new (SemaRef.Context) DeclRefExpr(Builtin, false,
02713                                                   SemaRef.Context.BuiltinFnTy,
02714                                                   VK_RValue, BuiltinLoc);
02715     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
02716     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
02717                                        CK_BuiltinFnToFnPtr).get();
02718 
02719     // Build the CallExpr
02720     ExprResult TheCall = new (SemaRef.Context) CallExpr(
02721         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
02722         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
02723 
02724     // Type-check the __builtin_shufflevector expression.
02725     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
02726   }
02727 
02728   /// \brief Build a new convert vector expression.
02729   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
02730                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
02731                                       SourceLocation RParenLoc) {
02732     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
02733                                          BuiltinLoc, RParenLoc);
02734   }
02735 
02736   /// \brief Build a new template argument pack expansion.
02737   ///
02738   /// By default, performs semantic analysis to build a new pack expansion
02739   /// for a template argument. Subclasses may override this routine to provide
02740   /// different behavior.
02741   TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
02742                                            SourceLocation EllipsisLoc,
02743                                            Optional<unsigned> NumExpansions) {
02744     switch (Pattern.getArgument().getKind()) {
02745     case TemplateArgument::Expression: {
02746       ExprResult Result
02747         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
02748                                        EllipsisLoc, NumExpansions);
02749       if (Result.isInvalid())
02750         return TemplateArgumentLoc();
02751 
02752       return TemplateArgumentLoc(Result.get(), Result.get());
02753     }
02754 
02755     case TemplateArgument::Template:
02756       return TemplateArgumentLoc(TemplateArgument(
02757                                           Pattern.getArgument().getAsTemplate(),
02758                                                   NumExpansions),
02759                                  Pattern.getTemplateQualifierLoc(),
02760                                  Pattern.getTemplateNameLoc(),
02761                                  EllipsisLoc);
02762 
02763     case TemplateArgument::Null:
02764     case TemplateArgument::Integral:
02765     case TemplateArgument::Declaration:
02766     case TemplateArgument::Pack:
02767     case TemplateArgument::TemplateExpansion:
02768     case TemplateArgument::NullPtr:
02769       llvm_unreachable("Pack expansion pattern has no parameter packs");
02770 
02771     case TemplateArgument::Type:
02772       if (TypeSourceInfo *Expansion
02773             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
02774                                            EllipsisLoc,
02775                                            NumExpansions))
02776         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
02777                                    Expansion);
02778       break;
02779     }
02780 
02781     return TemplateArgumentLoc();
02782   }
02783 
02784   /// \brief Build a new expression pack expansion.
02785   ///
02786   /// By default, performs semantic analysis to build a new pack expansion
02787   /// for an expression. Subclasses may override this routine to provide
02788   /// different behavior.
02789   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
02790                                   Optional<unsigned> NumExpansions) {
02791     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
02792   }
02793 
02794   /// \brief Build a new C++1z fold-expression.
02795   ///
02796   /// By default, performs semantic analysis in order to build a new fold
02797   /// expression.
02798   ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
02799                                 BinaryOperatorKind Operator,
02800                                 SourceLocation EllipsisLoc, Expr *RHS,
02801                                 SourceLocation RParenLoc) {
02802     return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
02803                                       RHS, RParenLoc);
02804   }
02805 
02806   /// \brief Build an empty C++1z fold-expression with the given operator.
02807   ///
02808   /// By default, produces the fallback value for the fold-expression, or
02809   /// produce an error if there is no fallback value.
02810   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
02811                                      BinaryOperatorKind Operator) {
02812     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
02813   }
02814 
02815   /// \brief Build a new atomic operation expression.
02816   ///
02817   /// By default, performs semantic analysis to build the new expression.
02818   /// Subclasses may override this routine to provide different behavior.
02819   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc,
02820                                MultiExprArg SubExprs,
02821                                QualType RetTy,
02822                                AtomicExpr::AtomicOp Op,
02823                                SourceLocation RParenLoc) {
02824     // Just create the expression; there is not any interesting semantic
02825     // analysis here because we can't actually build an AtomicExpr until
02826     // we are sure it is semantically sound.
02827     return new (SemaRef.Context) AtomicExpr(BuiltinLoc, SubExprs, RetTy, Op,
02828                                             RParenLoc);
02829   }
02830 
02831 private:
02832   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
02833                                      QualType ObjectType,
02834                                      NamedDecl *FirstQualifierInScope,
02835                                      CXXScopeSpec &SS);
02836 
02837   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
02838                                              QualType ObjectType,
02839                                              NamedDecl *FirstQualifierInScope,
02840                                              CXXScopeSpec &SS);
02841 
02842   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
02843                                             NamedDecl *FirstQualifierInScope,
02844                                             CXXScopeSpec &SS);
02845 };
02846 
02847 template<typename Derived>
02848 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S) {
02849   if (!S)
02850     return S;
02851 
02852   switch (S->getStmtClass()) {
02853   case Stmt::NoStmtClass: break;
02854 
02855   // Transform individual statement nodes
02856 #define STMT(Node, Parent)                                              \
02857   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
02858 #define ABSTRACT_STMT(Node)
02859 #define EXPR(Node, Parent)
02860 #include "clang/AST/StmtNodes.inc"
02861 
02862   // Transform expressions by calling TransformExpr.
02863 #define STMT(Node, Parent)
02864 #define ABSTRACT_STMT(Stmt)
02865 #define EXPR(Node, Parent) case Stmt::Node##Class:
02866 #include "clang/AST/StmtNodes.inc"
02867     {
02868       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
02869       if (E.isInvalid())
02870         return StmtError();
02871 
02872       return getSema().ActOnExprStmt(E);
02873     }
02874   }
02875 
02876   return S;
02877 }
02878 
02879 template<typename Derived>
02880 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
02881   if (!S)
02882     return S;
02883 
02884   switch (S->getClauseKind()) {
02885   default: break;
02886   // Transform individual clause nodes
02887 #define OPENMP_CLAUSE(Name, Class)                                             \
02888   case OMPC_ ## Name :                                                         \
02889     return getDerived().Transform ## Class(cast<Class>(S));
02890 #include "clang/Basic/OpenMPKinds.def"
02891   }
02892 
02893   return S;
02894 }
02895 
02896 
02897 template<typename Derived>
02898 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
02899   if (!E)
02900     return E;
02901 
02902   switch (E->getStmtClass()) {
02903     case Stmt::NoStmtClass: break;
02904 #define STMT(Node, Parent) case Stmt::Node##Class: break;
02905 #define ABSTRACT_STMT(Stmt)
02906 #define EXPR(Node, Parent)                                              \
02907     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
02908 #include "clang/AST/StmtNodes.inc"
02909   }
02910 
02911   return E;
02912 }
02913 
02914 template<typename Derived>
02915 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
02916                                                         bool NotCopyInit) {
02917   // Initializers are instantiated like expressions, except that various outer
02918   // layers are stripped.
02919   if (!Init)
02920     return Init;
02921 
02922   if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
02923     Init = ExprTemp->getSubExpr();
02924 
02925   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
02926     Init = MTE->GetTemporaryExpr();
02927 
02928   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
02929     Init = Binder->getSubExpr();
02930 
02931   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
02932     Init = ICE->getSubExprAsWritten();
02933 
02934   if (CXXStdInitializerListExpr *ILE =
02935           dyn_cast<CXXStdInitializerListExpr>(Init))
02936     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
02937 
02938   // If this is copy-initialization, we only need to reconstruct
02939   // InitListExprs. Other forms of copy-initialization will be a no-op if
02940   // the initializer is already the right type.
02941   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
02942   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
02943     return getDerived().TransformExpr(Init);
02944 
02945   // Revert value-initialization back to empty parens.
02946   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
02947     SourceRange Parens = VIE->getSourceRange();
02948     return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
02949                                              Parens.getEnd());
02950   }
02951 
02952   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
02953   if (isa<ImplicitValueInitExpr>(Init))
02954     return getDerived().RebuildParenListExpr(SourceLocation(), None,
02955                                              SourceLocation());
02956 
02957   // Revert initialization by constructor back to a parenthesized or braced list
02958   // of expressions. Any other form of initializer can just be reused directly.
02959   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
02960     return getDerived().TransformExpr(Init);
02961 
02962   // If the initialization implicitly converted an initializer list to a
02963   // std::initializer_list object, unwrap the std::initializer_list too.
02964   if (Construct && Construct->isStdInitListInitialization())
02965     return TransformInitializer(Construct->getArg(0), NotCopyInit);
02966 
02967   SmallVector<Expr*, 8> NewArgs;
02968   bool ArgChanged = false;
02969   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
02970                                   /*IsCall*/true, NewArgs, &ArgChanged))
02971     return ExprError();
02972 
02973   // If this was list initialization, revert to list form.
02974   if (Construct->isListInitialization())
02975     return getDerived().RebuildInitList(Construct->getLocStart(), NewArgs,
02976                                         Construct->getLocEnd(),
02977                                         Construct->getType());
02978 
02979   // Build a ParenListExpr to represent anything else.
02980   SourceRange Parens = Construct->getParenOrBraceRange();
02981   if (Parens.isInvalid()) {
02982     // This was a variable declaration's initialization for which no initializer
02983     // was specified.
02984     assert(NewArgs.empty() &&
02985            "no parens or braces but have direct init with arguments?");
02986     return ExprEmpty();
02987   }
02988   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
02989                                            Parens.getEnd());
02990 }
02991 
02992 template<typename Derived>
02993 bool TreeTransform<Derived>::TransformExprs(Expr **Inputs,
02994                                             unsigned NumInputs,
02995                                             bool IsCall,
02996                                       SmallVectorImpl<Expr *> &Outputs,
02997                                             bool *ArgChanged) {
02998   for (unsigned I = 0; I != NumInputs; ++I) {
02999     // If requested, drop call arguments that need to be dropped.
03000     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
03001       if (ArgChanged)
03002         *ArgChanged = true;
03003 
03004       break;
03005     }
03006 
03007     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
03008       Expr *Pattern = Expansion->getPattern();
03009 
03010       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
03011       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
03012       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
03013 
03014       // Determine whether the set of unexpanded parameter packs can and should
03015       // be expanded.
03016       bool Expand = true;
03017       bool RetainExpansion = false;
03018       Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
03019       Optional<unsigned> NumExpansions = OrigNumExpansions;
03020       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
03021                                                Pattern->getSourceRange(),
03022                                                Unexpanded,
03023                                                Expand, RetainExpansion,
03024                                                NumExpansions))
03025         return true;
03026 
03027       if (!Expand) {
03028         // The transform has determined that we should perform a simple
03029         // transformation on the pack expansion, producing another pack
03030         // expansion.
03031         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
03032         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
03033         if (OutPattern.isInvalid())
03034           return true;
03035 
03036         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
03037                                                 Expansion->getEllipsisLoc(),
03038                                                            NumExpansions);
03039         if (Out.isInvalid())
03040           return true;
03041 
03042         if (ArgChanged)
03043           *ArgChanged = true;
03044         Outputs.push_back(Out.get());
03045         continue;
03046       }
03047 
03048       // Record right away that the argument was changed.  This needs
03049       // to happen even if the array expands to nothing.
03050       if (ArgChanged) *ArgChanged = true;
03051 
03052       // The transform has determined that we should perform an elementwise
03053       // expansion of the pattern. Do so.
03054       for (unsigned I = 0; I != *NumExpansions; ++I) {
03055         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
03056         ExprResult Out = getDerived().TransformExpr(Pattern);
03057         if (Out.isInvalid())
03058           return true;
03059 
03060         // FIXME: Can this happen? We should not try to expand the pack
03061         // in this case.
03062         if (Out.get()->containsUnexpandedParameterPack()) {
03063           Out = getDerived().RebuildPackExpansion(
03064               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
03065           if (Out.isInvalid())
03066             return true;
03067         }
03068 
03069         Outputs.push_back(Out.get());
03070       }
03071 
03072       // If we're supposed to retain a pack expansion, do so by temporarily
03073       // forgetting the partially-substituted parameter pack.
03074       if (RetainExpansion) {
03075         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
03076 
03077         ExprResult Out = getDerived().TransformExpr(Pattern);
03078         if (Out.isInvalid())
03079           return true;
03080 
03081         Out = getDerived().RebuildPackExpansion(
03082             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
03083         if (Out.isInvalid())
03084           return true;
03085 
03086         Outputs.push_back(Out.get());
03087       }
03088 
03089       continue;
03090     }
03091 
03092     ExprResult Result =
03093       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
03094              : getDerived().TransformExpr(Inputs[I]);
03095     if (Result.isInvalid())
03096       return true;
03097 
03098     if (Result.get() != Inputs[I] && ArgChanged)
03099       *ArgChanged = true;
03100 
03101     Outputs.push_back(Result.get());
03102   }
03103 
03104   return false;
03105 }
03106 
03107 template<typename Derived>
03108 NestedNameSpecifierLoc
03109 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
03110                                                     NestedNameSpecifierLoc NNS,
03111                                                      QualType ObjectType,
03112                                              NamedDecl *FirstQualifierInScope) {
03113   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
03114   for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
03115        Qualifier = Qualifier.getPrefix())
03116     Qualifiers.push_back(Qualifier);
03117 
03118   CXXScopeSpec SS;
03119   while (!Qualifiers.empty()) {
03120     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
03121     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
03122 
03123     switch (QNNS->getKind()) {
03124     case NestedNameSpecifier::Identifier:
03125       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr,
03126                                               *QNNS->getAsIdentifier(),
03127                                               Q.getLocalBeginLoc(),
03128                                               Q.getLocalEndLoc(),
03129                                               ObjectType, false, SS,
03130                                               FirstQualifierInScope, false))
03131         return NestedNameSpecifierLoc();
03132 
03133       break;
03134 
03135     case NestedNameSpecifier::Namespace: {
03136       NamespaceDecl *NS
03137         = cast_or_null<NamespaceDecl>(
03138                                     getDerived().TransformDecl(
03139                                                           Q.getLocalBeginLoc(),
03140                                                        QNNS->getAsNamespace()));
03141       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
03142       break;
03143     }
03144 
03145     case NestedNameSpecifier::NamespaceAlias: {
03146       NamespaceAliasDecl *Alias
03147         = cast_or_null<NamespaceAliasDecl>(
03148                       getDerived().TransformDecl(Q.getLocalBeginLoc(),
03149                                                  QNNS->getAsNamespaceAlias()));
03150       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
03151                 Q.getLocalEndLoc());
03152       break;
03153     }
03154 
03155     case NestedNameSpecifier::Global:
03156       // There is no meaningful transformation that one could perform on the
03157       // global scope.
03158       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
03159       break;
03160 
03161     case NestedNameSpecifier::Super: {
03162       CXXRecordDecl *RD =
03163           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
03164               SourceLocation(), QNNS->getAsRecordDecl()));
03165       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
03166       break;
03167     }
03168 
03169     case NestedNameSpecifier::TypeSpecWithTemplate:
03170     case NestedNameSpecifier::TypeSpec: {
03171       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
03172                                               FirstQualifierInScope, SS);
03173 
03174       if (!TL)
03175         return NestedNameSpecifierLoc();
03176 
03177       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
03178           (SemaRef.getLangOpts().CPlusPlus11 &&
03179            TL.getType()->isEnumeralType())) {
03180         assert(!TL.getType().hasLocalQualifiers() &&
03181                "Can't get cv-qualifiers here");
03182         if (TL.getType()->isEnumeralType())
03183           SemaRef.Diag(TL.getBeginLoc(),
03184                        diag::warn_cxx98_compat_enum_nested_name_spec);
03185         SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
03186                   Q.getLocalEndLoc());
03187         break;
03188       }
03189       // If the nested-name-specifier is an invalid type def, don't emit an
03190       // error because a previous error should have already been emitted.
03191       TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
03192       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
03193         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
03194           << TL.getType() << SS.getRange();
03195       }
03196       return NestedNameSpecifierLoc();
03197     }
03198     }
03199 
03200     // The qualifier-in-scope and object type only apply to the leftmost entity.
03201     FirstQualifierInScope = nullptr;
03202     ObjectType = QualType();
03203   }
03204 
03205   // Don't rebuild the nested-name-specifier if we don't have to.
03206   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
03207       !getDerived().AlwaysRebuild())
03208     return NNS;
03209 
03210   // If we can re-use the source-location data from the original
03211   // nested-name-specifier, do so.
03212   if (SS.location_size() == NNS.getDataLength() &&
03213       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
03214     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
03215 
03216   // Allocate new nested-name-specifier location information.
03217   return SS.getWithLocInContext(SemaRef.Context);
03218 }
03219 
03220 template<typename Derived>
03221 DeclarationNameInfo
03222 TreeTransform<Derived>
03223 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
03224   DeclarationName Name = NameInfo.getName();
03225   if (!Name)
03226     return DeclarationNameInfo();
03227 
03228   switch (Name.getNameKind()) {
03229   case DeclarationName::Identifier:
03230   case DeclarationName::ObjCZeroArgSelector:
03231   case DeclarationName::ObjCOneArgSelector:
03232   case DeclarationName::ObjCMultiArgSelector:
03233   case DeclarationName::CXXOperatorName:
03234   case DeclarationName::CXXLiteralOperatorName:
03235   case DeclarationName::CXXUsingDirective:
03236     return NameInfo;
03237 
03238   case DeclarationName::CXXConstructorName:
03239   case DeclarationName::CXXDestructorName:
03240   case DeclarationName::CXXConversionFunctionName: {
03241     TypeSourceInfo *NewTInfo;
03242     CanQualType NewCanTy;
03243     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
03244       NewTInfo = getDerived().TransformType(OldTInfo);
03245       if (!NewTInfo)
03246         return DeclarationNameInfo();
03247       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
03248     }
03249     else {
03250       NewTInfo = nullptr;
03251       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
03252       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
03253       if (NewT.isNull())
03254         return DeclarationNameInfo();
03255       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
03256     }
03257 
03258     DeclarationName NewName
03259       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
03260                                                            NewCanTy);
03261     DeclarationNameInfo NewNameInfo(NameInfo);
03262     NewNameInfo.setName(NewName);
03263     NewNameInfo.setNamedTypeInfo(NewTInfo);
03264     return NewNameInfo;
03265   }
03266   }
03267 
03268   llvm_unreachable("Unknown name kind.");
03269 }
03270 
03271 template<typename Derived>
03272 TemplateName
03273 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
03274                                               TemplateName Name,
03275                                               SourceLocation NameLoc,
03276                                               QualType ObjectType,
03277                                               NamedDecl *FirstQualifierInScope) {
03278   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
03279     TemplateDecl *Template = QTN->getTemplateDecl();
03280     assert(Template && "qualified template name must refer to a template");
03281 
03282     TemplateDecl *TransTemplate
03283       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
03284                                                               Template));
03285     if (!TransTemplate)
03286       return TemplateName();
03287 
03288     if (!getDerived().AlwaysRebuild() &&
03289         SS.getScopeRep() == QTN->getQualifier() &&
03290         TransTemplate == Template)
03291       return Name;
03292 
03293     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
03294                                             TransTemplate);
03295   }
03296 
03297   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
03298     if (SS.getScopeRep()) {
03299       // These apply to the scope specifier, not the template.
03300       ObjectType = QualType();
03301       FirstQualifierInScope = nullptr;
03302     }
03303 
03304     if (!getDerived().AlwaysRebuild() &&
03305         SS.getScopeRep() == DTN->getQualifier() &&
03306         ObjectType.isNull())
03307       return Name;
03308 
03309     if (DTN->isIdentifier()) {
03310       return getDerived().RebuildTemplateName(SS,
03311                                               *DTN->getIdentifier(),
03312                                               NameLoc,
03313                                               ObjectType,
03314                                               FirstQualifierInScope);
03315     }
03316 
03317     return getDerived().RebuildTemplateName(SS, DTN->getOperator(), NameLoc,
03318                                             ObjectType);
03319   }
03320 
03321   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
03322     TemplateDecl *TransTemplate
03323       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
03324                                                               Template));
03325     if (!TransTemplate)
03326       return TemplateName();
03327 
03328     if (!getDerived().AlwaysRebuild() &&
03329         TransTemplate == Template)
03330       return Name;
03331 
03332     return TemplateName(TransTemplate);
03333   }
03334 
03335   if (SubstTemplateTemplateParmPackStorage *SubstPack
03336       = Name.getAsSubstTemplateTemplateParmPack()) {
03337     TemplateTemplateParmDecl *TransParam
03338     = cast_or_null<TemplateTemplateParmDecl>(
03339             getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
03340     if (!TransParam)
03341       return TemplateName();
03342 
03343     if (!getDerived().AlwaysRebuild() &&
03344         TransParam == SubstPack->getParameterPack())
03345       return Name;
03346 
03347     return getDerived().RebuildTemplateName(TransParam,
03348                                             SubstPack->getArgumentPack());
03349   }
03350 
03351   // These should be getting filtered out before they reach the AST.
03352   llvm_unreachable("overloaded function decl survived to here");
03353 }
03354 
03355 template<typename Derived>
03356 void TreeTransform<Derived>::InventTemplateArgumentLoc(
03357                                          const TemplateArgument &Arg,
03358                                          TemplateArgumentLoc &Output) {
03359   SourceLocation Loc = getDerived().getBaseLocation();
03360   switch (Arg.getKind()) {
03361   case TemplateArgument::Null:
03362     llvm_unreachable("null template argument in TreeTransform");
03363     break;
03364 
03365   case TemplateArgument::Type:
03366     Output = TemplateArgumentLoc(Arg,
03367                SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
03368 
03369     break;
03370 
03371   case TemplateArgument::Template:
03372   case TemplateArgument::TemplateExpansion: {
03373     NestedNameSpecifierLocBuilder Builder;
03374     TemplateName Template = Arg.getAsTemplate();
03375     if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
03376       Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
03377     else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
03378       Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
03379 
03380     if (Arg.getKind() == TemplateArgument::Template)
03381       Output = TemplateArgumentLoc(Arg,
03382                                    Builder.getWithLocInContext(SemaRef.Context),
03383                                    Loc);
03384     else
03385       Output = TemplateArgumentLoc(Arg,
03386                                    Builder.getWithLocInContext(SemaRef.Context),
03387                                    Loc, Loc);
03388 
03389     break;
03390   }
03391 
03392   case TemplateArgument::Expression:
03393     Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
03394     break;
03395 
03396   case TemplateArgument::Declaration:
03397   case TemplateArgument::Integral:
03398   case TemplateArgument::Pack:
03399   case TemplateArgument::NullPtr:
03400     Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
03401     break;
03402   }
03403 }
03404 
03405 template<typename Derived>
03406 bool TreeTransform<Derived>::TransformTemplateArgument(
03407                                          const TemplateArgumentLoc &Input,
03408                                          TemplateArgumentLoc &Output) {
03409   const TemplateArgument &Arg = Input.getArgument();
03410   switch (Arg.getKind()) {
03411   case TemplateArgument::Null:
03412   case TemplateArgument::Integral:
03413   case TemplateArgument::Pack:
03414   case TemplateArgument::Declaration:
03415   case TemplateArgument::NullPtr:
03416     llvm_unreachable("Unexpected TemplateArgument");
03417 
03418   case TemplateArgument::Type: {
03419     TypeSourceInfo *DI = Input.getTypeSourceInfo();
03420     if (!DI)
03421       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
03422 
03423     DI = getDerived().TransformType(DI);
03424     if (!DI) return true;
03425 
03426     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
03427     return false;
03428   }
03429 
03430   case TemplateArgument::Template: {
03431     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
03432     if (QualifierLoc) {
03433       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
03434       if (!QualifierLoc)
03435         return true;
03436     }
03437 
03438     CXXScopeSpec SS;
03439     SS.Adopt(QualifierLoc);
03440     TemplateName Template
03441       = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
03442                                            Input.getTemplateNameLoc());
03443     if (Template.isNull())
03444       return true;
03445 
03446     Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
03447                                  Input.getTemplateNameLoc());
03448     return false;
03449   }
03450 
03451   case TemplateArgument::TemplateExpansion:
03452     llvm_unreachable("Caller should expand pack expansions");
03453 
03454   case TemplateArgument::Expression: {
03455     // Template argument expressions are constant expressions.
03456     EnterExpressionEvaluationContext Unevaluated(getSema(),
03457                                                  Sema::ConstantEvaluated);
03458 
03459     Expr *InputExpr = Input.getSourceExpression();
03460     if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
03461 
03462     ExprResult E = getDerived().TransformExpr(InputExpr);
03463     E = SemaRef.ActOnConstantExpression(E);
03464     if (E.isInvalid()) return true;
03465     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
03466     return false;
03467   }
03468   }
03469 
03470   // Work around bogus GCC warning
03471   return true;
03472 }
03473 
03474 /// \brief Iterator adaptor that invents template argument location information
03475 /// for each of the template arguments in its underlying iterator.
03476 template<typename Derived, typename InputIterator>
03477 class TemplateArgumentLocInventIterator {
03478   TreeTransform<Derived> &Self;
03479   InputIterator Iter;
03480 
03481 public:
03482   typedef TemplateArgumentLoc value_type;
03483   typedef TemplateArgumentLoc reference;
03484   typedef typename std::iterator_traits<InputIterator>::difference_type
03485     difference_type;
03486   typedef std::input_iterator_tag iterator_category;
03487 
03488   class pointer {
03489     TemplateArgumentLoc Arg;
03490 
03491   public:
03492     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
03493 
03494     const TemplateArgumentLoc *operator->() const { return &Arg; }
03495   };
03496 
03497   TemplateArgumentLocInventIterator() { }
03498 
03499   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
03500                                              InputIterator Iter)
03501     : Self(Self), Iter(Iter) { }
03502 
03503   TemplateArgumentLocInventIterator &operator++() {
03504     ++Iter;
03505     return *this;
03506   }
03507 
03508   TemplateArgumentLocInventIterator operator++(int) {
03509     TemplateArgumentLocInventIterator Old(*this);
03510     ++(*this);
03511     return Old;
03512   }
03513 
03514   reference operator*() const {
03515     TemplateArgumentLoc Result;
03516     Self.InventTemplateArgumentLoc(*Iter, Result);
03517     return Result;
03518   }
03519 
03520   pointer operator->() const { return pointer(**this); }
03521 
03522   friend bool operator==(const TemplateArgumentLocInventIterator &X,
03523                          const TemplateArgumentLocInventIterator &Y) {
03524     return X.Iter == Y.Iter;
03525   }
03526 
03527   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
03528                          const TemplateArgumentLocInventIterator &Y) {
03529     return X.Iter != Y.Iter;
03530   }
03531 };
03532 
03533 template<typename Derived>
03534 template<typename InputIterator>
03535 bool TreeTransform<Derived>::TransformTemplateArguments(InputIterator First,
03536                                                         InputIterator Last,
03537                                             TemplateArgumentListInfo &Outputs) {
03538   for (; First != Last; ++First) {
03539     TemplateArgumentLoc Out;
03540     TemplateArgumentLoc In = *First;
03541 
03542     if (In.getArgument().getKind() == TemplateArgument::Pack) {
03543       // Unpack argument packs, which we translate them into separate
03544       // arguments.
03545       // FIXME: We could do much better if we could guarantee that the
03546       // TemplateArgumentLocInfo for the pack expansion would be usable for
03547       // all of the template arguments in the argument pack.
03548       typedef TemplateArgumentLocInventIterator<Derived,
03549                                                 TemplateArgument::pack_iterator>
03550         PackLocIterator;
03551       if (TransformTemplateArguments(PackLocIterator(*this,
03552                                                  In.getArgument().pack_begin()),
03553                                      PackLocIterator(*this,
03554                                                    In.getArgument().pack_end()),
03555                                      Outputs))
03556         return true;
03557 
03558       continue;
03559     }
03560 
03561     if (In.getArgument().isPackExpansion()) {
03562       // We have a pack expansion, for which we will be substituting into
03563       // the pattern.
03564       SourceLocation Ellipsis;
03565       Optional<unsigned> OrigNumExpansions;
03566       TemplateArgumentLoc Pattern
03567         = getSema().getTemplateArgumentPackExpansionPattern(
03568               In, Ellipsis, OrigNumExpansions);
03569 
03570       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
03571       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
03572       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
03573 
03574       // Determine whether the set of unexpanded parameter packs can and should
03575       // be expanded.
03576       bool Expand = true;
03577       bool RetainExpansion = false;
03578       Optional<unsigned> NumExpansions = OrigNumExpansions;
03579       if (getDerived().TryExpandParameterPacks(Ellipsis,
03580                                                Pattern.getSourceRange(),
03581                                                Unexpanded,
03582                                                Expand,
03583                                                RetainExpansion,
03584                                                NumExpansions))
03585         return true;
03586 
03587       if (!Expand) {
03588         // The transform has determined that we should perform a simple
03589         // transformation on the pack expansion, producing another pack
03590         // expansion.
03591         TemplateArgumentLoc OutPattern;
03592         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
03593         if (getDerived().TransformTemplateArgument(Pattern, OutPattern))
03594           return true;
03595 
03596         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
03597                                                 NumExpansions);
03598         if (Out.getArgument().isNull())
03599           return true;
03600 
03601         Outputs.addArgument(Out);
03602         continue;
03603       }
03604 
03605       // The transform has determined that we should perform an elementwise
03606       // expansion of the pattern. Do so.
03607       for (unsigned I = 0; I != *NumExpansions; ++I) {
03608         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
03609 
03610         if (getDerived().TransformTemplateArgument(Pattern, Out))
03611           return true;
03612 
03613         if (Out.getArgument().containsUnexpandedParameterPack()) {
03614           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
03615                                                   OrigNumExpansions);
03616           if (Out.getArgument().isNull())
03617             return true;
03618         }
03619 
03620         Outputs.addArgument(Out);
03621       }
03622 
03623       // If we're supposed to retain a pack expansion, do so by temporarily
03624       // forgetting the partially-substituted parameter pack.
03625       if (RetainExpansion) {
03626         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
03627 
03628         if (getDerived().TransformTemplateArgument(Pattern, Out))
03629           return true;
03630 
03631         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
03632                                                 OrigNumExpansions);
03633         if (Out.getArgument().isNull())
03634           return true;
03635 
03636         Outputs.addArgument(Out);
03637       }
03638 
03639       continue;
03640     }
03641 
03642     // The simple case:
03643     if (getDerived().TransformTemplateArgument(In, Out))
03644       return true;
03645 
03646     Outputs.addArgument(Out);
03647   }
03648 
03649   return false;
03650 
03651 }
03652 
03653 //===----------------------------------------------------------------------===//
03654 // Type transformation
03655 //===----------------------------------------------------------------------===//
03656 
03657 template<typename Derived>
03658 QualType TreeTransform<Derived>::TransformType(QualType T) {
03659   if (getDerived().AlreadyTransformed(T))
03660     return T;
03661 
03662   // Temporary workaround.  All of these transformations should
03663   // eventually turn into transformations on TypeLocs.
03664   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
03665                                                 getDerived().getBaseLocation());
03666 
03667   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
03668 
03669   if (!NewDI)
03670     return QualType();
03671 
03672   return NewDI->getType();
03673 }
03674 
03675 template<typename Derived>
03676 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
03677   // Refine the base location to the type's location.
03678   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
03679                        getDerived().getBaseEntity());
03680   if (getDerived().AlreadyTransformed(DI->getType()))
03681     return DI;
03682 
03683   TypeLocBuilder TLB;
03684 
03685   TypeLoc TL = DI->getTypeLoc();
03686   TLB.reserve(TL.getFullDataSize());
03687 
03688   QualType Result = getDerived().TransformType(TLB, TL);
03689   if (Result.isNull())
03690     return nullptr;
03691 
03692   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
03693 }
03694 
03695 template<typename Derived>
03696 QualType
03697 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
03698   switch (T.getTypeLocClass()) {
03699 #define ABSTRACT_TYPELOC(CLASS, PARENT)
03700 #define TYPELOC(CLASS, PARENT)                                                 \
03701   case TypeLoc::CLASS:                                                         \
03702     return getDerived().Transform##CLASS##Type(TLB,                            \
03703                                                T.castAs<CLASS##TypeLoc>());
03704 #include "clang/AST/TypeLocNodes.def"
03705   }
03706 
03707   llvm_unreachable("unhandled type loc!");
03708 }
03709 
03710 /// FIXME: By default, this routine adds type qualifiers only to types
03711 /// that can have qualifiers, and silently suppresses those qualifiers
03712 /// that are not permitted (e.g., qualifiers on reference or function
03713 /// types). This is the right thing for template instantiation, but
03714 /// probably not for other clients.
03715 template<typename Derived>
03716 QualType
03717 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
03718                                                QualifiedTypeLoc T) {
03719   Qualifiers Quals = T.getType().getLocalQualifiers();
03720 
03721   QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
03722   if (Result.isNull())
03723     return QualType();
03724 
03725   // Silently suppress qualifiers if the result type can't be qualified.
03726   // FIXME: this is the right thing for template instantiation, but
03727   // probably not for other clients.
03728   if (Result->isFunctionType() || Result->isReferenceType())
03729     return Result;
03730 
03731   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
03732   // resulting type.
03733   if (Quals.hasObjCLifetime()) {
03734     if (!Result->isObjCLifetimeType() && !Result->isDependentType())
03735       Quals.removeObjCLifetime();
03736     else if (Result.getObjCLifetime()) {
03737       // Objective-C ARC:
03738       //   A lifetime qualifier applied to a substituted template parameter
03739       //   overrides the lifetime qualifier from the template argument.
03740       const AutoType *AutoTy;
03741       if (const SubstTemplateTypeParmType *SubstTypeParam
03742                                 = dyn_cast<SubstTemplateTypeParmType>(Result)) {
03743         QualType Replacement = SubstTypeParam->getReplacementType();
03744         Qualifiers Qs = Replacement.getQualifiers();
03745         Qs.removeObjCLifetime();
03746         Replacement
03747           = SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(),
03748                                              Qs);
03749         Result = SemaRef.Context.getSubstTemplateTypeParmType(
03750                                         SubstTypeParam->getReplacedParameter(),
03751                                                               Replacement);
03752         TLB.TypeWasModifiedSafely(Result);
03753       } else if ((AutoTy = dyn_cast<AutoType>(Result)) && AutoTy->isDeduced()) {
03754         // 'auto' types behave the same way as template parameters.
03755         QualType Deduced = AutoTy->getDeducedType();
03756         Qualifiers Qs = Deduced.getQualifiers();
03757         Qs.removeObjCLifetime();
03758         Deduced = SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(),
03759                                                    Qs);
03760         Result = SemaRef.Context.getAutoType(Deduced, AutoTy->isDecltypeAuto(), 
03761                                 AutoTy->isDependentType());
03762         TLB.TypeWasModifiedSafely(Result);
03763       } else {
03764         // Otherwise, complain about the addition of a qualifier to an
03765         // already-qualified type.
03766         SourceRange R = T.getUnqualifiedLoc().getSourceRange();
03767         SemaRef.Diag(R.getBegin(), diag::err_attr_objc_ownership_redundant)
03768           << Result << R;
03769 
03770         Quals.removeObjCLifetime();
03771       }
03772     }
03773   }
03774   if (!Quals.empty()) {
03775     Result = SemaRef.BuildQualifiedType(Result, T.getBeginLoc(), Quals);
03776     // BuildQualifiedType might not add qualifiers if they are invalid.
03777     if (Result.hasLocalQualifiers())
03778       TLB.push<QualifiedTypeLoc>(Result);
03779     // No location information to preserve.
03780   }
03781 
03782   return Result;
03783 }
03784 
03785 template<typename Derived>
03786 TypeLoc
03787 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
03788                                                    QualType ObjectType,
03789                                                    NamedDecl *UnqualLookup,
03790                                                    CXXScopeSpec &SS) {
03791   if (getDerived().AlreadyTransformed(TL.getType()))
03792     return TL;
03793 
03794   TypeSourceInfo *TSI =
03795       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
03796   if (TSI)
03797     return TSI->getTypeLoc();
03798   return TypeLoc();
03799 }
03800 
03801 template<typename Derived>
03802 TypeSourceInfo *
03803 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
03804                                                    QualType ObjectType,
03805                                                    NamedDecl *UnqualLookup,
03806                                                    CXXScopeSpec &SS) {
03807   if (getDerived().AlreadyTransformed(TSInfo->getType()))
03808     return TSInfo;
03809 
03810   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
03811                                    UnqualLookup, SS);
03812 }
03813 
03814 template <typename Derived>
03815 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
03816     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
03817     CXXScopeSpec &SS) {
03818   QualType T = TL.getType();
03819   assert(!getDerived().AlreadyTransformed(T));
03820 
03821   TypeLocBuilder TLB;
03822   QualType Result;
03823 
03824   if (isa<TemplateSpecializationType>(T)) {
03825     TemplateSpecializationTypeLoc SpecTL =
03826         TL.castAs<TemplateSpecializationTypeLoc>();
03827 
03828     TemplateName Template
03829     = getDerived().TransformTemplateName(SS,
03830                                          SpecTL.getTypePtr()->getTemplateName(),
03831                                          SpecTL.getTemplateNameLoc(),
03832                                          ObjectType, UnqualLookup);
03833     if (Template.isNull())
03834       return nullptr;
03835 
03836     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
03837                                                               Template);
03838   } else if (isa<DependentTemplateSpecializationType>(T)) {
03839     DependentTemplateSpecializationTypeLoc SpecTL =
03840         TL.castAs<DependentTemplateSpecializationTypeLoc>();
03841 
03842     TemplateName Template
03843       = getDerived().RebuildTemplateName(SS,
03844                                          *SpecTL.getTypePtr()->getIdentifier(),
03845                                          SpecTL.getTemplateNameLoc(),
03846                                          ObjectType, UnqualLookup);
03847     if (Template.isNull())
03848       return nullptr;
03849 
03850     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
03851                                                                        SpecTL,
03852                                                                        Template,
03853                                                                        SS);
03854   } else {
03855     // Nothing special needs to be done for these.
03856     Result = getDerived().TransformType(TLB, TL);
03857   }
03858 
03859   if (Result.isNull())
03860     return nullptr;
03861 
03862   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
03863 }
03864 
03865 template <class TyLoc> static inline
03866 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
03867   TyLoc NewT = TLB.push<TyLoc>(T.getType());
03868   NewT.setNameLoc(T.getNameLoc());
03869   return T.getType();
03870 }
03871 
03872 template<typename Derived>
03873 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
03874                                                       BuiltinTypeLoc T) {
03875   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
03876   NewT.setBuiltinLoc(T.getBuiltinLoc());
03877   if (T.needsExtraLocalData())
03878     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
03879   return T.getType();
03880 }
03881 
03882 template<typename Derived>
03883 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
03884                                                       ComplexTypeLoc T) {
03885   // FIXME: recurse?
03886   return TransformTypeSpecType(TLB, T);
03887 }
03888 
03889 template <typename Derived>
03890 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
03891                                                        AdjustedTypeLoc TL) {
03892   // Adjustments applied during transformation are handled elsewhere.
03893   return getDerived().TransformType(TLB, TL.getOriginalLoc());
03894 }
03895 
03896 template<typename Derived>
03897 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
03898                                                       DecayedTypeLoc TL) {
03899   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
03900   if (OriginalType.isNull())
03901     return QualType();
03902 
03903   QualType Result = TL.getType();
03904   if (getDerived().AlwaysRebuild() ||
03905       OriginalType != TL.getOriginalLoc().getType())
03906     Result = SemaRef.Context.getDecayedType(OriginalType);
03907   TLB.push<DecayedTypeLoc>(Result);
03908   // Nothing to set for DecayedTypeLoc.
03909   return Result;
03910 }
03911 
03912 template<typename Derived>
03913 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
03914                                                       PointerTypeLoc TL) {
03915   QualType PointeeType
03916     = getDerived().TransformType(TLB, TL.getPointeeLoc());
03917   if (PointeeType.isNull())
03918     return QualType();
03919 
03920   QualType Result = TL.getType();
03921   if (PointeeType->getAs<ObjCObjectType>()) {
03922     // A dependent pointer type 'T *' has is being transformed such
03923     // that an Objective-C class type is being replaced for 'T'. The
03924     // resulting pointer type is an ObjCObjectPointerType, not a
03925     // PointerType.
03926     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
03927 
03928     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
03929     NewT.setStarLoc(TL.getStarLoc());
03930     return Result;
03931   }
03932 
03933   if (getDerived().AlwaysRebuild() ||
03934       PointeeType != TL.getPointeeLoc().getType()) {
03935     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
03936     if (Result.isNull())
03937       return QualType();
03938   }
03939 
03940   // Objective-C ARC can add lifetime qualifiers to the type that we're
03941   // pointing to.
03942   TLB.TypeWasModifiedSafely(Result->getPointeeType());
03943 
03944   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
03945   NewT.setSigilLoc(TL.getSigilLoc());
03946   return Result;
03947 }
03948 
03949 template<typename Derived>
03950 QualType
03951 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
03952                                                   BlockPointerTypeLoc TL) {
03953   QualType PointeeType
03954     = getDerived().TransformType(TLB, TL.getPointeeLoc());
03955   if (PointeeType.isNull())
03956     return QualType();
03957 
03958   QualType Result = TL.getType();
03959   if (getDerived().AlwaysRebuild() ||
03960       PointeeType != TL.getPointeeLoc().getType()) {
03961     Result = getDerived().RebuildBlockPointerType(PointeeType,
03962                                                   TL.getSigilLoc());
03963     if (Result.isNull())
03964       return QualType();
03965   }
03966 
03967   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
03968   NewT.setSigilLoc(TL.getSigilLoc());
03969   return Result;
03970 }
03971 
03972 /// Transforms a reference type.  Note that somewhat paradoxically we
03973 /// don't care whether the type itself is an l-value type or an r-value
03974 /// type;  we only care if the type was *written* as an l-value type
03975 /// or an r-value type.
03976 template<typename Derived>
03977 QualType
03978 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
03979                                                ReferenceTypeLoc TL) {
03980   const ReferenceType *T = TL.getTypePtr();
03981 
03982   // Note that this works with the pointee-as-written.
03983   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
03984   if (PointeeType.isNull())
03985     return QualType();
03986 
03987   QualType Result = TL.getType();
03988   if (getDerived().AlwaysRebuild() ||
03989       PointeeType != T->getPointeeTypeAsWritten()) {
03990     Result = getDerived().RebuildReferenceType(PointeeType,
03991                                                T->isSpelledAsLValue(),
03992                                                TL.getSigilLoc());
03993     if (Result.isNull())
03994       return QualType();
03995   }
03996 
03997   // Objective-C ARC can add lifetime qualifiers to the type that we're
03998   // referring to.
03999   TLB.TypeWasModifiedSafely(
04000                      Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
04001 
04002   // r-value references can be rebuilt as l-value references.
04003   ReferenceTypeLoc NewTL;
04004   if (isa<LValueReferenceType>(Result))
04005     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
04006   else
04007     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
04008   NewTL.setSigilLoc(TL.getSigilLoc());
04009 
04010   return Result;
04011 }
04012 
04013 template<typename Derived>
04014 QualType
04015 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
04016                                                  LValueReferenceTypeLoc TL) {
04017   return TransformReferenceType(TLB, TL);
04018 }
04019 
04020 template<typename Derived>
04021 QualType
04022 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
04023                                                  RValueReferenceTypeLoc TL) {
04024   return TransformReferenceType(TLB, TL);
04025 }
04026 
04027 template<typename Derived>
04028 QualType
04029 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
04030                                                    MemberPointerTypeLoc TL) {
04031   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
04032   if (PointeeType.isNull())
04033     return QualType();
04034 
04035   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
04036   TypeSourceInfo *NewClsTInfo = nullptr;
04037   if (OldClsTInfo) {
04038     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
04039     if (!NewClsTInfo)
04040       return QualType();
04041   }
04042 
04043   const MemberPointerType *T = TL.getTypePtr();
04044   QualType OldClsType = QualType(T->getClass(), 0);
04045   QualType NewClsType;
04046   if (NewClsTInfo)
04047     NewClsType = NewClsTInfo->getType();
04048   else {
04049     NewClsType = getDerived().TransformType(OldClsType);
04050     if (NewClsType.isNull())
04051       return QualType();
04052   }
04053 
04054   QualType Result = TL.getType();
04055   if (getDerived().AlwaysRebuild() ||
04056       PointeeType != T->getPointeeType() ||
04057       NewClsType != OldClsType) {
04058     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
04059                                                    TL.getStarLoc());
04060     if (Result.isNull())
04061       return QualType();
04062   }
04063 
04064   // If we had to adjust the pointee type when building a member pointer, make
04065   // sure to push TypeLoc info for it.
04066   const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
04067   if (MPT && PointeeType != MPT->getPointeeType()) {
04068     assert(isa<AdjustedType>(MPT->getPointeeType()));
04069     TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
04070   }
04071 
04072   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
04073   NewTL.setSigilLoc(TL.getSigilLoc());
04074   NewTL.setClassTInfo(NewClsTInfo);
04075 
04076   return Result;
04077 }
04078 
04079 template<typename Derived>
04080 QualType
04081 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
04082                                                    ConstantArrayTypeLoc TL) {
04083   const ConstantArrayType *T = TL.getTypePtr();
04084   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
04085   if (ElementType.isNull())
04086     return QualType();
04087 
04088   QualType Result = TL.getType();
04089   if (getDerived().AlwaysRebuild() ||
04090       ElementType != T->getElementType()) {
04091     Result = getDerived().RebuildConstantArrayType(ElementType,
04092                                                    T->getSizeModifier(),
04093                                                    T->getSize(),
04094                                              T->getIndexTypeCVRQualifiers(),
04095                                                    TL.getBracketsRange());
04096     if (Result.isNull())
04097       return QualType();
04098   }
04099 
04100   // We might have either a ConstantArrayType or a VariableArrayType now:
04101   // a ConstantArrayType is allowed to have an element type which is a
04102   // VariableArrayType if the type is dependent.  Fortunately, all array
04103   // types have the same location layout.
04104   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
04105   NewTL.setLBracketLoc(TL.getLBracketLoc());
04106   NewTL.setRBracketLoc(TL.getRBracketLoc());
04107 
04108   Expr *Size = TL.getSizeExpr();
04109   if (Size) {
04110     EnterExpressionEvaluationContext Unevaluated(SemaRef,
04111                                                  Sema::ConstantEvaluated);
04112     Size = getDerived().TransformExpr(Size).template getAs<Expr>();
04113     Size = SemaRef.ActOnConstantExpression(Size).get();
04114   }
04115   NewTL.setSizeExpr(Size);
04116 
04117   return Result;
04118 }
04119 
04120 template<typename Derived>
04121 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
04122                                               TypeLocBuilder &TLB,
04123                                               IncompleteArrayTypeLoc TL) {
04124   const IncompleteArrayType *T = TL.getTypePtr();
04125   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
04126   if (ElementType.isNull())
04127     return QualType();
04128 
04129   QualType Result = TL.getType();
04130   if (getDerived().AlwaysRebuild() ||
04131       ElementType != T->getElementType()) {
04132     Result = getDerived().RebuildIncompleteArrayType(ElementType,
04133                                                      T->getSizeModifier(),
04134                                            T->getIndexTypeCVRQualifiers(),
04135                                                      TL.getBracketsRange());
04136     if (Result.isNull())
04137       return QualType();
04138   }
04139 
04140   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
04141   NewTL.setLBracketLoc(TL.getLBracketLoc());
04142   NewTL.setRBracketLoc(TL.getRBracketLoc());
04143   NewTL.setSizeExpr(nullptr);
04144 
04145   return Result;
04146 }
04147 
04148 template<typename Derived>
04149 QualType
04150 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
04151                                                    VariableArrayTypeLoc TL) {
04152   const VariableArrayType *T = TL.getTypePtr();
04153   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
04154   if (ElementType.isNull())
04155     return QualType();
04156 
04157   ExprResult SizeResult
04158     = getDerived().TransformExpr(T->getSizeExpr());
04159   if (SizeResult.isInvalid())
04160     return QualType();
04161 
04162   Expr *Size = SizeResult.get();
04163 
04164   QualType Result = TL.getType();
04165   if (getDerived().AlwaysRebuild() ||
04166       ElementType != T->getElementType() ||
04167       Size != T->getSizeExpr()) {
04168     Result = getDerived().RebuildVariableArrayType(ElementType,
04169                                                    T->getSizeModifier(),
04170                                                    Size,
04171                                              T->getIndexTypeCVRQualifiers(),
04172                                                    TL.getBracketsRange());
04173     if (Result.isNull())
04174       return QualType();
04175   }
04176 
04177   // We might have constant size array now, but fortunately it has the same
04178   // location layout.
04179   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
04180   NewTL.setLBracketLoc(TL.getLBracketLoc());
04181   NewTL.setRBracketLoc(TL.getRBracketLoc());
04182   NewTL.setSizeExpr(Size);
04183 
04184   return Result;
04185 }
04186 
04187 template<typename Derived>
04188 QualType
04189 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
04190                                              DependentSizedArrayTypeLoc TL) {
04191   const DependentSizedArrayType *T = TL.getTypePtr();
04192   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
04193   if (ElementType.isNull())
04194     return QualType();
04195 
04196   // Array bounds are constant expressions.
04197   EnterExpressionEvaluationContext Unevaluated(SemaRef,
04198                                                Sema::ConstantEvaluated);
04199 
04200   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
04201   Expr *origSize = TL.getSizeExpr();
04202   if (!origSize) origSize = T->getSizeExpr();
04203 
04204   ExprResult sizeResult
04205     = getDerived().TransformExpr(origSize);
04206   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
04207   if (sizeResult.isInvalid())
04208     return QualType();
04209 
04210   Expr *size = sizeResult.get();
04211 
04212   QualType Result = TL.getType();
04213   if (getDerived().AlwaysRebuild() ||
04214       ElementType != T->getElementType() ||
04215       size != origSize) {
04216     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
04217                                                          T->getSizeModifier(),
04218                                                          size,
04219                                                 T->getIndexTypeCVRQualifiers(),
04220                                                         TL.getBracketsRange());
04221     if (Result.isNull())
04222       return QualType();
04223   }
04224 
04225   // We might have any sort of array type now, but fortunately they
04226   // all have the same location layout.
04227   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
04228   NewTL.setLBracketLoc(TL.getLBracketLoc());
04229   NewTL.setRBracketLoc(TL.getRBracketLoc());
04230   NewTL.setSizeExpr(size);
04231 
04232   return Result;
04233 }
04234 
04235 template<typename Derived>
04236 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
04237                                       TypeLocBuilder &TLB,
04238                                       DependentSizedExtVectorTypeLoc TL) {
04239   const DependentSizedExtVectorType *T = TL.getTypePtr();
04240 
04241   // FIXME: ext vector locs should be nested
04242   QualType ElementType = getDerived().TransformType(T->getElementType());
04243   if (ElementType.isNull())
04244     return QualType();
04245 
04246   // Vector sizes are constant expressions.
04247   EnterExpressionEvaluationContext Unevaluated(SemaRef,
04248                                                Sema::ConstantEvaluated);
04249 
04250   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
04251   Size = SemaRef.ActOnConstantExpression(Size);
04252   if (Size.isInvalid())
04253     return QualType();
04254 
04255   QualType Result = TL.getType();
04256   if (getDerived().AlwaysRebuild() ||
04257       ElementType != T->getElementType() ||
04258       Size.get() != T->getSizeExpr()) {
04259     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
04260                                                              Size.get(),
04261                                                          T->getAttributeLoc());
04262     if (Result.isNull())
04263       return QualType();
04264   }
04265 
04266   // Result might be dependent or not.
04267   if (isa<DependentSizedExtVectorType>(Result)) {
04268     DependentSizedExtVectorTypeLoc NewTL
04269       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
04270     NewTL.setNameLoc(TL.getNameLoc());
04271   } else {
04272     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
04273     NewTL.setNameLoc(TL.getNameLoc());
04274   }
04275 
04276   return Result;
04277 }
04278 
04279 template<typename Derived>
04280 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
04281                                                      VectorTypeLoc TL) {
04282   const VectorType *T = TL.getTypePtr();
04283   QualType ElementType = getDerived().TransformType(T->getElementType());
04284   if (ElementType.isNull())
04285     return QualType();
04286 
04287   QualType Result = TL.getType();
04288   if (getDerived().AlwaysRebuild() ||
04289       ElementType != T->getElementType()) {
04290     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
04291                                             T->getVectorKind());
04292     if (Result.isNull())
04293       return QualType();
04294   }
04295 
04296   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
04297   NewTL.setNameLoc(TL.getNameLoc());
04298 
04299   return Result;
04300 }
04301 
04302 template<typename Derived>
04303 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
04304                                                         ExtVectorTypeLoc TL) {
04305   const VectorType *T = TL.getTypePtr();
04306   QualType ElementType = getDerived().TransformType(T->getElementType());
04307   if (ElementType.isNull())
04308     return QualType();
04309 
04310   QualType Result = TL.getType();
04311   if (getDerived().AlwaysRebuild() ||
04312       ElementType != T->getElementType()) {
04313     Result = getDerived().RebuildExtVectorType(ElementType,
04314                                                T->getNumElements(),
04315                                                /*FIXME*/ SourceLocation());
04316     if (Result.isNull())
04317       return QualType();
04318   }
04319 
04320   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
04321   NewTL.setNameLoc(TL.getNameLoc());
04322 
04323   return Result;
04324 }
04325 
04326 template <typename Derived>
04327 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
04328     ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
04329     bool ExpectParameterPack) {
04330   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
04331   TypeSourceInfo *NewDI = nullptr;
04332 
04333   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
04334     // If we're substituting into a pack expansion type and we know the
04335     // length we want to expand to, just substitute for the pattern.
04336     TypeLoc OldTL = OldDI->getTypeLoc();
04337     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
04338 
04339     TypeLocBuilder TLB;
04340     TypeLoc NewTL = OldDI->getTypeLoc();
04341     TLB.reserve(NewTL.getFullDataSize());
04342 
04343     QualType Result = getDerived().TransformType(TLB,
04344                                                OldExpansionTL.getPatternLoc());
04345     if (Result.isNull())
04346       return nullptr;
04347 
04348     Result = RebuildPackExpansionType(Result,
04349                                 OldExpansionTL.getPatternLoc().getSourceRange(),
04350                                       OldExpansionTL.getEllipsisLoc(),
04351                                       NumExpansions);
04352     if (Result.isNull())
04353       return nullptr;
04354 
04355     PackExpansionTypeLoc NewExpansionTL
04356       = TLB.push<PackExpansionTypeLoc>(Result);
04357     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
04358     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
04359   } else
04360     NewDI = getDerived().TransformType(OldDI);
04361   if (!NewDI)
04362     return nullptr;
04363 
04364   if (NewDI == OldDI && indexAdjustment == 0)
04365     return OldParm;
04366 
04367   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
04368                                              OldParm->getDeclContext(),
04369                                              OldParm->getInnerLocStart(),
04370                                              OldParm->getLocation(),
04371                                              OldParm->getIdentifier(),
04372                                              NewDI->getType(),
04373                                              NewDI,
04374                                              OldParm->getStorageClass(),
04375                                              /* DefArg */ nullptr);
04376   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
04377                         OldParm->getFunctionScopeIndex() + indexAdjustment);
04378   return newParm;
04379 }
04380 
04381 template<typename Derived>
04382 bool TreeTransform<Derived>::
04383   TransformFunctionTypeParams(SourceLocation Loc,
04384                               ParmVarDecl **Params, unsigned NumParams,
04385                               const QualType *ParamTypes,
04386                               SmallVectorImpl<QualType> &OutParamTypes,
04387                               SmallVectorImpl<ParmVarDecl*> *PVars) {
04388   int indexAdjustment = 0;
04389 
04390   for (unsigned i = 0; i != NumParams; ++i) {
04391     if (ParmVarDecl *OldParm = Params[i]) {
04392       assert(OldParm->getFunctionScopeIndex() == i);
04393 
04394       Optional<unsigned> NumExpansions;
04395       ParmVarDecl *NewParm = nullptr;
04396       if (OldParm->isParameterPack()) {
04397         // We have a function parameter pack that may need to be expanded.
04398         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
04399 
04400         // Find the parameter packs that could be expanded.
04401         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
04402         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
04403         TypeLoc Pattern = ExpansionTL.getPatternLoc();
04404         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
04405         assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
04406 
04407         // Determine whether we should expand the parameter packs.
04408         bool ShouldExpand = false;
04409         bool RetainExpansion = false;
04410         Optional<unsigned> OrigNumExpansions =
04411             ExpansionTL.getTypePtr()->getNumExpansions();
04412         NumExpansions = OrigNumExpansions;
04413         if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
04414                                                  Pattern.getSourceRange(),
04415                                                  Unexpanded,
04416                                                  ShouldExpand,
04417                                                  RetainExpansion,
04418                                                  NumExpansions)) {
04419           return true;
04420         }
04421 
04422         if (ShouldExpand) {
04423           // Expand the function parameter pack into multiple, separate
04424           // parameters.
04425           getDerived().ExpandingFunctionParameterPack(OldParm);
04426           for (unsigned I = 0; I != *NumExpansions; ++I) {
04427             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
04428             ParmVarDecl *NewParm
04429               = getDerived().TransformFunctionTypeParam(OldParm,
04430                                                         indexAdjustment++,
04431                                                         OrigNumExpansions,
04432                                                 /*ExpectParameterPack=*/false);
04433             if (!NewParm)
04434               return true;
04435 
04436             OutParamTypes.push_back(NewParm->getType());
04437             if (PVars)
04438               PVars->push_back(NewParm);
04439           }
04440 
04441           // If we're supposed to retain a pack expansion, do so by temporarily
04442           // forgetting the partially-substituted parameter pack.
04443           if (RetainExpansion) {
04444             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
04445             ParmVarDecl *NewParm
04446               = getDerived().TransformFunctionTypeParam(OldParm,
04447                                                         indexAdjustment++,
04448                                                         OrigNumExpansions,
04449                                                 /*ExpectParameterPack=*/false);
04450             if (!NewParm)
04451               return true;
04452 
04453             OutParamTypes.push_back(NewParm->getType());
04454             if (PVars)
04455               PVars->push_back(NewParm);
04456           }
04457 
04458           // The next parameter should have the same adjustment as the
04459           // last thing we pushed, but we post-incremented indexAdjustment
04460           // on every push.  Also, if we push nothing, the adjustment should
04461           // go down by one.
04462           indexAdjustment--;
04463 
04464           // We're done with the pack expansion.
04465           continue;
04466         }
04467 
04468         // We'll substitute the parameter now without expanding the pack
04469         // expansion.
04470         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
04471         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
04472                                                           indexAdjustment,
04473                                                           NumExpansions,
04474                                                   /*ExpectParameterPack=*/true);
04475       } else {
04476         NewParm = getDerived().TransformFunctionTypeParam(
04477             OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
04478       }
04479 
04480       if (!NewParm)
04481         return true;
04482 
04483       OutParamTypes.push_back(NewParm->getType());
04484       if (PVars)
04485         PVars->push_back(NewParm);
04486       continue;
04487     }
04488 
04489     // Deal with the possibility that we don't have a parameter
04490     // declaration for this parameter.
04491     QualType OldType = ParamTypes[i];
04492     bool IsPackExpansion = false;
04493     Optional<unsigned> NumExpansions;
04494     QualType NewType;
04495     if (const PackExpansionType *Expansion
04496                                        = dyn_cast<PackExpansionType>(OldType)) {
04497       // We have a function parameter pack that may need to be expanded.
04498       QualType Pattern = Expansion->getPattern();
04499       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
04500       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
04501 
04502       // Determine whether we should expand the parameter packs.
04503       bool ShouldExpand = false;
04504       bool RetainExpansion = false;
04505       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
04506                                                Unexpanded,
04507                                                ShouldExpand,
04508                                                RetainExpansion,
04509                                                NumExpansions)) {
04510         return true;
04511       }
04512 
04513       if (ShouldExpand) {
04514         // Expand the function parameter pack into multiple, separate
04515         // parameters.
04516         for (unsigned I = 0; I != *NumExpansions; ++I) {
04517           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
04518           QualType NewType = getDerived().TransformType(Pattern);
04519           if (NewType.isNull())
04520             return true;
04521 
04522           OutParamTypes.push_back(NewType);
04523           if (PVars)
04524             PVars->push_back(nullptr);
04525         }
04526 
04527         // We're done with the pack expansion.
04528         continue;
04529       }
04530 
04531       // If we're supposed to retain a pack expansion, do so by temporarily
04532       // forgetting the partially-substituted parameter pack.
04533       if (RetainExpansion) {
04534         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
04535         QualType NewType = getDerived().TransformType(Pattern);
04536         if (NewType.isNull())
04537           return true;
04538 
04539         OutParamTypes.push_back(NewType);
04540         if (PVars)
04541           PVars->push_back(nullptr);
04542       }
04543 
04544       // We'll substitute the parameter now without expanding the pack
04545       // expansion.
04546       OldType = Expansion->getPattern();
04547       IsPackExpansion = true;
04548       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
04549       NewType = getDerived().TransformType(OldType);
04550     } else {
04551       NewType = getDerived().TransformType(OldType);
04552     }
04553 
04554     if (NewType.isNull())
04555       return true;
04556 
04557     if (IsPackExpansion)
04558       NewType = getSema().Context.getPackExpansionType(NewType,
04559                                                        NumExpansions);
04560 
04561     OutParamTypes.push_back(NewType);
04562     if (PVars)
04563       PVars->push_back(nullptr);
04564   }
04565 
04566 #ifndef NDEBUG
04567   if (PVars) {
04568     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
04569       if (ParmVarDecl *parm = (*PVars)[i])
04570         assert(parm->getFunctionScopeIndex() == i);
04571   }
04572 #endif
04573 
04574   return false;
04575 }
04576 
04577 template<typename Derived>
04578 QualType
04579 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
04580                                                    FunctionProtoTypeLoc TL) {
04581   SmallVector<QualType, 4> ExceptionStorage;
04582   TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
04583   return getDerived().TransformFunctionProtoType(
04584       TLB, TL, nullptr, 0,
04585       [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
04586         return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
04587                                             ExceptionStorage, Changed);
04588       });
04589 }
04590 
04591 template<typename Derived> template<typename Fn>
04592 QualType TreeTransform<Derived>::TransformFunctionProtoType(
04593     TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
04594     unsigned ThisTypeQuals, Fn TransformExceptionSpec) {
04595   // Transform the parameters and return type.
04596   //
04597   // We are required to instantiate the params and return type in source order.
04598   // When the function has a trailing return type, we instantiate the
04599   // parameters before the return type,  since the return type can then refer
04600   // to the parameters themselves (via decltype, sizeof, etc.).
04601   //
04602   SmallVector<QualType, 4> ParamTypes;
04603   SmallVector<ParmVarDecl*, 4> ParamDecls;
04604   const FunctionProtoType *T = TL.getTypePtr();
04605 
04606   QualType ResultType;
04607 
04608   if (T->hasTrailingReturn()) {
04609     if (getDerived().TransformFunctionTypeParams(
04610             TL.getBeginLoc(), TL.getParmArray(), TL.getNumParams(),
04611             TL.getTypePtr()->param_type_begin(), ParamTypes, &ParamDecls))
04612       return QualType();
04613 
04614     {
04615       // C++11 [expr.prim.general]p3:
04616       //   If a declaration declares a member function or member function
04617       //   template of a class X, the expression this is a prvalue of type
04618       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
04619       //   and the end of the function-definition, member-declarator, or
04620       //   declarator.
04621       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
04622 
04623       ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
04624       if (ResultType.isNull())
04625         return QualType();
04626     }
04627   }
04628   else {
04629     ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
04630     if (ResultType.isNull())
04631       return QualType();
04632 
04633     if (getDerived().TransformFunctionTypeParams(
04634             TL.getBeginLoc(), TL.getParmArray(), TL.getNumParams(),
04635             TL.getTypePtr()->param_type_begin(), ParamTypes, &ParamDecls))
04636       return QualType();
04637   }
04638 
04639   FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
04640 
04641   bool EPIChanged = false;
04642   if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
04643     return QualType();
04644 
04645   // FIXME: Need to transform ConsumedParameters for variadic template
04646   // expansion.
04647 
04648   QualType Result = TL.getType();
04649   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
04650       T->getNumParams() != ParamTypes.size() ||
04651       !std::equal(T->param_type_begin(), T->param_type_end(),
04652                   ParamTypes.begin()) || EPIChanged) {
04653     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
04654     if (Result.isNull())
04655       return QualType();
04656   }
04657 
04658   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
04659   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
04660   NewTL.setLParenLoc(TL.getLParenLoc());
04661   NewTL.setRParenLoc(TL.getRParenLoc());
04662   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
04663   for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
04664     NewTL.setParam(i, ParamDecls[i]);
04665 
04666   return Result;
04667 }
04668 
04669 template<typename Derived>
04670 bool TreeTransform<Derived>::TransformExceptionSpec(
04671     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
04672     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
04673   assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
04674 
04675   // Instantiate a dynamic noexcept expression, if any.
04676   if (ESI.Type == EST_ComputedNoexcept) {
04677     EnterExpressionEvaluationContext Unevaluated(getSema(),
04678                                                  Sema::ConstantEvaluated);
04679     ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
04680     if (NoexceptExpr.isInvalid())
04681       return true;
04682 
04683     NoexceptExpr = getSema().CheckBooleanCondition(
04684         NoexceptExpr.get(), NoexceptExpr.get()->getLocStart());
04685     if (NoexceptExpr.isInvalid())
04686       return true;
04687 
04688     if (!NoexceptExpr.get()->isValueDependent()) {
04689       NoexceptExpr = getSema().VerifyIntegerConstantExpression(
04690           NoexceptExpr.get(), nullptr,
04691           diag::err_noexcept_needs_constant_expression,
04692           /*AllowFold*/false);
04693       if (NoexceptExpr.isInvalid())
04694         return true;
04695     }
04696 
04697     if (ESI.NoexceptExpr != NoexceptExpr.get())
04698       Changed = true;
04699     ESI.NoexceptExpr = NoexceptExpr.get();
04700   }
04701 
04702   if (ESI.Type != EST_Dynamic)
04703     return false;
04704 
04705   // Instantiate a dynamic exception specification's type.
04706   for (QualType T : ESI.Exceptions) {
04707     if (const PackExpansionType *PackExpansion =
04708             T->getAs<PackExpansionType>()) {
04709       Changed = true;
04710 
04711       // We have a pack expansion. Instantiate it.
04712       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
04713       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
04714                                               Unexpanded);
04715       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
04716 
04717       // Determine whether the set of unexpanded parameter packs can and
04718       // should
04719       // be expanded.
04720       bool Expand = false;
04721       bool RetainExpansion = false;
04722       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
04723       // FIXME: Track the location of the ellipsis (and track source location
04724       // information for the types in the exception specification in general).
04725       if (getDerived().TryExpandParameterPacks(
04726               Loc, SourceRange(), Unexpanded, Expand,
04727               RetainExpansion, NumExpansions))
04728         return true;
04729 
04730       if (!Expand) {
04731         // We can't expand this pack expansion into separate arguments yet;
04732         // just substitute into the pattern and create a new pack expansion
04733         // type.
04734         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
04735         QualType U = getDerived().TransformType(PackExpansion->getPattern());
04736         if (U.isNull())
04737           return true;
04738 
04739         U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
04740         Exceptions.push_back(U);
04741         continue;
04742       }
04743 
04744       // Substitute into the pack expansion pattern for each slice of the
04745       // pack.
04746       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
04747         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
04748 
04749         QualType U = getDerived().TransformType(PackExpansion->getPattern());
04750         if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
04751           return true;
04752 
04753         Exceptions.push_back(U);
04754       }
04755     } else {
04756       QualType U = getDerived().TransformType(T);
04757       if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
04758         return true;
04759       if (T != U)
04760         Changed = true;
04761 
04762       Exceptions.push_back(U);
04763     }
04764   }
04765 
04766   ESI.Exceptions = Exceptions;
04767   return false;
04768 }
04769 
04770 template<typename Derived>
04771 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
04772                                                  TypeLocBuilder &TLB,
04773                                                  FunctionNoProtoTypeLoc TL) {
04774   const FunctionNoProtoType *T = TL.getTypePtr();
04775   QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
04776   if (ResultType.isNull())
04777     return QualType();
04778 
04779   QualType Result = TL.getType();
04780   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
04781     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
04782 
04783   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
04784   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
04785   NewTL.setLParenLoc(TL.getLParenLoc());
04786   NewTL.setRParenLoc(TL.getRParenLoc());
04787   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
04788 
04789   return Result;
04790 }
04791 
04792 template<typename Derived> QualType
04793 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
04794                                                  UnresolvedUsingTypeLoc TL) {
04795   const UnresolvedUsingType *T = TL.getTypePtr();
04796   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
04797   if (!D)
04798     return QualType();
04799 
04800   QualType Result = TL.getType();
04801   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
04802     Result = getDerived().RebuildUnresolvedUsingType(D);
04803     if (Result.isNull())
04804       return QualType();
04805   }
04806 
04807   // We might get an arbitrary type spec type back.  We should at
04808   // least always get a type spec type, though.
04809   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
04810   NewTL.setNameLoc(TL.getNameLoc());
04811 
04812   return Result;
04813 }
04814 
04815 template<typename Derived>
04816 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
04817                                                       TypedefTypeLoc TL) {
04818   const TypedefType *T = TL.getTypePtr();
04819   TypedefNameDecl *Typedef
04820     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
04821                                                                T->getDecl()));
04822   if (!Typedef)
04823     return QualType();
04824 
04825   QualType Result = TL.getType();
04826   if (getDerived().AlwaysRebuild() ||
04827       Typedef != T->getDecl()) {
04828     Result = getDerived().RebuildTypedefType(Typedef);
04829     if (Result.isNull())
04830       return QualType();
04831   }
04832 
04833   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
04834   NewTL.setNameLoc(TL.getNameLoc());
04835 
04836   return Result;
04837 }
04838 
04839 template<typename Derived>
04840 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
04841                                                       TypeOfExprTypeLoc TL) {
04842   // typeof expressions are not potentially evaluated contexts
04843   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
04844                                                Sema::ReuseLambdaContextDecl);
04845 
04846   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
04847   if (E.isInvalid())
04848     return QualType();
04849 
04850   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
04851   if (E.isInvalid())
04852     return QualType();
04853 
04854   QualType Result = TL.getType();
04855   if (getDerived().AlwaysRebuild() ||
04856       E.get() != TL.getUnderlyingExpr()) {
04857     Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
04858     if (Result.isNull())
04859       return QualType();
04860   }
04861   else E.get();
04862 
04863   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
04864   NewTL.setTypeofLoc(TL.getTypeofLoc());
04865   NewTL.setLParenLoc(TL.getLParenLoc());
04866   NewTL.setRParenLoc(TL.getRParenLoc());
04867 
04868   return Result;
04869 }
04870 
04871 template<typename Derived>
04872 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
04873                                                      TypeOfTypeLoc TL) {
04874   TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
04875   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
04876   if (!New_Under_TI)
04877     return QualType();
04878 
04879   QualType Result = TL.getType();
04880   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
04881     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
04882     if (Result.isNull())
04883       return QualType();
04884   }
04885 
04886   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
04887   NewTL.setTypeofLoc(TL.getTypeofLoc());
04888   NewTL.setLParenLoc(TL.getLParenLoc());
04889   NewTL.setRParenLoc(TL.getRParenLoc());
04890   NewTL.setUnderlyingTInfo(New_Under_TI);
04891 
04892   return Result;
04893 }
04894 
04895 template<typename Derived>
04896 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
04897                                                        DecltypeTypeLoc TL) {
04898   const DecltypeType *T = TL.getTypePtr();
04899 
04900   // decltype expressions are not potentially evaluated contexts
04901   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
04902                                                nullptr, /*IsDecltype=*/ true);
04903 
04904   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
04905   if (E.isInvalid())
04906     return QualType();
04907 
04908   E = getSema().ActOnDecltypeExpression(E.get());
04909   if (E.isInvalid())
04910     return QualType();
04911 
04912   QualType Result = TL.getType();
04913   if (getDerived().AlwaysRebuild() ||
04914       E.get() != T->getUnderlyingExpr()) {
04915     Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
04916     if (Result.isNull())
04917       return QualType();
04918   }
04919   else E.get();
04920 
04921   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
04922   NewTL.setNameLoc(TL.getNameLoc());
04923 
04924   return Result;
04925 }
04926 
04927 template<typename Derived>
04928 QualType TreeTransform<Derived>::TransformUnaryTransformType(
04929                                                             TypeLocBuilder &TLB,
04930                                                      UnaryTransformTypeLoc TL) {
04931   QualType Result = TL.getType();
04932   if (Result->isDependentType()) {
04933     const UnaryTransformType *T = TL.getTypePtr();
04934     QualType NewBase =
04935       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
04936     Result = getDerived().RebuildUnaryTransformType(NewBase,
04937                                                     T->getUTTKind(),
04938                                                     TL.getKWLoc());
04939     if (Result.isNull())
04940       return QualType();
04941   }
04942 
04943   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
04944   NewTL.setKWLoc(TL.getKWLoc());
04945   NewTL.setParensRange(TL.getParensRange());
04946   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
04947   return Result;
04948 }
04949 
04950 template<typename Derived>
04951 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
04952                                                    AutoTypeLoc TL) {
04953   const AutoType *T = TL.getTypePtr();
04954   QualType OldDeduced = T->getDeducedType();
04955   QualType NewDeduced;
04956   if (!OldDeduced.isNull()) {
04957     NewDeduced = getDerived().TransformType(OldDeduced);
04958     if (NewDeduced.isNull())
04959       return QualType();
04960   }
04961 
04962   QualType Result = TL.getType();
04963   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
04964       T->isDependentType()) {
04965     Result = getDerived().RebuildAutoType(NewDeduced, T->isDecltypeAuto());
04966     if (Result.isNull())
04967       return QualType();
04968   }
04969 
04970   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
04971   NewTL.setNameLoc(TL.getNameLoc());
04972 
04973   return Result;
04974 }
04975 
04976 template<typename Derived>
04977 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
04978                                                      RecordTypeLoc TL) {
04979   const RecordType *T = TL.getTypePtr();
04980   RecordDecl *Record
04981     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
04982                                                           T->getDecl()));
04983   if (!Record)
04984     return QualType();
04985 
04986   QualType Result = TL.getType();
04987   if (getDerived().AlwaysRebuild() ||
04988       Record != T->getDecl()) {
04989     Result = getDerived().RebuildRecordType(Record);
04990     if (Result.isNull())
04991       return QualType();
04992   }
04993 
04994   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
04995   NewTL.setNameLoc(TL.getNameLoc());
04996 
04997   return Result;
04998 }
04999 
05000 template<typename Derived>
05001 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
05002                                                    EnumTypeLoc TL) {
05003   const EnumType *T = TL.getTypePtr();
05004   EnumDecl *Enum
05005     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
05006                                                         T->getDecl()));
05007   if (!Enum)
05008     return QualType();
05009 
05010   QualType Result = TL.getType();
05011   if (getDerived().AlwaysRebuild() ||
05012       Enum != T->getDecl()) {
05013     Result = getDerived().RebuildEnumType(Enum);
05014     if (Result.isNull())
05015       return QualType();
05016   }
05017 
05018   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
05019   NewTL.setNameLoc(TL.getNameLoc());
05020 
05021   return Result;
05022 }
05023 
05024 template<typename Derived>
05025 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
05026                                          TypeLocBuilder &TLB,
05027                                          InjectedClassNameTypeLoc TL) {
05028   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
05029                                        TL.getTypePtr()->getDecl());
05030   if (!D) return QualType();
05031 
05032   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
05033   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
05034   return T;
05035 }
05036 
05037 template<typename Derived>
05038 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
05039                                                 TypeLocBuilder &TLB,
05040                                                 TemplateTypeParmTypeLoc TL) {
05041   return TransformTypeSpecType(TLB, TL);
05042 }
05043 
05044 template<typename Derived>
05045 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
05046                                          TypeLocBuilder &TLB,
05047                                          SubstTemplateTypeParmTypeLoc TL) {
05048   const SubstTemplateTypeParmType *T = TL.getTypePtr();
05049 
05050   // Substitute into the replacement type, which itself might involve something
05051   // that needs to be transformed. This only tends to occur with default
05052   // template arguments of template template parameters.
05053   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
05054   QualType Replacement = getDerived().TransformType(T->getReplacementType());
05055   if (Replacement.isNull())
05056     return QualType();
05057 
05058   // Always canonicalize the replacement type.
05059   Replacement = SemaRef.Context.getCanonicalType(Replacement);
05060   QualType Result
05061     = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
05062                                                    Replacement);
05063 
05064   // Propagate type-source information.
05065   SubstTemplateTypeParmTypeLoc NewTL
05066     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
05067   NewTL.setNameLoc(TL.getNameLoc());
05068   return Result;
05069 
05070 }
05071 
05072 template<typename Derived>
05073 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
05074                                           TypeLocBuilder &TLB,
05075                                           SubstTemplateTypeParmPackTypeLoc TL) {
05076   return TransformTypeSpecType(TLB, TL);
05077 }
05078 
05079 template<typename Derived>
05080 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
05081                                                         TypeLocBuilder &TLB,
05082                                            TemplateSpecializationTypeLoc TL) {
05083   const TemplateSpecializationType *T = TL.getTypePtr();
05084 
05085   // The nested-name-specifier never matters in a TemplateSpecializationType,
05086   // because we can't have a dependent nested-name-specifier anyway.
05087   CXXScopeSpec SS;
05088   TemplateName Template
05089     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
05090                                          TL.getTemplateNameLoc());
05091   if (Template.isNull())
05092     return QualType();
05093 
05094   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
05095 }
05096 
05097 template<typename Derived>
05098 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
05099                                                      AtomicTypeLoc TL) {
05100   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
05101   if (ValueType.isNull())
05102     return QualType();
05103 
05104   QualType Result = TL.getType();
05105   if (getDerived().AlwaysRebuild() ||
05106       ValueType != TL.getValueLoc().getType()) {
05107     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
05108     if (Result.isNull())
05109       return QualType();
05110   }
05111 
05112   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
05113   NewTL.setKWLoc(TL.getKWLoc());
05114   NewTL.setLParenLoc(TL.getLParenLoc());
05115   NewTL.setRParenLoc(TL.getRParenLoc());
05116 
05117   return Result;
05118 }
05119 
05120   /// \brief Simple iterator that traverses the template arguments in a
05121   /// container that provides a \c getArgLoc() member function.
05122   ///
05123   /// This iterator is intended to be used with the iterator form of
05124   /// \c TreeTransform<Derived>::TransformTemplateArguments().
05125   template<typename ArgLocContainer>
05126   class TemplateArgumentLocContainerIterator {
05127     ArgLocContainer *Container;
05128     unsigned Index;
05129 
05130   public:
05131     typedef TemplateArgumentLoc value_type;
05132     typedef TemplateArgumentLoc reference;
05133     typedef int difference_type;
05134     typedef std::input_iterator_tag iterator_category;
05135 
05136     class pointer {
05137       TemplateArgumentLoc Arg;
05138 
05139     public:
05140       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
05141 
05142       const TemplateArgumentLoc *operator->() const {
05143         return &Arg;
05144       }
05145     };
05146 
05147 
05148     TemplateArgumentLocContainerIterator() {}
05149 
05150     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
05151                                  unsigned Index)
05152       : Container(&Container), Index(Index) { }
05153 
05154     TemplateArgumentLocContainerIterator &operator++() {
05155       ++Index;
05156       return *this;
05157     }
05158 
05159     TemplateArgumentLocContainerIterator operator++(int) {
05160       TemplateArgumentLocContainerIterator Old(*this);
05161       ++(*this);
05162       return Old;
05163     }
05164 
05165     TemplateArgumentLoc operator*() const {
05166       return Container->getArgLoc(Index);
05167     }
05168 
05169     pointer operator->() const {
05170       return pointer(Container->getArgLoc(Index));
05171     }
05172 
05173     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
05174                            const TemplateArgumentLocContainerIterator &Y) {
05175       return X.Container == Y.Container && X.Index == Y.Index;
05176     }
05177 
05178     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
05179                            const TemplateArgumentLocContainerIterator &Y) {
05180       return !(X == Y);
05181     }
05182   };
05183 
05184 
05185 template <typename Derived>
05186 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
05187                                                         TypeLocBuilder &TLB,
05188                                            TemplateSpecializationTypeLoc TL,
05189                                                       TemplateName Template) {
05190   TemplateArgumentListInfo NewTemplateArgs;
05191   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
05192   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
05193   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
05194     ArgIterator;
05195   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
05196                                               ArgIterator(TL, TL.getNumArgs()),
05197                                               NewTemplateArgs))
05198     return QualType();
05199 
05200   // FIXME: maybe don't rebuild if all the template arguments are the same.
05201 
05202   QualType Result =
05203     getDerived().RebuildTemplateSpecializationType(Template,
05204                                                    TL.getTemplateNameLoc(),
05205                                                    NewTemplateArgs);
05206 
05207   if (!Result.isNull()) {
05208     // Specializations of template template parameters are represented as
05209     // TemplateSpecializationTypes, and substitution of type alias templates
05210     // within a dependent context can transform them into
05211     // DependentTemplateSpecializationTypes.
05212     if (isa<DependentTemplateSpecializationType>(Result)) {
05213       DependentTemplateSpecializationTypeLoc NewTL
05214         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
05215       NewTL.setElaboratedKeywordLoc(SourceLocation());
05216       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
05217       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
05218       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
05219       NewTL.setLAngleLoc(TL.getLAngleLoc());
05220       NewTL.setRAngleLoc(TL.getRAngleLoc());
05221       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
05222         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
05223       return Result;
05224     }
05225 
05226     TemplateSpecializationTypeLoc NewTL
05227       = TLB.push<TemplateSpecializationTypeLoc>(Result);
05228     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
05229     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
05230     NewTL.setLAngleLoc(TL.getLAngleLoc());
05231     NewTL.setRAngleLoc(TL.getRAngleLoc());
05232     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
05233       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
05234   }
05235 
05236   return Result;
05237 }
05238 
05239 template <typename Derived>
05240 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
05241                                      TypeLocBuilder &TLB,
05242                                      DependentTemplateSpecializationTypeLoc TL,
05243                                      TemplateName Template,
05244                                      CXXScopeSpec &SS) {
05245   TemplateArgumentListInfo NewTemplateArgs;
05246   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
05247   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
05248   typedef TemplateArgumentLocContainerIterator<
05249             DependentTemplateSpecializationTypeLoc> ArgIterator;
05250   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
05251                                               ArgIterator(TL, TL.getNumArgs()),
05252                                               NewTemplateArgs))
05253     return QualType();
05254 
05255   // FIXME: maybe don't rebuild if all the template arguments are the same.
05256 
05257   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
05258     QualType Result
05259       = getSema().Context.getDependentTemplateSpecializationType(
05260                                                 TL.getTypePtr()->getKeyword(),
05261                                                          DTN->getQualifier(),
05262                                                          DTN->getIdentifier(),
05263                                                                NewTemplateArgs);
05264 
05265     DependentTemplateSpecializationTypeLoc NewTL
05266       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
05267     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
05268     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
05269     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
05270     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
05271     NewTL.setLAngleLoc(TL.getLAngleLoc());
05272     NewTL.setRAngleLoc(TL.getRAngleLoc());
05273     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
05274       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
05275     return Result;
05276   }
05277 
05278   QualType Result
05279     = getDerived().RebuildTemplateSpecializationType(Template,
05280                                                      TL.getTemplateNameLoc(),
05281                                                      NewTemplateArgs);
05282 
05283   if (!Result.isNull()) {
05284     /// FIXME: Wrap this in an elaborated-type-specifier?
05285     TemplateSpecializationTypeLoc NewTL
05286       = TLB.push<TemplateSpecializationTypeLoc>(Result);
05287     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
05288     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
05289     NewTL.setLAngleLoc(TL.getLAngleLoc());
05290     NewTL.setRAngleLoc(TL.getRAngleLoc());
05291     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
05292       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
05293   }
05294 
05295   return Result;
05296 }
05297 
05298 template<typename Derived>
05299 QualType
05300 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
05301                                                 ElaboratedTypeLoc TL) {
05302   const ElaboratedType *T = TL.getTypePtr();
05303 
05304   NestedNameSpecifierLoc QualifierLoc;
05305   // NOTE: the qualifier in an ElaboratedType is optional.
05306   if (TL.getQualifierLoc()) {
05307     QualifierLoc
05308       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
05309     if (!QualifierLoc)
05310       return QualType();
05311   }
05312 
05313   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
05314   if (NamedT.isNull())
05315     return QualType();
05316 
05317   // C++0x [dcl.type.elab]p2:
05318   //   If the identifier resolves to a typedef-name or the simple-template-id
05319   //   resolves to an alias template specialization, the
05320   //   elaborated-type-specifier is ill-formed.
05321   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
05322     if (const TemplateSpecializationType *TST =
05323           NamedT->getAs<TemplateSpecializationType>()) {
05324       TemplateName Template = TST->getTemplateName();
05325       if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
05326               Template.getAsTemplateDecl())) {
05327         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
05328                      diag::err_tag_reference_non_tag) << 4;
05329         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
05330       }
05331     }
05332   }
05333 
05334   QualType Result = TL.getType();
05335   if (getDerived().AlwaysRebuild() ||
05336       QualifierLoc != TL.getQualifierLoc() ||
05337       NamedT != T->getNamedType()) {
05338     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
05339                                                 T->getKeyword(),
05340                                                 QualifierLoc, NamedT);
05341     if (Result.isNull())
05342       return QualType();
05343   }
05344 
05345   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
05346   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
05347   NewTL.setQualifierLoc(QualifierLoc);
05348   return Result;
05349 }
05350 
05351 template<typename Derived>
05352 QualType TreeTransform<Derived>::TransformAttributedType(
05353                                                 TypeLocBuilder &TLB,
05354                                                 AttributedTypeLoc TL) {
05355   const AttributedType *oldType = TL.getTypePtr();
05356   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
05357   if (modifiedType.isNull())
05358     return QualType();
05359 
05360   QualType result = TL.getType();
05361 
05362   // FIXME: dependent operand expressions?
05363   if (getDerived().AlwaysRebuild() ||
05364       modifiedType != oldType->getModifiedType()) {
05365     // TODO: this is really lame; we should really be rebuilding the
05366     // equivalent type from first principles.
05367     QualType equivalentType
05368       = getDerived().TransformType(oldType->getEquivalentType());
05369     if (equivalentType.isNull())
05370       return QualType();
05371     result = SemaRef.Context.getAttributedType(oldType->getAttrKind(),
05372                                                modifiedType,
05373                                                equivalentType);
05374   }
05375 
05376   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
05377   newTL.setAttrNameLoc(TL.getAttrNameLoc());
05378   if (TL.hasAttrOperand())
05379     newTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
05380   if (TL.hasAttrExprOperand())
05381     newTL.setAttrExprOperand(TL.getAttrExprOperand());
05382   else if (TL.hasAttrEnumOperand())
05383     newTL.setAttrEnumOperandLoc(TL.getAttrEnumOperandLoc());
05384 
05385   return result;
05386 }
05387 
05388 template<typename Derived>
05389 QualType
05390 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
05391                                            ParenTypeLoc TL) {
05392   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
05393   if (Inner.isNull())
05394     return QualType();
05395 
05396   QualType Result = TL.getType();
05397   if (getDerived().AlwaysRebuild() ||
05398       Inner != TL.getInnerLoc().getType()) {
05399     Result = getDerived().RebuildParenType(Inner);
05400     if (Result.isNull())
05401       return QualType();
05402   }
05403 
05404   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
05405   NewTL.setLParenLoc(TL.getLParenLoc());
05406   NewTL.setRParenLoc(TL.getRParenLoc());
05407   return Result;
05408 }
05409 
05410 template<typename Derived>
05411 QualType TreeTransform<Derived>::TransformDependentNameType(TypeLocBuilder &TLB,
05412                                                       DependentNameTypeLoc TL) {
05413   const DependentNameType *T = TL.getTypePtr();
05414 
05415   NestedNameSpecifierLoc QualifierLoc
05416     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
05417   if (!QualifierLoc)
05418     return QualType();
05419 
05420   QualType Result
05421     = getDerived().RebuildDependentNameType(T->getKeyword(),
05422                                             TL.getElaboratedKeywordLoc(),
05423                                             QualifierLoc,
05424                                             T->getIdentifier(),
05425                                             TL.getNameLoc());
05426   if (Result.isNull())
05427     return QualType();
05428 
05429   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
05430     QualType NamedT = ElabT->getNamedType();
05431     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
05432 
05433     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
05434     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
05435     NewTL.setQualifierLoc(QualifierLoc);
05436   } else {
05437     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
05438     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
05439     NewTL.setQualifierLoc(QualifierLoc);
05440     NewTL.setNameLoc(TL.getNameLoc());
05441   }
05442   return Result;
05443 }
05444 
05445 template<typename Derived>
05446 QualType TreeTransform<Derived>::
05447           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
05448                                  DependentTemplateSpecializationTypeLoc TL) {
05449   NestedNameSpecifierLoc QualifierLoc;
05450   if (TL.getQualifierLoc()) {
05451     QualifierLoc
05452       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
05453     if (!QualifierLoc)
05454       return QualType();
05455   }
05456 
05457   return getDerived()
05458            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
05459 }
05460 
05461 template<typename Derived>
05462 QualType TreeTransform<Derived>::
05463 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
05464                                    DependentTemplateSpecializationTypeLoc TL,
05465                                        NestedNameSpecifierLoc QualifierLoc) {
05466   const DependentTemplateSpecializationType *T = TL.getTypePtr();
05467 
05468   TemplateArgumentListInfo NewTemplateArgs;
05469   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
05470   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
05471 
05472   typedef TemplateArgumentLocContainerIterator<
05473   DependentTemplateSpecializationTypeLoc> ArgIterator;
05474   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
05475                                               ArgIterator(TL, TL.getNumArgs()),
05476                                               NewTemplateArgs))
05477     return QualType();
05478 
05479   QualType Result
05480     = getDerived().RebuildDependentTemplateSpecializationType(T->getKeyword(),
05481                                                               QualifierLoc,
05482                                                             T->getIdentifier(),
05483                                                        TL.getTemplateNameLoc(),
05484                                                             NewTemplateArgs);
05485   if (Result.isNull())
05486     return QualType();
05487 
05488   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
05489     QualType NamedT = ElabT->getNamedType();
05490 
05491     // Copy information relevant to the template specialization.
05492     TemplateSpecializationTypeLoc NamedTL
05493       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
05494     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
05495     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
05496     NamedTL.setLAngleLoc(TL.getLAngleLoc());
05497     NamedTL.setRAngleLoc(TL.getRAngleLoc());
05498     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
05499       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
05500 
05501     // Copy information relevant to the elaborated type.
05502     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
05503     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
05504     NewTL.setQualifierLoc(QualifierLoc);
05505   } else if (isa<DependentTemplateSpecializationType>(Result)) {
05506     DependentTemplateSpecializationTypeLoc SpecTL
05507       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
05508     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
05509     SpecTL.setQualifierLoc(QualifierLoc);
05510     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
05511     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
05512     SpecTL.setLAngleLoc(TL.getLAngleLoc());
05513     SpecTL.setRAngleLoc(TL.getRAngleLoc());
05514     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
05515       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
05516   } else {
05517     TemplateSpecializationTypeLoc SpecTL
05518       = TLB.push<TemplateSpecializationTypeLoc>(Result);
05519     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
05520     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
05521     SpecTL.setLAngleLoc(TL.getLAngleLoc());
05522     SpecTL.setRAngleLoc(TL.getRAngleLoc());
05523     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
05524       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
05525   }
05526   return Result;
05527 }
05528 
05529 template<typename Derived>
05530 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
05531                                                       PackExpansionTypeLoc TL) {
05532   QualType Pattern
05533     = getDerived().TransformType(TLB, TL.getPatternLoc());
05534   if (Pattern.isNull())
05535     return QualType();
05536 
05537   QualType Result = TL.getType();
05538   if (getDerived().AlwaysRebuild() ||
05539       Pattern != TL.getPatternLoc().getType()) {
05540     Result = getDerived().RebuildPackExpansionType(Pattern,
05541                                            TL.getPatternLoc().getSourceRange(),
05542                                                    TL.getEllipsisLoc(),
05543                                            TL.getTypePtr()->getNumExpansions());
05544     if (Result.isNull())
05545       return QualType();
05546   }
05547 
05548   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
05549   NewT.setEllipsisLoc(TL.getEllipsisLoc());
05550   return Result;
05551 }
05552 
05553 template<typename Derived>
05554 QualType
05555 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
05556                                                    ObjCInterfaceTypeLoc TL) {
05557   // ObjCInterfaceType is never dependent.
05558   TLB.pushFullCopy(TL);
05559   return TL.getType();
05560 }
05561 
05562 template<typename Derived>
05563 QualType
05564 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
05565                                                 ObjCObjectTypeLoc TL) {
05566   // ObjCObjectType is never dependent.
05567   TLB.pushFullCopy(TL);
05568   return TL.getType();
05569 }
05570 
05571 template<typename Derived>
05572 QualType
05573 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
05574                                                ObjCObjectPointerTypeLoc TL) {
05575   // ObjCObjectPointerType is never dependent.
05576   TLB.pushFullCopy(TL);
05577   return TL.getType();
05578 }
05579 
05580 //===----------------------------------------------------------------------===//
05581 // Statement transformation
05582 //===----------------------------------------------------------------------===//
05583 template<typename Derived>
05584 StmtResult
05585 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
05586   return S;
05587 }
05588 
05589 template<typename Derived>
05590 StmtResult
05591 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
05592   return getDerived().TransformCompoundStmt(S, false);
05593 }
05594 
05595 template<typename Derived>
05596 StmtResult
05597 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
05598                                               bool IsStmtExpr) {
05599   Sema::CompoundScopeRAII CompoundScope(getSema());
05600 
05601   bool SubStmtInvalid = false;
05602   bool SubStmtChanged = false;
05603   SmallVector<Stmt*, 8> Statements;
05604   for (auto *B : S->body()) {
05605     StmtResult Result = getDerived().TransformStmt(B);
05606     if (Result.isInvalid()) {
05607       // Immediately fail if this was a DeclStmt, since it's very
05608       // likely that this will cause problems for future statements.
05609       if (isa<DeclStmt>(B))
05610         return StmtError();
05611 
05612       // Otherwise, just keep processing substatements and fail later.
05613       SubStmtInvalid = true;
05614       continue;
05615     }
05616 
05617     SubStmtChanged = SubStmtChanged || Result.get() != B;
05618     Statements.push_back(Result.getAs<Stmt>());
05619   }
05620 
05621   if (SubStmtInvalid)
05622     return StmtError();
05623 
05624   if (!getDerived().AlwaysRebuild() &&
05625       !SubStmtChanged)
05626     return S;
05627 
05628   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
05629                                           Statements,
05630                                           S->getRBracLoc(),
05631                                           IsStmtExpr);
05632 }
05633 
05634 template<typename Derived>
05635 StmtResult
05636 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
05637   ExprResult LHS, RHS;
05638   {
05639     EnterExpressionEvaluationContext Unevaluated(SemaRef,
05640                                                  Sema::ConstantEvaluated);
05641 
05642     // Transform the left-hand case value.
05643     LHS = getDerived().TransformExpr(S->getLHS());
05644     LHS = SemaRef.ActOnConstantExpression(LHS);
05645     if (LHS.isInvalid())
05646       return StmtError();
05647 
05648     // Transform the right-hand case value (for the GNU case-range extension).
05649     RHS = getDerived().TransformExpr(S->getRHS());
05650     RHS = SemaRef.ActOnConstantExpression(RHS);
05651     if (RHS.isInvalid())
05652       return StmtError();
05653   }
05654 
05655   // Build the case statement.
05656   // Case statements are always rebuilt so that they will attached to their
05657   // transformed switch statement.
05658   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
05659                                                        LHS.get(),
05660                                                        S->getEllipsisLoc(),
05661                                                        RHS.get(),
05662                                                        S->getColonLoc());
05663   if (Case.isInvalid())
05664     return StmtError();
05665 
05666   // Transform the statement following the case
05667   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
05668   if (SubStmt.isInvalid())
05669     return StmtError();
05670 
05671   // Attach the body to the case statement
05672   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
05673 }
05674 
05675 template<typename Derived>
05676 StmtResult
05677 TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
05678   // Transform the statement following the default case
05679   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
05680   if (SubStmt.isInvalid())
05681     return StmtError();
05682 
05683   // Default statements are always rebuilt
05684   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
05685                                          SubStmt.get());
05686 }
05687 
05688 template<typename Derived>
05689 StmtResult
05690 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S) {
05691   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
05692   if (SubStmt.isInvalid())
05693     return StmtError();
05694 
05695   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
05696                                         S->getDecl());
05697   if (!LD)
05698     return StmtError();
05699 
05700 
05701   // FIXME: Pass the real colon location in.
05702   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
05703                                        cast<LabelDecl>(LD), SourceLocation(),
05704                                        SubStmt.get());
05705 }
05706 
05707 template <typename Derived>
05708 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
05709   if (!R)
05710     return R;
05711 
05712   switch (R->getKind()) {
05713 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
05714 #define ATTR(X)
05715 #define PRAGMA_SPELLING_ATTR(X)                                                \
05716   case attr::X:                                                                \
05717     return getDerived().Transform##X##Attr(cast<X##Attr>(R));
05718 #include "clang/Basic/AttrList.inc"
05719   default:
05720     return R;
05721   }
05722 }
05723 
05724 template <typename Derived>
05725 StmtResult TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S) {
05726   bool AttrsChanged = false;
05727   SmallVector<const Attr *, 1> Attrs;
05728 
05729   // Visit attributes and keep track if any are transformed.
05730   for (const auto *I : S->getAttrs()) {
05731     const Attr *R = getDerived().TransformAttr(I);
05732     AttrsChanged |= (I != R);
05733     Attrs.push_back(R);
05734   }
05735 
05736   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
05737   if (SubStmt.isInvalid())
05738     return StmtError();
05739 
05740   if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
05741     return S;
05742 
05743   return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
05744                                             SubStmt.get());
05745 }
05746 
05747 template<typename Derived>
05748 StmtResult
05749 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
05750   // Transform the condition
05751   ExprResult Cond;
05752   VarDecl *ConditionVar = nullptr;
05753   if (S->getConditionVariable()) {
05754     ConditionVar
05755       = cast_or_null<VarDecl>(
05756                    getDerived().TransformDefinition(
05757                                       S->getConditionVariable()->getLocation(),
05758                                                     S->getConditionVariable()));
05759     if (!ConditionVar)
05760       return StmtError();
05761   } else {
05762     Cond = getDerived().TransformExpr(S->getCond());
05763 
05764     if (Cond.isInvalid())
05765       return StmtError();
05766 
05767     // Convert the condition to a boolean value.
05768     if (S->getCond()) {
05769       ExprResult CondE = getSema().ActOnBooleanCondition(nullptr, S->getIfLoc(),
05770                                                          Cond.get());
05771       if (CondE.isInvalid())
05772         return StmtError();
05773 
05774       Cond = CondE.get();
05775     }
05776   }
05777 
05778   Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
05779   if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
05780     return StmtError();
05781 
05782   // Transform the "then" branch.
05783   StmtResult Then = getDerived().TransformStmt(S->getThen());
05784   if (Then.isInvalid())
05785     return StmtError();
05786 
05787   // Transform the "else" branch.
05788   StmtResult Else = getDerived().TransformStmt(S->getElse());
05789   if (Else.isInvalid())
05790     return StmtError();
05791 
05792   if (!getDerived().AlwaysRebuild() &&
05793       FullCond.get() == S->getCond() &&
05794       ConditionVar == S->getConditionVariable() &&
05795       Then.get() == S->getThen() &&
05796       Else.get() == S->getElse())
05797     return S;
05798 
05799   return getDerived().RebuildIfStmt(S->getIfLoc(), FullCond, ConditionVar,
05800                                     Then.get(),
05801                                     S->getElseLoc(), Else.get());
05802 }
05803 
05804 template<typename Derived>
05805 StmtResult
05806 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
05807   // Transform the condition.
05808   ExprResult Cond;
05809   VarDecl *ConditionVar = nullptr;
05810   if (S->getConditionVariable()) {
05811     ConditionVar
05812       = cast_or_null<VarDecl>(
05813                    getDerived().TransformDefinition(
05814                                       S->getConditionVariable()->getLocation(),
05815                                                     S->getConditionVariable()));
05816     if (!ConditionVar)
05817       return StmtError();
05818   } else {
05819     Cond = getDerived().TransformExpr(S->getCond());
05820 
05821     if (Cond.isInvalid())
05822       return StmtError();
05823   }
05824 
05825   // Rebuild the switch statement.
05826   StmtResult Switch
05827     = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Cond.get(),
05828                                           ConditionVar);
05829   if (Switch.isInvalid())
05830     return StmtError();
05831 
05832   // Transform the body of the switch statement.
05833   StmtResult Body = getDerived().TransformStmt(S->getBody());
05834   if (Body.isInvalid())
05835     return StmtError();
05836 
05837   // Complete the switch statement.
05838   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
05839                                             Body.get());
05840 }
05841 
05842 template<typename Derived>
05843 StmtResult
05844 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
05845   // Transform the condition
05846   ExprResult Cond;
05847   VarDecl *ConditionVar = nullptr;
05848   if (S->getConditionVariable()) {
05849     ConditionVar
05850       = cast_or_null<VarDecl>(
05851                    getDerived().TransformDefinition(
05852                                       S->getConditionVariable()->getLocation(),
05853                                                     S->getConditionVariable()));
05854     if (!ConditionVar)
05855       return StmtError();
05856   } else {
05857     Cond = getDerived().TransformExpr(S->getCond());
05858 
05859     if (Cond.isInvalid())
05860       return StmtError();
05861 
05862     if (S->getCond()) {
05863       // Convert the condition to a boolean value.
05864       ExprResult CondE = getSema().ActOnBooleanCondition(nullptr,
05865                                                          S->getWhileLoc(),
05866                                                          Cond.get());
05867       if (CondE.isInvalid())
05868         return StmtError();
05869       Cond = CondE;
05870     }
05871   }
05872 
05873   Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
05874   if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
05875     return StmtError();
05876 
05877   // Transform the body
05878   StmtResult Body = getDerived().TransformStmt(S->getBody());
05879   if (Body.isInvalid())
05880     return StmtError();
05881 
05882   if (!getDerived().AlwaysRebuild() &&
05883       FullCond.get() == S->getCond() &&
05884       ConditionVar == S->getConditionVariable() &&
05885       Body.get() == S->getBody())
05886     return Owned(S);
05887 
05888   return getDerived().RebuildWhileStmt(S->getWhileLoc(), FullCond,
05889                                        ConditionVar, Body.get());
05890 }
05891 
05892 template<typename Derived>
05893 StmtResult
05894 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
05895   // Transform the body
05896   StmtResult Body = getDerived().TransformStmt(S->getBody());
05897   if (Body.isInvalid())
05898     return StmtError();
05899 
05900   // Transform the condition
05901   ExprResult Cond = getDerived().TransformExpr(S->getCond());
05902   if (Cond.isInvalid())
05903     return StmtError();
05904 
05905   if (!getDerived().AlwaysRebuild() &&
05906       Cond.get() == S->getCond() &&
05907       Body.get() == S->getBody())
05908     return S;
05909 
05910   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
05911                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
05912                                     S->getRParenLoc());
05913 }
05914 
05915 template<typename Derived>
05916 StmtResult
05917 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
05918   // Transform the initialization statement
05919   StmtResult Init = getDerived().TransformStmt(S->getInit());
05920   if (Init.isInvalid())
05921     return StmtError();
05922 
05923   // Transform the condition
05924   ExprResult Cond;
05925   VarDecl *ConditionVar = nullptr;
05926   if (S->getConditionVariable()) {
05927     ConditionVar
05928       = cast_or_null<VarDecl>(
05929                    getDerived().TransformDefinition(
05930                                       S->getConditionVariable()->getLocation(),
05931                                                     S->getConditionVariable()));
05932     if (!ConditionVar)
05933       return StmtError();
05934   } else {
05935     Cond = getDerived().TransformExpr(S->getCond());
05936 
05937     if (Cond.isInvalid())
05938       return StmtError();
05939 
05940     if (S->getCond()) {
05941       // Convert the condition to a boolean value.
05942       ExprResult CondE = getSema().ActOnBooleanCondition(nullptr,
05943                                                          S->getForLoc(),
05944                                                          Cond.get());
05945       if (CondE.isInvalid())
05946         return StmtError();
05947 
05948       Cond = CondE.get();
05949     }
05950   }
05951 
05952   Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
05953   if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
05954     return StmtError();
05955 
05956   // Transform the increment
05957   ExprResult Inc = getDerived().TransformExpr(S->getInc());
05958   if (Inc.isInvalid())
05959     return StmtError();
05960 
05961   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
05962   if (S->getInc() && !FullInc.get())
05963     return StmtError();
05964 
05965   // Transform the body
05966   StmtResult Body = getDerived().TransformStmt(S->getBody());
05967   if (Body.isInvalid())
05968     return StmtError();
05969 
05970   if (!getDerived().AlwaysRebuild() &&
05971       Init.get() == S->getInit() &&
05972       FullCond.get() == S->getCond() &&
05973       Inc.get() == S->getInc() &&
05974       Body.get() == S->getBody())
05975     return S;
05976 
05977   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
05978                                      Init.get(), FullCond, ConditionVar,
05979                                      FullInc, S->getRParenLoc(), Body.get());
05980 }
05981 
05982 template<typename Derived>
05983 StmtResult
05984 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
05985   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
05986                                         S->getLabel());
05987   if (!LD)
05988     return StmtError();
05989 
05990   // Goto statements must always be rebuilt, to resolve the label.
05991   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
05992                                       cast<LabelDecl>(LD));
05993 }
05994 
05995 template<typename Derived>
05996 StmtResult
05997 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
05998   ExprResult Target = getDerived().TransformExpr(S->getTarget());
05999   if (Target.isInvalid())
06000     return StmtError();
06001   Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
06002 
06003   if (!getDerived().AlwaysRebuild() &&
06004       Target.get() == S->getTarget())
06005     return S;
06006 
06007   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
06008                                               Target.get());
06009 }
06010 
06011 template<typename Derived>
06012 StmtResult
06013 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
06014   return S;
06015 }
06016 
06017 template<typename Derived>
06018 StmtResult
06019 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
06020   return S;
06021 }
06022 
06023 template<typename Derived>
06024 StmtResult
06025 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
06026   ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
06027                                                         /*NotCopyInit*/false);
06028   if (Result.isInvalid())
06029     return StmtError();
06030 
06031   // FIXME: We always rebuild the return statement because there is no way
06032   // to tell whether the return type of the function has changed.
06033   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
06034 }
06035 
06036 template<typename Derived>
06037 StmtResult
06038 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
06039   bool DeclChanged = false;
06040   SmallVector<Decl *, 4> Decls;
06041   for (auto *D : S->decls()) {
06042     Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
06043     if (!Transformed)
06044       return StmtError();
06045 
06046     if (Transformed != D)
06047       DeclChanged = true;
06048 
06049     Decls.push_back(Transformed);
06050   }
06051 
06052   if (!getDerived().AlwaysRebuild() && !DeclChanged)
06053     return S;
06054 
06055   return getDerived().RebuildDeclStmt(Decls, S->getStartLoc(), S->getEndLoc());
06056 }
06057 
06058 template<typename Derived>
06059 StmtResult
06060 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
06061 
06062   SmallVector<Expr*, 8> Constraints;
06063   SmallVector<Expr*, 8> Exprs;
06064   SmallVector<IdentifierInfo *, 4> Names;
06065 
06066   ExprResult AsmString;
06067   SmallVector<Expr*, 8> Clobbers;
06068 
06069   bool ExprsChanged = false;
06070 
06071   // Go through the outputs.
06072   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
06073     Names.push_back(S->getOutputIdentifier(I));
06074 
06075     // No need to transform the constraint literal.
06076     Constraints.push_back(S->getOutputConstraintLiteral(I));
06077 
06078     // Transform the output expr.
06079     Expr *OutputExpr = S->getOutputExpr(I);
06080     ExprResult Result = getDerived().TransformExpr(OutputExpr);
06081     if (Result.isInvalid())
06082       return StmtError();
06083 
06084     ExprsChanged |= Result.get() != OutputExpr;
06085 
06086     Exprs.push_back(Result.get());
06087   }
06088 
06089   // Go through the inputs.
06090   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
06091     Names.push_back(S->getInputIdentifier(I));
06092 
06093     // No need to transform the constraint literal.
06094     Constraints.push_back(S->getInputConstraintLiteral(I));
06095 
06096     // Transform the input expr.
06097     Expr *InputExpr = S->getInputExpr(I);
06098     ExprResult Result = getDerived().TransformExpr(InputExpr);
06099     if (Result.isInvalid())
06100       return StmtError();
06101 
06102     ExprsChanged |= Result.get() != InputExpr;
06103 
06104     Exprs.push_back(Result.get());
06105   }
06106 
06107   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
06108     return S;
06109 
06110   // Go through the clobbers.
06111   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
06112     Clobbers.push_back(S->getClobberStringLiteral(I));
06113 
06114   // No need to transform the asm string literal.
06115   AsmString = S->getAsmString();
06116   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
06117                                         S->isVolatile(), S->getNumOutputs(),
06118                                         S->getNumInputs(), Names.data(),
06119                                         Constraints, Exprs, AsmString.get(),
06120                                         Clobbers, S->getRParenLoc());
06121 }
06122 
06123 template<typename Derived>
06124 StmtResult
06125 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
06126   ArrayRef<Token> AsmToks =
06127     llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
06128 
06129   bool HadError = false, HadChange = false;
06130 
06131   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
06132   SmallVector<Expr*, 8> TransformedExprs;
06133   TransformedExprs.reserve(SrcExprs.size());
06134   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
06135     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
06136     if (!Result.isUsable()) {
06137       HadError = true;
06138     } else {
06139       HadChange |= (Result.get() != SrcExprs[i]);
06140       TransformedExprs.push_back(Result.get());
06141     }
06142   }
06143 
06144   if (HadError) return StmtError();
06145   if (!HadChange && !getDerived().AlwaysRebuild())
06146     return Owned(S);
06147 
06148   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
06149                                        AsmToks, S->getAsmString(),
06150                                        S->getNumOutputs(), S->getNumInputs(),
06151                                        S->getAllConstraints(), S->getClobbers(),
06152                                        TransformedExprs, S->getEndLoc());
06153 }
06154 
06155 template<typename Derived>
06156 StmtResult
06157 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
06158   // Transform the body of the @try.
06159   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
06160   if (TryBody.isInvalid())
06161     return StmtError();
06162 
06163   // Transform the @catch statements (if present).
06164   bool AnyCatchChanged = false;
06165   SmallVector<Stmt*, 8> CatchStmts;
06166   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
06167     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
06168     if (Catch.isInvalid())
06169       return StmtError();
06170     if (Catch.get() != S->getCatchStmt(I))
06171       AnyCatchChanged = true;
06172     CatchStmts.push_back(Catch.get());
06173   }
06174 
06175   // Transform the @finally statement (if present).
06176   StmtResult Finally;
06177   if (S->getFinallyStmt()) {
06178     Finally = getDerived().TransformStmt(S->getFinallyStmt());
06179     if (Finally.isInvalid())
06180       return StmtError();
06181   }
06182 
06183   // If nothing changed, just retain this statement.
06184   if (!getDerived().AlwaysRebuild() &&
06185       TryBody.get() == S->getTryBody() &&
06186       !AnyCatchChanged &&
06187       Finally.get() == S->getFinallyStmt())
06188     return S;
06189 
06190   // Build a new statement.
06191   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
06192                                            CatchStmts, Finally.get());
06193 }
06194 
06195 template<typename Derived>
06196 StmtResult
06197 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
06198   // Transform the @catch parameter, if there is one.
06199   VarDecl *Var = nullptr;
06200   if (VarDecl *FromVar = S->getCatchParamDecl()) {
06201     TypeSourceInfo *TSInfo = nullptr;
06202     if (FromVar->getTypeSourceInfo()) {
06203       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
06204       if (!TSInfo)
06205         return StmtError();
06206     }
06207 
06208     QualType T;
06209     if (TSInfo)
06210       T = TSInfo->getType();
06211     else {
06212       T = getDerived().TransformType(FromVar->getType());
06213       if (T.isNull())
06214         return StmtError();
06215     }
06216 
06217     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
06218     if (!Var)
06219       return StmtError();
06220   }
06221 
06222   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
06223   if (Body.isInvalid())
06224     return StmtError();
06225 
06226   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
06227                                              S->getRParenLoc(),
06228                                              Var, Body.get());
06229 }
06230 
06231 template<typename Derived>
06232 StmtResult
06233 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
06234   // Transform the body.
06235   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
06236   if (Body.isInvalid())
06237     return StmtError();
06238 
06239   // If nothing changed, just retain this statement.
06240   if (!getDerived().AlwaysRebuild() &&
06241       Body.get() == S->getFinallyBody())
06242     return S;
06243 
06244   // Build a new statement.
06245   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
06246                                                Body.get());
06247 }
06248 
06249 template<typename Derived>
06250 StmtResult
06251 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
06252   ExprResult Operand;
06253   if (S->getThrowExpr()) {
06254     Operand = getDerived().TransformExpr(S->getThrowExpr());
06255     if (Operand.isInvalid())
06256       return StmtError();
06257   }
06258 
06259   if (!getDerived().AlwaysRebuild() &&
06260       Operand.get() == S->getThrowExpr())
06261     return S;
06262 
06263   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
06264 }
06265 
06266 template<typename Derived>
06267 StmtResult
06268 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
06269                                                   ObjCAtSynchronizedStmt *S) {
06270   // Transform the object we are locking.
06271   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
06272   if (Object.isInvalid())
06273     return StmtError();
06274   Object =
06275     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
06276                                                   Object.get());
06277   if (Object.isInvalid())
06278     return StmtError();
06279 
06280   // Transform the body.
06281   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
06282   if (Body.isInvalid())
06283     return StmtError();
06284 
06285   // If nothing change, just retain the current statement.
06286   if (!getDerived().AlwaysRebuild() &&
06287       Object.get() == S->getSynchExpr() &&
06288       Body.get() == S->getSynchBody())
06289     return S;
06290 
06291   // Build a new statement.
06292   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
06293                                                     Object.get(), Body.get());
06294 }
06295 
06296 template<typename Derived>
06297 StmtResult
06298 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
06299                                               ObjCAutoreleasePoolStmt *S) {
06300   // Transform the body.
06301   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
06302   if (Body.isInvalid())
06303     return StmtError();
06304 
06305   // If nothing changed, just retain this statement.
06306   if (!getDerived().AlwaysRebuild() &&
06307       Body.get() == S->getSubStmt())
06308     return S;
06309 
06310   // Build a new statement.
06311   return getDerived().RebuildObjCAutoreleasePoolStmt(
06312                         S->getAtLoc(), Body.get());
06313 }
06314 
06315 template<typename Derived>
06316 StmtResult
06317 TreeTransform<Derived>::TransformObjCForCollectionStmt(
06318                                                   ObjCForCollectionStmt *S) {
06319   // Transform the element statement.
06320   StmtResult Element = getDerived().TransformStmt(S->getElement());
06321   if (Element.isInvalid())
06322     return StmtError();
06323 
06324   // Transform the collection expression.
06325   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
06326   if (Collection.isInvalid())
06327     return StmtError();
06328 
06329   // Transform the body.
06330   StmtResult Body = getDerived().TransformStmt(S->getBody());
06331   if (Body.isInvalid())
06332     return StmtError();
06333 
06334   // If nothing changed, just retain this statement.
06335   if (!getDerived().AlwaysRebuild() &&
06336       Element.get() == S->getElement() &&
06337       Collection.get() == S->getCollection() &&
06338       Body.get() == S->getBody())
06339     return S;
06340 
06341   // Build a new statement.
06342   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
06343                                                    Element.get(),
06344                                                    Collection.get(),
06345                                                    S->getRParenLoc(),
06346                                                    Body.get());
06347 }
06348 
06349 template <typename Derived>
06350 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
06351   // Transform the exception declaration, if any.
06352   VarDecl *Var = nullptr;
06353   if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
06354     TypeSourceInfo *T =
06355         getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
06356     if (!T)
06357       return StmtError();
06358 
06359     Var = getDerived().RebuildExceptionDecl(
06360         ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
06361         ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
06362     if (!Var || Var->isInvalidDecl())
06363       return StmtError();
06364   }
06365 
06366   // Transform the actual exception handler.
06367   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
06368   if (Handler.isInvalid())
06369     return StmtError();
06370 
06371   if (!getDerived().AlwaysRebuild() && !Var &&
06372       Handler.get() == S->getHandlerBlock())
06373     return S;
06374 
06375   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
06376 }
06377 
06378 template <typename Derived>
06379 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
06380   // Transform the try block itself.
06381   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
06382   if (TryBlock.isInvalid())
06383     return StmtError();
06384 
06385   // Transform the handlers.
06386   bool HandlerChanged = false;
06387   SmallVector<Stmt *, 8> Handlers;
06388   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
06389     StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
06390     if (Handler.isInvalid())
06391       return StmtError();
06392 
06393     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
06394     Handlers.push_back(Handler.getAs<Stmt>());
06395   }
06396 
06397   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
06398       !HandlerChanged)
06399     return S;
06400 
06401   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
06402                                         Handlers);
06403 }
06404 
06405 template<typename Derived>
06406 StmtResult
06407 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
06408   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
06409   if (Range.isInvalid())
06410     return StmtError();
06411 
06412   StmtResult BeginEnd = getDerived().TransformStmt(S->getBeginEndStmt());
06413   if (BeginEnd.isInvalid())
06414     return StmtError();
06415 
06416   ExprResult Cond = getDerived().TransformExpr(S->getCond());
06417   if (Cond.isInvalid())
06418     return StmtError();
06419   if (Cond.get())
06420     Cond = SemaRef.CheckBooleanCondition(Cond.get(), S->getColonLoc());
06421   if (Cond.isInvalid())
06422     return StmtError();
06423   if (Cond.get())
06424     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
06425 
06426   ExprResult Inc = getDerived().TransformExpr(S->getInc());
06427   if (Inc.isInvalid())
06428     return StmtError();
06429   if (Inc.get())
06430     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
06431 
06432   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
06433   if (LoopVar.isInvalid())
06434     return StmtError();
06435 
06436   StmtResult NewStmt = S;
06437   if (getDerived().AlwaysRebuild() ||
06438       Range.get() != S->getRangeStmt() ||
06439       BeginEnd.get() != S->getBeginEndStmt() ||
06440       Cond.get() != S->getCond() ||
06441       Inc.get() != S->getInc() ||
06442       LoopVar.get() != S->getLoopVarStmt()) {
06443     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
06444                                                   S->getColonLoc(), Range.get(),
06445                                                   BeginEnd.get(), Cond.get(),
06446                                                   Inc.get(), LoopVar.get(),
06447                                                   S->getRParenLoc());
06448     if (NewStmt.isInvalid())
06449       return StmtError();
06450   }
06451 
06452   StmtResult Body = getDerived().TransformStmt(S->getBody());
06453   if (Body.isInvalid())
06454     return StmtError();
06455 
06456   // Body has changed but we didn't rebuild the for-range statement. Rebuild
06457   // it now so we have a new statement to attach the body to.
06458   if (Body.get() != S->getBody() && NewStmt.get() == S) {
06459     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
06460                                                   S->getColonLoc(), Range.get(),
06461                                                   BeginEnd.get(), Cond.get(),
06462                                                   Inc.get(), LoopVar.get(),
06463                                                   S->getRParenLoc());
06464     if (NewStmt.isInvalid())
06465       return StmtError();
06466   }
06467 
06468   if (NewStmt.get() == S)
06469     return S;
06470 
06471   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
06472 }
06473 
06474 template<typename Derived>
06475 StmtResult
06476 TreeTransform<Derived>::TransformMSDependentExistsStmt(
06477                                                     MSDependentExistsStmt *S) {
06478   // Transform the nested-name-specifier, if any.
06479   NestedNameSpecifierLoc QualifierLoc;
06480   if (S->getQualifierLoc()) {
06481     QualifierLoc
06482       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
06483     if (!QualifierLoc)
06484       return StmtError();
06485   }
06486 
06487   // Transform the declaration name.
06488   DeclarationNameInfo NameInfo = S->getNameInfo();
06489   if (NameInfo.getName()) {
06490     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
06491     if (!NameInfo.getName())
06492       return StmtError();
06493   }
06494 
06495   // Check whether anything changed.
06496   if (!getDerived().AlwaysRebuild() &&
06497       QualifierLoc == S->getQualifierLoc() &&
06498       NameInfo.getName() == S->getNameInfo().getName())
06499     return S;
06500 
06501   // Determine whether this name exists, if we can.
06502   CXXScopeSpec SS;
06503   SS.Adopt(QualifierLoc);
06504   bool Dependent = false;
06505   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
06506   case Sema::IER_Exists:
06507     if (S->isIfExists())
06508       break;
06509 
06510     return new (getSema().Context) NullStmt(S->getKeywordLoc());
06511 
06512   case Sema::IER_DoesNotExist:
06513     if (S->isIfNotExists())
06514       break;
06515 
06516     return new (getSema().Context) NullStmt(S->getKeywordLoc());
06517 
06518   case Sema::IER_Dependent:
06519     Dependent = true;
06520     break;
06521 
06522   case Sema::IER_Error:
06523     return StmtError();
06524   }
06525 
06526   // We need to continue with the instantiation, so do so now.
06527   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
06528   if (SubStmt.isInvalid())
06529     return StmtError();
06530 
06531   // If we have resolved the name, just transform to the substatement.
06532   if (!Dependent)
06533     return SubStmt;
06534 
06535   // The name is still dependent, so build a dependent expression again.
06536   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
06537                                                    S->isIfExists(),
06538                                                    QualifierLoc,
06539                                                    NameInfo,
06540                                                    SubStmt.get());
06541 }
06542 
06543 template<typename Derived>
06544 ExprResult
06545 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
06546   NestedNameSpecifierLoc QualifierLoc;
06547   if (E->getQualifierLoc()) {
06548     QualifierLoc
06549     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
06550     if (!QualifierLoc)
06551       return ExprError();
06552   }
06553 
06554   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
06555     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
06556   if (!PD)
06557     return ExprError();
06558 
06559   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
06560   if (Base.isInvalid())
06561     return ExprError();
06562 
06563   return new (SemaRef.getASTContext())
06564       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
06565                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
06566                         QualifierLoc, E->getMemberLoc());
06567 }
06568 
06569 template <typename Derived>
06570 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
06571   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
06572   if (TryBlock.isInvalid())
06573     return StmtError();
06574 
06575   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
06576   if (Handler.isInvalid())
06577     return StmtError();
06578 
06579   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
06580       Handler.get() == S->getHandler())
06581     return S;
06582 
06583   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
06584                                         TryBlock.get(), Handler.get());
06585 }
06586 
06587 template <typename Derived>
06588 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
06589   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
06590   if (Block.isInvalid())
06591     return StmtError();
06592 
06593   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
06594 }
06595 
06596 template <typename Derived>
06597 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
06598   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
06599   if (FilterExpr.isInvalid())
06600     return StmtError();
06601 
06602   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
06603   if (Block.isInvalid())
06604     return StmtError();
06605 
06606   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
06607                                            Block.get());
06608 }
06609 
06610 template <typename Derived>
06611 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
06612   if (isa<SEHFinallyStmt>(Handler))
06613     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
06614   else
06615     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
06616 }
06617 
06618 template<typename Derived>
06619 StmtResult
06620 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
06621   return S;
06622 }
06623 
06624 //===----------------------------------------------------------------------===//
06625 // OpenMP directive transformation
06626 //===----------------------------------------------------------------------===//
06627 template <typename Derived>
06628 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
06629     OMPExecutableDirective *D) {
06630 
06631   // Transform the clauses
06632   llvm::SmallVector<OMPClause *, 16> TClauses;
06633   ArrayRef<OMPClause *> Clauses = D->clauses();
06634   TClauses.reserve(Clauses.size());
06635   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
06636        I != E; ++I) {
06637     if (*I) {
06638       OMPClause *Clause = getDerived().TransformOMPClause(*I);
06639       if (Clause)
06640         TClauses.push_back(Clause);
06641     } else {
06642       TClauses.push_back(nullptr);
06643     }
06644   }
06645   StmtResult AssociatedStmt;
06646   if (D->hasAssociatedStmt()) {
06647     if (!D->getAssociatedStmt()) {
06648       return StmtError();
06649     }
06650     AssociatedStmt = getDerived().TransformStmt(D->getAssociatedStmt());
06651     if (AssociatedStmt.isInvalid()) {
06652       return StmtError();
06653     }
06654   }
06655   if (TClauses.size() != Clauses.size()) {
06656     return StmtError();
06657   }
06658 
06659   // Transform directive name for 'omp critical' directive.
06660   DeclarationNameInfo DirName;
06661   if (D->getDirectiveKind() == OMPD_critical) {
06662     DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
06663     DirName = getDerived().TransformDeclarationNameInfo(DirName);
06664   }
06665 
06666   return getDerived().RebuildOMPExecutableDirective(
06667       D->getDirectiveKind(), DirName, TClauses, AssociatedStmt.get(),
06668       D->getLocStart(), D->getLocEnd());
06669 }
06670 
06671 template <typename Derived>
06672 StmtResult
06673 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
06674   DeclarationNameInfo DirName;
06675   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
06676                                              D->getLocStart());
06677   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06678   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06679   return Res;
06680 }
06681 
06682 template <typename Derived>
06683 StmtResult
06684 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
06685   DeclarationNameInfo DirName;
06686   getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
06687                                              D->getLocStart());
06688   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06689   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06690   return Res;
06691 }
06692 
06693 template <typename Derived>
06694 StmtResult
06695 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
06696   DeclarationNameInfo DirName;
06697   getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
06698                                              D->getLocStart());
06699   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06700   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06701   return Res;
06702 }
06703 
06704 template <typename Derived>
06705 StmtResult
06706 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
06707   DeclarationNameInfo DirName;
06708   getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
06709                                              D->getLocStart());
06710   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06711   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06712   return Res;
06713 }
06714 
06715 template <typename Derived>
06716 StmtResult
06717 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
06718   DeclarationNameInfo DirName;
06719   getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
06720                                              D->getLocStart());
06721   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06722   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06723   return Res;
06724 }
06725 
06726 template <typename Derived>
06727 StmtResult
06728 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
06729   DeclarationNameInfo DirName;
06730   getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
06731                                              D->getLocStart());
06732   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06733   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06734   return Res;
06735 }
06736 
06737 template <typename Derived>
06738 StmtResult
06739 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
06740   DeclarationNameInfo DirName;
06741   getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
06742                                              D->getLocStart());
06743   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06744   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06745   return Res;
06746 }
06747 
06748 template <typename Derived>
06749 StmtResult
06750 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
06751   DeclarationNameInfo DirName;
06752   getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
06753                                              D->getLocStart());
06754   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06755   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06756   return Res;
06757 }
06758 
06759 template <typename Derived>
06760 StmtResult
06761 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
06762   getDerived().getSema().StartOpenMPDSABlock(
06763       OMPD_critical, D->getDirectiveName(), nullptr, D->getLocStart());
06764   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06765   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06766   return Res;
06767 }
06768 
06769 template <typename Derived>
06770 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
06771     OMPParallelForDirective *D) {
06772   DeclarationNameInfo DirName;
06773   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
06774                                              nullptr, D->getLocStart());
06775   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06776   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06777   return Res;
06778 }
06779 
06780 template <typename Derived>
06781 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
06782     OMPParallelForSimdDirective *D) {
06783   DeclarationNameInfo DirName;
06784   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
06785                                              nullptr, D->getLocStart());
06786   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06787   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06788   return Res;
06789 }
06790 
06791 template <typename Derived>
06792 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
06793     OMPParallelSectionsDirective *D) {
06794   DeclarationNameInfo DirName;
06795   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
06796                                              nullptr, D->getLocStart());
06797   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06798   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06799   return Res;
06800 }
06801 
06802 template <typename Derived>
06803 StmtResult
06804 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
06805   DeclarationNameInfo DirName;
06806   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
06807                                              D->getLocStart());
06808   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06809   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06810   return Res;
06811 }
06812 
06813 template <typename Derived>
06814 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
06815     OMPTaskyieldDirective *D) {
06816   DeclarationNameInfo DirName;
06817   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
06818                                              D->getLocStart());
06819   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06820   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06821   return Res;
06822 }
06823 
06824 template <typename Derived>
06825 StmtResult
06826 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
06827   DeclarationNameInfo DirName;
06828   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
06829                                              D->getLocStart());
06830   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06831   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06832   return Res;
06833 }
06834 
06835 template <typename Derived>
06836 StmtResult
06837 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
06838   DeclarationNameInfo DirName;
06839   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
06840                                              D->getLocStart());
06841   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06842   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06843   return Res;
06844 }
06845 
06846 template <typename Derived>
06847 StmtResult
06848 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
06849   DeclarationNameInfo DirName;
06850   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
06851                                              D->getLocStart());
06852   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06853   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06854   return Res;
06855 }
06856 
06857 template <typename Derived>
06858 StmtResult
06859 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
06860   DeclarationNameInfo DirName;
06861   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
06862                                              D->getLocStart());
06863   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06864   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06865   return Res;
06866 }
06867 
06868 template <typename Derived>
06869 StmtResult
06870 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
06871   DeclarationNameInfo DirName;
06872   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
06873                                              D->getLocStart());
06874   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06875   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06876   return Res;
06877 }
06878 
06879 template <typename Derived>
06880 StmtResult
06881 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
06882   DeclarationNameInfo DirName;
06883   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
06884                                              D->getLocStart());
06885   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06886   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06887   return Res;
06888 }
06889 
06890 template <typename Derived>
06891 StmtResult
06892 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
06893   DeclarationNameInfo DirName;
06894   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
06895                                              D->getLocStart());
06896   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
06897   getDerived().getSema().EndOpenMPDSABlock(Res.get());
06898   return Res;
06899 }
06900 
06901 //===----------------------------------------------------------------------===//
06902 // OpenMP clause transformation
06903 //===----------------------------------------------------------------------===//
06904 template <typename Derived>
06905 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
06906   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
06907   if (Cond.isInvalid())
06908     return nullptr;
06909   return getDerived().RebuildOMPIfClause(Cond.get(), C->getLocStart(),
06910                                          C->getLParenLoc(), C->getLocEnd());
06911 }
06912 
06913 template <typename Derived>
06914 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
06915   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
06916   if (Cond.isInvalid())
06917     return nullptr;
06918   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getLocStart(),
06919                                             C->getLParenLoc(), C->getLocEnd());
06920 }
06921 
06922 template <typename Derived>
06923 OMPClause *
06924 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
06925   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
06926   if (NumThreads.isInvalid())
06927     return nullptr;
06928   return getDerived().RebuildOMPNumThreadsClause(
06929       NumThreads.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
06930 }
06931 
06932 template <typename Derived>
06933 OMPClause *
06934 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
06935   ExprResult E = getDerived().TransformExpr(C->getSafelen());
06936   if (E.isInvalid())
06937     return nullptr;
06938   return getDerived().RebuildOMPSafelenClause(
06939       E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
06940 }
06941 
06942 template <typename Derived>
06943 OMPClause *
06944 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
06945   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
06946   if (E.isInvalid())
06947     return 0;
06948   return getDerived().RebuildOMPCollapseClause(
06949       E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
06950 }
06951 
06952 template <typename Derived>
06953 OMPClause *
06954 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
06955   return getDerived().RebuildOMPDefaultClause(
06956       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getLocStart(),
06957       C->getLParenLoc(), C->getLocEnd());
06958 }
06959 
06960 template <typename Derived>
06961 OMPClause *
06962 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
06963   return getDerived().RebuildOMPProcBindClause(
06964       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getLocStart(),
06965       C->getLParenLoc(), C->getLocEnd());
06966 }
06967 
06968 template <typename Derived>
06969 OMPClause *
06970 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
06971   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
06972   if (E.isInvalid())
06973     return nullptr;
06974   return getDerived().RebuildOMPScheduleClause(
06975       C->getScheduleKind(), E.get(), C->getLocStart(), C->getLParenLoc(),
06976       C->getScheduleKindLoc(), C->getCommaLoc(), C->getLocEnd());
06977 }
06978 
06979 template <typename Derived>
06980 OMPClause *
06981 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
06982   // No need to rebuild this clause, no template-dependent parameters.
06983   return C;
06984 }
06985 
06986 template <typename Derived>
06987 OMPClause *
06988 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
06989   // No need to rebuild this clause, no template-dependent parameters.
06990   return C;
06991 }
06992 
06993 template <typename Derived>
06994 OMPClause *
06995 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
06996   // No need to rebuild this clause, no template-dependent parameters.
06997   return C;
06998 }
06999 
07000 template <typename Derived>
07001 OMPClause *
07002 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
07003   // No need to rebuild this clause, no template-dependent parameters.
07004   return C;
07005 }
07006 
07007 template <typename Derived>
07008 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
07009   // No need to rebuild this clause, no template-dependent parameters.
07010   return C;
07011 }
07012 
07013 template <typename Derived>
07014 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
07015   // No need to rebuild this clause, no template-dependent parameters.
07016   return C;
07017 }
07018 
07019 template <typename Derived>
07020 OMPClause *
07021 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
07022   // No need to rebuild this clause, no template-dependent parameters.
07023   return C;
07024 }
07025 
07026 template <typename Derived>
07027 OMPClause *
07028 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
07029   // No need to rebuild this clause, no template-dependent parameters.
07030   return C;
07031 }
07032 
07033 template <typename Derived>
07034 OMPClause *
07035 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
07036   // No need to rebuild this clause, no template-dependent parameters.
07037   return C;
07038 }
07039 
07040 template <typename Derived>
07041 OMPClause *
07042 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
07043   llvm::SmallVector<Expr *, 16> Vars;
07044   Vars.reserve(C->varlist_size());
07045   for (auto *VE : C->varlists()) {
07046     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
07047     if (EVar.isInvalid())
07048       return nullptr;
07049     Vars.push_back(EVar.get());
07050   }
07051   return getDerived().RebuildOMPPrivateClause(
07052       Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
07053 }
07054 
07055 template <typename Derived>
07056 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
07057     OMPFirstprivateClause *C) {
07058   llvm::SmallVector<Expr *, 16> Vars;
07059   Vars.reserve(C->varlist_size());
07060   for (auto *VE : C->varlists()) {
07061     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
07062     if (EVar.isInvalid())
07063       return nullptr;
07064     Vars.push_back(EVar.get());
07065   }
07066   return getDerived().RebuildOMPFirstprivateClause(
07067       Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
07068 }
07069 
07070 template <typename Derived>
07071 OMPClause *
07072 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
07073   llvm::SmallVector<Expr *, 16> Vars;
07074   Vars.reserve(C->varlist_size());
07075   for (auto *VE : C->varlists()) {
07076     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
07077     if (EVar.isInvalid())
07078       return nullptr;
07079     Vars.push_back(EVar.get());
07080   }
07081   return getDerived().RebuildOMPLastprivateClause(
07082       Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
07083 }
07084 
07085 template <typename Derived>
07086 OMPClause *
07087 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
07088   llvm::SmallVector<Expr *, 16> Vars;
07089   Vars.reserve(C->varlist_size());
07090   for (auto *VE : C->varlists()) {
07091     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
07092     if (EVar.isInvalid())
07093       return nullptr;
07094     Vars.push_back(EVar.get());
07095   }
07096   return getDerived().RebuildOMPSharedClause(Vars, C->getLocStart(),
07097                                              C->getLParenLoc(), C->getLocEnd());
07098 }
07099 
07100 template <typename Derived>
07101 OMPClause *
07102 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
07103   llvm::SmallVector<Expr *, 16> Vars;
07104   Vars.reserve(C->varlist_size());
07105   for (auto *VE : C->varlists()) {
07106     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
07107     if (EVar.isInvalid())
07108       return nullptr;
07109     Vars.push_back(EVar.get());
07110   }
07111   CXXScopeSpec ReductionIdScopeSpec;
07112   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
07113 
07114   DeclarationNameInfo NameInfo = C->getNameInfo();
07115   if (NameInfo.getName()) {
07116     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
07117     if (!NameInfo.getName())
07118       return nullptr;
07119   }
07120   return getDerived().RebuildOMPReductionClause(
07121       Vars, C->getLocStart(), C->getLParenLoc(), C->getColonLoc(),
07122       C->getLocEnd(), ReductionIdScopeSpec, NameInfo);
07123 }
07124 
07125 template <typename Derived>
07126 OMPClause *
07127 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
07128   llvm::SmallVector<Expr *, 16> Vars;
07129   Vars.reserve(C->varlist_size());
07130   for (auto *VE : C->varlists()) {
07131     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
07132     if (EVar.isInvalid())
07133       return nullptr;
07134     Vars.push_back(EVar.get());
07135   }
07136   ExprResult Step = getDerived().TransformExpr(C->getStep());
07137   if (Step.isInvalid())
07138     return nullptr;
07139   return getDerived().RebuildOMPLinearClause(Vars, Step.get(), C->getLocStart(),
07140                                              C->getLParenLoc(),
07141                                              C->getColonLoc(), C->getLocEnd());
07142 }
07143 
07144 template <typename Derived>
07145 OMPClause *
07146 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
07147   llvm::SmallVector<Expr *, 16> Vars;
07148   Vars.reserve(C->varlist_size());
07149   for (auto *VE : C->varlists()) {
07150     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
07151     if (EVar.isInvalid())
07152       return nullptr;
07153     Vars.push_back(EVar.get());
07154   }
07155   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
07156   if (Alignment.isInvalid())
07157     return nullptr;
07158   return getDerived().RebuildOMPAlignedClause(
07159       Vars, Alignment.get(), C->getLocStart(), C->getLParenLoc(),
07160       C->getColonLoc(), C->getLocEnd());
07161 }
07162 
07163 template <typename Derived>
07164 OMPClause *
07165 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
07166   llvm::SmallVector<Expr *, 16> Vars;
07167   Vars.reserve(C->varlist_size());
07168   for (auto *VE : C->varlists()) {
07169     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
07170     if (EVar.isInvalid())
07171       return nullptr;
07172     Vars.push_back(EVar.get());
07173   }
07174   return getDerived().RebuildOMPCopyinClause(Vars, C->getLocStart(),
07175                                              C->getLParenLoc(), C->getLocEnd());
07176 }
07177 
07178 template <typename Derived>
07179 OMPClause *
07180 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
07181   llvm::SmallVector<Expr *, 16> Vars;
07182   Vars.reserve(C->varlist_size());
07183   for (auto *VE : C->varlists()) {
07184     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
07185     if (EVar.isInvalid())
07186       return nullptr;
07187     Vars.push_back(EVar.get());
07188   }
07189   return getDerived().RebuildOMPCopyprivateClause(
07190       Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
07191 }
07192 
07193 template <typename Derived>
07194 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
07195   llvm::SmallVector<Expr *, 16> Vars;
07196   Vars.reserve(C->varlist_size());
07197   for (auto *VE : C->varlists()) {
07198     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
07199     if (EVar.isInvalid())
07200       return nullptr;
07201     Vars.push_back(EVar.get());
07202   }
07203   return getDerived().RebuildOMPFlushClause(Vars, C->getLocStart(),
07204                                             C->getLParenLoc(), C->getLocEnd());
07205 }
07206 
07207 //===----------------------------------------------------------------------===//
07208 // Expression transformation
07209 //===----------------------------------------------------------------------===//
07210 template<typename Derived>
07211 ExprResult
07212 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
07213   if (!E->isTypeDependent())
07214     return E;
07215 
07216   return getDerived().RebuildPredefinedExpr(E->getLocation(),
07217                                             E->getIdentType());
07218 }
07219 
07220 template<typename Derived>
07221 ExprResult
07222 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
07223   NestedNameSpecifierLoc QualifierLoc;
07224   if (E->getQualifierLoc()) {
07225     QualifierLoc
07226       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
07227     if (!QualifierLoc)
07228       return ExprError();
07229   }
07230 
07231   ValueDecl *ND
07232     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
07233                                                          E->getDecl()));
07234   if (!ND)
07235     return ExprError();
07236 
07237   DeclarationNameInfo NameInfo = E->getNameInfo();
07238   if (NameInfo.getName()) {
07239     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
07240     if (!NameInfo.getName())
07241       return ExprError();
07242   }
07243 
07244   if (!getDerived().AlwaysRebuild() &&
07245       QualifierLoc == E->getQualifierLoc() &&
07246       ND == E->getDecl() &&
07247       NameInfo.getName() == E->getDecl()->getDeclName() &&
07248       !E->hasExplicitTemplateArgs()) {
07249 
07250     // Mark it referenced in the new context regardless.
07251     // FIXME: this is a bit instantiation-specific.
07252     SemaRef.MarkDeclRefReferenced(E);
07253 
07254     return E;
07255   }
07256 
07257   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
07258   if (E->hasExplicitTemplateArgs()) {
07259     TemplateArgs = &TransArgs;
07260     TransArgs.setLAngleLoc(E->getLAngleLoc());
07261     TransArgs.setRAngleLoc(E->getRAngleLoc());
07262     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
07263                                                 E->getNumTemplateArgs(),
07264                                                 TransArgs))
07265       return ExprError();
07266   }
07267 
07268   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
07269                                          TemplateArgs);
07270 }
07271 
07272 template<typename Derived>
07273 ExprResult
07274 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
07275   return E;
07276 }
07277 
07278 template<typename Derived>
07279 ExprResult
07280 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
07281   return E;
07282 }
07283 
07284 template<typename Derived>
07285 ExprResult
07286 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
07287   return E;
07288 }
07289 
07290 template<typename Derived>
07291 ExprResult
07292 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
07293   return E;
07294 }
07295 
07296 template<typename Derived>
07297 ExprResult
07298 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
07299   return E;
07300 }
07301 
07302 template<typename Derived>
07303 ExprResult
07304 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
07305   if (FunctionDecl *FD = E->getDirectCallee())
07306     SemaRef.MarkFunctionReferenced(E->getLocStart(), FD);
07307   return SemaRef.MaybeBindToTemporary(E);
07308 }
07309 
07310 template<typename Derived>
07311 ExprResult
07312 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
07313   ExprResult ControllingExpr =
07314     getDerived().TransformExpr(E->getControllingExpr());
07315   if (ControllingExpr.isInvalid())
07316     return ExprError();
07317 
07318   SmallVector<Expr *, 4> AssocExprs;
07319   SmallVector<TypeSourceInfo *, 4> AssocTypes;
07320   for (unsigned i = 0; i != E->getNumAssocs(); ++i) {
07321     TypeSourceInfo *TS = E->getAssocTypeSourceInfo(i);
07322     if (TS) {
07323       TypeSourceInfo *AssocType = getDerived().TransformType(TS);
07324       if (!AssocType)
07325         return ExprError();
07326       AssocTypes.push_back(AssocType);
07327     } else {
07328       AssocTypes.push_back(nullptr);
07329     }
07330 
07331     ExprResult AssocExpr = getDerived().TransformExpr(E->getAssocExpr(i));
07332     if (AssocExpr.isInvalid())
07333       return ExprError();
07334     AssocExprs.push_back(AssocExpr.get());
07335   }
07336 
07337   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
07338                                                   E->getDefaultLoc(),
07339                                                   E->getRParenLoc(),
07340                                                   ControllingExpr.get(),
07341                                                   AssocTypes,
07342                                                   AssocExprs);
07343 }
07344 
07345 template<typename Derived>
07346 ExprResult
07347 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
07348   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
07349   if (SubExpr.isInvalid())
07350     return ExprError();
07351 
07352   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
07353     return E;
07354 
07355   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
07356                                        E->getRParen());
07357 }
07358 
07359 /// \brief The operand of a unary address-of operator has special rules: it's
07360 /// allowed to refer to a non-static member of a class even if there's no 'this'
07361 /// object available.
07362 template<typename Derived>
07363 ExprResult
07364 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
07365   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
07366     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
07367   else
07368     return getDerived().TransformExpr(E);
07369 }
07370 
07371 template<typename Derived>
07372 ExprResult
07373 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
07374   ExprResult SubExpr;
07375   if (E->getOpcode() == UO_AddrOf)
07376     SubExpr = TransformAddressOfOperand(E->getSubExpr());
07377   else
07378     SubExpr = TransformExpr(E->getSubExpr());
07379   if (SubExpr.isInvalid())
07380     return ExprError();
07381 
07382   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
07383     return E;
07384 
07385   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
07386                                            E->getOpcode(),
07387                                            SubExpr.get());
07388 }
07389 
07390 template<typename Derived>
07391 ExprResult
07392 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
07393   // Transform the type.
07394   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
07395   if (!Type)
07396     return ExprError();
07397 
07398   // Transform all of the components into components similar to what the
07399   // parser uses.
07400   // FIXME: It would be slightly more efficient in the non-dependent case to
07401   // just map FieldDecls, rather than requiring the rebuilder to look for
07402   // the fields again. However, __builtin_offsetof is rare enough in
07403   // template code that we don't care.
07404   bool ExprChanged = false;
07405   typedef Sema::OffsetOfComponent Component;
07406   typedef OffsetOfExpr::OffsetOfNode Node;
07407   SmallVector<Component, 4> Components;
07408   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
07409     const Node &ON = E->getComponent(I);
07410     Component Comp;
07411     Comp.isBrackets = true;
07412     Comp.LocStart = ON.getSourceRange().getBegin();
07413     Comp.LocEnd = ON.getSourceRange().getEnd();
07414     switch (ON.getKind()) {
07415     case Node::Array: {
07416       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
07417       ExprResult Index = getDerived().TransformExpr(FromIndex);
07418       if (Index.isInvalid())
07419         return ExprError();
07420 
07421       ExprChanged = ExprChanged || Index.get() != FromIndex;
07422       Comp.isBrackets = true;
07423       Comp.U.E = Index.get();
07424       break;
07425     }
07426 
07427     case Node::Field:
07428     case Node::Identifier:
07429       Comp.isBrackets = false;
07430       Comp.U.IdentInfo = ON.getFieldName();
07431       if (!Comp.U.IdentInfo)
07432         continue;
07433 
07434       break;
07435 
07436     case Node::Base:
07437       // Will be recomputed during the rebuild.
07438       continue;
07439     }
07440 
07441     Components.push_back(Comp);
07442   }
07443 
07444   // If nothing changed, retain the existing expression.
07445   if (!getDerived().AlwaysRebuild() &&
07446       Type == E->getTypeSourceInfo() &&
07447       !ExprChanged)
07448     return E;
07449 
07450   // Build a new offsetof expression.
07451   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
07452                                           Components.data(), Components.size(),
07453                                           E->getRParenLoc());
07454 }
07455 
07456 template<typename Derived>
07457 ExprResult
07458 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
07459   assert(getDerived().AlreadyTransformed(E->getType()) &&
07460          "opaque value expression requires transformation");
07461   return E;
07462 }
07463 
07464 template<typename Derived>
07465 ExprResult
07466 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
07467   return E;
07468 }
07469 
07470 template<typename Derived>
07471 ExprResult
07472 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
07473   // Rebuild the syntactic form.  The original syntactic form has
07474   // opaque-value expressions in it, so strip those away and rebuild
07475   // the result.  This is a really awful way of doing this, but the
07476   // better solution (rebuilding the semantic expressions and
07477   // rebinding OVEs as necessary) doesn't work; we'd need
07478   // TreeTransform to not strip away implicit conversions.
07479   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
07480   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
07481   if (result.isInvalid()) return ExprError();
07482 
07483   // If that gives us a pseudo-object result back, the pseudo-object
07484   // expression must have been an lvalue-to-rvalue conversion which we
07485   // should reapply.
07486   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
07487     result = SemaRef.checkPseudoObjectRValue(result.get());
07488 
07489   return result;
07490 }
07491 
07492 template<typename Derived>
07493 ExprResult
07494 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
07495                                                 UnaryExprOrTypeTraitExpr *E) {
07496   if (E->isArgumentType()) {
07497     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
07498 
07499     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
07500     if (!NewT)
07501       return ExprError();
07502 
07503     if (!getDerived().AlwaysRebuild() && OldT == NewT)
07504       return E;
07505 
07506     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
07507                                                     E->getKind(),
07508                                                     E->getSourceRange());
07509   }
07510 
07511   // C++0x [expr.sizeof]p1:
07512   //   The operand is either an expression, which is an unevaluated operand
07513   //   [...]
07514   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
07515                                                Sema::ReuseLambdaContextDecl);
07516 
07517   // Try to recover if we have something like sizeof(T::X) where X is a type.
07518   // Notably, there must be *exactly* one set of parens if X is a type.
07519   TypeSourceInfo *RecoveryTSI = nullptr;
07520   ExprResult SubExpr;
07521   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
07522   if (auto *DRE =
07523           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
07524     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
07525         PE, DRE, false, &RecoveryTSI);
07526   else
07527     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
07528 
07529   if (RecoveryTSI) {
07530     return getDerived().RebuildUnaryExprOrTypeTrait(
07531         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
07532   } else if (SubExpr.isInvalid())
07533     return ExprError();
07534 
07535   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
07536     return E;
07537 
07538   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
07539                                                   E->getOperatorLoc(),
07540                                                   E->getKind(),
07541                                                   E->getSourceRange());
07542 }
07543 
07544 template<typename Derived>
07545 ExprResult
07546 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
07547   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
07548   if (LHS.isInvalid())
07549     return ExprError();
07550 
07551   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
07552   if (RHS.isInvalid())
07553     return ExprError();
07554 
07555 
07556   if (!getDerived().AlwaysRebuild() &&
07557       LHS.get() == E->getLHS() &&
07558       RHS.get() == E->getRHS())
07559     return E;
07560 
07561   return getDerived().RebuildArraySubscriptExpr(LHS.get(),
07562                                            /*FIXME:*/E->getLHS()->getLocStart(),
07563                                                 RHS.get(),
07564                                                 E->getRBracketLoc());
07565 }
07566 
07567 template<typename Derived>
07568 ExprResult
07569 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
07570   // Transform the callee.
07571   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
07572   if (Callee.isInvalid())
07573     return ExprError();
07574 
07575   // Transform arguments.
07576   bool ArgChanged = false;
07577   SmallVector<Expr*, 8> Args;
07578   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
07579                                   &ArgChanged))
07580     return ExprError();
07581 
07582   if (!getDerived().AlwaysRebuild() &&
07583       Callee.get() == E->getCallee() &&
07584       !ArgChanged)
07585     return SemaRef.MaybeBindToTemporary(E);
07586 
07587   // FIXME: Wrong source location information for the '('.
07588   SourceLocation FakeLParenLoc
07589     = ((Expr *)Callee.get())->getSourceRange().getBegin();
07590   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
07591                                       Args,
07592                                       E->getRParenLoc());
07593 }
07594 
07595 template<typename Derived>
07596 ExprResult
07597 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
07598   ExprResult Base = getDerived().TransformExpr(E->getBase());
07599   if (Base.isInvalid())
07600     return ExprError();
07601 
07602   NestedNameSpecifierLoc QualifierLoc;
07603   if (E->hasQualifier()) {
07604     QualifierLoc
07605       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
07606 
07607     if (!QualifierLoc)
07608       return ExprError();
07609   }
07610   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
07611 
07612   ValueDecl *Member
07613     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
07614                                                          E->getMemberDecl()));
07615   if (!Member)
07616     return ExprError();
07617 
07618   NamedDecl *FoundDecl = E->getFoundDecl();
07619   if (FoundDecl == E->getMemberDecl()) {
07620     FoundDecl = Member;
07621   } else {
07622     FoundDecl = cast_or_null<NamedDecl>(
07623                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
07624     if (!FoundDecl)
07625       return ExprError();
07626   }
07627 
07628   if (!getDerived().AlwaysRebuild() &&
07629       Base.get() == E->getBase() &&
07630       QualifierLoc == E->getQualifierLoc() &&
07631       Member == E->getMemberDecl() &&
07632       FoundDecl == E->getFoundDecl() &&
07633       !E->hasExplicitTemplateArgs()) {
07634 
07635     // Mark it referenced in the new context regardless.
07636     // FIXME: this is a bit instantiation-specific.
07637     SemaRef.MarkMemberReferenced(E);
07638 
07639     return E;
07640   }
07641 
07642   TemplateArgumentListInfo TransArgs;
07643   if (E->hasExplicitTemplateArgs()) {
07644     TransArgs.setLAngleLoc(E->getLAngleLoc());
07645     TransArgs.setRAngleLoc(E->getRAngleLoc());
07646     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
07647                                                 E->getNumTemplateArgs(),
07648                                                 TransArgs))
07649       return ExprError();
07650   }
07651 
07652   // FIXME: Bogus source location for the operator
07653   SourceLocation FakeOperatorLoc =
07654       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
07655 
07656   // FIXME: to do this check properly, we will need to preserve the
07657   // first-qualifier-in-scope here, just in case we had a dependent
07658   // base (and therefore couldn't do the check) and a
07659   // nested-name-qualifier (and therefore could do the lookup).
07660   NamedDecl *FirstQualifierInScope = nullptr;
07661 
07662   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
07663                                         E->isArrow(),
07664                                         QualifierLoc,
07665                                         TemplateKWLoc,
07666                                         E->getMemberNameInfo(),
07667                                         Member,
07668                                         FoundDecl,
07669                                         (E->hasExplicitTemplateArgs()
07670                                            ? &TransArgs : nullptr),
07671                                         FirstQualifierInScope);
07672 }
07673 
07674 template<typename Derived>
07675 ExprResult
07676 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
07677   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
07678   if (LHS.isInvalid())
07679     return ExprError();
07680 
07681   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
07682   if (RHS.isInvalid())
07683     return ExprError();
07684 
07685   if (!getDerived().AlwaysRebuild() &&
07686       LHS.get() == E->getLHS() &&
07687       RHS.get() == E->getRHS())
07688     return E;
07689 
07690   Sema::FPContractStateRAII FPContractState(getSema());
07691   getSema().FPFeatures.fp_contract = E->isFPContractable();
07692 
07693   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
07694                                             LHS.get(), RHS.get());
07695 }
07696 
07697 template<typename Derived>
07698 ExprResult
07699 TreeTransform<Derived>::TransformCompoundAssignOperator(
07700                                                       CompoundAssignOperator *E) {
07701   return getDerived().TransformBinaryOperator(E);
07702 }
07703 
07704 template<typename Derived>
07705 ExprResult TreeTransform<Derived>::
07706 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
07707   // Just rebuild the common and RHS expressions and see whether we
07708   // get any changes.
07709 
07710   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
07711   if (commonExpr.isInvalid())
07712     return ExprError();
07713 
07714   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
07715   if (rhs.isInvalid())
07716     return ExprError();
07717 
07718   if (!getDerived().AlwaysRebuild() &&
07719       commonExpr.get() == e->getCommon() &&
07720       rhs.get() == e->getFalseExpr())
07721     return e;
07722 
07723   return getDerived().RebuildConditionalOperator(commonExpr.get(),
07724                                                  e->getQuestionLoc(),
07725                                                  nullptr,
07726                                                  e->getColonLoc(),
07727                                                  rhs.get());
07728 }
07729 
07730 template<typename Derived>
07731 ExprResult
07732 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
07733   ExprResult Cond = getDerived().TransformExpr(E->getCond());
07734   if (Cond.isInvalid())
07735     return ExprError();
07736 
07737   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
07738   if (LHS.isInvalid())
07739     return ExprError();
07740 
07741   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
07742   if (RHS.isInvalid())
07743     return ExprError();
07744 
07745   if (!getDerived().AlwaysRebuild() &&
07746       Cond.get() == E->getCond() &&
07747       LHS.get() == E->getLHS() &&
07748       RHS.get() == E->getRHS())
07749     return E;
07750 
07751   return getDerived().RebuildConditionalOperator(Cond.get(),
07752                                                  E->getQuestionLoc(),
07753                                                  LHS.get(),
07754                                                  E->getColonLoc(),
07755                                                  RHS.get());
07756 }
07757 
07758 template<typename Derived>
07759 ExprResult
07760 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
07761   // Implicit casts are eliminated during transformation, since they
07762   // will be recomputed by semantic analysis after transformation.
07763   return getDerived().TransformExpr(E->getSubExprAsWritten());
07764 }
07765 
07766 template<typename Derived>
07767 ExprResult
07768 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
07769   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
07770   if (!Type)
07771     return ExprError();
07772 
07773   ExprResult SubExpr
07774     = getDerived().TransformExpr(E->getSubExprAsWritten());
07775   if (SubExpr.isInvalid())
07776     return ExprError();
07777 
07778   if (!getDerived().AlwaysRebuild() &&
07779       Type == E->getTypeInfoAsWritten() &&
07780       SubExpr.get() == E->getSubExpr())
07781     return E;
07782 
07783   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
07784                                             Type,
07785                                             E->getRParenLoc(),
07786                                             SubExpr.get());
07787 }
07788 
07789 template<typename Derived>
07790 ExprResult
07791 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
07792   TypeSourceInfo *OldT = E->getTypeSourceInfo();
07793   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
07794   if (!NewT)
07795     return ExprError();
07796 
07797   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
07798   if (Init.isInvalid())
07799     return ExprError();
07800 
07801   if (!getDerived().AlwaysRebuild() &&
07802       OldT == NewT &&
07803       Init.get() == E->getInitializer())
07804     return SemaRef.MaybeBindToTemporary(E);
07805 
07806   // Note: the expression type doesn't necessarily match the
07807   // type-as-written, but that's okay, because it should always be
07808   // derivable from the initializer.
07809 
07810   return getDerived().RebuildCompoundLiteralExpr(E->getLParenLoc(), NewT,
07811                                    /*FIXME:*/E->getInitializer()->getLocEnd(),
07812                                                  Init.get());
07813 }
07814 
07815 template<typename Derived>
07816 ExprResult
07817 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
07818   ExprResult Base = getDerived().TransformExpr(E->getBase());
07819   if (Base.isInvalid())
07820     return ExprError();
07821 
07822   if (!getDerived().AlwaysRebuild() &&
07823       Base.get() == E->getBase())
07824     return E;
07825 
07826   // FIXME: Bad source location
07827   SourceLocation FakeOperatorLoc =
07828       SemaRef.getLocForEndOfToken(E->getBase()->getLocEnd());
07829   return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
07830                                                   E->getAccessorLoc(),
07831                                                   E->getAccessor());
07832 }
07833 
07834 template<typename Derived>
07835 ExprResult
07836 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
07837   bool InitChanged = false;
07838 
07839   SmallVector<Expr*, 4> Inits;
07840   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
07841                                   Inits, &InitChanged))
07842     return ExprError();
07843 
07844   if (!getDerived().AlwaysRebuild() && !InitChanged)
07845     return E;
07846 
07847   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
07848                                       E->getRBraceLoc(), E->getType());
07849 }
07850 
07851 template<typename Derived>
07852 ExprResult
07853 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
07854   Designation Desig;
07855 
07856   // transform the initializer value
07857   ExprResult Init = getDerived().TransformExpr(E->getInit());
07858   if (Init.isInvalid())
07859     return ExprError();
07860 
07861   // transform the designators.
07862   SmallVector<Expr*, 4> ArrayExprs;
07863   bool ExprChanged = false;
07864   for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
07865                                              DEnd = E->designators_end();
07866        D != DEnd; ++D) {
07867     if (D->isFieldDesignator()) {
07868       Desig.AddDesignator(Designator::getField(D->getFieldName(),
07869                                                D->getDotLoc(),
07870                                                D->getFieldLoc()));
07871       continue;
07872     }
07873 
07874     if (D->isArrayDesignator()) {
07875       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(*D));
07876       if (Index.isInvalid())
07877         return ExprError();
07878 
07879       Desig.AddDesignator(Designator::getArray(Index.get(),
07880                                                D->getLBracketLoc()));
07881 
07882       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(*D);
07883       ArrayExprs.push_back(Index.get());
07884       continue;
07885     }
07886 
07887     assert(D->isArrayRangeDesignator() && "New kind of designator?");
07888     ExprResult Start
07889       = getDerived().TransformExpr(E->getArrayRangeStart(*D));
07890     if (Start.isInvalid())
07891       return ExprError();
07892 
07893     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(*D));
07894     if (End.isInvalid())
07895       return ExprError();
07896 
07897     Desig.AddDesignator(Designator::getArrayRange(Start.get(),
07898                                                   End.get(),
07899                                                   D->getLBracketLoc(),
07900                                                   D->getEllipsisLoc()));
07901 
07902     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(*D) ||
07903       End.get() != E->getArrayRangeEnd(*D);
07904 
07905     ArrayExprs.push_back(Start.get());
07906     ArrayExprs.push_back(End.get());
07907   }
07908 
07909   if (!getDerived().AlwaysRebuild() &&
07910       Init.get() == E->getInit() &&
07911       !ExprChanged)
07912     return E;
07913 
07914   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
07915                                                 E->getEqualOrColonLoc(),
07916                                                 E->usesGNUSyntax(), Init.get());
07917 }
07918 
07919 template<typename Derived>
07920 ExprResult
07921 TreeTransform<Derived>::TransformImplicitValueInitExpr(
07922                                                      ImplicitValueInitExpr *E) {
07923   TemporaryBase Rebase(*this, E->getLocStart(), DeclarationName());
07924 
07925   // FIXME: Will we ever have proper type location here? Will we actually
07926   // need to transform the type?
07927   QualType T = getDerived().TransformType(E->getType());
07928   if (T.isNull())
07929     return ExprError();
07930 
07931   if (!getDerived().AlwaysRebuild() &&
07932       T == E->getType())
07933     return E;
07934 
07935   return getDerived().RebuildImplicitValueInitExpr(T);
07936 }
07937 
07938 template<typename Derived>
07939 ExprResult
07940 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
07941   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
07942   if (!TInfo)
07943     return ExprError();
07944 
07945   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
07946   if (SubExpr.isInvalid())
07947     return ExprError();
07948 
07949   if (!getDerived().AlwaysRebuild() &&
07950       TInfo == E->getWrittenTypeInfo() &&
07951       SubExpr.get() == E->getSubExpr())
07952     return E;
07953 
07954   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
07955                                        TInfo, E->getRParenLoc());
07956 }
07957 
07958 template<typename Derived>
07959 ExprResult
07960 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
07961   bool ArgumentChanged = false;
07962   SmallVector<Expr*, 4> Inits;
07963   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
07964                      &ArgumentChanged))
07965     return ExprError();
07966 
07967   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
07968                                            Inits,
07969                                            E->getRParenLoc());
07970 }
07971 
07972 /// \brief Transform an address-of-label expression.
07973 ///
07974 /// By default, the transformation of an address-of-label expression always
07975 /// rebuilds the expression, so that the label identifier can be resolved to
07976 /// the corresponding label statement by semantic analysis.
07977 template<typename Derived>
07978 ExprResult
07979 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
07980   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
07981                                         E->getLabel());
07982   if (!LD)
07983     return ExprError();
07984 
07985   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
07986                                            cast<LabelDecl>(LD));
07987 }
07988 
07989 template<typename Derived>
07990 ExprResult
07991 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
07992   SemaRef.ActOnStartStmtExpr();
07993   StmtResult SubStmt
07994     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
07995   if (SubStmt.isInvalid()) {
07996     SemaRef.ActOnStmtExprError();
07997     return ExprError();
07998   }
07999 
08000   if (!getDerived().AlwaysRebuild() &&
08001       SubStmt.get() == E->getSubStmt()) {
08002     // Calling this an 'error' is unintuitive, but it does the right thing.
08003     SemaRef.ActOnStmtExprError();
08004     return SemaRef.MaybeBindToTemporary(E);
08005   }
08006 
08007   return getDerived().RebuildStmtExpr(E->getLParenLoc(),
08008                                       SubStmt.get(),
08009                                       E->getRParenLoc());
08010 }
08011 
08012 template<typename Derived>
08013 ExprResult
08014 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
08015   ExprResult Cond = getDerived().TransformExpr(E->getCond());
08016   if (Cond.isInvalid())
08017     return ExprError();
08018 
08019   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
08020   if (LHS.isInvalid())
08021     return ExprError();
08022 
08023   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
08024   if (RHS.isInvalid())
08025     return ExprError();
08026 
08027   if (!getDerived().AlwaysRebuild() &&
08028       Cond.get() == E->getCond() &&
08029       LHS.get() == E->getLHS() &&
08030       RHS.get() == E->getRHS())
08031     return E;
08032 
08033   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
08034                                         Cond.get(), LHS.get(), RHS.get(),
08035                                         E->getRParenLoc());
08036 }
08037 
08038 template<typename Derived>
08039 ExprResult
08040 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
08041   return E;
08042 }
08043 
08044 template<typename Derived>
08045 ExprResult
08046 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
08047   switch (E->getOperator()) {
08048   case OO_New:
08049   case OO_Delete:
08050   case OO_Array_New:
08051   case OO_Array_Delete:
08052     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
08053 
08054   case OO_Call: {
08055     // This is a call to an object's operator().
08056     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
08057 
08058     // Transform the object itself.
08059     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
08060     if (Object.isInvalid())
08061       return ExprError();
08062 
08063     // FIXME: Poor location information
08064     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
08065         static_cast<Expr *>(Object.get())->getLocEnd());
08066 
08067     // Transform the call arguments.
08068     SmallVector<Expr*, 8> Args;
08069     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
08070                                     Args))
08071       return ExprError();
08072 
08073     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc,
08074                                         Args,
08075                                         E->getLocEnd());
08076   }
08077 
08078 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
08079   case OO_##Name:
08080 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
08081 #include "clang/Basic/OperatorKinds.def"
08082   case OO_Subscript:
08083     // Handled below.
08084     break;
08085 
08086   case OO_Conditional:
08087     llvm_unreachable("conditional operator is not actually overloadable");
08088 
08089   case OO_None:
08090   case NUM_OVERLOADED_OPERATORS:
08091     llvm_unreachable("not an overloaded operator?");
08092   }
08093 
08094   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
08095   if (Callee.isInvalid())
08096     return ExprError();
08097 
08098   ExprResult First;
08099   if (E->getOperator() == OO_Amp)
08100     First = getDerived().TransformAddressOfOperand(E->getArg(0));
08101   else
08102     First = getDerived().TransformExpr(E->getArg(0));
08103   if (First.isInvalid())
08104     return ExprError();
08105 
08106   ExprResult Second;
08107   if (E->getNumArgs() == 2) {
08108     Second = getDerived().TransformExpr(E->getArg(1));
08109     if (Second.isInvalid())
08110       return ExprError();
08111   }
08112 
08113   if (!getDerived().AlwaysRebuild() &&
08114       Callee.get() == E->getCallee() &&
08115       First.get() == E->getArg(0) &&
08116       (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
08117     return SemaRef.MaybeBindToTemporary(E);
08118 
08119   Sema::FPContractStateRAII FPContractState(getSema());
08120   getSema().FPFeatures.fp_contract = E->isFPContractable();
08121 
08122   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
08123                                                  E->getOperatorLoc(),
08124                                                  Callee.get(),
08125                                                  First.get(),
08126                                                  Second.get());
08127 }
08128 
08129 template<typename Derived>
08130 ExprResult
08131 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
08132   return getDerived().TransformCallExpr(E);
08133 }
08134 
08135 template<typename Derived>
08136 ExprResult
08137 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
08138   // Transform the callee.
08139   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
08140   if (Callee.isInvalid())
08141     return ExprError();
08142 
08143   // Transform exec config.
08144   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
08145   if (EC.isInvalid())
08146     return ExprError();
08147 
08148   // Transform arguments.
08149   bool ArgChanged = false;
08150   SmallVector<Expr*, 8> Args;
08151   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
08152                                   &ArgChanged))
08153     return ExprError();
08154 
08155   if (!getDerived().AlwaysRebuild() &&
08156       Callee.get() == E->getCallee() &&
08157       !ArgChanged)
08158     return SemaRef.MaybeBindToTemporary(E);
08159 
08160   // FIXME: Wrong source location information for the '('.
08161   SourceLocation FakeLParenLoc
08162     = ((Expr *)Callee.get())->getSourceRange().getBegin();
08163   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
08164                                       Args,
08165                                       E->getRParenLoc(), EC.get());
08166 }
08167 
08168 template<typename Derived>
08169 ExprResult
08170 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
08171   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
08172   if (!Type)
08173     return ExprError();
08174 
08175   ExprResult SubExpr
08176     = getDerived().TransformExpr(E->getSubExprAsWritten());
08177   if (SubExpr.isInvalid())
08178     return ExprError();
08179 
08180   if (!getDerived().AlwaysRebuild() &&
08181       Type == E->getTypeInfoAsWritten() &&
08182       SubExpr.get() == E->getSubExpr())
08183     return E;
08184   return getDerived().RebuildCXXNamedCastExpr(
08185       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
08186       Type, E->getAngleBrackets().getEnd(),
08187       // FIXME. this should be '(' location
08188       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
08189 }
08190 
08191 template<typename Derived>
08192 ExprResult
08193 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
08194   return getDerived().TransformCXXNamedCastExpr(E);
08195 }
08196 
08197 template<typename Derived>
08198 ExprResult
08199 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
08200   return getDerived().TransformCXXNamedCastExpr(E);
08201 }
08202 
08203 template<typename Derived>
08204 ExprResult
08205 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
08206                                                       CXXReinterpretCastExpr *E) {
08207   return getDerived().TransformCXXNamedCastExpr(E);
08208 }
08209 
08210 template<typename Derived>
08211 ExprResult
08212 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
08213   return getDerived().TransformCXXNamedCastExpr(E);
08214 }
08215 
08216 template<typename Derived>
08217 ExprResult
08218 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
08219                                                      CXXFunctionalCastExpr *E) {
08220   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
08221   if (!Type)
08222     return ExprError();
08223 
08224   ExprResult SubExpr
08225     = getDerived().TransformExpr(E->getSubExprAsWritten());
08226   if (SubExpr.isInvalid())
08227     return ExprError();
08228 
08229   if (!getDerived().AlwaysRebuild() &&
08230       Type == E->getTypeInfoAsWritten() &&
08231       SubExpr.get() == E->getSubExpr())
08232     return E;
08233 
08234   return getDerived().RebuildCXXFunctionalCastExpr(Type,
08235                                                    E->getLParenLoc(),
08236                                                    SubExpr.get(),
08237                                                    E->getRParenLoc());
08238 }
08239 
08240 template<typename Derived>
08241 ExprResult
08242 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
08243   if (E->isTypeOperand()) {
08244     TypeSourceInfo *TInfo
08245       = getDerived().TransformType(E->getTypeOperandSourceInfo());
08246     if (!TInfo)
08247       return ExprError();
08248 
08249     if (!getDerived().AlwaysRebuild() &&
08250         TInfo == E->getTypeOperandSourceInfo())
08251       return E;
08252 
08253     return getDerived().RebuildCXXTypeidExpr(E->getType(),
08254                                              E->getLocStart(),
08255                                              TInfo,
08256                                              E->getLocEnd());
08257   }
08258 
08259   // We don't know whether the subexpression is potentially evaluated until
08260   // after we perform semantic analysis.  We speculatively assume it is
08261   // unevaluated; it will get fixed later if the subexpression is in fact
08262   // potentially evaluated.
08263   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
08264                                                Sema::ReuseLambdaContextDecl);
08265 
08266   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
08267   if (SubExpr.isInvalid())
08268     return ExprError();
08269 
08270   if (!getDerived().AlwaysRebuild() &&
08271       SubExpr.get() == E->getExprOperand())
08272     return E;
08273 
08274   return getDerived().RebuildCXXTypeidExpr(E->getType(),
08275                                            E->getLocStart(),
08276                                            SubExpr.get(),
08277                                            E->getLocEnd());
08278 }
08279 
08280 template<typename Derived>
08281 ExprResult
08282 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
08283   if (E->isTypeOperand()) {
08284     TypeSourceInfo *TInfo
08285       = getDerived().TransformType(E->getTypeOperandSourceInfo());
08286     if (!TInfo)
08287       return ExprError();
08288 
08289     if (!getDerived().AlwaysRebuild() &&
08290         TInfo == E->getTypeOperandSourceInfo())
08291       return E;
08292 
08293     return getDerived().RebuildCXXUuidofExpr(E->getType(),
08294                                              E->getLocStart(),
08295                                              TInfo,
08296                                              E->getLocEnd());
08297   }
08298 
08299   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
08300 
08301   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
08302   if (SubExpr.isInvalid())
08303     return ExprError();
08304 
08305   if (!getDerived().AlwaysRebuild() &&
08306       SubExpr.get() == E->getExprOperand())
08307     return E;
08308 
08309   return getDerived().RebuildCXXUuidofExpr(E->getType(),
08310                                            E->getLocStart(),
08311                                            SubExpr.get(),
08312                                            E->getLocEnd());
08313 }
08314 
08315 template<typename Derived>
08316 ExprResult
08317 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
08318   return E;
08319 }
08320 
08321 template<typename Derived>
08322 ExprResult
08323 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
08324                                                      CXXNullPtrLiteralExpr *E) {
08325   return E;
08326 }
08327 
08328 template<typename Derived>
08329 ExprResult
08330 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
08331   QualType T = getSema().getCurrentThisType();
08332 
08333   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
08334     // Make sure that we capture 'this'.
08335     getSema().CheckCXXThisCapture(E->getLocStart());
08336     return E;
08337   }
08338 
08339   return getDerived().RebuildCXXThisExpr(E->getLocStart(), T, E->isImplicit());
08340 }
08341 
08342 template<typename Derived>
08343 ExprResult
08344 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
08345   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
08346   if (SubExpr.isInvalid())
08347     return ExprError();
08348 
08349   if (!getDerived().AlwaysRebuild() &&
08350       SubExpr.get() == E->getSubExpr())
08351     return E;
08352 
08353   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
08354                                           E->isThrownVariableInScope());
08355 }
08356 
08357 template<typename Derived>
08358 ExprResult
08359 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
08360   ParmVarDecl *Param
08361     = cast_or_null<ParmVarDecl>(getDerived().TransformDecl(E->getLocStart(),
08362                                                            E->getParam()));
08363   if (!Param)
08364     return ExprError();
08365 
08366   if (!getDerived().AlwaysRebuild() &&
08367       Param == E->getParam())
08368     return E;
08369 
08370   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
08371 }
08372 
08373 template<typename Derived>
08374 ExprResult
08375 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
08376   FieldDecl *Field
08377     = cast_or_null<FieldDecl>(getDerived().TransformDecl(E->getLocStart(),
08378                                                          E->getField()));
08379   if (!Field)
08380     return ExprError();
08381 
08382   if (!getDerived().AlwaysRebuild() && Field == E->getField())
08383     return E;
08384 
08385   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
08386 }
08387 
08388 template<typename Derived>
08389 ExprResult
08390 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
08391                                                     CXXScalarValueInitExpr *E) {
08392   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
08393   if (!T)
08394     return ExprError();
08395 
08396   if (!getDerived().AlwaysRebuild() &&
08397       T == E->getTypeSourceInfo())
08398     return E;
08399 
08400   return getDerived().RebuildCXXScalarValueInitExpr(T,
08401                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
08402                                                     E->getRParenLoc());
08403 }
08404 
08405 template<typename Derived>
08406 ExprResult
08407 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
08408   // Transform the type that we're allocating
08409   TypeSourceInfo *AllocTypeInfo
08410     = getDerived().TransformType(E->getAllocatedTypeSourceInfo());
08411   if (!AllocTypeInfo)
08412     return ExprError();
08413 
08414   // Transform the size of the array we're allocating (if any).
08415   ExprResult ArraySize = getDerived().TransformExpr(E->getArraySize());
08416   if (ArraySize.isInvalid())
08417     return ExprError();
08418 
08419   // Transform the placement arguments (if any).
08420   bool ArgumentChanged = false;
08421   SmallVector<Expr*, 8> PlacementArgs;
08422   if (getDerived().TransformExprs(E->getPlacementArgs(),
08423                                   E->getNumPlacementArgs(), true,
08424                                   PlacementArgs, &ArgumentChanged))
08425     return ExprError();
08426 
08427   // Transform the initializer (if any).
08428   Expr *OldInit = E->getInitializer();
08429   ExprResult NewInit;
08430   if (OldInit)
08431     NewInit = getDerived().TransformInitializer(OldInit, true);
08432   if (NewInit.isInvalid())
08433     return ExprError();
08434 
08435   // Transform new operator and delete operator.
08436   FunctionDecl *OperatorNew = nullptr;
08437   if (E->getOperatorNew()) {
08438     OperatorNew = cast_or_null<FunctionDecl>(
08439                                  getDerived().TransformDecl(E->getLocStart(),
08440                                                          E->getOperatorNew()));
08441     if (!OperatorNew)
08442       return ExprError();
08443   }
08444 
08445   FunctionDecl *OperatorDelete = nullptr;
08446   if (E->getOperatorDelete()) {
08447     OperatorDelete = cast_or_null<FunctionDecl>(
08448                                    getDerived().TransformDecl(E->getLocStart(),
08449                                                        E->getOperatorDelete()));
08450     if (!OperatorDelete)
08451       return ExprError();
08452   }
08453 
08454   if (!getDerived().AlwaysRebuild() &&
08455       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
08456       ArraySize.get() == E->getArraySize() &&
08457       NewInit.get() == OldInit &&
08458       OperatorNew == E->getOperatorNew() &&
08459       OperatorDelete == E->getOperatorDelete() &&
08460       !ArgumentChanged) {
08461     // Mark any declarations we need as referenced.
08462     // FIXME: instantiation-specific.
08463     if (OperatorNew)
08464       SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorNew);
08465     if (OperatorDelete)
08466       SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
08467 
08468     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
08469       QualType ElementType
08470         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
08471       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
08472         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
08473         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
08474           SemaRef.MarkFunctionReferenced(E->getLocStart(), Destructor);
08475         }
08476       }
08477     }
08478 
08479     return E;
08480   }
08481 
08482   QualType AllocType = AllocTypeInfo->getType();
08483   if (!ArraySize.get()) {
08484     // If no array size was specified, but the new expression was
08485     // instantiated with an array type (e.g., "new T" where T is
08486     // instantiated with "int[4]"), extract the outer bound from the
08487     // array type as our array size. We do this with constant and
08488     // dependently-sized array types.
08489     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
08490     if (!ArrayT) {
08491       // Do nothing
08492     } else if (const ConstantArrayType *ConsArrayT
08493                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
08494       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
08495                                          SemaRef.Context.getSizeType(),
08496                                          /*FIXME:*/ E->getLocStart());
08497       AllocType = ConsArrayT->getElementType();
08498     } else if (const DependentSizedArrayType *DepArrayT
08499                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
08500       if (DepArrayT->getSizeExpr()) {
08501         ArraySize = DepArrayT->getSizeExpr();
08502         AllocType = DepArrayT->getElementType();
08503       }
08504     }
08505   }
08506 
08507   return getDerived().RebuildCXXNewExpr(E->getLocStart(),
08508                                         E->isGlobalNew(),
08509                                         /*FIXME:*/E->getLocStart(),
08510                                         PlacementArgs,
08511                                         /*FIXME:*/E->getLocStart(),
08512                                         E->getTypeIdParens(),
08513                                         AllocType,
08514                                         AllocTypeInfo,
08515                                         ArraySize.get(),
08516                                         E->getDirectInitRange(),
08517                                         NewInit.get());
08518 }
08519 
08520 template<typename Derived>
08521 ExprResult
08522 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
08523   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
08524   if (Operand.isInvalid())
08525     return ExprError();
08526 
08527   // Transform the delete operator, if known.
08528   FunctionDecl *OperatorDelete = nullptr;
08529   if (E->getOperatorDelete()) {
08530     OperatorDelete = cast_or_null<FunctionDecl>(
08531                                    getDerived().TransformDecl(E->getLocStart(),
08532                                                        E->getOperatorDelete()));
08533     if (!OperatorDelete)
08534       return ExprError();
08535   }
08536 
08537   if (!getDerived().AlwaysRebuild() &&
08538       Operand.get() == E->getArgument() &&
08539       OperatorDelete == E->getOperatorDelete()) {
08540     // Mark any declarations we need as referenced.
08541     // FIXME: instantiation-specific.
08542     if (OperatorDelete)
08543       SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
08544 
08545     if (!E->getArgument()->isTypeDependent()) {
08546       QualType Destroyed = SemaRef.Context.getBaseElementType(
08547                                                          E->getDestroyedType());
08548       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
08549         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
08550         SemaRef.MarkFunctionReferenced(E->getLocStart(),
08551                                        SemaRef.LookupDestructor(Record));
08552       }
08553     }
08554 
08555     return E;
08556   }
08557 
08558   return getDerived().RebuildCXXDeleteExpr(E->getLocStart(),
08559                                            E->isGlobalDelete(),
08560                                            E->isArrayForm(),
08561                                            Operand.get());
08562 }
08563 
08564 template<typename Derived>
08565 ExprResult
08566 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
08567                                                      CXXPseudoDestructorExpr *E) {
08568   ExprResult Base = getDerived().TransformExpr(E->getBase());
08569   if (Base.isInvalid())
08570     return ExprError();
08571 
08572   ParsedType ObjectTypePtr;
08573   bool MayBePseudoDestructor = false;
08574   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
08575                                               E->getOperatorLoc(),
08576                                         E->isArrow()? tok::arrow : tok::period,
08577                                               ObjectTypePtr,
08578                                               MayBePseudoDestructor);
08579   if (Base.isInvalid())
08580     return ExprError();
08581 
08582   QualType ObjectType = ObjectTypePtr.get();
08583   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
08584   if (QualifierLoc) {
08585     QualifierLoc
08586       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
08587     if (!QualifierLoc)
08588       return ExprError();
08589   }
08590   CXXScopeSpec SS;
08591   SS.Adopt(QualifierLoc);
08592 
08593   PseudoDestructorTypeStorage Destroyed;
08594   if (E->getDestroyedTypeInfo()) {
08595     TypeSourceInfo *DestroyedTypeInfo
08596       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
08597                                                 ObjectType, nullptr, SS);
08598     if (!DestroyedTypeInfo)
08599       return ExprError();
08600     Destroyed = DestroyedTypeInfo;
08601   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
08602     // We aren't likely to be able to resolve the identifier down to a type
08603     // now anyway, so just retain the identifier.
08604     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
08605                                             E->getDestroyedTypeLoc());
08606   } else {
08607     // Look for a destructor known with the given name.
08608     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
08609                                               *E->getDestroyedTypeIdentifier(),
08610                                                 E->getDestroyedTypeLoc(),
08611                                                 /*Scope=*/nullptr,
08612                                                 SS, ObjectTypePtr,
08613                                                 false);
08614     if (!T)
08615       return ExprError();
08616 
08617     Destroyed
08618       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
08619                                                  E->getDestroyedTypeLoc());
08620   }
08621 
08622   TypeSourceInfo *ScopeTypeInfo = nullptr;
08623   if (E->getScopeTypeInfo()) {
08624     CXXScopeSpec EmptySS;
08625     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
08626                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
08627     if (!ScopeTypeInfo)
08628       return ExprError();
08629   }
08630 
08631   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
08632                                                      E->getOperatorLoc(),
08633                                                      E->isArrow(),
08634                                                      SS,
08635                                                      ScopeTypeInfo,
08636                                                      E->getColonColonLoc(),
08637                                                      E->getTildeLoc(),
08638                                                      Destroyed);
08639 }
08640 
08641 template<typename Derived>
08642 ExprResult
08643 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
08644                                                   UnresolvedLookupExpr *Old) {
08645   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
08646                  Sema::LookupOrdinaryName);
08647 
08648   // Transform all the decls.
08649   for (UnresolvedLookupExpr::decls_iterator I = Old->decls_begin(),
08650          E = Old->decls_end(); I != E; ++I) {
08651     NamedDecl *InstD = static_cast<NamedDecl*>(
08652                                  getDerived().TransformDecl(Old->getNameLoc(),
08653                                                             *I));
08654     if (!InstD) {
08655       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
08656       // This can happen because of dependent hiding.
08657       if (isa<UsingShadowDecl>(*I))
08658         continue;
08659       else {
08660         R.clear();
08661         return ExprError();
08662       }
08663     }
08664 
08665     // Expand using declarations.
08666     if (isa<UsingDecl>(InstD)) {
08667       UsingDecl *UD = cast<UsingDecl>(InstD);
08668       for (auto *I : UD->shadows())
08669         R.addDecl(I);
08670       continue;
08671     }
08672 
08673     R.addDecl(InstD);
08674   }
08675 
08676   // Resolve a kind, but don't do any further analysis.  If it's
08677   // ambiguous, the callee needs to deal with it.
08678   R.resolveKind();
08679 
08680   // Rebuild the nested-name qualifier, if present.
08681   CXXScopeSpec SS;
08682   if (Old->getQualifierLoc()) {
08683     NestedNameSpecifierLoc QualifierLoc
08684       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
08685     if (!QualifierLoc)
08686       return ExprError();
08687 
08688     SS.Adopt(QualifierLoc);
08689   }
08690 
08691   if (Old->getNamingClass()) {
08692     CXXRecordDecl *NamingClass
08693       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
08694                                                             Old->getNameLoc(),
08695                                                         Old->getNamingClass()));
08696     if (!NamingClass) {
08697       R.clear();
08698       return ExprError();
08699     }
08700 
08701     R.setNamingClass(NamingClass);
08702   }
08703 
08704   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
08705 
08706   // If we have neither explicit template arguments, nor the template keyword,
08707   // it's a normal declaration name.
08708   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid())
08709     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
08710 
08711   // If we have template arguments, rebuild them, then rebuild the
08712   // templateid expression.
08713   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
08714   if (Old->hasExplicitTemplateArgs() &&
08715       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
08716                                               Old->getNumTemplateArgs(),
08717                                               TransArgs)) {
08718     R.clear();
08719     return ExprError();
08720   }
08721 
08722   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
08723                                             Old->requiresADL(), &TransArgs);
08724 }
08725 
08726 template<typename Derived>
08727 ExprResult
08728 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
08729   bool ArgChanged = false;
08730   SmallVector<TypeSourceInfo *, 4> Args;
08731   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
08732     TypeSourceInfo *From = E->getArg(I);
08733     TypeLoc FromTL = From->getTypeLoc();
08734     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
08735       TypeLocBuilder TLB;
08736       TLB.reserve(FromTL.getFullDataSize());
08737       QualType To = getDerived().TransformType(TLB, FromTL);
08738       if (To.isNull())
08739         return ExprError();
08740 
08741       if (To == From->getType())
08742         Args.push_back(From);
08743       else {
08744         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
08745         ArgChanged = true;
08746       }
08747       continue;
08748     }
08749 
08750     ArgChanged = true;
08751 
08752     // We have a pack expansion. Instantiate it.
08753     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
08754     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
08755     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
08756     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
08757 
08758     // Determine whether the set of unexpanded parameter packs can and should
08759     // be expanded.
08760     bool Expand = true;
08761     bool RetainExpansion = false;
08762     Optional<unsigned> OrigNumExpansions =
08763         ExpansionTL.getTypePtr()->getNumExpansions();
08764     Optional<unsigned> NumExpansions = OrigNumExpansions;
08765     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
08766                                              PatternTL.getSourceRange(),
08767                                              Unexpanded,
08768                                              Expand, RetainExpansion,
08769                                              NumExpansions))
08770       return ExprError();
08771 
08772     if (!Expand) {
08773       // The transform has determined that we should perform a simple
08774       // transformation on the pack expansion, producing another pack
08775       // expansion.
08776       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
08777 
08778       TypeLocBuilder TLB;
08779       TLB.reserve(From->getTypeLoc().getFullDataSize());
08780 
08781       QualType To = getDerived().TransformType(TLB, PatternTL);
08782       if (To.isNull())
08783         return ExprError();
08784 
08785       To = getDerived().RebuildPackExpansionType(To,
08786                                                  PatternTL.getSourceRange(),
08787                                                  ExpansionTL.getEllipsisLoc(),
08788                                                  NumExpansions);
08789       if (To.isNull())
08790         return ExprError();
08791 
08792       PackExpansionTypeLoc ToExpansionTL
08793         = TLB.push<PackExpansionTypeLoc>(To);
08794       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
08795       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
08796       continue;
08797     }
08798 
08799     // Expand the pack expansion by substituting for each argument in the
08800     // pack(s).
08801     for (unsigned I = 0; I != *NumExpansions; ++I) {
08802       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
08803       TypeLocBuilder TLB;
08804       TLB.reserve(PatternTL.getFullDataSize());
08805       QualType To = getDerived().TransformType(TLB, PatternTL);
08806       if (To.isNull())
08807         return ExprError();
08808 
08809       if (To->containsUnexpandedParameterPack()) {
08810         To = getDerived().RebuildPackExpansionType(To,
08811                                                    PatternTL.getSourceRange(),
08812                                                    ExpansionTL.getEllipsisLoc(),
08813                                                    NumExpansions);
08814         if (To.isNull())
08815           return ExprError();
08816 
08817         PackExpansionTypeLoc ToExpansionTL
08818           = TLB.push<PackExpansionTypeLoc>(To);
08819         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
08820       }
08821 
08822       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
08823     }
08824 
08825     if (!RetainExpansion)
08826       continue;
08827 
08828     // If we're supposed to retain a pack expansion, do so by temporarily
08829     // forgetting the partially-substituted parameter pack.
08830     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
08831 
08832     TypeLocBuilder TLB;
08833     TLB.reserve(From->getTypeLoc().getFullDataSize());
08834 
08835     QualType To = getDerived().TransformType(TLB, PatternTL);
08836     if (To.isNull())
08837       return ExprError();
08838 
08839     To = getDerived().RebuildPackExpansionType(To,
08840                                                PatternTL.getSourceRange(),
08841                                                ExpansionTL.getEllipsisLoc(),
08842                                                NumExpansions);
08843     if (To.isNull())
08844       return ExprError();
08845 
08846     PackExpansionTypeLoc ToExpansionTL
08847       = TLB.push<PackExpansionTypeLoc>(To);
08848     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
08849     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
08850   }
08851 
08852   if (!getDerived().AlwaysRebuild() && !ArgChanged)
08853     return E;
08854 
08855   return getDerived().RebuildTypeTrait(E->getTrait(),
08856                                        E->getLocStart(),
08857                                        Args,
08858                                        E->getLocEnd());
08859 }
08860 
08861 template<typename Derived>
08862 ExprResult
08863 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
08864   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
08865   if (!T)
08866     return ExprError();
08867 
08868   if (!getDerived().AlwaysRebuild() &&
08869       T == E->getQueriedTypeSourceInfo())
08870     return E;
08871 
08872   ExprResult SubExpr;
08873   {
08874     EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
08875     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
08876     if (SubExpr.isInvalid())
08877       return ExprError();
08878 
08879     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
08880       return E;
08881   }
08882 
08883   return getDerived().RebuildArrayTypeTrait(E->getTrait(),
08884                                             E->getLocStart(),
08885                                             T,
08886                                             SubExpr.get(),
08887                                             E->getLocEnd());
08888 }
08889 
08890 template<typename Derived>
08891 ExprResult
08892 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
08893   ExprResult SubExpr;
08894   {
08895     EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
08896     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
08897     if (SubExpr.isInvalid())
08898       return ExprError();
08899 
08900     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
08901       return E;
08902   }
08903 
08904   return getDerived().RebuildExpressionTrait(
08905       E->getTrait(), E->getLocStart(), SubExpr.get(), E->getLocEnd());
08906 }
08907 
08908 template <typename Derived>
08909 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
08910     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
08911     TypeSourceInfo **RecoveryTSI) {
08912   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
08913       DRE, AddrTaken, RecoveryTSI);
08914 
08915   // Propagate both errors and recovered types, which return ExprEmpty.
08916   if (!NewDRE.isUsable())
08917     return NewDRE;
08918 
08919   // We got an expr, wrap it up in parens.
08920   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
08921     return PE;
08922   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
08923                                        PE->getRParen());
08924 }
08925 
08926 template <typename Derived>
08927 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
08928     DependentScopeDeclRefExpr *E) {
08929   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
08930                                             nullptr);
08931 }
08932 
08933 template<typename Derived>
08934 ExprResult
08935 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
08936                                                DependentScopeDeclRefExpr *E,
08937                                                bool IsAddressOfOperand,
08938                                                TypeSourceInfo **RecoveryTSI) {
08939   assert(E->getQualifierLoc());
08940   NestedNameSpecifierLoc QualifierLoc
08941   = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
08942   if (!QualifierLoc)
08943     return ExprError();
08944   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
08945 
08946   // TODO: If this is a conversion-function-id, verify that the
08947   // destination type name (if present) resolves the same way after
08948   // instantiation as it did in the local scope.
08949 
08950   DeclarationNameInfo NameInfo
08951     = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
08952   if (!NameInfo.getName())
08953     return ExprError();
08954 
08955   if (!E->hasExplicitTemplateArgs()) {
08956     if (!getDerived().AlwaysRebuild() &&
08957         QualifierLoc == E->getQualifierLoc() &&
08958         // Note: it is sufficient to compare the Name component of NameInfo:
08959         // if name has not changed, DNLoc has not changed either.
08960         NameInfo.getName() == E->getDeclName())
08961       return E;
08962 
08963     return getDerived().RebuildDependentScopeDeclRefExpr(
08964         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
08965         IsAddressOfOperand, RecoveryTSI);
08966   }
08967 
08968   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
08969   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
08970                                               E->getNumTemplateArgs(),
08971                                               TransArgs))
08972     return ExprError();
08973 
08974   return getDerived().RebuildDependentScopeDeclRefExpr(
08975       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
08976       RecoveryTSI);
08977 }
08978 
08979 template<typename Derived>
08980 ExprResult
08981 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
08982   // CXXConstructExprs other than for list-initialization and
08983   // CXXTemporaryObjectExpr are always implicit, so when we have
08984   // a 1-argument construction we just transform that argument.
08985   if ((E->getNumArgs() == 1 ||
08986        (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
08987       (!getDerived().DropCallArgument(E->getArg(0))) &&
08988       !E->isListInitialization())
08989     return getDerived().TransformExpr(E->getArg(0));
08990 
08991   TemporaryBase Rebase(*this, /*FIXME*/E->getLocStart(), DeclarationName());
08992 
08993   QualType T = getDerived().TransformType(E->getType());
08994   if (T.isNull())
08995     return ExprError();
08996 
08997   CXXConstructorDecl *Constructor
08998     = cast_or_null<CXXConstructorDecl>(
08999                                 getDerived().TransformDecl(E->getLocStart(),
09000                                                          E->getConstructor()));
09001   if (!Constructor)
09002     return ExprError();
09003 
09004   bool ArgumentChanged = false;
09005   SmallVector<Expr*, 8> Args;
09006   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
09007                                   &ArgumentChanged))
09008     return ExprError();
09009 
09010   if (!getDerived().AlwaysRebuild() &&
09011       T == E->getType() &&
09012       Constructor == E->getConstructor() &&
09013       !ArgumentChanged) {
09014     // Mark the constructor as referenced.
09015     // FIXME: Instantiation-specific
09016     SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
09017     return E;
09018   }
09019 
09020   return getDerived().RebuildCXXConstructExpr(T, /*FIXME:*/E->getLocStart(),
09021                                               Constructor, E->isElidable(),
09022                                               Args,
09023                                               E->hadMultipleCandidates(),
09024                                               E->isListInitialization(),
09025                                               E->isStdInitListInitialization(),
09026                                               E->requiresZeroInitialization(),
09027                                               E->getConstructionKind(),
09028                                               E->getParenOrBraceRange());
09029 }
09030 
09031 /// \brief Transform a C++ temporary-binding expression.
09032 ///
09033 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
09034 /// transform the subexpression and return that.
09035 template<typename Derived>
09036 ExprResult
09037 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
09038   return getDerived().TransformExpr(E->getSubExpr());
09039 }
09040 
09041 /// \brief Transform a C++ expression that contains cleanups that should
09042 /// be run after the expression is evaluated.
09043 ///
09044 /// Since ExprWithCleanups nodes are implicitly generated, we
09045 /// just transform the subexpression and return that.
09046 template<typename Derived>
09047 ExprResult
09048 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
09049   return getDerived().TransformExpr(E->getSubExpr());
09050 }
09051 
09052 template<typename Derived>
09053 ExprResult
09054 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
09055                                                     CXXTemporaryObjectExpr *E) {
09056   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
09057   if (!T)
09058     return ExprError();
09059 
09060   CXXConstructorDecl *Constructor
09061     = cast_or_null<CXXConstructorDecl>(
09062                                   getDerived().TransformDecl(E->getLocStart(),
09063                                                          E->getConstructor()));
09064   if (!Constructor)
09065     return ExprError();
09066 
09067   bool ArgumentChanged = false;
09068   SmallVector<Expr*, 8> Args;
09069   Args.reserve(E->getNumArgs());
09070   if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
09071                      &ArgumentChanged))
09072     return ExprError();
09073 
09074   if (!getDerived().AlwaysRebuild() &&
09075       T == E->getTypeSourceInfo() &&
09076       Constructor == E->getConstructor() &&
09077       !ArgumentChanged) {
09078     // FIXME: Instantiation-specific
09079     SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
09080     return SemaRef.MaybeBindToTemporary(E);
09081   }
09082 
09083   // FIXME: Pass in E->isListInitialization().
09084   return getDerived().RebuildCXXTemporaryObjectExpr(T,
09085                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
09086                                                     Args,
09087                                                     E->getLocEnd());
09088 }
09089 
09090 template<typename Derived>
09091 ExprResult
09092 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
09093    
09094   // Transform any init-capture expressions before entering the scope of the 
09095   // lambda body, because they are not semantically within that scope.
09096   SmallVector<InitCaptureInfoTy, 8> InitCaptureExprsAndTypes;
09097   InitCaptureExprsAndTypes.resize(E->explicit_capture_end() -
09098       E->explicit_capture_begin());
09099   
09100   for (LambdaExpr::capture_iterator C = E->capture_begin(),
09101       CEnd = E->capture_end();
09102       C != CEnd; ++C) {
09103     if (!C->isInitCapture())
09104       continue;
09105     EnterExpressionEvaluationContext  EEEC(getSema(), 
09106         Sema::PotentiallyEvaluated);    
09107     ExprResult NewExprInitResult = getDerived().TransformInitializer(
09108         C->getCapturedVar()->getInit(),
09109         C->getCapturedVar()->getInitStyle() == VarDecl::CallInit);
09110     
09111     if (NewExprInitResult.isInvalid())
09112       return ExprError();
09113     Expr *NewExprInit = NewExprInitResult.get();
09114       
09115     VarDecl *OldVD = C->getCapturedVar();
09116     QualType NewInitCaptureType = 
09117         getSema().performLambdaInitCaptureInitialization(C->getLocation(), 
09118             OldVD->getType()->isReferenceType(), OldVD->getIdentifier(), 
09119             NewExprInit);
09120     NewExprInitResult = NewExprInit;
09121     InitCaptureExprsAndTypes[C - E->capture_begin()] =
09122         std::make_pair(NewExprInitResult, NewInitCaptureType);
09123 
09124   }
09125 
09126   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
09127   // Transform the template parameters, and add them to the current
09128   // instantiation scope. The null case is handled correctly.
09129   LSI->GLTemplateParameterList = getDerived().TransformTemplateParameterList(
09130       E->getTemplateParameterList());
09131 
09132   // Check to see if the TypeSourceInfo of the call operator needs to
09133   // be transformed, and if so do the transformation in the 
09134   // CurrentInstantiationScope.
09135 
09136   TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
09137   FunctionProtoTypeLoc OldCallOpFPTL = 
09138       OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
09139   TypeSourceInfo *NewCallOpTSI = nullptr;
09140 
09141   const bool CallOpWasAlreadyTransformed = 
09142       getDerived().AlreadyTransformed(OldCallOpTSI->getType()); 
09143   
09144   // Use the Old Call Operator's TypeSourceInfo if it is already transformed.
09145   if (CallOpWasAlreadyTransformed)  
09146     NewCallOpTSI = OldCallOpTSI;  
09147   else {
09148     // Transform the TypeSourceInfo of the Original Lambda's Call Operator.
09149     // The transformation MUST be done in the CurrentInstantiationScope since
09150     // it introduces a mapping of the original to the newly created 
09151     // transformed parameters.
09152 
09153     TypeLocBuilder NewCallOpTLBuilder;
09154     SmallVector<QualType, 4> ExceptionStorage;
09155     TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
09156     QualType NewCallOpType = TransformFunctionProtoType(
09157         NewCallOpTLBuilder, OldCallOpFPTL, nullptr, 0,
09158         [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
09159           return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
09160                                               ExceptionStorage, Changed);
09161         });
09162     NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
09163                                                         NewCallOpType);
09164   }
09165   // Extract the ParmVarDecls from the NewCallOpTSI and add them to
09166   // the vector below - this will be used to synthesize the 
09167   // NewCallOperator.  Additionally, add the parameters of the untransformed 
09168   // lambda call operator to the CurrentInstantiationScope.
09169   SmallVector<ParmVarDecl *, 4> Params;  
09170   {
09171     FunctionProtoTypeLoc NewCallOpFPTL = 
09172         NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
09173     ParmVarDecl **NewParamDeclArray = NewCallOpFPTL.getParmArray();
09174     const unsigned NewNumArgs = NewCallOpFPTL.getNumParams();
09175 
09176     for (unsigned I = 0; I < NewNumArgs; ++I) {
09177       // If this call operator's type does not require transformation, 
09178       // the parameters do not get added to the current instantiation scope, 
09179       // - so ADD them! This allows the following to compile when the enclosing
09180       // template is specialized and the entire lambda expression has to be
09181       // transformed. 
09182       // template<class T> void foo(T t) {
09183       //   auto L = [](auto a) {
09184       //       auto M = [](char b) { <-- note: non-generic lambda
09185       //         auto N = [](auto c) {
09186       //            int x = sizeof(a);
09187       //            x = sizeof(b); <-- specifically this line
09188       //            x = sizeof(c);
09189       //          };
09190       //        };
09191       //      };
09192       //    }
09193       // foo('a')
09194       if (CallOpWasAlreadyTransformed)
09195         getDerived().transformedLocalDecl(NewParamDeclArray[I],
09196                                           NewParamDeclArray[I]);
09197       // Add to Params array, so these parameters can be used to create
09198       // the newly transformed call operator.
09199       Params.push_back(NewParamDeclArray[I]);
09200     }
09201   }
09202 
09203   if (!NewCallOpTSI)
09204     return ExprError();
09205 
09206   // Create the local class that will describe the lambda.
09207   CXXRecordDecl *Class
09208     = getSema().createLambdaClosureType(E->getIntroducerRange(),
09209                                         NewCallOpTSI,
09210                                         /*KnownDependent=*/false,
09211                                         E->getCaptureDefault());
09212 
09213   getDerived().transformedLocalDecl(E->getLambdaClass(), Class);
09214 
09215   // Build the call operator.
09216   CXXMethodDecl *NewCallOperator
09217     = getSema().startLambdaDefinition(Class, E->getIntroducerRange(),
09218                                       NewCallOpTSI,
09219                                       E->getCallOperator()->getLocEnd(),
09220                                       Params);
09221   LSI->CallOperator = NewCallOperator;
09222 
09223   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
09224 
09225   return getDerived().TransformLambdaScope(E, NewCallOperator, 
09226       InitCaptureExprsAndTypes);
09227 }
09228 
09229 template<typename Derived>
09230 ExprResult
09231 TreeTransform<Derived>::TransformLambdaScope(LambdaExpr *E,
09232     CXXMethodDecl *CallOperator, 
09233     ArrayRef<InitCaptureInfoTy> InitCaptureExprsAndTypes) {
09234   bool Invalid = false;
09235 
09236   // Introduce the context of the call operator.
09237   Sema::ContextRAII SavedContext(getSema(), CallOperator,
09238                                  /*NewThisContext*/false);
09239 
09240   LambdaScopeInfo *const LSI = getSema().getCurLambda();
09241   // Enter the scope of the lambda.
09242   getSema().buildLambdaScope(LSI, CallOperator, E->getIntroducerRange(),
09243                                  E->getCaptureDefault(),
09244                                  E->getCaptureDefaultLoc(),
09245                                  E->hasExplicitParameters(),
09246                                  E->hasExplicitResultType(),
09247                                  E->isMutable());
09248 
09249   // Transform captures.
09250   bool FinishedExplicitCaptures = false;
09251   for (LambdaExpr::capture_iterator C = E->capture_begin(),
09252                                  CEnd = E->capture_end();
09253        C != CEnd; ++C) {
09254     // When we hit the first implicit capture, tell Sema that we've finished
09255     // the list of explicit captures.
09256     if (!FinishedExplicitCaptures && C->isImplicit()) {
09257       getSema().finishLambdaExplicitCaptures(LSI);
09258       FinishedExplicitCaptures = true;
09259     }
09260 
09261     // Capturing 'this' is trivial.
09262     if (C->capturesThis()) {
09263       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit());
09264       continue;
09265     }
09266     // Captured expression will be recaptured during captured variables
09267     // rebuilding.
09268     if (C->capturesVLAType())
09269       continue;
09270 
09271     // Rebuild init-captures, including the implied field declaration.
09272     if (C->isInitCapture()) {
09273       
09274       InitCaptureInfoTy InitExprTypePair = 
09275           InitCaptureExprsAndTypes[C - E->capture_begin()];
09276       ExprResult Init = InitExprTypePair.first;
09277       QualType InitQualType = InitExprTypePair.second;
09278       if (Init.isInvalid() || InitQualType.isNull()) {
09279         Invalid = true;
09280         continue;
09281       }
09282       VarDecl *OldVD = C->getCapturedVar();
09283       VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
09284           OldVD->getLocation(), InitExprTypePair.second, 
09285           OldVD->getIdentifier(), Init.get());
09286       if (!NewVD)
09287         Invalid = true;
09288       else {
09289         getDerived().transformedLocalDecl(OldVD, NewVD);
09290       }
09291       getSema().buildInitCaptureField(LSI, NewVD);
09292       continue;
09293     }
09294 
09295     assert(C->capturesVariable() && "unexpected kind of lambda capture");
09296 
09297     // Determine the capture kind for Sema.
09298     Sema::TryCaptureKind Kind
09299       = C->isImplicit()? Sema::TryCapture_Implicit
09300                        : C->getCaptureKind() == LCK_ByCopy
09301                            ? Sema::TryCapture_ExplicitByVal
09302                            : Sema::TryCapture_ExplicitByRef;
09303     SourceLocation EllipsisLoc;
09304     if (C->isPackExpansion()) {
09305       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
09306       bool ShouldExpand = false;
09307       bool RetainExpansion = false;
09308       Optional<unsigned> NumExpansions;
09309       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
09310                                                C->getLocation(),
09311                                                Unexpanded,
09312                                                ShouldExpand, RetainExpansion,
09313                                                NumExpansions)) {
09314         Invalid = true;
09315         continue;
09316       }
09317 
09318       if (ShouldExpand) {
09319         // The transform has determined that we should perform an expansion;
09320         // transform and capture each of the arguments.
09321         // expansion of the pattern. Do so.
09322         VarDecl *Pack = C->getCapturedVar();
09323         for (unsigned I = 0; I != *NumExpansions; ++I) {
09324           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
09325           VarDecl *CapturedVar
09326             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
09327                                                                Pack));
09328           if (!CapturedVar) {
09329             Invalid = true;
09330             continue;
09331           }
09332 
09333           // Capture the transformed variable.
09334           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
09335         }
09336 
09337         // FIXME: Retain a pack expansion if RetainExpansion is true.
09338 
09339         continue;
09340       }
09341 
09342       EllipsisLoc = C->getEllipsisLoc();
09343     }
09344 
09345     // Transform the captured variable.
09346     VarDecl *CapturedVar
09347       = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
09348                                                          C->getCapturedVar()));
09349     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
09350       Invalid = true;
09351       continue;
09352     }
09353 
09354     // Capture the transformed variable.
09355     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
09356   }
09357   if (!FinishedExplicitCaptures)
09358     getSema().finishLambdaExplicitCaptures(LSI);
09359 
09360 
09361   // Enter a new evaluation context to insulate the lambda from any
09362   // cleanups from the enclosing full-expression.
09363   getSema().PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
09364 
09365   if (Invalid) {
09366     getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/nullptr,
09367                                /*IsInstantiation=*/true);
09368     return ExprError();
09369   }
09370 
09371   // Instantiate the body of the lambda expression.
09372   StmtResult Body = getDerived().TransformStmt(E->getBody());
09373   if (Body.isInvalid()) {
09374     getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/nullptr,
09375                                /*IsInstantiation=*/true);
09376     return ExprError();
09377   }
09378 
09379   return getSema().ActOnLambdaExpr(E->getLocStart(), Body.get(),
09380                                    /*CurScope=*/nullptr,
09381                                    /*IsInstantiation=*/true);
09382 }
09383 
09384 template<typename Derived>
09385 ExprResult
09386 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
09387                                                   CXXUnresolvedConstructExpr *E) {
09388   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
09389   if (!T)
09390     return ExprError();
09391 
09392   bool ArgumentChanged = false;
09393   SmallVector<Expr*, 8> Args;
09394   Args.reserve(E->arg_size());
09395   if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
09396                                   &ArgumentChanged))
09397     return ExprError();
09398 
09399   if (!getDerived().AlwaysRebuild() &&
09400       T == E->getTypeSourceInfo() &&
09401       !ArgumentChanged)
09402     return E;
09403 
09404   // FIXME: we're faking the locations of the commas
09405   return getDerived().RebuildCXXUnresolvedConstructExpr(T,
09406                                                         E->getLParenLoc(),
09407                                                         Args,
09408                                                         E->getRParenLoc());
09409 }
09410 
09411 template<typename Derived>
09412 ExprResult
09413 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
09414                                              CXXDependentScopeMemberExpr *E) {
09415   // Transform the base of the expression.
09416   ExprResult Base((Expr*) nullptr);
09417   Expr *OldBase;
09418   QualType BaseType;
09419   QualType ObjectType;
09420   if (!E->isImplicitAccess()) {
09421     OldBase = E->getBase();
09422     Base = getDerived().TransformExpr(OldBase);
09423     if (Base.isInvalid())
09424       return ExprError();
09425 
09426     // Start the member reference and compute the object's type.
09427     ParsedType ObjectTy;
09428     bool MayBePseudoDestructor = false;
09429     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
09430                                                 E->getOperatorLoc(),
09431                                       E->isArrow()? tok::arrow : tok::period,
09432                                                 ObjectTy,
09433                                                 MayBePseudoDestructor);
09434     if (Base.isInvalid())
09435       return ExprError();
09436 
09437     ObjectType = ObjectTy.get();
09438     BaseType = ((Expr*) Base.get())->getType();
09439   } else {
09440     OldBase = nullptr;
09441     BaseType = getDerived().TransformType(E->getBaseType());
09442     ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
09443   }
09444 
09445   // Transform the first part of the nested-name-specifier that qualifies
09446   // the member name.
09447   NamedDecl *FirstQualifierInScope
09448     = getDerived().TransformFirstQualifierInScope(
09449                                             E->getFirstQualifierFoundInScope(),
09450                                             E->getQualifierLoc().getBeginLoc());
09451 
09452   NestedNameSpecifierLoc QualifierLoc;
09453   if (E->getQualifier()) {
09454     QualifierLoc
09455       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
09456                                                      ObjectType,
09457                                                      FirstQualifierInScope);
09458     if (!QualifierLoc)
09459       return ExprError();
09460   }
09461 
09462   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
09463 
09464   // TODO: If this is a conversion-function-id, verify that the
09465   // destination type name (if present) resolves the same way after
09466   // instantiation as it did in the local scope.
09467 
09468   DeclarationNameInfo NameInfo
09469     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
09470   if (!NameInfo.getName())
09471     return ExprError();
09472 
09473   if (!E->hasExplicitTemplateArgs()) {
09474     // This is a reference to a member without an explicitly-specified
09475     // template argument list. Optimize for this common case.
09476     if (!getDerived().AlwaysRebuild() &&
09477         Base.get() == OldBase &&
09478         BaseType == E->getBaseType() &&
09479         QualifierLoc == E->getQualifierLoc() &&
09480         NameInfo.getName() == E->getMember() &&
09481         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
09482       return E;
09483 
09484     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
09485                                                        BaseType,
09486                                                        E->isArrow(),
09487                                                        E->getOperatorLoc(),
09488                                                        QualifierLoc,
09489                                                        TemplateKWLoc,
09490                                                        FirstQualifierInScope,
09491                                                        NameInfo,
09492                                                        /*TemplateArgs*/nullptr);
09493   }
09494 
09495   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
09496   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
09497                                               E->getNumTemplateArgs(),
09498                                               TransArgs))
09499     return ExprError();
09500 
09501   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
09502                                                      BaseType,
09503                                                      E->isArrow(),
09504                                                      E->getOperatorLoc(),
09505                                                      QualifierLoc,
09506                                                      TemplateKWLoc,
09507                                                      FirstQualifierInScope,
09508                                                      NameInfo,
09509                                                      &TransArgs);
09510 }
09511 
09512 template<typename Derived>
09513 ExprResult
09514 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
09515   // Transform the base of the expression.
09516   ExprResult Base((Expr*) nullptr);
09517   QualType BaseType;
09518   if (!Old->isImplicitAccess()) {
09519     Base = getDerived().TransformExpr(Old->getBase());
09520     if (Base.isInvalid())
09521       return ExprError();
09522     Base = getSema().PerformMemberExprBaseConversion(Base.get(),
09523                                                      Old->isArrow());
09524     if (Base.isInvalid())
09525       return ExprError();
09526     BaseType = Base.get()->getType();
09527   } else {
09528     BaseType = getDerived().TransformType(Old->getBaseType());
09529   }
09530 
09531   NestedNameSpecifierLoc QualifierLoc;
09532   if (Old->getQualifierLoc()) {
09533     QualifierLoc
09534     = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
09535     if (!QualifierLoc)
09536       return ExprError();
09537   }
09538 
09539   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
09540 
09541   LookupResult R(SemaRef, Old->getMemberNameInfo(),
09542                  Sema::LookupOrdinaryName);
09543 
09544   // Transform all the decls.
09545   for (UnresolvedMemberExpr::decls_iterator I = Old->decls_begin(),
09546          E = Old->decls_end(); I != E; ++I) {
09547     NamedDecl *InstD = static_cast<NamedDecl*>(
09548                                 getDerived().TransformDecl(Old->getMemberLoc(),
09549                                                            *I));
09550     if (!InstD) {
09551       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
09552       // This can happen because of dependent hiding.
09553       if (isa<UsingShadowDecl>(*I))
09554         continue;
09555       else {
09556         R.clear();
09557         return ExprError();
09558       }
09559     }
09560 
09561     // Expand using declarations.
09562     if (isa<UsingDecl>(InstD)) {
09563       UsingDecl *UD = cast<UsingDecl>(InstD);
09564       for (auto *I : UD->shadows())
09565         R.addDecl(I);
09566       continue;
09567     }
09568 
09569     R.addDecl(InstD);
09570   }
09571 
09572   R.resolveKind();
09573 
09574   // Determine the naming class.
09575   if (Old->getNamingClass()) {
09576     CXXRecordDecl *NamingClass
09577       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
09578                                                           Old->getMemberLoc(),
09579                                                         Old->getNamingClass()));
09580     if (!NamingClass)
09581       return ExprError();
09582 
09583     R.setNamingClass(NamingClass);
09584   }
09585 
09586   TemplateArgumentListInfo TransArgs;
09587   if (Old->hasExplicitTemplateArgs()) {
09588     TransArgs.setLAngleLoc(Old->getLAngleLoc());
09589     TransArgs.setRAngleLoc(Old->getRAngleLoc());
09590     if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
09591                                                 Old->getNumTemplateArgs(),
09592                                                 TransArgs))
09593       return ExprError();
09594   }
09595 
09596   // FIXME: to do this check properly, we will need to preserve the
09597   // first-qualifier-in-scope here, just in case we had a dependent
09598   // base (and therefore couldn't do the check) and a
09599   // nested-name-qualifier (and therefore could do the lookup).
09600   NamedDecl *FirstQualifierInScope = nullptr;
09601 
09602   return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
09603                                                   BaseType,
09604                                                   Old->getOperatorLoc(),
09605                                                   Old->isArrow(),
09606                                                   QualifierLoc,
09607                                                   TemplateKWLoc,
09608                                                   FirstQualifierInScope,
09609                                                   R,
09610                                               (Old->hasExplicitTemplateArgs()
09611                                                   ? &TransArgs : nullptr));
09612 }
09613 
09614 template<typename Derived>
09615 ExprResult
09616 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
09617   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
09618   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
09619   if (SubExpr.isInvalid())
09620     return ExprError();
09621 
09622   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
09623     return E;
09624 
09625   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
09626 }
09627 
09628 template<typename Derived>
09629 ExprResult
09630 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
09631   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
09632   if (Pattern.isInvalid())
09633     return ExprError();
09634 
09635   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
09636     return E;
09637 
09638   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
09639                                            E->getNumExpansions());
09640 }
09641 
09642 template<typename Derived>
09643 ExprResult
09644 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
09645   // If E is not value-dependent, then nothing will change when we transform it.
09646   // Note: This is an instantiation-centric view.
09647   if (!E->isValueDependent())
09648     return E;
09649 
09650   // Note: None of the implementations of TryExpandParameterPacks can ever
09651   // produce a diagnostic when given only a single unexpanded parameter pack,
09652   // so
09653   UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
09654   bool ShouldExpand = false;
09655   bool RetainExpansion = false;
09656   Optional<unsigned> NumExpansions;
09657   if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
09658                                            Unexpanded,
09659                                            ShouldExpand, RetainExpansion,
09660                                            NumExpansions))
09661     return ExprError();
09662 
09663   if (RetainExpansion)
09664     return E;
09665 
09666   NamedDecl *Pack = E->getPack();
09667   if (!ShouldExpand) {
09668     Pack = cast_or_null<NamedDecl>(getDerived().TransformDecl(E->getPackLoc(),
09669                                                               Pack));
09670     if (!Pack)
09671       return ExprError();
09672   }
09673 
09674 
09675   // We now know the length of the parameter pack, so build a new expression
09676   // that stores that length.
09677   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
09678                                             E->getPackLoc(), E->getRParenLoc(),
09679                                             NumExpansions);
09680 }
09681 
09682 template<typename Derived>
09683 ExprResult
09684 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
09685                                           SubstNonTypeTemplateParmPackExpr *E) {
09686   // Default behavior is to do nothing with this transformation.
09687   return E;
09688 }
09689 
09690 template<typename Derived>
09691 ExprResult
09692 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
09693                                           SubstNonTypeTemplateParmExpr *E) {
09694   // Default behavior is to do nothing with this transformation.
09695   return E;
09696 }
09697 
09698 template<typename Derived>
09699 ExprResult
09700 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
09701   // Default behavior is to do nothing with this transformation.
09702   return E;
09703 }
09704 
09705 template<typename Derived>
09706 ExprResult
09707 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
09708                                                   MaterializeTemporaryExpr *E) {
09709   return getDerived().TransformExpr(E->GetTemporaryExpr());
09710 }
09711 
09712 template<typename Derived>
09713 ExprResult
09714 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
09715   Expr *Pattern = E->getPattern();
09716 
09717   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
09718   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
09719   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
09720 
09721   // Determine whether the set of unexpanded parameter packs can and should
09722   // be expanded.
09723   bool Expand = true;
09724   bool RetainExpansion = false;
09725   Optional<unsigned> NumExpansions;
09726   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
09727                                            Pattern->getSourceRange(),
09728                                            Unexpanded,
09729                                            Expand, RetainExpansion,
09730                                            NumExpansions))
09731     return true;
09732 
09733   if (!Expand) {
09734     // Do not expand any packs here, just transform and rebuild a fold
09735     // expression.
09736     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
09737 
09738     ExprResult LHS =
09739         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
09740     if (LHS.isInvalid())
09741       return true;
09742 
09743     ExprResult RHS =
09744         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
09745     if (RHS.isInvalid())
09746       return true;
09747 
09748     if (!getDerived().AlwaysRebuild() &&
09749         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
09750       return E;
09751 
09752     return getDerived().RebuildCXXFoldExpr(
09753         E->getLocStart(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
09754         RHS.get(), E->getLocEnd());
09755   }
09756 
09757   // The transform has determined that we should perform an elementwise
09758   // expansion of the pattern. Do so.
09759   ExprResult Result = getDerived().TransformExpr(E->getInit());
09760   if (Result.isInvalid())
09761     return true;
09762   bool LeftFold = E->isLeftFold();
09763 
09764   // If we're retaining an expansion for a right fold, it is the innermost
09765   // component and takes the init (if any).
09766   if (!LeftFold && RetainExpansion) {
09767     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
09768 
09769     ExprResult Out = getDerived().TransformExpr(Pattern);
09770     if (Out.isInvalid())
09771       return true;
09772 
09773     Result = getDerived().RebuildCXXFoldExpr(
09774         E->getLocStart(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
09775         Result.get(), E->getLocEnd());
09776     if (Result.isInvalid())
09777       return true;
09778   }
09779 
09780   for (unsigned I = 0; I != *NumExpansions; ++I) {
09781     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
09782         getSema(), LeftFold ? I : *NumExpansions - I - 1);
09783     ExprResult Out = getDerived().TransformExpr(Pattern);
09784     if (Out.isInvalid())
09785       return true;
09786 
09787     if (Out.get()->containsUnexpandedParameterPack()) {
09788       // We still have a pack; retain a pack expansion for this slice.
09789       Result = getDerived().RebuildCXXFoldExpr(
09790           E->getLocStart(),
09791           LeftFold ? Result.get() : Out.get(),
09792           E->getOperator(), E->getEllipsisLoc(),
09793           LeftFold ? Out.get() : Result.get(),
09794           E->getLocEnd());
09795     } else if (Result.isUsable()) {
09796       // We've got down to a single element; build a binary operator.
09797       Result = getDerived().RebuildBinaryOperator(
09798           E->getEllipsisLoc(), E->getOperator(),
09799           LeftFold ? Result.get() : Out.get(),
09800           LeftFold ? Out.get() : Result.get());
09801     } else
09802       Result = Out;
09803 
09804     if (Result.isInvalid())
09805       return true;
09806   }
09807 
09808   // If we're retaining an expansion for a left fold, it is the outermost
09809   // component and takes the complete expansion so far as its init (if any).
09810   if (LeftFold && RetainExpansion) {
09811     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
09812 
09813     ExprResult Out = getDerived().TransformExpr(Pattern);
09814     if (Out.isInvalid())
09815       return true;
09816 
09817     Result = getDerived().RebuildCXXFoldExpr(
09818         E->getLocStart(), Result.get(),
09819         E->getOperator(), E->getEllipsisLoc(),
09820         Out.get(), E->getLocEnd());
09821     if (Result.isInvalid())
09822       return true;
09823   }
09824 
09825   // If we had no init and an empty pack, and we're not retaining an expansion,
09826   // then produce a fallback value or error.
09827   if (Result.isUnset())
09828     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
09829                                                 E->getOperator());
09830 
09831   return Result;
09832 }
09833 
09834 template<typename Derived>
09835 ExprResult
09836 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
09837     CXXStdInitializerListExpr *E) {
09838   return getDerived().TransformExpr(E->getSubExpr());
09839 }
09840 
09841 template<typename Derived>
09842 ExprResult
09843 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
09844   return SemaRef.MaybeBindToTemporary(E);
09845 }
09846 
09847 template<typename Derived>
09848 ExprResult
09849 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
09850   return E;
09851 }
09852 
09853 template<typename Derived>
09854 ExprResult
09855 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
09856   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
09857   if (SubExpr.isInvalid())
09858     return ExprError();
09859 
09860   if (!getDerived().AlwaysRebuild() &&
09861       SubExpr.get() == E->getSubExpr())
09862     return E;
09863 
09864   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
09865 }
09866 
09867 template<typename Derived>
09868 ExprResult
09869 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
09870   // Transform each of the elements.
09871   SmallVector<Expr *, 8> Elements;
09872   bool ArgChanged = false;
09873   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
09874                                   /*IsCall=*/false, Elements, &ArgChanged))
09875     return ExprError();
09876 
09877   if (!getDerived().AlwaysRebuild() && !ArgChanged)
09878     return SemaRef.MaybeBindToTemporary(E);
09879 
09880   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
09881                                               Elements.data(),
09882                                               Elements.size());
09883 }
09884 
09885 template<typename Derived>
09886 ExprResult
09887 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
09888                                                     ObjCDictionaryLiteral *E) {
09889   // Transform each of the elements.
09890   SmallVector<ObjCDictionaryElement, 8> Elements;
09891   bool ArgChanged = false;
09892   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
09893     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
09894 
09895     if (OrigElement.isPackExpansion()) {
09896       // This key/value element is a pack expansion.
09897       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
09898       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
09899       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
09900       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
09901 
09902       // Determine whether the set of unexpanded parameter packs can
09903       // and should be expanded.
09904       bool Expand = true;
09905       bool RetainExpansion = false;
09906       Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
09907       Optional<unsigned> NumExpansions = OrigNumExpansions;
09908       SourceRange PatternRange(OrigElement.Key->getLocStart(),
09909                                OrigElement.Value->getLocEnd());
09910      if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
09911                                                PatternRange,
09912                                                Unexpanded,
09913                                                Expand, RetainExpansion,
09914                                                NumExpansions))
09915         return ExprError();
09916 
09917       if (!Expand) {
09918         // The transform has determined that we should perform a simple
09919         // transformation on the pack expansion, producing another pack
09920         // expansion.
09921         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
09922         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
09923         if (Key.isInvalid())
09924           return ExprError();
09925 
09926         if (Key.get() != OrigElement.Key)
09927           ArgChanged = true;
09928 
09929         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
09930         if (Value.isInvalid())
09931           return ExprError();
09932 
09933         if (Value.get() != OrigElement.Value)
09934           ArgChanged = true;
09935 
09936         ObjCDictionaryElement Expansion = {
09937           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
09938         };
09939         Elements.push_back(Expansion);
09940         continue;
09941       }
09942 
09943       // Record right away that the argument was changed.  This needs
09944       // to happen even if the array expands to nothing.
09945       ArgChanged = true;
09946 
09947       // The transform has determined that we should perform an elementwise
09948       // expansion of the pattern. Do so.
09949       for (unsigned I = 0; I != *NumExpansions; ++I) {
09950         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
09951         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
09952         if (Key.isInvalid())
09953           return ExprError();
09954 
09955         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
09956         if (Value.isInvalid())
09957           return ExprError();
09958 
09959         ObjCDictionaryElement Element = {
09960           Key.get(), Value.get(), SourceLocation(), NumExpansions
09961         };
09962 
09963         // If any unexpanded parameter packs remain, we still have a
09964         // pack expansion.
09965         // FIXME: Can this really happen?
09966         if (Key.get()->containsUnexpandedParameterPack() ||
09967             Value.get()->containsUnexpandedParameterPack())
09968           Element.EllipsisLoc = OrigElement.EllipsisLoc;
09969 
09970         Elements.push_back(Element);
09971       }
09972 
09973       // FIXME: Retain a pack expansion if RetainExpansion is true.
09974 
09975       // We've finished with this pack expansion.
09976       continue;
09977     }
09978 
09979     // Transform and check key.
09980     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
09981     if (Key.isInvalid())
09982       return ExprError();
09983 
09984     if (Key.get() != OrigElement.Key)
09985       ArgChanged = true;
09986 
09987     // Transform and check value.
09988     ExprResult Value
09989       = getDerived().TransformExpr(OrigElement.Value);
09990     if (Value.isInvalid())
09991       return ExprError();
09992 
09993     if (Value.get() != OrigElement.Value)
09994       ArgChanged = true;
09995 
09996     ObjCDictionaryElement Element = {
09997       Key.get(), Value.get(), SourceLocation(), None
09998     };
09999     Elements.push_back(Element);
10000   }
10001 
10002   if (!getDerived().AlwaysRebuild() && !ArgChanged)
10003     return SemaRef.MaybeBindToTemporary(E);
10004 
10005   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
10006                                                    Elements.data(),
10007                                                    Elements.size());
10008 }
10009 
10010 template<typename Derived>
10011 ExprResult
10012 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
10013   TypeSourceInfo *EncodedTypeInfo
10014     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
10015   if (!EncodedTypeInfo)
10016     return ExprError();
10017 
10018   if (!getDerived().AlwaysRebuild() &&
10019       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
10020     return E;
10021 
10022   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
10023                                             EncodedTypeInfo,
10024                                             E->getRParenLoc());
10025 }
10026 
10027 template<typename Derived>
10028 ExprResult TreeTransform<Derived>::
10029 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
10030   // This is a kind of implicit conversion, and it needs to get dropped
10031   // and recomputed for the same general reasons that ImplicitCastExprs
10032   // do, as well a more specific one: this expression is only valid when
10033   // it appears *immediately* as an argument expression.
10034   return getDerived().TransformExpr(E->getSubExpr());
10035 }
10036 
10037 template<typename Derived>
10038 ExprResult TreeTransform<Derived>::
10039 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
10040   TypeSourceInfo *TSInfo
10041     = getDerived().TransformType(E->getTypeInfoAsWritten());
10042   if (!TSInfo)
10043     return ExprError();
10044 
10045   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
10046   if (Result.isInvalid())
10047     return ExprError();
10048 
10049   if (!getDerived().AlwaysRebuild() &&
10050       TSInfo == E->getTypeInfoAsWritten() &&
10051       Result.get() == E->getSubExpr())
10052     return E;
10053 
10054   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
10055                                       E->getBridgeKeywordLoc(), TSInfo,
10056                                       Result.get());
10057 }
10058 
10059 template<typename Derived>
10060 ExprResult
10061 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
10062   // Transform arguments.
10063   bool ArgChanged = false;
10064   SmallVector<Expr*, 8> Args;
10065   Args.reserve(E->getNumArgs());
10066   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
10067                                   &ArgChanged))
10068     return ExprError();
10069 
10070   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
10071     // Class message: transform the receiver type.
10072     TypeSourceInfo *ReceiverTypeInfo
10073       = getDerived().TransformType(E->getClassReceiverTypeInfo());
10074     if (!ReceiverTypeInfo)
10075       return ExprError();
10076 
10077     // If nothing changed, just retain the existing message send.
10078     if (!getDerived().AlwaysRebuild() &&
10079         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
10080       return SemaRef.MaybeBindToTemporary(E);
10081 
10082     // Build a new class message send.
10083     SmallVector<SourceLocation, 16> SelLocs;
10084     E->getSelectorLocs(SelLocs);
10085     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
10086                                                E->getSelector(),
10087                                                SelLocs,
10088                                                E->getMethodDecl(),
10089                                                E->getLeftLoc(),
10090                                                Args,
10091                                                E->getRightLoc());
10092   }
10093 
10094   // Instance message: transform the receiver
10095   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
10096          "Only class and instance messages may be instantiated");
10097   ExprResult Receiver
10098     = getDerived().TransformExpr(E->getInstanceReceiver());
10099   if (Receiver.isInvalid())
10100     return ExprError();
10101 
10102   // If nothing changed, just retain the existing message send.
10103   if (!getDerived().AlwaysRebuild() &&
10104       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
10105     return SemaRef.MaybeBindToTemporary(E);
10106 
10107   // Build a new instance message send.
10108   SmallVector<SourceLocation, 16> SelLocs;
10109   E->getSelectorLocs(SelLocs);
10110   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
10111                                              E->getSelector(),
10112                                              SelLocs,
10113                                              E->getMethodDecl(),
10114                                              E->getLeftLoc(),
10115                                              Args,
10116                                              E->getRightLoc());
10117 }
10118 
10119 template<typename Derived>
10120 ExprResult
10121 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
10122   return E;
10123 }
10124 
10125 template<typename Derived>
10126 ExprResult
10127 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
10128   return E;
10129 }
10130 
10131 template<typename Derived>
10132 ExprResult
10133 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
10134   // Transform the base expression.
10135   ExprResult Base = getDerived().TransformExpr(E->getBase());
10136   if (Base.isInvalid())
10137     return ExprError();
10138 
10139   // We don't need to transform the ivar; it will never change.
10140 
10141   // If nothing changed, just retain the existing expression.
10142   if (!getDerived().AlwaysRebuild() &&
10143       Base.get() == E->getBase())
10144     return E;
10145 
10146   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
10147                                              E->getLocation(),
10148                                              E->isArrow(), E->isFreeIvar());
10149 }
10150 
10151 template<typename Derived>
10152 ExprResult
10153 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
10154   // 'super' and types never change. Property never changes. Just
10155   // retain the existing expression.
10156   if (!E->isObjectReceiver())
10157     return E;
10158 
10159   // Transform the base expression.
10160   ExprResult Base = getDerived().TransformExpr(E->getBase());
10161   if (Base.isInvalid())
10162     return ExprError();
10163 
10164   // We don't need to transform the property; it will never change.
10165 
10166   // If nothing changed, just retain the existing expression.
10167   if (!getDerived().AlwaysRebuild() &&
10168       Base.get() == E->getBase())
10169     return E;
10170 
10171   if (E->isExplicitProperty())
10172     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
10173                                                    E->getExplicitProperty(),
10174                                                    E->getLocation());
10175 
10176   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
10177                                                  SemaRef.Context.PseudoObjectTy,
10178                                                  E->getImplicitPropertyGetter(),
10179                                                  E->getImplicitPropertySetter(),
10180                                                  E->getLocation());
10181 }
10182 
10183 template<typename Derived>
10184 ExprResult
10185 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
10186   // Transform the base expression.
10187   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
10188   if (Base.isInvalid())
10189     return ExprError();
10190 
10191   // Transform the key expression.
10192   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
10193   if (Key.isInvalid())
10194     return ExprError();
10195 
10196   // If nothing changed, just retain the existing expression.
10197   if (!getDerived().AlwaysRebuild() &&
10198       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
10199     return E;
10200 
10201   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
10202                                                   Base.get(), Key.get(),
10203                                                   E->getAtIndexMethodDecl(),
10204                                                   E->setAtIndexMethodDecl());
10205 }
10206 
10207 template<typename Derived>
10208 ExprResult
10209 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
10210   // Transform the base expression.
10211   ExprResult Base = getDerived().TransformExpr(E->getBase());
10212   if (Base.isInvalid())
10213     return ExprError();
10214 
10215   // If nothing changed, just retain the existing expression.
10216   if (!getDerived().AlwaysRebuild() &&
10217       Base.get() == E->getBase())
10218     return E;
10219 
10220   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
10221                                          E->getOpLoc(),
10222                                          E->isArrow());
10223 }
10224 
10225 template<typename Derived>
10226 ExprResult
10227 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
10228   bool ArgumentChanged = false;
10229   SmallVector<Expr*, 8> SubExprs;
10230   SubExprs.reserve(E->getNumSubExprs());
10231   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
10232                                   SubExprs, &ArgumentChanged))
10233     return ExprError();
10234 
10235   if (!getDerived().AlwaysRebuild() &&
10236       !ArgumentChanged)
10237     return E;
10238 
10239   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
10240                                                SubExprs,
10241                                                E->getRParenLoc());
10242 }
10243 
10244 template<typename Derived>
10245 ExprResult
10246 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
10247   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
10248   if (SrcExpr.isInvalid())
10249     return ExprError();
10250 
10251   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
10252   if (!Type)
10253     return ExprError();
10254 
10255   if (!getDerived().AlwaysRebuild() &&
10256       Type == E->getTypeSourceInfo() &&
10257       SrcExpr.get() == E->getSrcExpr())
10258     return E;
10259 
10260   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
10261                                                SrcExpr.get(), Type,
10262                                                E->getRParenLoc());
10263 }
10264 
10265 template<typename Derived>
10266 ExprResult
10267 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
10268   BlockDecl *oldBlock = E->getBlockDecl();
10269 
10270   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
10271   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
10272 
10273   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
10274   blockScope->TheDecl->setBlockMissingReturnType(
10275                          oldBlock->blockMissingReturnType());
10276 
10277   SmallVector<ParmVarDecl*, 4> params;
10278   SmallVector<QualType, 4> paramTypes;
10279 
10280   // Parameter substitution.
10281   if (getDerived().TransformFunctionTypeParams(E->getCaretLocation(),
10282                                                oldBlock->param_begin(),
10283                                                oldBlock->param_size(),
10284                                                nullptr, paramTypes, &params)) {
10285     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
10286     return ExprError();
10287   }
10288 
10289   const FunctionProtoType *exprFunctionType = E->getFunctionType();
10290   QualType exprResultType =
10291       getDerived().TransformType(exprFunctionType->getReturnType());
10292 
10293   QualType functionType =
10294     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes,
10295                                           exprFunctionType->getExtProtoInfo());
10296   blockScope->FunctionType = functionType;
10297 
10298   // Set the parameters on the block decl.
10299   if (!params.empty())
10300     blockScope->TheDecl->setParams(params);
10301 
10302   if (!oldBlock->blockMissingReturnType()) {
10303     blockScope->HasImplicitReturnType = false;
10304     blockScope->ReturnType = exprResultType;
10305   }
10306 
10307   // Transform the body
10308   StmtResult body = getDerived().TransformStmt(E->getBody());
10309   if (body.isInvalid()) {
10310     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
10311     return ExprError();
10312   }
10313 
10314 #ifndef NDEBUG
10315   // In builds with assertions, make sure that we captured everything we
10316   // captured before.
10317   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
10318     for (const auto &I : oldBlock->captures()) {
10319       VarDecl *oldCapture = I.getVariable();
10320 
10321       // Ignore parameter packs.
10322       if (isa<ParmVarDecl>(oldCapture) &&
10323           cast<ParmVarDecl>(oldCapture)->isParameterPack())
10324         continue;
10325 
10326       VarDecl *newCapture =
10327         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
10328                                                  oldCapture));
10329       assert(blockScope->CaptureMap.count(newCapture));
10330     }
10331     assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
10332   }
10333 #endif
10334 
10335   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
10336                                     /*Scope=*/nullptr);
10337 }
10338 
10339 template<typename Derived>
10340 ExprResult
10341 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
10342   llvm_unreachable("Cannot transform asType expressions yet");
10343 }
10344 
10345 template<typename Derived>
10346 ExprResult
10347 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
10348   QualType RetTy = getDerived().TransformType(E->getType());
10349   bool ArgumentChanged = false;
10350   SmallVector<Expr*, 8> SubExprs;
10351   SubExprs.reserve(E->getNumSubExprs());
10352   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
10353                                   SubExprs, &ArgumentChanged))
10354     return ExprError();
10355 
10356   if (!getDerived().AlwaysRebuild() &&
10357       !ArgumentChanged)
10358     return E;
10359 
10360   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
10361                                         RetTy, E->getOp(), E->getRParenLoc());
10362 }
10363 
10364 //===----------------------------------------------------------------------===//
10365 // Type reconstruction
10366 //===----------------------------------------------------------------------===//
10367 
10368 template<typename Derived>
10369 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
10370                                                     SourceLocation Star) {
10371   return SemaRef.BuildPointerType(PointeeType, Star,
10372                                   getDerived().getBaseEntity());
10373 }
10374 
10375 template<typename Derived>
10376 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
10377                                                          SourceLocation Star) {
10378   return SemaRef.BuildBlockPointerType(PointeeType, Star,
10379                                        getDerived().getBaseEntity());
10380 }
10381 
10382 template<typename Derived>
10383 QualType
10384 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
10385                                              bool WrittenAsLValue,
10386                                              SourceLocation Sigil) {
10387   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
10388                                     Sigil, getDerived().getBaseEntity());
10389 }
10390 
10391 template<typename Derived>
10392 QualType
10393 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
10394                                                  QualType ClassType,
10395                                                  SourceLocation Sigil) {
10396   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
10397                                         getDerived().getBaseEntity());
10398 }
10399 
10400 template<typename Derived>
10401 QualType
10402 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
10403                                          ArrayType::ArraySizeModifier SizeMod,
10404                                          const llvm::APInt *Size,
10405                                          Expr *SizeExpr,
10406                                          unsigned IndexTypeQuals,
10407                                          SourceRange BracketsRange) {
10408   if (SizeExpr || !Size)
10409     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
10410                                   IndexTypeQuals, BracketsRange,
10411                                   getDerived().getBaseEntity());
10412 
10413   QualType Types[] = {
10414     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
10415     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
10416     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
10417   };
10418   const unsigned NumTypes = llvm::array_lengthof(Types);
10419   QualType SizeType;
10420   for (unsigned I = 0; I != NumTypes; ++I)
10421     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
10422       SizeType = Types[I];
10423       break;
10424     }
10425 
10426   // Note that we can return a VariableArrayType here in the case where
10427   // the element type was a dependent VariableArrayType.
10428   IntegerLiteral *ArraySize
10429       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
10430                                /*FIXME*/BracketsRange.getBegin());
10431   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
10432                                 IndexTypeQuals, BracketsRange,
10433                                 getDerived().getBaseEntity());
10434 }
10435 
10436 template<typename Derived>
10437 QualType
10438 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
10439                                                  ArrayType::ArraySizeModifier SizeMod,
10440                                                  const llvm::APInt &Size,
10441                                                  unsigned IndexTypeQuals,
10442                                                  SourceRange BracketsRange) {
10443   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, nullptr,
10444                                         IndexTypeQuals, BracketsRange);
10445 }
10446 
10447 template<typename Derived>
10448 QualType
10449 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
10450                                           ArrayType::ArraySizeModifier SizeMod,
10451                                                  unsigned IndexTypeQuals,
10452                                                    SourceRange BracketsRange) {
10453   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
10454                                        IndexTypeQuals, BracketsRange);
10455 }
10456 
10457 template<typename Derived>
10458 QualType
10459 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
10460                                           ArrayType::ArraySizeModifier SizeMod,
10461                                                  Expr *SizeExpr,
10462                                                  unsigned IndexTypeQuals,
10463                                                  SourceRange BracketsRange) {
10464   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
10465                                        SizeExpr,
10466                                        IndexTypeQuals, BracketsRange);
10467 }
10468 
10469 template<typename Derived>
10470 QualType
10471 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
10472                                           ArrayType::ArraySizeModifier SizeMod,
10473                                                        Expr *SizeExpr,
10474                                                        unsigned IndexTypeQuals,
10475                                                    SourceRange BracketsRange) {
10476   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
10477                                        SizeExpr,
10478                                        IndexTypeQuals, BracketsRange);
10479 }
10480 
10481 template<typename Derived>
10482 QualType TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
10483                                                unsigned NumElements,
10484                                                VectorType::VectorKind VecKind) {
10485   // FIXME: semantic checking!
10486   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
10487 }
10488 
10489 template<typename Derived>
10490 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
10491                                                       unsigned NumElements,
10492                                                  SourceLocation AttributeLoc) {
10493   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
10494                           NumElements, true);
10495   IntegerLiteral *VectorSize
10496     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
10497                              AttributeLoc);
10498   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
10499 }
10500 
10501 template<typename Derived>
10502 QualType
10503 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
10504                                                            Expr *SizeExpr,
10505                                                   SourceLocation AttributeLoc) {
10506   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
10507 }
10508 
10509 template<typename Derived>
10510 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
10511     QualType T,
10512     MutableArrayRef<QualType> ParamTypes,
10513     const FunctionProtoType::ExtProtoInfo &EPI) {
10514   return SemaRef.BuildFunctionType(T, ParamTypes,
10515                                    getDerived().getBaseLocation(),
10516                                    getDerived().getBaseEntity(),
10517                                    EPI);
10518 }
10519 
10520 template<typename Derived>
10521 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
10522   return SemaRef.Context.getFunctionNoProtoType(T);
10523 }
10524 
10525 template<typename Derived>
10526 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(Decl *D) {
10527   assert(D && "no decl found");
10528   if (D->isInvalidDecl()) return QualType();
10529 
10530   // FIXME: Doesn't account for ObjCInterfaceDecl!
10531   TypeDecl *Ty;
10532   if (isa<UsingDecl>(D)) {
10533     UsingDecl *Using = cast<UsingDecl>(D);
10534     assert(Using->hasTypename() &&
10535            "UnresolvedUsingTypenameDecl transformed to non-typename using");
10536 
10537     // A valid resolved using typename decl points to exactly one type decl.
10538     assert(++Using->shadow_begin() == Using->shadow_end());
10539     Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
10540 
10541   } else {
10542     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
10543            "UnresolvedUsingTypenameDecl transformed to non-using decl");
10544     Ty = cast<UnresolvedUsingTypenameDecl>(D);
10545   }
10546 
10547   return SemaRef.Context.getTypeDeclType(Ty);
10548 }
10549 
10550 template<typename Derived>
10551 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
10552                                                        SourceLocation Loc) {
10553   return SemaRef.BuildTypeofExprType(E, Loc);
10554 }
10555 
10556 template<typename Derived>
10557 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
10558   return SemaRef.Context.getTypeOfType(Underlying);
10559 }
10560 
10561 template<typename Derived>
10562 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
10563                                                      SourceLocation Loc) {
10564   return SemaRef.BuildDecltypeType(E, Loc);
10565 }
10566 
10567 template<typename Derived>
10568 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
10569                                             UnaryTransformType::UTTKind UKind,
10570                                             SourceLocation Loc) {
10571   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
10572 }
10573 
10574 template<typename Derived>
10575 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
10576                                                       TemplateName Template,
10577                                              SourceLocation TemplateNameLoc,
10578                                      TemplateArgumentListInfo &TemplateArgs) {
10579   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
10580 }
10581 
10582 template<typename Derived>
10583 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
10584                                                    SourceLocation KWLoc) {
10585   return SemaRef.BuildAtomicType(ValueType, KWLoc);
10586 }
10587 
10588 template<typename Derived>
10589 TemplateName
10590 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
10591                                             bool TemplateKW,
10592                                             TemplateDecl *Template) {
10593   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
10594                                                   Template);
10595 }
10596 
10597 template<typename Derived>
10598 TemplateName
10599 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
10600                                             const IdentifierInfo &Name,
10601                                             SourceLocation NameLoc,
10602                                             QualType ObjectType,
10603                                             NamedDecl *FirstQualifierInScope) {
10604   UnqualifiedId TemplateName;
10605   TemplateName.setIdentifier(&Name, NameLoc);
10606   Sema::TemplateTy Template;
10607   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
10608   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
10609                                        SS, TemplateKWLoc, TemplateName,
10610                                        ParsedType::make(ObjectType),
10611                                        /*EnteringContext=*/false,
10612                                        Template);
10613   return Template.get();
10614 }
10615 
10616 template<typename Derived>
10617 TemplateName
10618 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
10619                                             OverloadedOperatorKind Operator,
10620                                             SourceLocation NameLoc,
10621                                             QualType ObjectType) {
10622   UnqualifiedId Name;
10623   // FIXME: Bogus location information.
10624   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
10625   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
10626   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
10627   Sema::TemplateTy Template;
10628   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
10629                                        SS, TemplateKWLoc, Name,
10630                                        ParsedType::make(ObjectType),
10631                                        /*EnteringContext=*/false,
10632                                        Template);
10633   return Template.get();
10634 }
10635 
10636 template<typename Derived>
10637 ExprResult
10638 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
10639                                                    SourceLocation OpLoc,
10640                                                    Expr *OrigCallee,
10641                                                    Expr *First,
10642                                                    Expr *Second) {
10643   Expr *Callee = OrigCallee->IgnoreParenCasts();
10644   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
10645 
10646   if (First->getObjectKind() == OK_ObjCProperty) {
10647     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
10648     if (BinaryOperator::isAssignmentOp(Opc))
10649       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
10650                                                  First, Second);
10651     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
10652     if (Result.isInvalid())
10653       return ExprError();
10654     First = Result.get();
10655   }
10656 
10657   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
10658     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
10659     if (Result.isInvalid())
10660       return ExprError();
10661     Second = Result.get();
10662   }
10663 
10664   // Determine whether this should be a builtin operation.
10665   if (Op == OO_Subscript) {
10666     if (!First->getType()->isOverloadableType() &&
10667         !Second->getType()->isOverloadableType())
10668       return getSema().CreateBuiltinArraySubscriptExpr(First,
10669                                                        Callee->getLocStart(),
10670                                                        Second, OpLoc);
10671   } else if (Op == OO_Arrow) {
10672     // -> is never a builtin operation.
10673     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
10674   } else if (Second == nullptr || isPostIncDec) {
10675     if (!First->getType()->isOverloadableType()) {
10676       // The argument is not of overloadable type, so try to create a
10677       // built-in unary operation.
10678       UnaryOperatorKind Opc
10679         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
10680 
10681       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
10682     }
10683   } else {
10684     if (!First->getType()->isOverloadableType() &&
10685         !Second->getType()->isOverloadableType()) {
10686       // Neither of the arguments is an overloadable type, so try to
10687       // create a built-in binary operation.
10688       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
10689       ExprResult Result
10690         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
10691       if (Result.isInvalid())
10692         return ExprError();
10693 
10694       return Result;
10695     }
10696   }
10697 
10698   // Compute the transformed set of functions (and function templates) to be
10699   // used during overload resolution.
10700   UnresolvedSet<16> Functions;
10701 
10702   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
10703     assert(ULE->requiresADL());
10704     Functions.append(ULE->decls_begin(), ULE->decls_end());
10705   } else {
10706     // If we've resolved this to a particular non-member function, just call
10707     // that function. If we resolved it to a member function,
10708     // CreateOverloaded* will find that function for us.
10709     NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
10710     if (!isa<CXXMethodDecl>(ND))
10711       Functions.addDecl(ND);
10712   }
10713 
10714   // Add any functions found via argument-dependent lookup.
10715   Expr *Args[2] = { First, Second };
10716   unsigned NumArgs = 1 + (Second != nullptr);
10717 
10718   // Create the overloaded operator invocation for unary operators.
10719   if (NumArgs == 1 || isPostIncDec) {
10720     UnaryOperatorKind Opc
10721       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
10722     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First);
10723   }
10724 
10725   if (Op == OO_Subscript) {
10726     SourceLocation LBrace;
10727     SourceLocation RBrace;
10728 
10729     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
10730         DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
10731         LBrace = SourceLocation::getFromRawEncoding(
10732                     NameLoc.CXXOperatorName.BeginOpNameLoc);
10733         RBrace = SourceLocation::getFromRawEncoding(
10734                     NameLoc.CXXOperatorName.EndOpNameLoc);
10735     } else {
10736         LBrace = Callee->getLocStart();
10737         RBrace = OpLoc;
10738     }
10739 
10740     return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
10741                                                       First, Second);
10742   }
10743 
10744   // Create the overloaded operator invocation for binary operators.
10745   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
10746   ExprResult Result
10747     = SemaRef.CreateOverloadedBinOp(OpLoc, Opc, Functions, Args[0], Args[1]);
10748   if (Result.isInvalid())
10749     return ExprError();
10750 
10751   return Result;
10752 }
10753 
10754 template<typename Derived>
10755 ExprResult
10756 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
10757                                                      SourceLocation OperatorLoc,
10758                                                        bool isArrow,
10759                                                        CXXScopeSpec &SS,
10760                                                      TypeSourceInfo *ScopeType,
10761                                                        SourceLocation CCLoc,
10762                                                        SourceLocation TildeLoc,
10763                                         PseudoDestructorTypeStorage Destroyed) {
10764   QualType BaseType = Base->getType();
10765   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
10766       (!isArrow && !BaseType->getAs<RecordType>()) ||
10767       (isArrow && BaseType->getAs<PointerType>() &&
10768        !BaseType->getAs<PointerType>()->getPointeeType()
10769                                               ->template getAs<RecordType>())){
10770     // This pseudo-destructor expression is still a pseudo-destructor.
10771     return SemaRef.BuildPseudoDestructorExpr(Base, OperatorLoc,
10772                                              isArrow? tok::arrow : tok::period,
10773                                              SS, ScopeType, CCLoc, TildeLoc,
10774                                              Destroyed,
10775                                              /*FIXME?*/true);
10776   }
10777 
10778   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
10779   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
10780                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
10781   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
10782   NameInfo.setNamedTypeInfo(DestroyedType);
10783 
10784   // The scope type is now known to be a valid nested name specifier
10785   // component. Tack it on to the end of the nested name specifier.
10786   if (ScopeType) {
10787     if (!ScopeType->getType()->getAs<TagType>()) {
10788       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
10789                      diag::err_expected_class_or_namespace)
10790           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
10791       return ExprError();
10792     }
10793     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
10794               CCLoc);
10795   }
10796 
10797   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
10798   return getSema().BuildMemberReferenceExpr(Base, BaseType,
10799                                             OperatorLoc, isArrow,
10800                                             SS, TemplateKWLoc,
10801                                             /*FIXME: FirstQualifier*/ nullptr,
10802                                             NameInfo,
10803                                             /*TemplateArgs*/ nullptr);
10804 }
10805 
10806 template<typename Derived>
10807 StmtResult
10808 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
10809   SourceLocation Loc = S->getLocStart();
10810   CapturedDecl *CD = S->getCapturedDecl();
10811   unsigned NumParams = CD->getNumParams();
10812   unsigned ContextParamPos = CD->getContextParamPosition();
10813   SmallVector<Sema::CapturedParamNameType, 4> Params;
10814   for (unsigned I = 0; I < NumParams; ++I) {
10815     if (I != ContextParamPos) {
10816       Params.push_back(
10817              std::make_pair(
10818                   CD->getParam(I)->getName(),
10819                   getDerived().TransformType(CD->getParam(I)->getType())));
10820     } else {
10821       Params.push_back(std::make_pair(StringRef(), QualType()));
10822     }
10823   }
10824   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
10825                                      S->getCapturedRegionKind(), Params);
10826   StmtResult Body;
10827   {
10828     Sema::CompoundScopeRAII CompoundScope(getSema());
10829     Body = getDerived().TransformStmt(S->getCapturedStmt());
10830   }
10831 
10832   if (Body.isInvalid()) {
10833     getSema().ActOnCapturedRegionError();
10834     return StmtError();
10835   }
10836 
10837   return getSema().ActOnCapturedRegionEnd(Body.get());
10838 }
10839 
10840 } // end namespace clang
10841 
10842 #endif