1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for C++ declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/LiteralSupport.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/CXXFieldCollector.h"
32 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Initialization.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/ParsedTemplate.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaInternal.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include <map>
44 #include <set>
45 
46 using namespace clang;
47 
48 //===----------------------------------------------------------------------===//
49 // CheckDefaultArgumentVisitor
50 //===----------------------------------------------------------------------===//
51 
52 namespace {
53   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54   /// the default argument of a parameter to determine whether it
55   /// contains any ill-formed subexpressions. For example, this will
56   /// diagnose the use of local variables or parameters within the
57   /// default argument expression.
58   class CheckDefaultArgumentVisitor
59     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
60     Expr *DefaultArg;
61     Sema *S;
62 
63   public:
64     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
65       : DefaultArg(defarg), S(s) {}
66 
67     bool VisitExpr(Expr *Node);
68     bool VisitDeclRefExpr(DeclRefExpr *DRE);
69     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
70     bool VisitLambdaExpr(LambdaExpr *Lambda);
71     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
72   };
73 
74   /// VisitExpr - Visit all of the children of this expression.
75   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76     bool IsInvalid = false;
77     for (Stmt *SubStmt : Node->children())
78       IsInvalid |= Visit(SubStmt);
79     return IsInvalid;
80   }
81 
82   /// VisitDeclRefExpr - Visit a reference to a declaration, to
83   /// determine whether this declaration can be used in the default
84   /// argument expression.
85   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
86     NamedDecl *Decl = DRE->getDecl();
87     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88       // C++ [dcl.fct.default]p9
89       //   Default arguments are evaluated each time the function is
90       //   called. The order of evaluation of function arguments is
91       //   unspecified. Consequently, parameters of a function shall not
92       //   be used in default argument expressions, even if they are not
93       //   evaluated. Parameters of a function declared before a default
94       //   argument expression are in scope and can hide namespace and
95       //   class member names.
96       return S->Diag(DRE->getLocStart(),
97                      diag::err_param_default_argument_references_param)
98          << Param->getDeclName() << DefaultArg->getSourceRange();
99     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
100       // C++ [dcl.fct.default]p7
101       //   Local variables shall not be used in default argument
102       //   expressions.
103       if (VDecl->isLocalVarDecl())
104         return S->Diag(DRE->getLocStart(),
105                        diag::err_param_default_argument_references_local)
106           << VDecl->getDeclName() << DefaultArg->getSourceRange();
107     }
108 
109     return false;
110   }
111 
112   /// VisitCXXThisExpr - Visit a C++ "this" expression.
113   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114     // C++ [dcl.fct.default]p8:
115     //   The keyword this shall not be used in a default argument of a
116     //   member function.
117     return S->Diag(ThisE->getLocStart(),
118                    diag::err_param_default_argument_references_this)
119                << ThisE->getSourceRange();
120   }
121 
122   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123     bool Invalid = false;
124     for (PseudoObjectExpr::semantics_iterator
125            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126       Expr *E = *i;
127 
128       // Look through bindings.
129       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130         E = OVE->getSourceExpr();
131         assert(E && "pseudo-object binding without source expression?");
132       }
133 
134       Invalid |= Visit(E);
135     }
136     return Invalid;
137   }
138 
139   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140     // C++11 [expr.lambda.prim]p13:
141     //   A lambda-expression appearing in a default argument shall not
142     //   implicitly or explicitly capture any entity.
143     if (Lambda->capture_begin() == Lambda->capture_end())
144       return false;
145 
146     return S->Diag(Lambda->getLocStart(),
147                    diag::err_lambda_capture_default_arg);
148   }
149 }
150 
151 void
152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
153                                                  const CXXMethodDecl *Method) {
154   // If we have an MSAny spec already, don't bother.
155   if (!Method || ComputedEST == EST_MSAny)
156     return;
157 
158   const FunctionProtoType *Proto
159     = Method->getType()->getAs<FunctionProtoType>();
160   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
161   if (!Proto)
162     return;
163 
164   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165 
166   // If we have a throw-all spec at this point, ignore the function.
167   if (ComputedEST == EST_None)
168     return;
169 
170   switch(EST) {
171   // If this function can throw any exceptions, make a note of that.
172   case EST_MSAny:
173   case EST_None:
174     ClearExceptions();
175     ComputedEST = EST;
176     return;
177   // FIXME: If the call to this decl is using any of its default arguments, we
178   // need to search them for potentially-throwing calls.
179   // If this function has a basic noexcept, it doesn't affect the outcome.
180   case EST_BasicNoexcept:
181     return;
182   // If we're still at noexcept(true) and there's a nothrow() callee,
183   // change to that specification.
184   case EST_DynamicNone:
185     if (ComputedEST == EST_BasicNoexcept)
186       ComputedEST = EST_DynamicNone;
187     return;
188   // Check out noexcept specs.
189   case EST_ComputedNoexcept:
190   {
191     FunctionProtoType::NoexceptResult NR =
192         Proto->getNoexceptSpec(Self->Context);
193     assert(NR != FunctionProtoType::NR_NoNoexcept &&
194            "Must have noexcept result for EST_ComputedNoexcept.");
195     assert(NR != FunctionProtoType::NR_Dependent &&
196            "Should not generate implicit declarations for dependent cases, "
197            "and don't know how to handle them anyway.");
198     // noexcept(false) -> no spec on the new function
199     if (NR == FunctionProtoType::NR_Throw) {
200       ClearExceptions();
201       ComputedEST = EST_None;
202     }
203     // noexcept(true) won't change anything either.
204     return;
205   }
206   default:
207     break;
208   }
209   assert(EST == EST_Dynamic && "EST case not considered earlier.");
210   assert(ComputedEST != EST_None &&
211          "Shouldn't collect exceptions when throw-all is guaranteed.");
212   ComputedEST = EST_Dynamic;
213   // Record the exceptions in this function's exception specification.
214   for (const auto &E : Proto->exceptions())
215     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
216       Exceptions.push_back(E);
217 }
218 
219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
220   if (!E || ComputedEST == EST_MSAny)
221     return;
222 
223   // FIXME:
224   //
225   // C++0x [except.spec]p14:
226   //   [An] implicit exception-specification specifies the type-id T if and
227   // only if T is allowed by the exception-specification of a function directly
228   // invoked by f's implicit definition; f shall allow all exceptions if any
229   // function it directly invokes allows all exceptions, and f shall allow no
230   // exceptions if every function it directly invokes allows no exceptions.
231   //
232   // Note in particular that if an implicit exception-specification is generated
233   // for a function containing a throw-expression, that specification can still
234   // be noexcept(true).
235   //
236   // Note also that 'directly invoked' is not defined in the standard, and there
237   // is no indication that we should only consider potentially-evaluated calls.
238   //
239   // Ultimately we should implement the intent of the standard: the exception
240   // specification should be the set of exceptions which can be thrown by the
241   // implicit definition. For now, we assume that any non-nothrow expression can
242   // throw any exception.
243 
244   if (Self->canThrow(E))
245     ComputedEST = EST_None;
246 }
247 
248 bool
249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
250                               SourceLocation EqualLoc) {
251   if (RequireCompleteType(Param->getLocation(), Param->getType(),
252                           diag::err_typecheck_decl_incomplete_type)) {
253     Param->setInvalidDecl();
254     return true;
255   }
256 
257   // C++ [dcl.fct.default]p5
258   //   A default argument expression is implicitly converted (clause
259   //   4) to the parameter type. The default argument expression has
260   //   the same semantic constraints as the initializer expression in
261   //   a declaration of a variable of the parameter type, using the
262   //   copy-initialization semantics (8.5).
263   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264                                                                     Param);
265   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266                                                            EqualLoc);
267   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269   if (Result.isInvalid())
270     return true;
271   Arg = Result.getAs<Expr>();
272 
273   CheckCompletedExpr(Arg, EqualLoc);
274   Arg = MaybeCreateExprWithCleanups(Arg);
275 
276   // Okay: add the default argument to the parameter
277   Param->setDefaultArg(Arg);
278 
279   // We have already instantiated this parameter; provide each of the
280   // instantiations with the uninstantiated default argument.
281   UnparsedDefaultArgInstantiationsMap::iterator InstPos
282     = UnparsedDefaultArgInstantiations.find(Param);
283   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286 
287     // We're done tracking this parameter's instantiations.
288     UnparsedDefaultArgInstantiations.erase(InstPos);
289   }
290 
291   return false;
292 }
293 
294 /// ActOnParamDefaultArgument - Check whether the default argument
295 /// provided for a function parameter is well-formed. If so, attach it
296 /// to the parameter declaration.
297 void
298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
299                                 Expr *DefaultArg) {
300   if (!param || !DefaultArg)
301     return;
302 
303   ParmVarDecl *Param = cast<ParmVarDecl>(param);
304   UnparsedDefaultArgLocs.erase(Param);
305 
306   // Default arguments are only permitted in C++
307   if (!getLangOpts().CPlusPlus) {
308     Diag(EqualLoc, diag::err_param_default_argument)
309       << DefaultArg->getSourceRange();
310     Param->setInvalidDecl();
311     return;
312   }
313 
314   // Check for unexpanded parameter packs.
315   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316     Param->setInvalidDecl();
317     return;
318   }
319 
320   // C++11 [dcl.fct.default]p3
321   //   A default argument expression [...] shall not be specified for a
322   //   parameter pack.
323   if (Param->isParameterPack()) {
324     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325         << DefaultArg->getSourceRange();
326     return;
327   }
328 
329   // Check that the default argument is well-formed
330   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331   if (DefaultArgChecker.Visit(DefaultArg)) {
332     Param->setInvalidDecl();
333     return;
334   }
335 
336   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
337 }
338 
339 /// ActOnParamUnparsedDefaultArgument - We've seen a default
340 /// argument for a function parameter, but we can't parse it yet
341 /// because we're inside a class definition. Note that this default
342 /// argument will be parsed later.
343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
344                                              SourceLocation EqualLoc,
345                                              SourceLocation ArgLoc) {
346   if (!param)
347     return;
348 
349   ParmVarDecl *Param = cast<ParmVarDecl>(param);
350   Param->setUnparsedDefaultArg();
351   UnparsedDefaultArgLocs[Param] = ArgLoc;
352 }
353 
354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355 /// the default argument for the parameter param failed.
356 void Sema::ActOnParamDefaultArgumentError(Decl *param,
357                                           SourceLocation EqualLoc) {
358   if (!param)
359     return;
360 
361   ParmVarDecl *Param = cast<ParmVarDecl>(param);
362   Param->setInvalidDecl();
363   UnparsedDefaultArgLocs.erase(Param);
364   Param->setDefaultArg(new(Context)
365                        OpaqueValueExpr(EqualLoc,
366                                        Param->getType().getNonReferenceType(),
367                                        VK_RValue));
368 }
369 
370 /// CheckExtraCXXDefaultArguments - Check for any extra default
371 /// arguments in the declarator, which is not a function declaration
372 /// or definition and therefore is not permitted to have default
373 /// arguments. This routine should be invoked for every declarator
374 /// that is not a function declaration or definition.
375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
376   // C++ [dcl.fct.default]p3
377   //   A default argument expression shall be specified only in the
378   //   parameter-declaration-clause of a function declaration or in a
379   //   template-parameter (14.1). It shall not be specified for a
380   //   parameter pack. If it is specified in a
381   //   parameter-declaration-clause, it shall not occur within a
382   //   declarator or abstract-declarator of a parameter-declaration.
383   bool MightBeFunction = D.isFunctionDeclarationContext();
384   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
385     DeclaratorChunk &chunk = D.getTypeObject(i);
386     if (chunk.Kind == DeclaratorChunk::Function) {
387       if (MightBeFunction) {
388         // This is a function declaration. It can have default arguments, but
389         // keep looking in case its return type is a function type with default
390         // arguments.
391         MightBeFunction = false;
392         continue;
393       }
394       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395            ++argIdx) {
396         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
397         if (Param->hasUnparsedDefaultArg()) {
398           std::unique_ptr<CachedTokens> Toks =
399               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
400           SourceRange SR;
401           if (Toks->size() > 1)
402             SR = SourceRange((*Toks)[1].getLocation(),
403                              Toks->back().getLocation());
404           else
405             SR = UnparsedDefaultArgLocs[Param];
406           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
407             << SR;
408         } else if (Param->getDefaultArg()) {
409           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410             << Param->getDefaultArg()->getSourceRange();
411           Param->setDefaultArg(nullptr);
412         }
413       }
414     } else if (chunk.Kind != DeclaratorChunk::Paren) {
415       MightBeFunction = false;
416     }
417   }
418 }
419 
420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423     if (!PVD->hasDefaultArg())
424       return false;
425     if (!PVD->hasInheritedDefaultArg())
426       return true;
427   }
428   return false;
429 }
430 
431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
432 /// function, once we already know that they have the same
433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434 /// error, false otherwise.
435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436                                 Scope *S) {
437   bool Invalid = false;
438 
439   // The declaration context corresponding to the scope is the semantic
440   // parent, unless this is a local function declaration, in which case
441   // it is that surrounding function.
442   DeclContext *ScopeDC = New->isLocalExternDecl()
443                              ? New->getLexicalDeclContext()
444                              : New->getDeclContext();
445 
446   // Find the previous declaration for the purpose of default arguments.
447   FunctionDecl *PrevForDefaultArgs = Old;
448   for (/**/; PrevForDefaultArgs;
449        // Don't bother looking back past the latest decl if this is a local
450        // extern declaration; nothing else could work.
451        PrevForDefaultArgs = New->isLocalExternDecl()
452                                 ? nullptr
453                                 : PrevForDefaultArgs->getPreviousDecl()) {
454     // Ignore hidden declarations.
455     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456       continue;
457 
458     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459         !New->isCXXClassMember()) {
460       // Ignore default arguments of old decl if they are not in
461       // the same scope and this is not an out-of-line definition of
462       // a member function.
463       continue;
464     }
465 
466     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467       // If only one of these is a local function declaration, then they are
468       // declared in different scopes, even though isDeclInScope may think
469       // they're in the same scope. (If both are local, the scope check is
470       // sufficent, and if neither is local, then they are in the same scope.)
471       continue;
472     }
473 
474     // We found the right previous declaration.
475     break;
476   }
477 
478   // C++ [dcl.fct.default]p4:
479   //   For non-template functions, default arguments can be added in
480   //   later declarations of a function in the same
481   //   scope. Declarations in different scopes have completely
482   //   distinct sets of default arguments. That is, declarations in
483   //   inner scopes do not acquire default arguments from
484   //   declarations in outer scopes, and vice versa. In a given
485   //   function declaration, all parameters subsequent to a
486   //   parameter with a default argument shall have default
487   //   arguments supplied in this or previous declarations. A
488   //   default argument shall not be redefined by a later
489   //   declaration (not even to the same value).
490   //
491   // C++ [dcl.fct.default]p6:
492   //   Except for member functions of class templates, the default arguments
493   //   in a member function definition that appears outside of the class
494   //   definition are added to the set of default arguments provided by the
495   //   member function declaration in the class definition.
496   for (unsigned p = 0, NumParams = PrevForDefaultArgs
497                                        ? PrevForDefaultArgs->getNumParams()
498                                        : 0;
499        p < NumParams; ++p) {
500     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501     ParmVarDecl *NewParam = New->getParamDecl(p);
502 
503     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504     bool NewParamHasDfl = NewParam->hasDefaultArg();
505 
506     if (OldParamHasDfl && NewParamHasDfl) {
507       unsigned DiagDefaultParamID =
508         diag::err_param_default_argument_redefinition;
509 
510       // MSVC accepts that default parameters be redefined for member functions
511       // of template class. The new default parameter's value is ignored.
512       Invalid = true;
513       if (getLangOpts().MicrosoftExt) {
514         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
515         if (MD && MD->getParent()->getDescribedClassTemplate()) {
516           // Merge the old default argument into the new parameter.
517           NewParam->setHasInheritedDefaultArg();
518           if (OldParam->hasUninstantiatedDefaultArg())
519             NewParam->setUninstantiatedDefaultArg(
520                                       OldParam->getUninstantiatedDefaultArg());
521           else
522             NewParam->setDefaultArg(OldParam->getInit());
523           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
524           Invalid = false;
525         }
526       }
527 
528       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529       // hint here. Alternatively, we could walk the type-source information
530       // for NewParam to find the last source location in the type... but it
531       // isn't worth the effort right now. This is the kind of test case that
532       // is hard to get right:
533       //   int f(int);
534       //   void g(int (*fp)(int) = f);
535       //   void g(int (*fp)(int) = &f);
536       Diag(NewParam->getLocation(), DiagDefaultParamID)
537         << NewParam->getDefaultArgRange();
538 
539       // Look for the function declaration where the default argument was
540       // actually written, which may be a declaration prior to Old.
541       for (auto Older = PrevForDefaultArgs;
542            OldParam->hasInheritedDefaultArg(); /**/) {
543         Older = Older->getPreviousDecl();
544         OldParam = Older->getParamDecl(p);
545       }
546 
547       Diag(OldParam->getLocation(), diag::note_previous_definition)
548         << OldParam->getDefaultArgRange();
549     } else if (OldParamHasDfl) {
550       // Merge the old default argument into the new parameter.
551       // It's important to use getInit() here;  getDefaultArg()
552       // strips off any top-level ExprWithCleanups.
553       NewParam->setHasInheritedDefaultArg();
554       if (OldParam->hasUnparsedDefaultArg())
555         NewParam->setUnparsedDefaultArg();
556       else if (OldParam->hasUninstantiatedDefaultArg())
557         NewParam->setUninstantiatedDefaultArg(
558                                       OldParam->getUninstantiatedDefaultArg());
559       else
560         NewParam->setDefaultArg(OldParam->getInit());
561     } else if (NewParamHasDfl) {
562       if (New->getDescribedFunctionTemplate()) {
563         // Paragraph 4, quoted above, only applies to non-template functions.
564         Diag(NewParam->getLocation(),
565              diag::err_param_default_argument_template_redecl)
566           << NewParam->getDefaultArgRange();
567         Diag(PrevForDefaultArgs->getLocation(),
568              diag::note_template_prev_declaration)
569             << false;
570       } else if (New->getTemplateSpecializationKind()
571                    != TSK_ImplicitInstantiation &&
572                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
573         // C++ [temp.expr.spec]p21:
574         //   Default function arguments shall not be specified in a declaration
575         //   or a definition for one of the following explicit specializations:
576         //     - the explicit specialization of a function template;
577         //     - the explicit specialization of a member function template;
578         //     - the explicit specialization of a member function of a class
579         //       template where the class template specialization to which the
580         //       member function specialization belongs is implicitly
581         //       instantiated.
582         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
583           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
584           << New->getDeclName()
585           << NewParam->getDefaultArgRange();
586       } else if (New->getDeclContext()->isDependentContext()) {
587         // C++ [dcl.fct.default]p6 (DR217):
588         //   Default arguments for a member function of a class template shall
589         //   be specified on the initial declaration of the member function
590         //   within the class template.
591         //
592         // Reading the tea leaves a bit in DR217 and its reference to DR205
593         // leads me to the conclusion that one cannot add default function
594         // arguments for an out-of-line definition of a member function of a
595         // dependent type.
596         int WhichKind = 2;
597         if (CXXRecordDecl *Record
598               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
599           if (Record->getDescribedClassTemplate())
600             WhichKind = 0;
601           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
602             WhichKind = 1;
603           else
604             WhichKind = 2;
605         }
606 
607         Diag(NewParam->getLocation(),
608              diag::err_param_default_argument_member_template_redecl)
609           << WhichKind
610           << NewParam->getDefaultArgRange();
611       }
612     }
613   }
614 
615   // DR1344: If a default argument is added outside a class definition and that
616   // default argument makes the function a special member function, the program
617   // is ill-formed. This can only happen for constructors.
618   if (isa<CXXConstructorDecl>(New) &&
619       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
620     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
621                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
622     if (NewSM != OldSM) {
623       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
624       assert(NewParam->hasDefaultArg());
625       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
626         << NewParam->getDefaultArgRange() << NewSM;
627       Diag(Old->getLocation(), diag::note_previous_declaration);
628     }
629   }
630 
631   const FunctionDecl *Def;
632   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
633   // template has a constexpr specifier then all its declarations shall
634   // contain the constexpr specifier.
635   if (New->isConstexpr() != Old->isConstexpr()) {
636     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
637       << New << New->isConstexpr();
638     Diag(Old->getLocation(), diag::note_previous_declaration);
639     Invalid = true;
640   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
641              Old->isDefined(Def)) {
642     // C++11 [dcl.fcn.spec]p4:
643     //   If the definition of a function appears in a translation unit before its
644     //   first declaration as inline, the program is ill-formed.
645     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
646     Diag(Def->getLocation(), diag::note_previous_definition);
647     Invalid = true;
648   }
649 
650   // FIXME: It's not clear what should happen if multiple declarations of a
651   // deduction guide have different explicitness. For now at least we simply
652   // reject any case where the explicitness changes.
653   auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
654   if (NewGuide && NewGuide->isExplicitSpecified() !=
655                       cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
656     Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
657       << NewGuide->isExplicitSpecified();
658     Diag(Old->getLocation(), diag::note_previous_declaration);
659   }
660 
661   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
662   // argument expression, that declaration shall be a definition and shall be
663   // the only declaration of the function or function template in the
664   // translation unit.
665   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
666       functionDeclHasDefaultArgument(Old)) {
667     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
668     Diag(Old->getLocation(), diag::note_previous_declaration);
669     Invalid = true;
670   }
671 
672   return Invalid;
673 }
674 
675 NamedDecl *
676 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
677                                    MultiTemplateParamsArg TemplateParamLists) {
678   assert(D.isDecompositionDeclarator());
679   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
680 
681   // The syntax only allows a decomposition declarator as a simple-declaration
682   // or a for-range-declaration, but we parse it in more cases than that.
683   if (!D.mayHaveDecompositionDeclarator()) {
684     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
685       << Decomp.getSourceRange();
686     return nullptr;
687   }
688 
689   if (!TemplateParamLists.empty()) {
690     // FIXME: There's no rule against this, but there are also no rules that
691     // would actually make it usable, so we reject it for now.
692     Diag(TemplateParamLists.front()->getTemplateLoc(),
693          diag::err_decomp_decl_template);
694     return nullptr;
695   }
696 
697   Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
698                                    ? diag::warn_cxx14_compat_decomp_decl
699                                    : diag::ext_decomp_decl)
700       << Decomp.getSourceRange();
701 
702   // The semantic context is always just the current context.
703   DeclContext *const DC = CurContext;
704 
705   // C++1z [dcl.dcl]/8:
706   //   The decl-specifier-seq shall contain only the type-specifier auto
707   //   and cv-qualifiers.
708   auto &DS = D.getDeclSpec();
709   {
710     SmallVector<StringRef, 8> BadSpecifiers;
711     SmallVector<SourceLocation, 8> BadSpecifierLocs;
712     if (auto SCS = DS.getStorageClassSpec()) {
713       BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
714       BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
715     }
716     if (auto TSCS = DS.getThreadStorageClassSpec()) {
717       BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
718       BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
719     }
720     if (DS.isConstexprSpecified()) {
721       BadSpecifiers.push_back("constexpr");
722       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
723     }
724     if (DS.isInlineSpecified()) {
725       BadSpecifiers.push_back("inline");
726       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
727     }
728     if (!BadSpecifiers.empty()) {
729       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
730       Err << (int)BadSpecifiers.size()
731           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
732       // Don't add FixItHints to remove the specifiers; we do still respect
733       // them when building the underlying variable.
734       for (auto Loc : BadSpecifierLocs)
735         Err << SourceRange(Loc, Loc);
736     }
737     // We can't recover from it being declared as a typedef.
738     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
739       return nullptr;
740   }
741 
742   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
743   QualType R = TInfo->getType();
744 
745   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
746                                       UPPC_DeclarationType))
747     D.setInvalidType();
748 
749   // The syntax only allows a single ref-qualifier prior to the decomposition
750   // declarator. No other declarator chunks are permitted. Also check the type
751   // specifier here.
752   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
753       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
754       (D.getNumTypeObjects() == 1 &&
755        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
756     Diag(Decomp.getLSquareLoc(),
757          (D.hasGroupingParens() ||
758           (D.getNumTypeObjects() &&
759            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
760              ? diag::err_decomp_decl_parens
761              : diag::err_decomp_decl_type)
762         << R;
763 
764     // In most cases, there's no actual problem with an explicitly-specified
765     // type, but a function type won't work here, and ActOnVariableDeclarator
766     // shouldn't be called for such a type.
767     if (R->isFunctionType())
768       D.setInvalidType();
769   }
770 
771   // Build the BindingDecls.
772   SmallVector<BindingDecl*, 8> Bindings;
773 
774   // Build the BindingDecls.
775   for (auto &B : D.getDecompositionDeclarator().bindings()) {
776     // Check for name conflicts.
777     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
778     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
779                           ForRedeclaration);
780     LookupName(Previous, S,
781                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
782 
783     // It's not permitted to shadow a template parameter name.
784     if (Previous.isSingleResult() &&
785         Previous.getFoundDecl()->isTemplateParameter()) {
786       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
787                                       Previous.getFoundDecl());
788       Previous.clear();
789     }
790 
791     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
792                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
793     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
794                          /*AllowInlineNamespace*/false);
795     if (!Previous.empty()) {
796       auto *Old = Previous.getRepresentativeDecl();
797       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
798       Diag(Old->getLocation(), diag::note_previous_definition);
799     }
800 
801     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
802     PushOnScopeChains(BD, S, true);
803     Bindings.push_back(BD);
804     ParsingInitForAutoVars.insert(BD);
805   }
806 
807   // There are no prior lookup results for the variable itself, because it
808   // is unnamed.
809   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
810                                Decomp.getLSquareLoc());
811   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
812 
813   // Build the variable that holds the non-decomposed object.
814   bool AddToScope = true;
815   NamedDecl *New =
816       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
817                               MultiTemplateParamsArg(), AddToScope, Bindings);
818   CurContext->addHiddenDecl(New);
819 
820   if (isInOpenMPDeclareTargetContext())
821     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
822 
823   return New;
824 }
825 
826 static bool checkSimpleDecomposition(
827     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
828     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
829     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
830   if ((int64_t)Bindings.size() != NumElems) {
831     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
832         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
833         << (NumElems < Bindings.size());
834     return true;
835   }
836 
837   unsigned I = 0;
838   for (auto *B : Bindings) {
839     SourceLocation Loc = B->getLocation();
840     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
841     if (E.isInvalid())
842       return true;
843     E = GetInit(Loc, E.get(), I++);
844     if (E.isInvalid())
845       return true;
846     B->setBinding(ElemType, E.get());
847   }
848 
849   return false;
850 }
851 
852 static bool checkArrayLikeDecomposition(Sema &S,
853                                         ArrayRef<BindingDecl *> Bindings,
854                                         ValueDecl *Src, QualType DecompType,
855                                         const llvm::APSInt &NumElems,
856                                         QualType ElemType) {
857   return checkSimpleDecomposition(
858       S, Bindings, Src, DecompType, NumElems, ElemType,
859       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
860         ExprResult E = S.ActOnIntegerConstant(Loc, I);
861         if (E.isInvalid())
862           return ExprError();
863         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
864       });
865 }
866 
867 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
868                                     ValueDecl *Src, QualType DecompType,
869                                     const ConstantArrayType *CAT) {
870   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
871                                      llvm::APSInt(CAT->getSize()),
872                                      CAT->getElementType());
873 }
874 
875 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
876                                      ValueDecl *Src, QualType DecompType,
877                                      const VectorType *VT) {
878   return checkArrayLikeDecomposition(
879       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
880       S.Context.getQualifiedType(VT->getElementType(),
881                                  DecompType.getQualifiers()));
882 }
883 
884 static bool checkComplexDecomposition(Sema &S,
885                                       ArrayRef<BindingDecl *> Bindings,
886                                       ValueDecl *Src, QualType DecompType,
887                                       const ComplexType *CT) {
888   return checkSimpleDecomposition(
889       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
890       S.Context.getQualifiedType(CT->getElementType(),
891                                  DecompType.getQualifiers()),
892       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
893         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
894       });
895 }
896 
897 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
898                                      TemplateArgumentListInfo &Args) {
899   SmallString<128> SS;
900   llvm::raw_svector_ostream OS(SS);
901   bool First = true;
902   for (auto &Arg : Args.arguments()) {
903     if (!First)
904       OS << ", ";
905     Arg.getArgument().print(PrintingPolicy, OS);
906     First = false;
907   }
908   return OS.str();
909 }
910 
911 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
912                                      SourceLocation Loc, StringRef Trait,
913                                      TemplateArgumentListInfo &Args,
914                                      unsigned DiagID) {
915   auto DiagnoseMissing = [&] {
916     if (DiagID)
917       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
918                                                Args);
919     return true;
920   };
921 
922   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
923   NamespaceDecl *Std = S.getStdNamespace();
924   if (!Std)
925     return DiagnoseMissing();
926 
927   // Look up the trait itself, within namespace std. We can diagnose various
928   // problems with this lookup even if we've been asked to not diagnose a
929   // missing specialization, because this can only fail if the user has been
930   // declaring their own names in namespace std or we don't support the
931   // standard library implementation in use.
932   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
933                       Loc, Sema::LookupOrdinaryName);
934   if (!S.LookupQualifiedName(Result, Std))
935     return DiagnoseMissing();
936   if (Result.isAmbiguous())
937     return true;
938 
939   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
940   if (!TraitTD) {
941     Result.suppressDiagnostics();
942     NamedDecl *Found = *Result.begin();
943     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
944     S.Diag(Found->getLocation(), diag::note_declared_at);
945     return true;
946   }
947 
948   // Build the template-id.
949   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
950   if (TraitTy.isNull())
951     return true;
952   if (!S.isCompleteType(Loc, TraitTy)) {
953     if (DiagID)
954       S.RequireCompleteType(
955           Loc, TraitTy, DiagID,
956           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
957     return true;
958   }
959 
960   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
961   assert(RD && "specialization of class template is not a class?");
962 
963   // Look up the member of the trait type.
964   S.LookupQualifiedName(TraitMemberLookup, RD);
965   return TraitMemberLookup.isAmbiguous();
966 }
967 
968 static TemplateArgumentLoc
969 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
970                                    uint64_t I) {
971   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
972   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
973 }
974 
975 static TemplateArgumentLoc
976 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
977   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
978 }
979 
980 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
981 
982 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
983                                llvm::APSInt &Size) {
984   EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated);
985 
986   DeclarationName Value = S.PP.getIdentifierInfo("value");
987   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
988 
989   // Form template argument list for tuple_size<T>.
990   TemplateArgumentListInfo Args(Loc, Loc);
991   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
992 
993   // If there's no tuple_size specialization, it's not tuple-like.
994   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
995     return IsTupleLike::NotTupleLike;
996 
997   // If we get this far, we've committed to the tuple interpretation, but
998   // we can still fail if there actually isn't a usable ::value.
999 
1000   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1001     LookupResult &R;
1002     TemplateArgumentListInfo &Args;
1003     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1004         : R(R), Args(Args) {}
1005     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1006       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1007           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1008     }
1009   } Diagnoser(R, Args);
1010 
1011   if (R.empty()) {
1012     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1013     return IsTupleLike::Error;
1014   }
1015 
1016   ExprResult E =
1017       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1018   if (E.isInvalid())
1019     return IsTupleLike::Error;
1020 
1021   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1022   if (E.isInvalid())
1023     return IsTupleLike::Error;
1024 
1025   return IsTupleLike::TupleLike;
1026 }
1027 
1028 /// \return std::tuple_element<I, T>::type.
1029 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1030                                         unsigned I, QualType T) {
1031   // Form template argument list for tuple_element<I, T>.
1032   TemplateArgumentListInfo Args(Loc, Loc);
1033   Args.addArgument(
1034       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1035   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1036 
1037   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1038   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1039   if (lookupStdTypeTraitMember(
1040           S, R, Loc, "tuple_element", Args,
1041           diag::err_decomp_decl_std_tuple_element_not_specialized))
1042     return QualType();
1043 
1044   auto *TD = R.getAsSingle<TypeDecl>();
1045   if (!TD) {
1046     R.suppressDiagnostics();
1047     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1048       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1049     if (!R.empty())
1050       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1051     return QualType();
1052   }
1053 
1054   return S.Context.getTypeDeclType(TD);
1055 }
1056 
1057 namespace {
1058 struct BindingDiagnosticTrap {
1059   Sema &S;
1060   DiagnosticErrorTrap Trap;
1061   BindingDecl *BD;
1062 
1063   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1064       : S(S), Trap(S.Diags), BD(BD) {}
1065   ~BindingDiagnosticTrap() {
1066     if (Trap.hasErrorOccurred())
1067       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1068   }
1069 };
1070 }
1071 
1072 static bool checkTupleLikeDecomposition(Sema &S,
1073                                         ArrayRef<BindingDecl *> Bindings,
1074                                         VarDecl *Src, QualType DecompType,
1075                                         const llvm::APSInt &TupleSize) {
1076   if ((int64_t)Bindings.size() != TupleSize) {
1077     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1078         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1079         << (TupleSize < Bindings.size());
1080     return true;
1081   }
1082 
1083   if (Bindings.empty())
1084     return false;
1085 
1086   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1087 
1088   // [dcl.decomp]p3:
1089   //   The unqualified-id get is looked up in the scope of E by class member
1090   //   access lookup
1091   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1092   bool UseMemberGet = false;
1093   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1094     if (auto *RD = DecompType->getAsCXXRecordDecl())
1095       S.LookupQualifiedName(MemberGet, RD);
1096     if (MemberGet.isAmbiguous())
1097       return true;
1098     UseMemberGet = !MemberGet.empty();
1099     S.FilterAcceptableTemplateNames(MemberGet);
1100   }
1101 
1102   unsigned I = 0;
1103   for (auto *B : Bindings) {
1104     BindingDiagnosticTrap Trap(S, B);
1105     SourceLocation Loc = B->getLocation();
1106 
1107     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1108     if (E.isInvalid())
1109       return true;
1110 
1111     //   e is an lvalue if the type of the entity is an lvalue reference and
1112     //   an xvalue otherwise
1113     if (!Src->getType()->isLValueReferenceType())
1114       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1115                                    E.get(), nullptr, VK_XValue);
1116 
1117     TemplateArgumentListInfo Args(Loc, Loc);
1118     Args.addArgument(
1119         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1120 
1121     if (UseMemberGet) {
1122       //   if [lookup of member get] finds at least one declaration, the
1123       //   initializer is e.get<i-1>().
1124       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1125                                      CXXScopeSpec(), SourceLocation(), nullptr,
1126                                      MemberGet, &Args, nullptr);
1127       if (E.isInvalid())
1128         return true;
1129 
1130       E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1131     } else {
1132       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1133       //   in the associated namespaces.
1134       Expr *Get = UnresolvedLookupExpr::Create(
1135           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1136           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1137           UnresolvedSetIterator(), UnresolvedSetIterator());
1138 
1139       Expr *Arg = E.get();
1140       E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1141     }
1142     if (E.isInvalid())
1143       return true;
1144     Expr *Init = E.get();
1145 
1146     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1147     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1148     if (T.isNull())
1149       return true;
1150 
1151     //   each vi is a variable of type "reference to T" initialized with the
1152     //   initializer, where the reference is an lvalue reference if the
1153     //   initializer is an lvalue and an rvalue reference otherwise
1154     QualType RefType =
1155         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1156     if (RefType.isNull())
1157       return true;
1158     auto *RefVD = VarDecl::Create(
1159         S.Context, Src->getDeclContext(), Loc, Loc,
1160         B->getDeclName().getAsIdentifierInfo(), RefType,
1161         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1162     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1163     RefVD->setTSCSpec(Src->getTSCSpec());
1164     RefVD->setImplicit();
1165     if (Src->isInlineSpecified())
1166       RefVD->setInlineSpecified();
1167     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1168 
1169     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1170     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1171     InitializationSequence Seq(S, Entity, Kind, Init);
1172     E = Seq.Perform(S, Entity, Kind, Init);
1173     if (E.isInvalid())
1174       return true;
1175     E = S.ActOnFinishFullExpr(E.get(), Loc);
1176     if (E.isInvalid())
1177       return true;
1178     RefVD->setInit(E.get());
1179     RefVD->checkInitIsICE();
1180 
1181     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1182                                    DeclarationNameInfo(B->getDeclName(), Loc),
1183                                    RefVD);
1184     if (E.isInvalid())
1185       return true;
1186 
1187     B->setBinding(T, E.get());
1188     I++;
1189   }
1190 
1191   return false;
1192 }
1193 
1194 /// Find the base class to decompose in a built-in decomposition of a class type.
1195 /// This base class search is, unfortunately, not quite like any other that we
1196 /// perform anywhere else in C++.
1197 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1198                                                       SourceLocation Loc,
1199                                                       const CXXRecordDecl *RD,
1200                                                       CXXCastPath &BasePath) {
1201   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1202                           CXXBasePath &Path) {
1203     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1204   };
1205 
1206   const CXXRecordDecl *ClassWithFields = nullptr;
1207   if (RD->hasDirectFields())
1208     // [dcl.decomp]p4:
1209     //   Otherwise, all of E's non-static data members shall be public direct
1210     //   members of E ...
1211     ClassWithFields = RD;
1212   else {
1213     //   ... or of ...
1214     CXXBasePaths Paths;
1215     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1216     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1217       // If no classes have fields, just decompose RD itself. (This will work
1218       // if and only if zero bindings were provided.)
1219       return RD;
1220     }
1221 
1222     CXXBasePath *BestPath = nullptr;
1223     for (auto &P : Paths) {
1224       if (!BestPath)
1225         BestPath = &P;
1226       else if (!S.Context.hasSameType(P.back().Base->getType(),
1227                                       BestPath->back().Base->getType())) {
1228         //   ... the same ...
1229         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1230           << false << RD << BestPath->back().Base->getType()
1231           << P.back().Base->getType();
1232         return nullptr;
1233       } else if (P.Access < BestPath->Access) {
1234         BestPath = &P;
1235       }
1236     }
1237 
1238     //   ... unambiguous ...
1239     QualType BaseType = BestPath->back().Base->getType();
1240     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1241       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1242         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1243       return nullptr;
1244     }
1245 
1246     //   ... public base class of E.
1247     if (BestPath->Access != AS_public) {
1248       S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1249         << RD << BaseType;
1250       for (auto &BS : *BestPath) {
1251         if (BS.Base->getAccessSpecifier() != AS_public) {
1252           S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1253             << (BS.Base->getAccessSpecifier() == AS_protected)
1254             << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1255           break;
1256         }
1257       }
1258       return nullptr;
1259     }
1260 
1261     ClassWithFields = BaseType->getAsCXXRecordDecl();
1262     S.BuildBasePathArray(Paths, BasePath);
1263   }
1264 
1265   // The above search did not check whether the selected class itself has base
1266   // classes with fields, so check that now.
1267   CXXBasePaths Paths;
1268   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1269     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1270       << (ClassWithFields == RD) << RD << ClassWithFields
1271       << Paths.front().back().Base->getType();
1272     return nullptr;
1273   }
1274 
1275   return ClassWithFields;
1276 }
1277 
1278 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1279                                      ValueDecl *Src, QualType DecompType,
1280                                      const CXXRecordDecl *RD) {
1281   CXXCastPath BasePath;
1282   RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1283   if (!RD)
1284     return true;
1285   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1286                                                  DecompType.getQualifiers());
1287 
1288   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1289     unsigned NumFields =
1290         std::count_if(RD->field_begin(), RD->field_end(),
1291                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1292     assert(Bindings.size() != NumFields);
1293     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1294         << DecompType << (unsigned)Bindings.size() << NumFields
1295         << (NumFields < Bindings.size());
1296     return true;
1297   };
1298 
1299   //   all of E's non-static data members shall be public [...] members,
1300   //   E shall not have an anonymous union member, ...
1301   unsigned I = 0;
1302   for (auto *FD : RD->fields()) {
1303     if (FD->isUnnamedBitfield())
1304       continue;
1305 
1306     if (FD->isAnonymousStructOrUnion()) {
1307       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1308         << DecompType << FD->getType()->isUnionType();
1309       S.Diag(FD->getLocation(), diag::note_declared_at);
1310       return true;
1311     }
1312 
1313     // We have a real field to bind.
1314     if (I >= Bindings.size())
1315       return DiagnoseBadNumberOfBindings();
1316     auto *B = Bindings[I++];
1317 
1318     SourceLocation Loc = B->getLocation();
1319     if (FD->getAccess() != AS_public) {
1320       S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1321 
1322       // Determine whether the access specifier was explicit.
1323       bool Implicit = true;
1324       for (const auto *D : RD->decls()) {
1325         if (declaresSameEntity(D, FD))
1326           break;
1327         if (isa<AccessSpecDecl>(D)) {
1328           Implicit = false;
1329           break;
1330         }
1331       }
1332 
1333       S.Diag(FD->getLocation(), diag::note_access_natural)
1334         << (FD->getAccess() == AS_protected) << Implicit;
1335       return true;
1336     }
1337 
1338     // Initialize the binding to Src.FD.
1339     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1340     if (E.isInvalid())
1341       return true;
1342     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1343                             VK_LValue, &BasePath);
1344     if (E.isInvalid())
1345       return true;
1346     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1347                                   CXXScopeSpec(), FD,
1348                                   DeclAccessPair::make(FD, FD->getAccess()),
1349                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1350     if (E.isInvalid())
1351       return true;
1352 
1353     // If the type of the member is T, the referenced type is cv T, where cv is
1354     // the cv-qualification of the decomposition expression.
1355     //
1356     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1357     // 'const' to the type of the field.
1358     Qualifiers Q = DecompType.getQualifiers();
1359     if (FD->isMutable())
1360       Q.removeConst();
1361     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1362   }
1363 
1364   if (I != Bindings.size())
1365     return DiagnoseBadNumberOfBindings();
1366 
1367   return false;
1368 }
1369 
1370 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1371   QualType DecompType = DD->getType();
1372 
1373   // If the type of the decomposition is dependent, then so is the type of
1374   // each binding.
1375   if (DecompType->isDependentType()) {
1376     for (auto *B : DD->bindings())
1377       B->setType(Context.DependentTy);
1378     return;
1379   }
1380 
1381   DecompType = DecompType.getNonReferenceType();
1382   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1383 
1384   // C++1z [dcl.decomp]/2:
1385   //   If E is an array type [...]
1386   // As an extension, we also support decomposition of built-in complex and
1387   // vector types.
1388   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1389     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1390       DD->setInvalidDecl();
1391     return;
1392   }
1393   if (auto *VT = DecompType->getAs<VectorType>()) {
1394     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1395       DD->setInvalidDecl();
1396     return;
1397   }
1398   if (auto *CT = DecompType->getAs<ComplexType>()) {
1399     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1400       DD->setInvalidDecl();
1401     return;
1402   }
1403 
1404   // C++1z [dcl.decomp]/3:
1405   //   if the expression std::tuple_size<E>::value is a well-formed integral
1406   //   constant expression, [...]
1407   llvm::APSInt TupleSize(32);
1408   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1409   case IsTupleLike::Error:
1410     DD->setInvalidDecl();
1411     return;
1412 
1413   case IsTupleLike::TupleLike:
1414     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1415       DD->setInvalidDecl();
1416     return;
1417 
1418   case IsTupleLike::NotTupleLike:
1419     break;
1420   }
1421 
1422   // C++1z [dcl.dcl]/8:
1423   //   [E shall be of array or non-union class type]
1424   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1425   if (!RD || RD->isUnion()) {
1426     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1427         << DD << !RD << DecompType;
1428     DD->setInvalidDecl();
1429     return;
1430   }
1431 
1432   // C++1z [dcl.decomp]/4:
1433   //   all of E's non-static data members shall be [...] direct members of
1434   //   E or of the same unambiguous public base class of E, ...
1435   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1436     DD->setInvalidDecl();
1437 }
1438 
1439 /// \brief Merge the exception specifications of two variable declarations.
1440 ///
1441 /// This is called when there's a redeclaration of a VarDecl. The function
1442 /// checks if the redeclaration might have an exception specification and
1443 /// validates compatibility and merges the specs if necessary.
1444 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1445   // Shortcut if exceptions are disabled.
1446   if (!getLangOpts().CXXExceptions)
1447     return;
1448 
1449   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1450          "Should only be called if types are otherwise the same.");
1451 
1452   QualType NewType = New->getType();
1453   QualType OldType = Old->getType();
1454 
1455   // We're only interested in pointers and references to functions, as well
1456   // as pointers to member functions.
1457   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1458     NewType = R->getPointeeType();
1459     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1460   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1461     NewType = P->getPointeeType();
1462     OldType = OldType->getAs<PointerType>()->getPointeeType();
1463   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1464     NewType = M->getPointeeType();
1465     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1466   }
1467 
1468   if (!NewType->isFunctionProtoType())
1469     return;
1470 
1471   // There's lots of special cases for functions. For function pointers, system
1472   // libraries are hopefully not as broken so that we don't need these
1473   // workarounds.
1474   if (CheckEquivalentExceptionSpec(
1475         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1476         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1477     New->setInvalidDecl();
1478   }
1479 }
1480 
1481 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1482 /// function declaration are well-formed according to C++
1483 /// [dcl.fct.default].
1484 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1485   unsigned NumParams = FD->getNumParams();
1486   unsigned p;
1487 
1488   // Find first parameter with a default argument
1489   for (p = 0; p < NumParams; ++p) {
1490     ParmVarDecl *Param = FD->getParamDecl(p);
1491     if (Param->hasDefaultArg())
1492       break;
1493   }
1494 
1495   // C++11 [dcl.fct.default]p4:
1496   //   In a given function declaration, each parameter subsequent to a parameter
1497   //   with a default argument shall have a default argument supplied in this or
1498   //   a previous declaration or shall be a function parameter pack. A default
1499   //   argument shall not be redefined by a later declaration (not even to the
1500   //   same value).
1501   unsigned LastMissingDefaultArg = 0;
1502   for (; p < NumParams; ++p) {
1503     ParmVarDecl *Param = FD->getParamDecl(p);
1504     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1505       if (Param->isInvalidDecl())
1506         /* We already complained about this parameter. */;
1507       else if (Param->getIdentifier())
1508         Diag(Param->getLocation(),
1509              diag::err_param_default_argument_missing_name)
1510           << Param->getIdentifier();
1511       else
1512         Diag(Param->getLocation(),
1513              diag::err_param_default_argument_missing);
1514 
1515       LastMissingDefaultArg = p;
1516     }
1517   }
1518 
1519   if (LastMissingDefaultArg > 0) {
1520     // Some default arguments were missing. Clear out all of the
1521     // default arguments up to (and including) the last missing
1522     // default argument, so that we leave the function parameters
1523     // in a semantically valid state.
1524     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1525       ParmVarDecl *Param = FD->getParamDecl(p);
1526       if (Param->hasDefaultArg()) {
1527         Param->setDefaultArg(nullptr);
1528       }
1529     }
1530   }
1531 }
1532 
1533 // CheckConstexprParameterTypes - Check whether a function's parameter types
1534 // are all literal types. If so, return true. If not, produce a suitable
1535 // diagnostic and return false.
1536 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1537                                          const FunctionDecl *FD) {
1538   unsigned ArgIndex = 0;
1539   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1540   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1541                                               e = FT->param_type_end();
1542        i != e; ++i, ++ArgIndex) {
1543     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1544     SourceLocation ParamLoc = PD->getLocation();
1545     if (!(*i)->isDependentType() &&
1546         SemaRef.RequireLiteralType(ParamLoc, *i,
1547                                    diag::err_constexpr_non_literal_param,
1548                                    ArgIndex+1, PD->getSourceRange(),
1549                                    isa<CXXConstructorDecl>(FD)))
1550       return false;
1551   }
1552   return true;
1553 }
1554 
1555 /// \brief Get diagnostic %select index for tag kind for
1556 /// record diagnostic message.
1557 /// WARNING: Indexes apply to particular diagnostics only!
1558 ///
1559 /// \returns diagnostic %select index.
1560 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1561   switch (Tag) {
1562   case TTK_Struct: return 0;
1563   case TTK_Interface: return 1;
1564   case TTK_Class:  return 2;
1565   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1566   }
1567 }
1568 
1569 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1570 // the requirements of a constexpr function definition or a constexpr
1571 // constructor definition. If so, return true. If not, produce appropriate
1572 // diagnostics and return false.
1573 //
1574 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1575 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1576   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1577   if (MD && MD->isInstance()) {
1578     // C++11 [dcl.constexpr]p4:
1579     //  The definition of a constexpr constructor shall satisfy the following
1580     //  constraints:
1581     //  - the class shall not have any virtual base classes;
1582     const CXXRecordDecl *RD = MD->getParent();
1583     if (RD->getNumVBases()) {
1584       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1585         << isa<CXXConstructorDecl>(NewFD)
1586         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1587       for (const auto &I : RD->vbases())
1588         Diag(I.getLocStart(),
1589              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
1590       return false;
1591     }
1592   }
1593 
1594   if (!isa<CXXConstructorDecl>(NewFD)) {
1595     // C++11 [dcl.constexpr]p3:
1596     //  The definition of a constexpr function shall satisfy the following
1597     //  constraints:
1598     // - it shall not be virtual;
1599     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1600     if (Method && Method->isVirtual()) {
1601       Method = Method->getCanonicalDecl();
1602       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1603 
1604       // If it's not obvious why this function is virtual, find an overridden
1605       // function which uses the 'virtual' keyword.
1606       const CXXMethodDecl *WrittenVirtual = Method;
1607       while (!WrittenVirtual->isVirtualAsWritten())
1608         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1609       if (WrittenVirtual != Method)
1610         Diag(WrittenVirtual->getLocation(),
1611              diag::note_overridden_virtual_function);
1612       return false;
1613     }
1614 
1615     // - its return type shall be a literal type;
1616     QualType RT = NewFD->getReturnType();
1617     if (!RT->isDependentType() &&
1618         RequireLiteralType(NewFD->getLocation(), RT,
1619                            diag::err_constexpr_non_literal_return))
1620       return false;
1621   }
1622 
1623   // - each of its parameter types shall be a literal type;
1624   if (!CheckConstexprParameterTypes(*this, NewFD))
1625     return false;
1626 
1627   return true;
1628 }
1629 
1630 /// Check the given declaration statement is legal within a constexpr function
1631 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1632 ///
1633 /// \return true if the body is OK (maybe only as an extension), false if we
1634 ///         have diagnosed a problem.
1635 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1636                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1637   // C++11 [dcl.constexpr]p3 and p4:
1638   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1639   //  contain only
1640   for (const auto *DclIt : DS->decls()) {
1641     switch (DclIt->getKind()) {
1642     case Decl::StaticAssert:
1643     case Decl::Using:
1644     case Decl::UsingShadow:
1645     case Decl::UsingDirective:
1646     case Decl::UnresolvedUsingTypename:
1647     case Decl::UnresolvedUsingValue:
1648       //   - static_assert-declarations
1649       //   - using-declarations,
1650       //   - using-directives,
1651       continue;
1652 
1653     case Decl::Typedef:
1654     case Decl::TypeAlias: {
1655       //   - typedef declarations and alias-declarations that do not define
1656       //     classes or enumerations,
1657       const auto *TN = cast<TypedefNameDecl>(DclIt);
1658       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1659         // Don't allow variably-modified types in constexpr functions.
1660         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1661         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1662           << TL.getSourceRange() << TL.getType()
1663           << isa<CXXConstructorDecl>(Dcl);
1664         return false;
1665       }
1666       continue;
1667     }
1668 
1669     case Decl::Enum:
1670     case Decl::CXXRecord:
1671       // C++1y allows types to be defined, not just declared.
1672       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1673         SemaRef.Diag(DS->getLocStart(),
1674                      SemaRef.getLangOpts().CPlusPlus14
1675                        ? diag::warn_cxx11_compat_constexpr_type_definition
1676                        : diag::ext_constexpr_type_definition)
1677           << isa<CXXConstructorDecl>(Dcl);
1678       continue;
1679 
1680     case Decl::EnumConstant:
1681     case Decl::IndirectField:
1682     case Decl::ParmVar:
1683       // These can only appear with other declarations which are banned in
1684       // C++11 and permitted in C++1y, so ignore them.
1685       continue;
1686 
1687     case Decl::Var:
1688     case Decl::Decomposition: {
1689       // C++1y [dcl.constexpr]p3 allows anything except:
1690       //   a definition of a variable of non-literal type or of static or
1691       //   thread storage duration or for which no initialization is performed.
1692       const auto *VD = cast<VarDecl>(DclIt);
1693       if (VD->isThisDeclarationADefinition()) {
1694         if (VD->isStaticLocal()) {
1695           SemaRef.Diag(VD->getLocation(),
1696                        diag::err_constexpr_local_var_static)
1697             << isa<CXXConstructorDecl>(Dcl)
1698             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1699           return false;
1700         }
1701         if (!VD->getType()->isDependentType() &&
1702             SemaRef.RequireLiteralType(
1703               VD->getLocation(), VD->getType(),
1704               diag::err_constexpr_local_var_non_literal_type,
1705               isa<CXXConstructorDecl>(Dcl)))
1706           return false;
1707         if (!VD->getType()->isDependentType() &&
1708             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1709           SemaRef.Diag(VD->getLocation(),
1710                        diag::err_constexpr_local_var_no_init)
1711             << isa<CXXConstructorDecl>(Dcl);
1712           return false;
1713         }
1714       }
1715       SemaRef.Diag(VD->getLocation(),
1716                    SemaRef.getLangOpts().CPlusPlus14
1717                     ? diag::warn_cxx11_compat_constexpr_local_var
1718                     : diag::ext_constexpr_local_var)
1719         << isa<CXXConstructorDecl>(Dcl);
1720       continue;
1721     }
1722 
1723     case Decl::NamespaceAlias:
1724     case Decl::Function:
1725       // These are disallowed in C++11 and permitted in C++1y. Allow them
1726       // everywhere as an extension.
1727       if (!Cxx1yLoc.isValid())
1728         Cxx1yLoc = DS->getLocStart();
1729       continue;
1730 
1731     default:
1732       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1733         << isa<CXXConstructorDecl>(Dcl);
1734       return false;
1735     }
1736   }
1737 
1738   return true;
1739 }
1740 
1741 /// Check that the given field is initialized within a constexpr constructor.
1742 ///
1743 /// \param Dcl The constexpr constructor being checked.
1744 /// \param Field The field being checked. This may be a member of an anonymous
1745 ///        struct or union nested within the class being checked.
1746 /// \param Inits All declarations, including anonymous struct/union members and
1747 ///        indirect members, for which any initialization was provided.
1748 /// \param Diagnosed Set to true if an error is produced.
1749 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1750                                           const FunctionDecl *Dcl,
1751                                           FieldDecl *Field,
1752                                           llvm::SmallSet<Decl*, 16> &Inits,
1753                                           bool &Diagnosed) {
1754   if (Field->isInvalidDecl())
1755     return;
1756 
1757   if (Field->isUnnamedBitfield())
1758     return;
1759 
1760   // Anonymous unions with no variant members and empty anonymous structs do not
1761   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1762   // indirect fields don't need initializing.
1763   if (Field->isAnonymousStructOrUnion() &&
1764       (Field->getType()->isUnionType()
1765            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1766            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1767     return;
1768 
1769   if (!Inits.count(Field)) {
1770     if (!Diagnosed) {
1771       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1772       Diagnosed = true;
1773     }
1774     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1775   } else if (Field->isAnonymousStructOrUnion()) {
1776     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1777     for (auto *I : RD->fields())
1778       // If an anonymous union contains an anonymous struct of which any member
1779       // is initialized, all members must be initialized.
1780       if (!RD->isUnion() || Inits.count(I))
1781         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1782   }
1783 }
1784 
1785 /// Check the provided statement is allowed in a constexpr function
1786 /// definition.
1787 static bool
1788 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1789                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1790                            SourceLocation &Cxx1yLoc) {
1791   // - its function-body shall be [...] a compound-statement that contains only
1792   switch (S->getStmtClass()) {
1793   case Stmt::NullStmtClass:
1794     //   - null statements,
1795     return true;
1796 
1797   case Stmt::DeclStmtClass:
1798     //   - static_assert-declarations
1799     //   - using-declarations,
1800     //   - using-directives,
1801     //   - typedef declarations and alias-declarations that do not define
1802     //     classes or enumerations,
1803     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1804       return false;
1805     return true;
1806 
1807   case Stmt::ReturnStmtClass:
1808     //   - and exactly one return statement;
1809     if (isa<CXXConstructorDecl>(Dcl)) {
1810       // C++1y allows return statements in constexpr constructors.
1811       if (!Cxx1yLoc.isValid())
1812         Cxx1yLoc = S->getLocStart();
1813       return true;
1814     }
1815 
1816     ReturnStmts.push_back(S->getLocStart());
1817     return true;
1818 
1819   case Stmt::CompoundStmtClass: {
1820     // C++1y allows compound-statements.
1821     if (!Cxx1yLoc.isValid())
1822       Cxx1yLoc = S->getLocStart();
1823 
1824     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1825     for (auto *BodyIt : CompStmt->body()) {
1826       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1827                                       Cxx1yLoc))
1828         return false;
1829     }
1830     return true;
1831   }
1832 
1833   case Stmt::AttributedStmtClass:
1834     if (!Cxx1yLoc.isValid())
1835       Cxx1yLoc = S->getLocStart();
1836     return true;
1837 
1838   case Stmt::IfStmtClass: {
1839     // C++1y allows if-statements.
1840     if (!Cxx1yLoc.isValid())
1841       Cxx1yLoc = S->getLocStart();
1842 
1843     IfStmt *If = cast<IfStmt>(S);
1844     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1845                                     Cxx1yLoc))
1846       return false;
1847     if (If->getElse() &&
1848         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1849                                     Cxx1yLoc))
1850       return false;
1851     return true;
1852   }
1853 
1854   case Stmt::WhileStmtClass:
1855   case Stmt::DoStmtClass:
1856   case Stmt::ForStmtClass:
1857   case Stmt::CXXForRangeStmtClass:
1858   case Stmt::ContinueStmtClass:
1859     // C++1y allows all of these. We don't allow them as extensions in C++11,
1860     // because they don't make sense without variable mutation.
1861     if (!SemaRef.getLangOpts().CPlusPlus14)
1862       break;
1863     if (!Cxx1yLoc.isValid())
1864       Cxx1yLoc = S->getLocStart();
1865     for (Stmt *SubStmt : S->children())
1866       if (SubStmt &&
1867           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1868                                       Cxx1yLoc))
1869         return false;
1870     return true;
1871 
1872   case Stmt::SwitchStmtClass:
1873   case Stmt::CaseStmtClass:
1874   case Stmt::DefaultStmtClass:
1875   case Stmt::BreakStmtClass:
1876     // C++1y allows switch-statements, and since they don't need variable
1877     // mutation, we can reasonably allow them in C++11 as an extension.
1878     if (!Cxx1yLoc.isValid())
1879       Cxx1yLoc = S->getLocStart();
1880     for (Stmt *SubStmt : S->children())
1881       if (SubStmt &&
1882           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1883                                       Cxx1yLoc))
1884         return false;
1885     return true;
1886 
1887   default:
1888     if (!isa<Expr>(S))
1889       break;
1890 
1891     // C++1y allows expression-statements.
1892     if (!Cxx1yLoc.isValid())
1893       Cxx1yLoc = S->getLocStart();
1894     return true;
1895   }
1896 
1897   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1898     << isa<CXXConstructorDecl>(Dcl);
1899   return false;
1900 }
1901 
1902 /// Check the body for the given constexpr function declaration only contains
1903 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1904 ///
1905 /// \return true if the body is OK, false if we have diagnosed a problem.
1906 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1907   if (isa<CXXTryStmt>(Body)) {
1908     // C++11 [dcl.constexpr]p3:
1909     //  The definition of a constexpr function shall satisfy the following
1910     //  constraints: [...]
1911     // - its function-body shall be = delete, = default, or a
1912     //   compound-statement
1913     //
1914     // C++11 [dcl.constexpr]p4:
1915     //  In the definition of a constexpr constructor, [...]
1916     // - its function-body shall not be a function-try-block;
1917     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1918       << isa<CXXConstructorDecl>(Dcl);
1919     return false;
1920   }
1921 
1922   SmallVector<SourceLocation, 4> ReturnStmts;
1923 
1924   // - its function-body shall be [...] a compound-statement that contains only
1925   //   [... list of cases ...]
1926   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1927   SourceLocation Cxx1yLoc;
1928   for (auto *BodyIt : CompBody->body()) {
1929     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1930       return false;
1931   }
1932 
1933   if (Cxx1yLoc.isValid())
1934     Diag(Cxx1yLoc,
1935          getLangOpts().CPlusPlus14
1936            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1937            : diag::ext_constexpr_body_invalid_stmt)
1938       << isa<CXXConstructorDecl>(Dcl);
1939 
1940   if (const CXXConstructorDecl *Constructor
1941         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1942     const CXXRecordDecl *RD = Constructor->getParent();
1943     // DR1359:
1944     // - every non-variant non-static data member and base class sub-object
1945     //   shall be initialized;
1946     // DR1460:
1947     // - if the class is a union having variant members, exactly one of them
1948     //   shall be initialized;
1949     if (RD->isUnion()) {
1950       if (Constructor->getNumCtorInitializers() == 0 &&
1951           RD->hasVariantMembers()) {
1952         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1953         return false;
1954       }
1955     } else if (!Constructor->isDependentContext() &&
1956                !Constructor->isDelegatingConstructor()) {
1957       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1958 
1959       // Skip detailed checking if we have enough initializers, and we would
1960       // allow at most one initializer per member.
1961       bool AnyAnonStructUnionMembers = false;
1962       unsigned Fields = 0;
1963       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1964            E = RD->field_end(); I != E; ++I, ++Fields) {
1965         if (I->isAnonymousStructOrUnion()) {
1966           AnyAnonStructUnionMembers = true;
1967           break;
1968         }
1969       }
1970       // DR1460:
1971       // - if the class is a union-like class, but is not a union, for each of
1972       //   its anonymous union members having variant members, exactly one of
1973       //   them shall be initialized;
1974       if (AnyAnonStructUnionMembers ||
1975           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1976         // Check initialization of non-static data members. Base classes are
1977         // always initialized so do not need to be checked. Dependent bases
1978         // might not have initializers in the member initializer list.
1979         llvm::SmallSet<Decl*, 16> Inits;
1980         for (const auto *I: Constructor->inits()) {
1981           if (FieldDecl *FD = I->getMember())
1982             Inits.insert(FD);
1983           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1984             Inits.insert(ID->chain_begin(), ID->chain_end());
1985         }
1986 
1987         bool Diagnosed = false;
1988         for (auto *I : RD->fields())
1989           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1990         if (Diagnosed)
1991           return false;
1992       }
1993     }
1994   } else {
1995     if (ReturnStmts.empty()) {
1996       // C++1y doesn't require constexpr functions to contain a 'return'
1997       // statement. We still do, unless the return type might be void, because
1998       // otherwise if there's no return statement, the function cannot
1999       // be used in a core constant expression.
2000       bool OK = getLangOpts().CPlusPlus14 &&
2001                 (Dcl->getReturnType()->isVoidType() ||
2002                  Dcl->getReturnType()->isDependentType());
2003       Diag(Dcl->getLocation(),
2004            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2005               : diag::err_constexpr_body_no_return);
2006       if (!OK)
2007         return false;
2008     } else if (ReturnStmts.size() > 1) {
2009       Diag(ReturnStmts.back(),
2010            getLangOpts().CPlusPlus14
2011              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2012              : diag::ext_constexpr_body_multiple_return);
2013       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2014         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2015     }
2016   }
2017 
2018   // C++11 [dcl.constexpr]p5:
2019   //   if no function argument values exist such that the function invocation
2020   //   substitution would produce a constant expression, the program is
2021   //   ill-formed; no diagnostic required.
2022   // C++11 [dcl.constexpr]p3:
2023   //   - every constructor call and implicit conversion used in initializing the
2024   //     return value shall be one of those allowed in a constant expression.
2025   // C++11 [dcl.constexpr]p4:
2026   //   - every constructor involved in initializing non-static data members and
2027   //     base class sub-objects shall be a constexpr constructor.
2028   SmallVector<PartialDiagnosticAt, 8> Diags;
2029   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2030     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2031       << isa<CXXConstructorDecl>(Dcl);
2032     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2033       Diag(Diags[I].first, Diags[I].second);
2034     // Don't return false here: we allow this for compatibility in
2035     // system headers.
2036   }
2037 
2038   return true;
2039 }
2040 
2041 /// isCurrentClassName - Determine whether the identifier II is the
2042 /// name of the class type currently being defined. In the case of
2043 /// nested classes, this will only return true if II is the name of
2044 /// the innermost class.
2045 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2046                               const CXXScopeSpec *SS) {
2047   assert(getLangOpts().CPlusPlus && "No class names in C!");
2048 
2049   CXXRecordDecl *CurDecl;
2050   if (SS && SS->isSet() && !SS->isInvalid()) {
2051     DeclContext *DC = computeDeclContext(*SS, true);
2052     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2053   } else
2054     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2055 
2056   if (CurDecl && CurDecl->getIdentifier())
2057     return &II == CurDecl->getIdentifier();
2058   return false;
2059 }
2060 
2061 /// \brief Determine whether the identifier II is a typo for the name of
2062 /// the class type currently being defined. If so, update it to the identifier
2063 /// that should have been used.
2064 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2065   assert(getLangOpts().CPlusPlus && "No class names in C!");
2066 
2067   if (!getLangOpts().SpellChecking)
2068     return false;
2069 
2070   CXXRecordDecl *CurDecl;
2071   if (SS && SS->isSet() && !SS->isInvalid()) {
2072     DeclContext *DC = computeDeclContext(*SS, true);
2073     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2074   } else
2075     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2076 
2077   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2078       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2079           < II->getLength()) {
2080     II = CurDecl->getIdentifier();
2081     return true;
2082   }
2083 
2084   return false;
2085 }
2086 
2087 /// \brief Determine whether the given class is a base class of the given
2088 /// class, including looking at dependent bases.
2089 static bool findCircularInheritance(const CXXRecordDecl *Class,
2090                                     const CXXRecordDecl *Current) {
2091   SmallVector<const CXXRecordDecl*, 8> Queue;
2092 
2093   Class = Class->getCanonicalDecl();
2094   while (true) {
2095     for (const auto &I : Current->bases()) {
2096       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2097       if (!Base)
2098         continue;
2099 
2100       Base = Base->getDefinition();
2101       if (!Base)
2102         continue;
2103 
2104       if (Base->getCanonicalDecl() == Class)
2105         return true;
2106 
2107       Queue.push_back(Base);
2108     }
2109 
2110     if (Queue.empty())
2111       return false;
2112 
2113     Current = Queue.pop_back_val();
2114   }
2115 
2116   return false;
2117 }
2118 
2119 /// \brief Check the validity of a C++ base class specifier.
2120 ///
2121 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2122 /// and returns NULL otherwise.
2123 CXXBaseSpecifier *
2124 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2125                          SourceRange SpecifierRange,
2126                          bool Virtual, AccessSpecifier Access,
2127                          TypeSourceInfo *TInfo,
2128                          SourceLocation EllipsisLoc) {
2129   QualType BaseType = TInfo->getType();
2130 
2131   // C++ [class.union]p1:
2132   //   A union shall not have base classes.
2133   if (Class->isUnion()) {
2134     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2135       << SpecifierRange;
2136     return nullptr;
2137   }
2138 
2139   if (EllipsisLoc.isValid() &&
2140       !TInfo->getType()->containsUnexpandedParameterPack()) {
2141     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2142       << TInfo->getTypeLoc().getSourceRange();
2143     EllipsisLoc = SourceLocation();
2144   }
2145 
2146   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2147 
2148   if (BaseType->isDependentType()) {
2149     // Make sure that we don't have circular inheritance among our dependent
2150     // bases. For non-dependent bases, the check for completeness below handles
2151     // this.
2152     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2153       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2154           ((BaseDecl = BaseDecl->getDefinition()) &&
2155            findCircularInheritance(Class, BaseDecl))) {
2156         Diag(BaseLoc, diag::err_circular_inheritance)
2157           << BaseType << Context.getTypeDeclType(Class);
2158 
2159         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2160           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2161             << BaseType;
2162 
2163         return nullptr;
2164       }
2165     }
2166 
2167     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2168                                           Class->getTagKind() == TTK_Class,
2169                                           Access, TInfo, EllipsisLoc);
2170   }
2171 
2172   // Base specifiers must be record types.
2173   if (!BaseType->isRecordType()) {
2174     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2175     return nullptr;
2176   }
2177 
2178   // C++ [class.union]p1:
2179   //   A union shall not be used as a base class.
2180   if (BaseType->isUnionType()) {
2181     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2182     return nullptr;
2183   }
2184 
2185   // For the MS ABI, propagate DLL attributes to base class templates.
2186   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2187     if (Attr *ClassAttr = getDLLAttr(Class)) {
2188       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2189               BaseType->getAsCXXRecordDecl())) {
2190         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2191                                             BaseLoc);
2192       }
2193     }
2194   }
2195 
2196   // C++ [class.derived]p2:
2197   //   The class-name in a base-specifier shall not be an incompletely
2198   //   defined class.
2199   if (RequireCompleteType(BaseLoc, BaseType,
2200                           diag::err_incomplete_base_class, SpecifierRange)) {
2201     Class->setInvalidDecl();
2202     return nullptr;
2203   }
2204 
2205   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2206   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2207   assert(BaseDecl && "Record type has no declaration");
2208   BaseDecl = BaseDecl->getDefinition();
2209   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2210   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2211   assert(CXXBaseDecl && "Base type is not a C++ type");
2212 
2213   // A class which contains a flexible array member is not suitable for use as a
2214   // base class:
2215   //   - If the layout determines that a base comes before another base,
2216   //     the flexible array member would index into the subsequent base.
2217   //   - If the layout determines that base comes before the derived class,
2218   //     the flexible array member would index into the derived class.
2219   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2220     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2221       << CXXBaseDecl->getDeclName();
2222     return nullptr;
2223   }
2224 
2225   // C++ [class]p3:
2226   //   If a class is marked final and it appears as a base-type-specifier in
2227   //   base-clause, the program is ill-formed.
2228   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2229     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2230       << CXXBaseDecl->getDeclName()
2231       << FA->isSpelledAsSealed();
2232     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2233         << CXXBaseDecl->getDeclName() << FA->getRange();
2234     return nullptr;
2235   }
2236 
2237   if (BaseDecl->isInvalidDecl())
2238     Class->setInvalidDecl();
2239 
2240   // Create the base specifier.
2241   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2242                                         Class->getTagKind() == TTK_Class,
2243                                         Access, TInfo, EllipsisLoc);
2244 }
2245 
2246 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2247 /// one entry in the base class list of a class specifier, for
2248 /// example:
2249 ///    class foo : public bar, virtual private baz {
2250 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2251 BaseResult
2252 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2253                          ParsedAttributes &Attributes,
2254                          bool Virtual, AccessSpecifier Access,
2255                          ParsedType basetype, SourceLocation BaseLoc,
2256                          SourceLocation EllipsisLoc) {
2257   if (!classdecl)
2258     return true;
2259 
2260   AdjustDeclIfTemplate(classdecl);
2261   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2262   if (!Class)
2263     return true;
2264 
2265   // We haven't yet attached the base specifiers.
2266   Class->setIsParsingBaseSpecifiers();
2267 
2268   // We do not support any C++11 attributes on base-specifiers yet.
2269   // Diagnose any attributes we see.
2270   if (!Attributes.empty()) {
2271     for (AttributeList *Attr = Attributes.getList(); Attr;
2272          Attr = Attr->getNext()) {
2273       if (Attr->isInvalid() ||
2274           Attr->getKind() == AttributeList::IgnoredAttribute)
2275         continue;
2276       Diag(Attr->getLoc(),
2277            Attr->getKind() == AttributeList::UnknownAttribute
2278              ? diag::warn_unknown_attribute_ignored
2279              : diag::err_base_specifier_attribute)
2280         << Attr->getName();
2281     }
2282   }
2283 
2284   TypeSourceInfo *TInfo = nullptr;
2285   GetTypeFromParser(basetype, &TInfo);
2286 
2287   if (EllipsisLoc.isInvalid() &&
2288       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2289                                       UPPC_BaseType))
2290     return true;
2291 
2292   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2293                                                       Virtual, Access, TInfo,
2294                                                       EllipsisLoc))
2295     return BaseSpec;
2296   else
2297     Class->setInvalidDecl();
2298 
2299   return true;
2300 }
2301 
2302 /// Use small set to collect indirect bases.  As this is only used
2303 /// locally, there's no need to abstract the small size parameter.
2304 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2305 
2306 /// \brief Recursively add the bases of Type.  Don't add Type itself.
2307 static void
2308 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2309                   const QualType &Type)
2310 {
2311   // Even though the incoming type is a base, it might not be
2312   // a class -- it could be a template parm, for instance.
2313   if (auto Rec = Type->getAs<RecordType>()) {
2314     auto Decl = Rec->getAsCXXRecordDecl();
2315 
2316     // Iterate over its bases.
2317     for (const auto &BaseSpec : Decl->bases()) {
2318       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2319         .getUnqualifiedType();
2320       if (Set.insert(Base).second)
2321         // If we've not already seen it, recurse.
2322         NoteIndirectBases(Context, Set, Base);
2323     }
2324   }
2325 }
2326 
2327 /// \brief Performs the actual work of attaching the given base class
2328 /// specifiers to a C++ class.
2329 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2330                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2331  if (Bases.empty())
2332     return false;
2333 
2334   // Used to keep track of which base types we have already seen, so
2335   // that we can properly diagnose redundant direct base types. Note
2336   // that the key is always the unqualified canonical type of the base
2337   // class.
2338   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2339 
2340   // Used to track indirect bases so we can see if a direct base is
2341   // ambiguous.
2342   IndirectBaseSet IndirectBaseTypes;
2343 
2344   // Copy non-redundant base specifiers into permanent storage.
2345   unsigned NumGoodBases = 0;
2346   bool Invalid = false;
2347   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2348     QualType NewBaseType
2349       = Context.getCanonicalType(Bases[idx]->getType());
2350     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2351 
2352     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2353     if (KnownBase) {
2354       // C++ [class.mi]p3:
2355       //   A class shall not be specified as a direct base class of a
2356       //   derived class more than once.
2357       Diag(Bases[idx]->getLocStart(),
2358            diag::err_duplicate_base_class)
2359         << KnownBase->getType()
2360         << Bases[idx]->getSourceRange();
2361 
2362       // Delete the duplicate base class specifier; we're going to
2363       // overwrite its pointer later.
2364       Context.Deallocate(Bases[idx]);
2365 
2366       Invalid = true;
2367     } else {
2368       // Okay, add this new base class.
2369       KnownBase = Bases[idx];
2370       Bases[NumGoodBases++] = Bases[idx];
2371 
2372       // Note this base's direct & indirect bases, if there could be ambiguity.
2373       if (Bases.size() > 1)
2374         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2375 
2376       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2377         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2378         if (Class->isInterface() &&
2379               (!RD->isInterface() ||
2380                KnownBase->getAccessSpecifier() != AS_public)) {
2381           // The Microsoft extension __interface does not permit bases that
2382           // are not themselves public interfaces.
2383           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2384             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2385             << RD->getSourceRange();
2386           Invalid = true;
2387         }
2388         if (RD->hasAttr<WeakAttr>())
2389           Class->addAttr(WeakAttr::CreateImplicit(Context));
2390       }
2391     }
2392   }
2393 
2394   // Attach the remaining base class specifiers to the derived class.
2395   Class->setBases(Bases.data(), NumGoodBases);
2396 
2397   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2398     // Check whether this direct base is inaccessible due to ambiguity.
2399     QualType BaseType = Bases[idx]->getType();
2400     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2401       .getUnqualifiedType();
2402 
2403     if (IndirectBaseTypes.count(CanonicalBase)) {
2404       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2405                          /*DetectVirtual=*/true);
2406       bool found
2407         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2408       assert(found);
2409       (void)found;
2410 
2411       if (Paths.isAmbiguous(CanonicalBase))
2412         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2413           << BaseType << getAmbiguousPathsDisplayString(Paths)
2414           << Bases[idx]->getSourceRange();
2415       else
2416         assert(Bases[idx]->isVirtual());
2417     }
2418 
2419     // Delete the base class specifier, since its data has been copied
2420     // into the CXXRecordDecl.
2421     Context.Deallocate(Bases[idx]);
2422   }
2423 
2424   return Invalid;
2425 }
2426 
2427 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2428 /// class, after checking whether there are any duplicate base
2429 /// classes.
2430 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2431                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2432   if (!ClassDecl || Bases.empty())
2433     return;
2434 
2435   AdjustDeclIfTemplate(ClassDecl);
2436   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2437 }
2438 
2439 /// \brief Determine whether the type \p Derived is a C++ class that is
2440 /// derived from the type \p Base.
2441 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2442   if (!getLangOpts().CPlusPlus)
2443     return false;
2444 
2445   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2446   if (!DerivedRD)
2447     return false;
2448 
2449   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2450   if (!BaseRD)
2451     return false;
2452 
2453   // If either the base or the derived type is invalid, don't try to
2454   // check whether one is derived from the other.
2455   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2456     return false;
2457 
2458   // FIXME: In a modules build, do we need the entire path to be visible for us
2459   // to be able to use the inheritance relationship?
2460   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2461     return false;
2462 
2463   return DerivedRD->isDerivedFrom(BaseRD);
2464 }
2465 
2466 /// \brief Determine whether the type \p Derived is a C++ class that is
2467 /// derived from the type \p Base.
2468 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2469                          CXXBasePaths &Paths) {
2470   if (!getLangOpts().CPlusPlus)
2471     return false;
2472 
2473   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2474   if (!DerivedRD)
2475     return false;
2476 
2477   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2478   if (!BaseRD)
2479     return false;
2480 
2481   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2482     return false;
2483 
2484   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2485 }
2486 
2487 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2488                               CXXCastPath &BasePathArray) {
2489   assert(BasePathArray.empty() && "Base path array must be empty!");
2490   assert(Paths.isRecordingPaths() && "Must record paths!");
2491 
2492   const CXXBasePath &Path = Paths.front();
2493 
2494   // We first go backward and check if we have a virtual base.
2495   // FIXME: It would be better if CXXBasePath had the base specifier for
2496   // the nearest virtual base.
2497   unsigned Start = 0;
2498   for (unsigned I = Path.size(); I != 0; --I) {
2499     if (Path[I - 1].Base->isVirtual()) {
2500       Start = I - 1;
2501       break;
2502     }
2503   }
2504 
2505   // Now add all bases.
2506   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2507     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2508 }
2509 
2510 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2511 /// conversion (where Derived and Base are class types) is
2512 /// well-formed, meaning that the conversion is unambiguous (and
2513 /// that all of the base classes are accessible). Returns true
2514 /// and emits a diagnostic if the code is ill-formed, returns false
2515 /// otherwise. Loc is the location where this routine should point to
2516 /// if there is an error, and Range is the source range to highlight
2517 /// if there is an error.
2518 ///
2519 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2520 /// diagnostic for the respective type of error will be suppressed, but the
2521 /// check for ill-formed code will still be performed.
2522 bool
2523 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2524                                    unsigned InaccessibleBaseID,
2525                                    unsigned AmbigiousBaseConvID,
2526                                    SourceLocation Loc, SourceRange Range,
2527                                    DeclarationName Name,
2528                                    CXXCastPath *BasePath,
2529                                    bool IgnoreAccess) {
2530   // First, determine whether the path from Derived to Base is
2531   // ambiguous. This is slightly more expensive than checking whether
2532   // the Derived to Base conversion exists, because here we need to
2533   // explore multiple paths to determine if there is an ambiguity.
2534   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2535                      /*DetectVirtual=*/false);
2536   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2537   assert(DerivationOkay &&
2538          "Can only be used with a derived-to-base conversion");
2539   (void)DerivationOkay;
2540 
2541   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
2542     if (!IgnoreAccess) {
2543       // Check that the base class can be accessed.
2544       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2545                                    InaccessibleBaseID)) {
2546         case AR_inaccessible:
2547           return true;
2548         case AR_accessible:
2549         case AR_dependent:
2550         case AR_delayed:
2551           break;
2552       }
2553     }
2554 
2555     // Build a base path if necessary.
2556     if (BasePath)
2557       BuildBasePathArray(Paths, *BasePath);
2558     return false;
2559   }
2560 
2561   if (AmbigiousBaseConvID) {
2562     // We know that the derived-to-base conversion is ambiguous, and
2563     // we're going to produce a diagnostic. Perform the derived-to-base
2564     // search just one more time to compute all of the possible paths so
2565     // that we can print them out. This is more expensive than any of
2566     // the previous derived-to-base checks we've done, but at this point
2567     // performance isn't as much of an issue.
2568     Paths.clear();
2569     Paths.setRecordingPaths(true);
2570     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2571     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2572     (void)StillOkay;
2573 
2574     // Build up a textual representation of the ambiguous paths, e.g.,
2575     // D -> B -> A, that will be used to illustrate the ambiguous
2576     // conversions in the diagnostic. We only print one of the paths
2577     // to each base class subobject.
2578     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2579 
2580     Diag(Loc, AmbigiousBaseConvID)
2581     << Derived << Base << PathDisplayStr << Range << Name;
2582   }
2583   return true;
2584 }
2585 
2586 bool
2587 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2588                                    SourceLocation Loc, SourceRange Range,
2589                                    CXXCastPath *BasePath,
2590                                    bool IgnoreAccess) {
2591   return CheckDerivedToBaseConversion(
2592       Derived, Base, diag::err_upcast_to_inaccessible_base,
2593       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2594       BasePath, IgnoreAccess);
2595 }
2596 
2597 
2598 /// @brief Builds a string representing ambiguous paths from a
2599 /// specific derived class to different subobjects of the same base
2600 /// class.
2601 ///
2602 /// This function builds a string that can be used in error messages
2603 /// to show the different paths that one can take through the
2604 /// inheritance hierarchy to go from the derived class to different
2605 /// subobjects of a base class. The result looks something like this:
2606 /// @code
2607 /// struct D -> struct B -> struct A
2608 /// struct D -> struct C -> struct A
2609 /// @endcode
2610 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2611   std::string PathDisplayStr;
2612   std::set<unsigned> DisplayedPaths;
2613   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2614        Path != Paths.end(); ++Path) {
2615     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2616       // We haven't displayed a path to this particular base
2617       // class subobject yet.
2618       PathDisplayStr += "\n    ";
2619       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2620       for (CXXBasePath::const_iterator Element = Path->begin();
2621            Element != Path->end(); ++Element)
2622         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2623     }
2624   }
2625 
2626   return PathDisplayStr;
2627 }
2628 
2629 //===----------------------------------------------------------------------===//
2630 // C++ class member Handling
2631 //===----------------------------------------------------------------------===//
2632 
2633 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2634 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2635                                 SourceLocation ASLoc,
2636                                 SourceLocation ColonLoc,
2637                                 AttributeList *Attrs) {
2638   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2639   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2640                                                   ASLoc, ColonLoc);
2641   CurContext->addHiddenDecl(ASDecl);
2642   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2643 }
2644 
2645 /// CheckOverrideControl - Check C++11 override control semantics.
2646 void Sema::CheckOverrideControl(NamedDecl *D) {
2647   if (D->isInvalidDecl())
2648     return;
2649 
2650   // We only care about "override" and "final" declarations.
2651   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2652     return;
2653 
2654   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2655 
2656   // We can't check dependent instance methods.
2657   if (MD && MD->isInstance() &&
2658       (MD->getParent()->hasAnyDependentBases() ||
2659        MD->getType()->isDependentType()))
2660     return;
2661 
2662   if (MD && !MD->isVirtual()) {
2663     // If we have a non-virtual method, check if if hides a virtual method.
2664     // (In that case, it's most likely the method has the wrong type.)
2665     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2666     FindHiddenVirtualMethods(MD, OverloadedMethods);
2667 
2668     if (!OverloadedMethods.empty()) {
2669       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2670         Diag(OA->getLocation(),
2671              diag::override_keyword_hides_virtual_member_function)
2672           << "override" << (OverloadedMethods.size() > 1);
2673       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2674         Diag(FA->getLocation(),
2675              diag::override_keyword_hides_virtual_member_function)
2676           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2677           << (OverloadedMethods.size() > 1);
2678       }
2679       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2680       MD->setInvalidDecl();
2681       return;
2682     }
2683     // Fall through into the general case diagnostic.
2684     // FIXME: We might want to attempt typo correction here.
2685   }
2686 
2687   if (!MD || !MD->isVirtual()) {
2688     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2689       Diag(OA->getLocation(),
2690            diag::override_keyword_only_allowed_on_virtual_member_functions)
2691         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2692       D->dropAttr<OverrideAttr>();
2693     }
2694     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2695       Diag(FA->getLocation(),
2696            diag::override_keyword_only_allowed_on_virtual_member_functions)
2697         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2698         << FixItHint::CreateRemoval(FA->getLocation());
2699       D->dropAttr<FinalAttr>();
2700     }
2701     return;
2702   }
2703 
2704   // C++11 [class.virtual]p5:
2705   //   If a function is marked with the virt-specifier override and
2706   //   does not override a member function of a base class, the program is
2707   //   ill-formed.
2708   bool HasOverriddenMethods =
2709     MD->begin_overridden_methods() != MD->end_overridden_methods();
2710   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2711     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2712       << MD->getDeclName();
2713 }
2714 
2715 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2716   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2717     return;
2718   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2719   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
2720       isa<CXXDestructorDecl>(MD))
2721     return;
2722 
2723   SourceLocation Loc = MD->getLocation();
2724   SourceLocation SpellingLoc = Loc;
2725   if (getSourceManager().isMacroArgExpansion(Loc))
2726     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2727   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2728   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2729       return;
2730 
2731   if (MD->size_overridden_methods() > 0) {
2732     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
2733       << MD->getDeclName();
2734     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2735     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2736   }
2737 }
2738 
2739 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2740 /// function overrides a virtual member function marked 'final', according to
2741 /// C++11 [class.virtual]p4.
2742 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2743                                                   const CXXMethodDecl *Old) {
2744   FinalAttr *FA = Old->getAttr<FinalAttr>();
2745   if (!FA)
2746     return false;
2747 
2748   Diag(New->getLocation(), diag::err_final_function_overridden)
2749     << New->getDeclName()
2750     << FA->isSpelledAsSealed();
2751   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2752   return true;
2753 }
2754 
2755 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2756   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2757   // FIXME: Destruction of ObjC lifetime types has side-effects.
2758   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2759     return !RD->isCompleteDefinition() ||
2760            !RD->hasTrivialDefaultConstructor() ||
2761            !RD->hasTrivialDestructor();
2762   return false;
2763 }
2764 
2765 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2766   for (AttributeList *it = list; it != nullptr; it = it->getNext())
2767     if (it->isDeclspecPropertyAttribute())
2768       return it;
2769   return nullptr;
2770 }
2771 
2772 // Check if there is a field shadowing.
2773 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2774                                       DeclarationName FieldName,
2775                                       const CXXRecordDecl *RD) {
2776   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2777     return;
2778 
2779   // To record a shadowed field in a base
2780   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2781   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2782                            CXXBasePath &Path) {
2783     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2784     // Record an ambiguous path directly
2785     if (Bases.find(Base) != Bases.end())
2786       return true;
2787     for (const auto Field : Base->lookup(FieldName)) {
2788       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2789           Field->getAccess() != AS_private) {
2790         assert(Field->getAccess() != AS_none);
2791         assert(Bases.find(Base) == Bases.end());
2792         Bases[Base] = Field;
2793         return true;
2794       }
2795     }
2796     return false;
2797   };
2798 
2799   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2800                      /*DetectVirtual=*/true);
2801   if (!RD->lookupInBases(FieldShadowed, Paths))
2802     return;
2803 
2804   for (const auto &P : Paths) {
2805     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2806     auto It = Bases.find(Base);
2807     // Skip duplicated bases
2808     if (It == Bases.end())
2809       continue;
2810     auto BaseField = It->second;
2811     assert(BaseField->getAccess() != AS_private);
2812     if (AS_none !=
2813         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2814       Diag(Loc, diag::warn_shadow_field)
2815         << FieldName.getAsString() << RD->getName() << Base->getName();
2816       Diag(BaseField->getLocation(), diag::note_shadow_field);
2817       Bases.erase(It);
2818     }
2819   }
2820 }
2821 
2822 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2823 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2824 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2825 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2826 /// present (but parsing it has been deferred).
2827 NamedDecl *
2828 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2829                                MultiTemplateParamsArg TemplateParameterLists,
2830                                Expr *BW, const VirtSpecifiers &VS,
2831                                InClassInitStyle InitStyle) {
2832   const DeclSpec &DS = D.getDeclSpec();
2833   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2834   DeclarationName Name = NameInfo.getName();
2835   SourceLocation Loc = NameInfo.getLoc();
2836 
2837   // For anonymous bitfields, the location should point to the type.
2838   if (Loc.isInvalid())
2839     Loc = D.getLocStart();
2840 
2841   Expr *BitWidth = static_cast<Expr*>(BW);
2842 
2843   assert(isa<CXXRecordDecl>(CurContext));
2844   assert(!DS.isFriendSpecified());
2845 
2846   bool isFunc = D.isDeclarationOfFunction();
2847 
2848   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2849     // The Microsoft extension __interface only permits public member functions
2850     // and prohibits constructors, destructors, operators, non-public member
2851     // functions, static methods and data members.
2852     unsigned InvalidDecl;
2853     bool ShowDeclName = true;
2854     if (!isFunc)
2855       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2856     else if (AS != AS_public)
2857       InvalidDecl = 2;
2858     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2859       InvalidDecl = 3;
2860     else switch (Name.getNameKind()) {
2861       case DeclarationName::CXXConstructorName:
2862         InvalidDecl = 4;
2863         ShowDeclName = false;
2864         break;
2865 
2866       case DeclarationName::CXXDestructorName:
2867         InvalidDecl = 5;
2868         ShowDeclName = false;
2869         break;
2870 
2871       case DeclarationName::CXXOperatorName:
2872       case DeclarationName::CXXConversionFunctionName:
2873         InvalidDecl = 6;
2874         break;
2875 
2876       default:
2877         InvalidDecl = 0;
2878         break;
2879     }
2880 
2881     if (InvalidDecl) {
2882       if (ShowDeclName)
2883         Diag(Loc, diag::err_invalid_member_in_interface)
2884           << (InvalidDecl-1) << Name;
2885       else
2886         Diag(Loc, diag::err_invalid_member_in_interface)
2887           << (InvalidDecl-1) << "";
2888       return nullptr;
2889     }
2890   }
2891 
2892   // C++ 9.2p6: A member shall not be declared to have automatic storage
2893   // duration (auto, register) or with the extern storage-class-specifier.
2894   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2895   // data members and cannot be applied to names declared const or static,
2896   // and cannot be applied to reference members.
2897   switch (DS.getStorageClassSpec()) {
2898   case DeclSpec::SCS_unspecified:
2899   case DeclSpec::SCS_typedef:
2900   case DeclSpec::SCS_static:
2901     break;
2902   case DeclSpec::SCS_mutable:
2903     if (isFunc) {
2904       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2905 
2906       // FIXME: It would be nicer if the keyword was ignored only for this
2907       // declarator. Otherwise we could get follow-up errors.
2908       D.getMutableDeclSpec().ClearStorageClassSpecs();
2909     }
2910     break;
2911   default:
2912     Diag(DS.getStorageClassSpecLoc(),
2913          diag::err_storageclass_invalid_for_member);
2914     D.getMutableDeclSpec().ClearStorageClassSpecs();
2915     break;
2916   }
2917 
2918   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2919                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2920                       !isFunc);
2921 
2922   if (DS.isConstexprSpecified() && isInstField) {
2923     SemaDiagnosticBuilder B =
2924         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2925     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2926     if (InitStyle == ICIS_NoInit) {
2927       B << 0 << 0;
2928       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2929         B << FixItHint::CreateRemoval(ConstexprLoc);
2930       else {
2931         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2932         D.getMutableDeclSpec().ClearConstexprSpec();
2933         const char *PrevSpec;
2934         unsigned DiagID;
2935         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2936             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2937         (void)Failed;
2938         assert(!Failed && "Making a constexpr member const shouldn't fail");
2939       }
2940     } else {
2941       B << 1;
2942       const char *PrevSpec;
2943       unsigned DiagID;
2944       if (D.getMutableDeclSpec().SetStorageClassSpec(
2945           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2946           Context.getPrintingPolicy())) {
2947         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2948                "This is the only DeclSpec that should fail to be applied");
2949         B << 1;
2950       } else {
2951         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2952         isInstField = false;
2953       }
2954     }
2955   }
2956 
2957   NamedDecl *Member;
2958   if (isInstField) {
2959     CXXScopeSpec &SS = D.getCXXScopeSpec();
2960 
2961     // Data members must have identifiers for names.
2962     if (!Name.isIdentifier()) {
2963       Diag(Loc, diag::err_bad_variable_name)
2964         << Name;
2965       return nullptr;
2966     }
2967 
2968     IdentifierInfo *II = Name.getAsIdentifierInfo();
2969 
2970     // Member field could not be with "template" keyword.
2971     // So TemplateParameterLists should be empty in this case.
2972     if (TemplateParameterLists.size()) {
2973       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2974       if (TemplateParams->size()) {
2975         // There is no such thing as a member field template.
2976         Diag(D.getIdentifierLoc(), diag::err_template_member)
2977             << II
2978             << SourceRange(TemplateParams->getTemplateLoc(),
2979                 TemplateParams->getRAngleLoc());
2980       } else {
2981         // There is an extraneous 'template<>' for this member.
2982         Diag(TemplateParams->getTemplateLoc(),
2983             diag::err_template_member_noparams)
2984             << II
2985             << SourceRange(TemplateParams->getTemplateLoc(),
2986                 TemplateParams->getRAngleLoc());
2987       }
2988       return nullptr;
2989     }
2990 
2991     if (SS.isSet() && !SS.isInvalid()) {
2992       // The user provided a superfluous scope specifier inside a class
2993       // definition:
2994       //
2995       // class X {
2996       //   int X::member;
2997       // };
2998       if (DeclContext *DC = computeDeclContext(SS, false))
2999         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
3000       else
3001         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3002           << Name << SS.getRange();
3003 
3004       SS.clear();
3005     }
3006 
3007     AttributeList *MSPropertyAttr =
3008       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
3009     if (MSPropertyAttr) {
3010       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3011                                 BitWidth, InitStyle, AS, MSPropertyAttr);
3012       if (!Member)
3013         return nullptr;
3014       isInstField = false;
3015     } else {
3016       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3017                                 BitWidth, InitStyle, AS);
3018       if (!Member)
3019         return nullptr;
3020     }
3021 
3022     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3023   } else {
3024     Member = HandleDeclarator(S, D, TemplateParameterLists);
3025     if (!Member)
3026       return nullptr;
3027 
3028     // Non-instance-fields can't have a bitfield.
3029     if (BitWidth) {
3030       if (Member->isInvalidDecl()) {
3031         // don't emit another diagnostic.
3032       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3033         // C++ 9.6p3: A bit-field shall not be a static member.
3034         // "static member 'A' cannot be a bit-field"
3035         Diag(Loc, diag::err_static_not_bitfield)
3036           << Name << BitWidth->getSourceRange();
3037       } else if (isa<TypedefDecl>(Member)) {
3038         // "typedef member 'x' cannot be a bit-field"
3039         Diag(Loc, diag::err_typedef_not_bitfield)
3040           << Name << BitWidth->getSourceRange();
3041       } else {
3042         // A function typedef ("typedef int f(); f a;").
3043         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3044         Diag(Loc, diag::err_not_integral_type_bitfield)
3045           << Name << cast<ValueDecl>(Member)->getType()
3046           << BitWidth->getSourceRange();
3047       }
3048 
3049       BitWidth = nullptr;
3050       Member->setInvalidDecl();
3051     }
3052 
3053     Member->setAccess(AS);
3054 
3055     // If we have declared a member function template or static data member
3056     // template, set the access of the templated declaration as well.
3057     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3058       FunTmpl->getTemplatedDecl()->setAccess(AS);
3059     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3060       VarTmpl->getTemplatedDecl()->setAccess(AS);
3061   }
3062 
3063   if (VS.isOverrideSpecified())
3064     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3065   if (VS.isFinalSpecified())
3066     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3067                                             VS.isFinalSpelledSealed()));
3068 
3069   if (VS.getLastLocation().isValid()) {
3070     // Update the end location of a method that has a virt-specifiers.
3071     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3072       MD->setRangeEnd(VS.getLastLocation());
3073   }
3074 
3075   CheckOverrideControl(Member);
3076 
3077   assert((Name || isInstField) && "No identifier for non-field ?");
3078 
3079   if (isInstField) {
3080     FieldDecl *FD = cast<FieldDecl>(Member);
3081     FieldCollector->Add(FD);
3082 
3083     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3084       // Remember all explicit private FieldDecls that have a name, no side
3085       // effects and are not part of a dependent type declaration.
3086       if (!FD->isImplicit() && FD->getDeclName() &&
3087           FD->getAccess() == AS_private &&
3088           !FD->hasAttr<UnusedAttr>() &&
3089           !FD->getParent()->isDependentContext() &&
3090           !InitializationHasSideEffects(*FD))
3091         UnusedPrivateFields.insert(FD);
3092     }
3093   }
3094 
3095   return Member;
3096 }
3097 
3098 namespace {
3099   class UninitializedFieldVisitor
3100       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3101     Sema &S;
3102     // List of Decls to generate a warning on.  Also remove Decls that become
3103     // initialized.
3104     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3105     // List of base classes of the record.  Classes are removed after their
3106     // initializers.
3107     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3108     // Vector of decls to be removed from the Decl set prior to visiting the
3109     // nodes.  These Decls may have been initialized in the prior initializer.
3110     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3111     // If non-null, add a note to the warning pointing back to the constructor.
3112     const CXXConstructorDecl *Constructor;
3113     // Variables to hold state when processing an initializer list.  When
3114     // InitList is true, special case initialization of FieldDecls matching
3115     // InitListFieldDecl.
3116     bool InitList;
3117     FieldDecl *InitListFieldDecl;
3118     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3119 
3120   public:
3121     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3122     UninitializedFieldVisitor(Sema &S,
3123                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3124                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3125       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3126         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3127 
3128     // Returns true if the use of ME is not an uninitialized use.
3129     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3130                                          bool CheckReferenceOnly) {
3131       llvm::SmallVector<FieldDecl*, 4> Fields;
3132       bool ReferenceField = false;
3133       while (ME) {
3134         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3135         if (!FD)
3136           return false;
3137         Fields.push_back(FD);
3138         if (FD->getType()->isReferenceType())
3139           ReferenceField = true;
3140         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3141       }
3142 
3143       // Binding a reference to an unintialized field is not an
3144       // uninitialized use.
3145       if (CheckReferenceOnly && !ReferenceField)
3146         return true;
3147 
3148       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3149       // Discard the first field since it is the field decl that is being
3150       // initialized.
3151       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3152         UsedFieldIndex.push_back((*I)->getFieldIndex());
3153       }
3154 
3155       for (auto UsedIter = UsedFieldIndex.begin(),
3156                 UsedEnd = UsedFieldIndex.end(),
3157                 OrigIter = InitFieldIndex.begin(),
3158                 OrigEnd = InitFieldIndex.end();
3159            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3160         if (*UsedIter < *OrigIter)
3161           return true;
3162         if (*UsedIter > *OrigIter)
3163           break;
3164       }
3165 
3166       return false;
3167     }
3168 
3169     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3170                           bool AddressOf) {
3171       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3172         return;
3173 
3174       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3175       // or union.
3176       MemberExpr *FieldME = ME;
3177 
3178       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3179 
3180       Expr *Base = ME;
3181       while (MemberExpr *SubME =
3182                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3183 
3184         if (isa<VarDecl>(SubME->getMemberDecl()))
3185           return;
3186 
3187         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3188           if (!FD->isAnonymousStructOrUnion())
3189             FieldME = SubME;
3190 
3191         if (!FieldME->getType().isPODType(S.Context))
3192           AllPODFields = false;
3193 
3194         Base = SubME->getBase();
3195       }
3196 
3197       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3198         return;
3199 
3200       if (AddressOf && AllPODFields)
3201         return;
3202 
3203       ValueDecl* FoundVD = FieldME->getMemberDecl();
3204 
3205       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3206         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3207           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3208         }
3209 
3210         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3211           QualType T = BaseCast->getType();
3212           if (T->isPointerType() &&
3213               BaseClasses.count(T->getPointeeType())) {
3214             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3215                 << T->getPointeeType() << FoundVD;
3216           }
3217         }
3218       }
3219 
3220       if (!Decls.count(FoundVD))
3221         return;
3222 
3223       const bool IsReference = FoundVD->getType()->isReferenceType();
3224 
3225       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3226         // Special checking for initializer lists.
3227         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3228           return;
3229         }
3230       } else {
3231         // Prevent double warnings on use of unbounded references.
3232         if (CheckReferenceOnly && !IsReference)
3233           return;
3234       }
3235 
3236       unsigned diag = IsReference
3237           ? diag::warn_reference_field_is_uninit
3238           : diag::warn_field_is_uninit;
3239       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3240       if (Constructor)
3241         S.Diag(Constructor->getLocation(),
3242                diag::note_uninit_in_this_constructor)
3243           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3244 
3245     }
3246 
3247     void HandleValue(Expr *E, bool AddressOf) {
3248       E = E->IgnoreParens();
3249 
3250       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3251         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3252                          AddressOf /*AddressOf*/);
3253         return;
3254       }
3255 
3256       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3257         Visit(CO->getCond());
3258         HandleValue(CO->getTrueExpr(), AddressOf);
3259         HandleValue(CO->getFalseExpr(), AddressOf);
3260         return;
3261       }
3262 
3263       if (BinaryConditionalOperator *BCO =
3264               dyn_cast<BinaryConditionalOperator>(E)) {
3265         Visit(BCO->getCond());
3266         HandleValue(BCO->getFalseExpr(), AddressOf);
3267         return;
3268       }
3269 
3270       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3271         HandleValue(OVE->getSourceExpr(), AddressOf);
3272         return;
3273       }
3274 
3275       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3276         switch (BO->getOpcode()) {
3277         default:
3278           break;
3279         case(BO_PtrMemD):
3280         case(BO_PtrMemI):
3281           HandleValue(BO->getLHS(), AddressOf);
3282           Visit(BO->getRHS());
3283           return;
3284         case(BO_Comma):
3285           Visit(BO->getLHS());
3286           HandleValue(BO->getRHS(), AddressOf);
3287           return;
3288         }
3289       }
3290 
3291       Visit(E);
3292     }
3293 
3294     void CheckInitListExpr(InitListExpr *ILE) {
3295       InitFieldIndex.push_back(0);
3296       for (auto Child : ILE->children()) {
3297         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3298           CheckInitListExpr(SubList);
3299         } else {
3300           Visit(Child);
3301         }
3302         ++InitFieldIndex.back();
3303       }
3304       InitFieldIndex.pop_back();
3305     }
3306 
3307     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3308                           FieldDecl *Field, const Type *BaseClass) {
3309       // Remove Decls that may have been initialized in the previous
3310       // initializer.
3311       for (ValueDecl* VD : DeclsToRemove)
3312         Decls.erase(VD);
3313       DeclsToRemove.clear();
3314 
3315       Constructor = FieldConstructor;
3316       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3317 
3318       if (ILE && Field) {
3319         InitList = true;
3320         InitListFieldDecl = Field;
3321         InitFieldIndex.clear();
3322         CheckInitListExpr(ILE);
3323       } else {
3324         InitList = false;
3325         Visit(E);
3326       }
3327 
3328       if (Field)
3329         Decls.erase(Field);
3330       if (BaseClass)
3331         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3332     }
3333 
3334     void VisitMemberExpr(MemberExpr *ME) {
3335       // All uses of unbounded reference fields will warn.
3336       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3337     }
3338 
3339     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3340       if (E->getCastKind() == CK_LValueToRValue) {
3341         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3342         return;
3343       }
3344 
3345       Inherited::VisitImplicitCastExpr(E);
3346     }
3347 
3348     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3349       if (E->getConstructor()->isCopyConstructor()) {
3350         Expr *ArgExpr = E->getArg(0);
3351         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3352           if (ILE->getNumInits() == 1)
3353             ArgExpr = ILE->getInit(0);
3354         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3355           if (ICE->getCastKind() == CK_NoOp)
3356             ArgExpr = ICE->getSubExpr();
3357         HandleValue(ArgExpr, false /*AddressOf*/);
3358         return;
3359       }
3360       Inherited::VisitCXXConstructExpr(E);
3361     }
3362 
3363     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3364       Expr *Callee = E->getCallee();
3365       if (isa<MemberExpr>(Callee)) {
3366         HandleValue(Callee, false /*AddressOf*/);
3367         for (auto Arg : E->arguments())
3368           Visit(Arg);
3369         return;
3370       }
3371 
3372       Inherited::VisitCXXMemberCallExpr(E);
3373     }
3374 
3375     void VisitCallExpr(CallExpr *E) {
3376       // Treat std::move as a use.
3377       if (E->getNumArgs() == 1) {
3378         if (FunctionDecl *FD = E->getDirectCallee()) {
3379           if (FD->isInStdNamespace() && FD->getIdentifier() &&
3380               FD->getIdentifier()->isStr("move")) {
3381             HandleValue(E->getArg(0), false /*AddressOf*/);
3382             return;
3383           }
3384         }
3385       }
3386 
3387       Inherited::VisitCallExpr(E);
3388     }
3389 
3390     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3391       Expr *Callee = E->getCallee();
3392 
3393       if (isa<UnresolvedLookupExpr>(Callee))
3394         return Inherited::VisitCXXOperatorCallExpr(E);
3395 
3396       Visit(Callee);
3397       for (auto Arg : E->arguments())
3398         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3399     }
3400 
3401     void VisitBinaryOperator(BinaryOperator *E) {
3402       // If a field assignment is detected, remove the field from the
3403       // uninitiailized field set.
3404       if (E->getOpcode() == BO_Assign)
3405         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3406           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3407             if (!FD->getType()->isReferenceType())
3408               DeclsToRemove.push_back(FD);
3409 
3410       if (E->isCompoundAssignmentOp()) {
3411         HandleValue(E->getLHS(), false /*AddressOf*/);
3412         Visit(E->getRHS());
3413         return;
3414       }
3415 
3416       Inherited::VisitBinaryOperator(E);
3417     }
3418 
3419     void VisitUnaryOperator(UnaryOperator *E) {
3420       if (E->isIncrementDecrementOp()) {
3421         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3422         return;
3423       }
3424       if (E->getOpcode() == UO_AddrOf) {
3425         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3426           HandleValue(ME->getBase(), true /*AddressOf*/);
3427           return;
3428         }
3429       }
3430 
3431       Inherited::VisitUnaryOperator(E);
3432     }
3433   };
3434 
3435   // Diagnose value-uses of fields to initialize themselves, e.g.
3436   //   foo(foo)
3437   // where foo is not also a parameter to the constructor.
3438   // Also diagnose across field uninitialized use such as
3439   //   x(y), y(x)
3440   // TODO: implement -Wuninitialized and fold this into that framework.
3441   static void DiagnoseUninitializedFields(
3442       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3443 
3444     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3445                                            Constructor->getLocation())) {
3446       return;
3447     }
3448 
3449     if (Constructor->isInvalidDecl())
3450       return;
3451 
3452     const CXXRecordDecl *RD = Constructor->getParent();
3453 
3454     if (RD->getDescribedClassTemplate())
3455       return;
3456 
3457     // Holds fields that are uninitialized.
3458     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3459 
3460     // At the beginning, all fields are uninitialized.
3461     for (auto *I : RD->decls()) {
3462       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3463         UninitializedFields.insert(FD);
3464       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3465         UninitializedFields.insert(IFD->getAnonField());
3466       }
3467     }
3468 
3469     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3470     for (auto I : RD->bases())
3471       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3472 
3473     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3474       return;
3475 
3476     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3477                                                    UninitializedFields,
3478                                                    UninitializedBaseClasses);
3479 
3480     for (const auto *FieldInit : Constructor->inits()) {
3481       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3482         break;
3483 
3484       Expr *InitExpr = FieldInit->getInit();
3485       if (!InitExpr)
3486         continue;
3487 
3488       if (CXXDefaultInitExpr *Default =
3489               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3490         InitExpr = Default->getExpr();
3491         if (!InitExpr)
3492           continue;
3493         // In class initializers will point to the constructor.
3494         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3495                                               FieldInit->getAnyMember(),
3496                                               FieldInit->getBaseClass());
3497       } else {
3498         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3499                                               FieldInit->getAnyMember(),
3500                                               FieldInit->getBaseClass());
3501       }
3502     }
3503   }
3504 } // namespace
3505 
3506 /// \brief Enter a new C++ default initializer scope. After calling this, the
3507 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3508 /// parsing or instantiating the initializer failed.
3509 void Sema::ActOnStartCXXInClassMemberInitializer() {
3510   // Create a synthetic function scope to represent the call to the constructor
3511   // that notionally surrounds a use of this initializer.
3512   PushFunctionScope();
3513 }
3514 
3515 /// \brief This is invoked after parsing an in-class initializer for a
3516 /// non-static C++ class member, and after instantiating an in-class initializer
3517 /// in a class template. Such actions are deferred until the class is complete.
3518 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3519                                                   SourceLocation InitLoc,
3520                                                   Expr *InitExpr) {
3521   // Pop the notional constructor scope we created earlier.
3522   PopFunctionScopeInfo(nullptr, D);
3523 
3524   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3525   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3526          "must set init style when field is created");
3527 
3528   if (!InitExpr) {
3529     D->setInvalidDecl();
3530     if (FD)
3531       FD->removeInClassInitializer();
3532     return;
3533   }
3534 
3535   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3536     FD->setInvalidDecl();
3537     FD->removeInClassInitializer();
3538     return;
3539   }
3540 
3541   ExprResult Init = InitExpr;
3542   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3543     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3544     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
3545         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
3546         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3547     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3548     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3549     if (Init.isInvalid()) {
3550       FD->setInvalidDecl();
3551       return;
3552     }
3553   }
3554 
3555   // C++11 [class.base.init]p7:
3556   //   The initialization of each base and member constitutes a
3557   //   full-expression.
3558   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3559   if (Init.isInvalid()) {
3560     FD->setInvalidDecl();
3561     return;
3562   }
3563 
3564   InitExpr = Init.get();
3565 
3566   FD->setInClassInitializer(InitExpr);
3567 }
3568 
3569 /// \brief Find the direct and/or virtual base specifiers that
3570 /// correspond to the given base type, for use in base initialization
3571 /// within a constructor.
3572 static bool FindBaseInitializer(Sema &SemaRef,
3573                                 CXXRecordDecl *ClassDecl,
3574                                 QualType BaseType,
3575                                 const CXXBaseSpecifier *&DirectBaseSpec,
3576                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3577   // First, check for a direct base class.
3578   DirectBaseSpec = nullptr;
3579   for (const auto &Base : ClassDecl->bases()) {
3580     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3581       // We found a direct base of this type. That's what we're
3582       // initializing.
3583       DirectBaseSpec = &Base;
3584       break;
3585     }
3586   }
3587 
3588   // Check for a virtual base class.
3589   // FIXME: We might be able to short-circuit this if we know in advance that
3590   // there are no virtual bases.
3591   VirtualBaseSpec = nullptr;
3592   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3593     // We haven't found a base yet; search the class hierarchy for a
3594     // virtual base class.
3595     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3596                        /*DetectVirtual=*/false);
3597     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3598                               SemaRef.Context.getTypeDeclType(ClassDecl),
3599                               BaseType, Paths)) {
3600       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3601            Path != Paths.end(); ++Path) {
3602         if (Path->back().Base->isVirtual()) {
3603           VirtualBaseSpec = Path->back().Base;
3604           break;
3605         }
3606       }
3607     }
3608   }
3609 
3610   return DirectBaseSpec || VirtualBaseSpec;
3611 }
3612 
3613 /// \brief Handle a C++ member initializer using braced-init-list syntax.
3614 MemInitResult
3615 Sema::ActOnMemInitializer(Decl *ConstructorD,
3616                           Scope *S,
3617                           CXXScopeSpec &SS,
3618                           IdentifierInfo *MemberOrBase,
3619                           ParsedType TemplateTypeTy,
3620                           const DeclSpec &DS,
3621                           SourceLocation IdLoc,
3622                           Expr *InitList,
3623                           SourceLocation EllipsisLoc) {
3624   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3625                              DS, IdLoc, InitList,
3626                              EllipsisLoc);
3627 }
3628 
3629 /// \brief Handle a C++ member initializer using parentheses syntax.
3630 MemInitResult
3631 Sema::ActOnMemInitializer(Decl *ConstructorD,
3632                           Scope *S,
3633                           CXXScopeSpec &SS,
3634                           IdentifierInfo *MemberOrBase,
3635                           ParsedType TemplateTypeTy,
3636                           const DeclSpec &DS,
3637                           SourceLocation IdLoc,
3638                           SourceLocation LParenLoc,
3639                           ArrayRef<Expr *> Args,
3640                           SourceLocation RParenLoc,
3641                           SourceLocation EllipsisLoc) {
3642   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3643                                            Args, RParenLoc);
3644   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3645                              DS, IdLoc, List, EllipsisLoc);
3646 }
3647 
3648 namespace {
3649 
3650 // Callback to only accept typo corrections that can be a valid C++ member
3651 // intializer: either a non-static field member or a base class.
3652 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3653 public:
3654   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3655       : ClassDecl(ClassDecl) {}
3656 
3657   bool ValidateCandidate(const TypoCorrection &candidate) override {
3658     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3659       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3660         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3661       return isa<TypeDecl>(ND);
3662     }
3663     return false;
3664   }
3665 
3666 private:
3667   CXXRecordDecl *ClassDecl;
3668 };
3669 
3670 }
3671 
3672 /// \brief Handle a C++ member initializer.
3673 MemInitResult
3674 Sema::BuildMemInitializer(Decl *ConstructorD,
3675                           Scope *S,
3676                           CXXScopeSpec &SS,
3677                           IdentifierInfo *MemberOrBase,
3678                           ParsedType TemplateTypeTy,
3679                           const DeclSpec &DS,
3680                           SourceLocation IdLoc,
3681                           Expr *Init,
3682                           SourceLocation EllipsisLoc) {
3683   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3684   if (!Res.isUsable())
3685     return true;
3686   Init = Res.get();
3687 
3688   if (!ConstructorD)
3689     return true;
3690 
3691   AdjustDeclIfTemplate(ConstructorD);
3692 
3693   CXXConstructorDecl *Constructor
3694     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3695   if (!Constructor) {
3696     // The user wrote a constructor initializer on a function that is
3697     // not a C++ constructor. Ignore the error for now, because we may
3698     // have more member initializers coming; we'll diagnose it just
3699     // once in ActOnMemInitializers.
3700     return true;
3701   }
3702 
3703   CXXRecordDecl *ClassDecl = Constructor->getParent();
3704 
3705   // C++ [class.base.init]p2:
3706   //   Names in a mem-initializer-id are looked up in the scope of the
3707   //   constructor's class and, if not found in that scope, are looked
3708   //   up in the scope containing the constructor's definition.
3709   //   [Note: if the constructor's class contains a member with the
3710   //   same name as a direct or virtual base class of the class, a
3711   //   mem-initializer-id naming the member or base class and composed
3712   //   of a single identifier refers to the class member. A
3713   //   mem-initializer-id for the hidden base class may be specified
3714   //   using a qualified name. ]
3715   if (!SS.getScopeRep() && !TemplateTypeTy) {
3716     // Look for a member, first.
3717     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3718     if (!Result.empty()) {
3719       ValueDecl *Member;
3720       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3721           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3722         if (EllipsisLoc.isValid())
3723           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3724             << MemberOrBase
3725             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3726 
3727         return BuildMemberInitializer(Member, Init, IdLoc);
3728       }
3729     }
3730   }
3731   // It didn't name a member, so see if it names a class.
3732   QualType BaseType;
3733   TypeSourceInfo *TInfo = nullptr;
3734 
3735   if (TemplateTypeTy) {
3736     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3737   } else if (DS.getTypeSpecType() == TST_decltype) {
3738     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3739   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3740     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3741     return true;
3742   } else {
3743     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3744     LookupParsedName(R, S, &SS);
3745 
3746     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3747     if (!TyD) {
3748       if (R.isAmbiguous()) return true;
3749 
3750       // We don't want access-control diagnostics here.
3751       R.suppressDiagnostics();
3752 
3753       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3754         bool NotUnknownSpecialization = false;
3755         DeclContext *DC = computeDeclContext(SS, false);
3756         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3757           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3758 
3759         if (!NotUnknownSpecialization) {
3760           // When the scope specifier can refer to a member of an unknown
3761           // specialization, we take it as a type name.
3762           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3763                                        SS.getWithLocInContext(Context),
3764                                        *MemberOrBase, IdLoc);
3765           if (BaseType.isNull())
3766             return true;
3767 
3768           R.clear();
3769           R.setLookupName(MemberOrBase);
3770         }
3771       }
3772 
3773       // If no results were found, try to correct typos.
3774       TypoCorrection Corr;
3775       if (R.empty() && BaseType.isNull() &&
3776           (Corr = CorrectTypo(
3777                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3778                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3779                CTK_ErrorRecovery, ClassDecl))) {
3780         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3781           // We have found a non-static data member with a similar
3782           // name to what was typed; complain and initialize that
3783           // member.
3784           diagnoseTypo(Corr,
3785                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3786                          << MemberOrBase << true);
3787           return BuildMemberInitializer(Member, Init, IdLoc);
3788         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3789           const CXXBaseSpecifier *DirectBaseSpec;
3790           const CXXBaseSpecifier *VirtualBaseSpec;
3791           if (FindBaseInitializer(*this, ClassDecl,
3792                                   Context.getTypeDeclType(Type),
3793                                   DirectBaseSpec, VirtualBaseSpec)) {
3794             // We have found a direct or virtual base class with a
3795             // similar name to what was typed; complain and initialize
3796             // that base class.
3797             diagnoseTypo(Corr,
3798                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3799                            << MemberOrBase << false,
3800                          PDiag() /*Suppress note, we provide our own.*/);
3801 
3802             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3803                                                               : VirtualBaseSpec;
3804             Diag(BaseSpec->getLocStart(),
3805                  diag::note_base_class_specified_here)
3806               << BaseSpec->getType()
3807               << BaseSpec->getSourceRange();
3808 
3809             TyD = Type;
3810           }
3811         }
3812       }
3813 
3814       if (!TyD && BaseType.isNull()) {
3815         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3816           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3817         return true;
3818       }
3819     }
3820 
3821     if (BaseType.isNull()) {
3822       BaseType = Context.getTypeDeclType(TyD);
3823       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3824       if (SS.isSet()) {
3825         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3826                                              BaseType);
3827         TInfo = Context.CreateTypeSourceInfo(BaseType);
3828         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3829         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3830         TL.setElaboratedKeywordLoc(SourceLocation());
3831         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3832       }
3833     }
3834   }
3835 
3836   if (!TInfo)
3837     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3838 
3839   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3840 }
3841 
3842 /// Checks a member initializer expression for cases where reference (or
3843 /// pointer) members are bound to by-value parameters (or their addresses).
3844 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3845                                                Expr *Init,
3846                                                SourceLocation IdLoc) {
3847   QualType MemberTy = Member->getType();
3848 
3849   // We only handle pointers and references currently.
3850   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3851   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3852     return;
3853 
3854   const bool IsPointer = MemberTy->isPointerType();
3855   if (IsPointer) {
3856     if (const UnaryOperator *Op
3857           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3858       // The only case we're worried about with pointers requires taking the
3859       // address.
3860       if (Op->getOpcode() != UO_AddrOf)
3861         return;
3862 
3863       Init = Op->getSubExpr();
3864     } else {
3865       // We only handle address-of expression initializers for pointers.
3866       return;
3867     }
3868   }
3869 
3870   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3871     // We only warn when referring to a non-reference parameter declaration.
3872     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3873     if (!Parameter || Parameter->getType()->isReferenceType())
3874       return;
3875 
3876     S.Diag(Init->getExprLoc(),
3877            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3878                      : diag::warn_bind_ref_member_to_parameter)
3879       << Member << Parameter << Init->getSourceRange();
3880   } else {
3881     // Other initializers are fine.
3882     return;
3883   }
3884 
3885   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3886     << (unsigned)IsPointer;
3887 }
3888 
3889 MemInitResult
3890 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3891                              SourceLocation IdLoc) {
3892   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3893   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3894   assert((DirectMember || IndirectMember) &&
3895          "Member must be a FieldDecl or IndirectFieldDecl");
3896 
3897   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3898     return true;
3899 
3900   if (Member->isInvalidDecl())
3901     return true;
3902 
3903   MultiExprArg Args;
3904   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3905     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3906   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3907     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3908   } else {
3909     // Template instantiation doesn't reconstruct ParenListExprs for us.
3910     Args = Init;
3911   }
3912 
3913   SourceRange InitRange = Init->getSourceRange();
3914 
3915   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3916     // Can't check initialization for a member of dependent type or when
3917     // any of the arguments are type-dependent expressions.
3918     DiscardCleanupsInEvaluationContext();
3919   } else {
3920     bool InitList = false;
3921     if (isa<InitListExpr>(Init)) {
3922       InitList = true;
3923       Args = Init;
3924     }
3925 
3926     // Initialize the member.
3927     InitializedEntity MemberEntity =
3928       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3929                    : InitializedEntity::InitializeMember(IndirectMember,
3930                                                          nullptr);
3931     InitializationKind Kind =
3932       InitList ? InitializationKind::CreateDirectList(IdLoc)
3933                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3934                                                   InitRange.getEnd());
3935 
3936     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3937     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3938                                             nullptr);
3939     if (MemberInit.isInvalid())
3940       return true;
3941 
3942     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3943 
3944     // C++11 [class.base.init]p7:
3945     //   The initialization of each base and member constitutes a
3946     //   full-expression.
3947     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3948     if (MemberInit.isInvalid())
3949       return true;
3950 
3951     Init = MemberInit.get();
3952   }
3953 
3954   if (DirectMember) {
3955     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3956                                             InitRange.getBegin(), Init,
3957                                             InitRange.getEnd());
3958   } else {
3959     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3960                                             InitRange.getBegin(), Init,
3961                                             InitRange.getEnd());
3962   }
3963 }
3964 
3965 MemInitResult
3966 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3967                                  CXXRecordDecl *ClassDecl) {
3968   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3969   if (!LangOpts.CPlusPlus11)
3970     return Diag(NameLoc, diag::err_delegating_ctor)
3971       << TInfo->getTypeLoc().getLocalSourceRange();
3972   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3973 
3974   bool InitList = true;
3975   MultiExprArg Args = Init;
3976   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3977     InitList = false;
3978     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3979   }
3980 
3981   SourceRange InitRange = Init->getSourceRange();
3982   // Initialize the object.
3983   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3984                                      QualType(ClassDecl->getTypeForDecl(), 0));
3985   InitializationKind Kind =
3986     InitList ? InitializationKind::CreateDirectList(NameLoc)
3987              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3988                                                 InitRange.getEnd());
3989   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3990   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3991                                               Args, nullptr);
3992   if (DelegationInit.isInvalid())
3993     return true;
3994 
3995   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3996          "Delegating constructor with no target?");
3997 
3998   // C++11 [class.base.init]p7:
3999   //   The initialization of each base and member constitutes a
4000   //   full-expression.
4001   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4002                                        InitRange.getBegin());
4003   if (DelegationInit.isInvalid())
4004     return true;
4005 
4006   // If we are in a dependent context, template instantiation will
4007   // perform this type-checking again. Just save the arguments that we
4008   // received in a ParenListExpr.
4009   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4010   // of the information that we have about the base
4011   // initializer. However, deconstructing the ASTs is a dicey process,
4012   // and this approach is far more likely to get the corner cases right.
4013   if (CurContext->isDependentContext())
4014     DelegationInit = Init;
4015 
4016   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4017                                           DelegationInit.getAs<Expr>(),
4018                                           InitRange.getEnd());
4019 }
4020 
4021 MemInitResult
4022 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4023                            Expr *Init, CXXRecordDecl *ClassDecl,
4024                            SourceLocation EllipsisLoc) {
4025   SourceLocation BaseLoc
4026     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4027 
4028   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4029     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4030              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4031 
4032   // C++ [class.base.init]p2:
4033   //   [...] Unless the mem-initializer-id names a nonstatic data
4034   //   member of the constructor's class or a direct or virtual base
4035   //   of that class, the mem-initializer is ill-formed. A
4036   //   mem-initializer-list can initialize a base class using any
4037   //   name that denotes that base class type.
4038   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4039 
4040   SourceRange InitRange = Init->getSourceRange();
4041   if (EllipsisLoc.isValid()) {
4042     // This is a pack expansion.
4043     if (!BaseType->containsUnexpandedParameterPack())  {
4044       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4045         << SourceRange(BaseLoc, InitRange.getEnd());
4046 
4047       EllipsisLoc = SourceLocation();
4048     }
4049   } else {
4050     // Check for any unexpanded parameter packs.
4051     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4052       return true;
4053 
4054     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4055       return true;
4056   }
4057 
4058   // Check for direct and virtual base classes.
4059   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4060   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4061   if (!Dependent) {
4062     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4063                                        BaseType))
4064       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4065 
4066     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4067                         VirtualBaseSpec);
4068 
4069     // C++ [base.class.init]p2:
4070     // Unless the mem-initializer-id names a nonstatic data member of the
4071     // constructor's class or a direct or virtual base of that class, the
4072     // mem-initializer is ill-formed.
4073     if (!DirectBaseSpec && !VirtualBaseSpec) {
4074       // If the class has any dependent bases, then it's possible that
4075       // one of those types will resolve to the same type as
4076       // BaseType. Therefore, just treat this as a dependent base
4077       // class initialization.  FIXME: Should we try to check the
4078       // initialization anyway? It seems odd.
4079       if (ClassDecl->hasAnyDependentBases())
4080         Dependent = true;
4081       else
4082         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4083           << BaseType << Context.getTypeDeclType(ClassDecl)
4084           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4085     }
4086   }
4087 
4088   if (Dependent) {
4089     DiscardCleanupsInEvaluationContext();
4090 
4091     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4092                                             /*IsVirtual=*/false,
4093                                             InitRange.getBegin(), Init,
4094                                             InitRange.getEnd(), EllipsisLoc);
4095   }
4096 
4097   // C++ [base.class.init]p2:
4098   //   If a mem-initializer-id is ambiguous because it designates both
4099   //   a direct non-virtual base class and an inherited virtual base
4100   //   class, the mem-initializer is ill-formed.
4101   if (DirectBaseSpec && VirtualBaseSpec)
4102     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4103       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4104 
4105   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4106   if (!BaseSpec)
4107     BaseSpec = VirtualBaseSpec;
4108 
4109   // Initialize the base.
4110   bool InitList = true;
4111   MultiExprArg Args = Init;
4112   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4113     InitList = false;
4114     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4115   }
4116 
4117   InitializedEntity BaseEntity =
4118     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4119   InitializationKind Kind =
4120     InitList ? InitializationKind::CreateDirectList(BaseLoc)
4121              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4122                                                 InitRange.getEnd());
4123   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4124   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4125   if (BaseInit.isInvalid())
4126     return true;
4127 
4128   // C++11 [class.base.init]p7:
4129   //   The initialization of each base and member constitutes a
4130   //   full-expression.
4131   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4132   if (BaseInit.isInvalid())
4133     return true;
4134 
4135   // If we are in a dependent context, template instantiation will
4136   // perform this type-checking again. Just save the arguments that we
4137   // received in a ParenListExpr.
4138   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4139   // of the information that we have about the base
4140   // initializer. However, deconstructing the ASTs is a dicey process,
4141   // and this approach is far more likely to get the corner cases right.
4142   if (CurContext->isDependentContext())
4143     BaseInit = Init;
4144 
4145   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4146                                           BaseSpec->isVirtual(),
4147                                           InitRange.getBegin(),
4148                                           BaseInit.getAs<Expr>(),
4149                                           InitRange.getEnd(), EllipsisLoc);
4150 }
4151 
4152 // Create a static_cast\<T&&>(expr).
4153 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4154   if (T.isNull()) T = E->getType();
4155   QualType TargetType = SemaRef.BuildReferenceType(
4156       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4157   SourceLocation ExprLoc = E->getLocStart();
4158   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4159       TargetType, ExprLoc);
4160 
4161   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4162                                    SourceRange(ExprLoc, ExprLoc),
4163                                    E->getSourceRange()).get();
4164 }
4165 
4166 /// ImplicitInitializerKind - How an implicit base or member initializer should
4167 /// initialize its base or member.
4168 enum ImplicitInitializerKind {
4169   IIK_Default,
4170   IIK_Copy,
4171   IIK_Move,
4172   IIK_Inherit
4173 };
4174 
4175 static bool
4176 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4177                              ImplicitInitializerKind ImplicitInitKind,
4178                              CXXBaseSpecifier *BaseSpec,
4179                              bool IsInheritedVirtualBase,
4180                              CXXCtorInitializer *&CXXBaseInit) {
4181   InitializedEntity InitEntity
4182     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4183                                         IsInheritedVirtualBase);
4184 
4185   ExprResult BaseInit;
4186 
4187   switch (ImplicitInitKind) {
4188   case IIK_Inherit:
4189   case IIK_Default: {
4190     InitializationKind InitKind
4191       = InitializationKind::CreateDefault(Constructor->getLocation());
4192     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4193     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4194     break;
4195   }
4196 
4197   case IIK_Move:
4198   case IIK_Copy: {
4199     bool Moving = ImplicitInitKind == IIK_Move;
4200     ParmVarDecl *Param = Constructor->getParamDecl(0);
4201     QualType ParamType = Param->getType().getNonReferenceType();
4202 
4203     Expr *CopyCtorArg =
4204       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4205                           SourceLocation(), Param, false,
4206                           Constructor->getLocation(), ParamType,
4207                           VK_LValue, nullptr);
4208 
4209     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4210 
4211     // Cast to the base class to avoid ambiguities.
4212     QualType ArgTy =
4213       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4214                                        ParamType.getQualifiers());
4215 
4216     if (Moving) {
4217       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4218     }
4219 
4220     CXXCastPath BasePath;
4221     BasePath.push_back(BaseSpec);
4222     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4223                                             CK_UncheckedDerivedToBase,
4224                                             Moving ? VK_XValue : VK_LValue,
4225                                             &BasePath).get();
4226 
4227     InitializationKind InitKind
4228       = InitializationKind::CreateDirect(Constructor->getLocation(),
4229                                          SourceLocation(), SourceLocation());
4230     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4231     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4232     break;
4233   }
4234   }
4235 
4236   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4237   if (BaseInit.isInvalid())
4238     return true;
4239 
4240   CXXBaseInit =
4241     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4242                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4243                                                         SourceLocation()),
4244                                              BaseSpec->isVirtual(),
4245                                              SourceLocation(),
4246                                              BaseInit.getAs<Expr>(),
4247                                              SourceLocation(),
4248                                              SourceLocation());
4249 
4250   return false;
4251 }
4252 
4253 static bool RefersToRValueRef(Expr *MemRef) {
4254   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4255   return Referenced->getType()->isRValueReferenceType();
4256 }
4257 
4258 static bool
4259 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4260                                ImplicitInitializerKind ImplicitInitKind,
4261                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4262                                CXXCtorInitializer *&CXXMemberInit) {
4263   if (Field->isInvalidDecl())
4264     return true;
4265 
4266   SourceLocation Loc = Constructor->getLocation();
4267 
4268   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4269     bool Moving = ImplicitInitKind == IIK_Move;
4270     ParmVarDecl *Param = Constructor->getParamDecl(0);
4271     QualType ParamType = Param->getType().getNonReferenceType();
4272 
4273     // Suppress copying zero-width bitfields.
4274     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4275       return false;
4276 
4277     Expr *MemberExprBase =
4278       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4279                           SourceLocation(), Param, false,
4280                           Loc, ParamType, VK_LValue, nullptr);
4281 
4282     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4283 
4284     if (Moving) {
4285       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4286     }
4287 
4288     // Build a reference to this field within the parameter.
4289     CXXScopeSpec SS;
4290     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4291                               Sema::LookupMemberName);
4292     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4293                                   : cast<ValueDecl>(Field), AS_public);
4294     MemberLookup.resolveKind();
4295     ExprResult CtorArg
4296       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4297                                          ParamType, Loc,
4298                                          /*IsArrow=*/false,
4299                                          SS,
4300                                          /*TemplateKWLoc=*/SourceLocation(),
4301                                          /*FirstQualifierInScope=*/nullptr,
4302                                          MemberLookup,
4303                                          /*TemplateArgs=*/nullptr,
4304                                          /*S*/nullptr);
4305     if (CtorArg.isInvalid())
4306       return true;
4307 
4308     // C++11 [class.copy]p15:
4309     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4310     //     with static_cast<T&&>(x.m);
4311     if (RefersToRValueRef(CtorArg.get())) {
4312       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4313     }
4314 
4315     InitializedEntity Entity =
4316         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4317                                                        /*Implicit*/ true)
4318                  : InitializedEntity::InitializeMember(Field, nullptr,
4319                                                        /*Implicit*/ true);
4320 
4321     // Direct-initialize to use the copy constructor.
4322     InitializationKind InitKind =
4323       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4324 
4325     Expr *CtorArgE = CtorArg.getAs<Expr>();
4326     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4327     ExprResult MemberInit =
4328         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4329     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4330     if (MemberInit.isInvalid())
4331       return true;
4332 
4333     if (Indirect)
4334       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4335           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4336     else
4337       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4338           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4339     return false;
4340   }
4341 
4342   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4343          "Unhandled implicit init kind!");
4344 
4345   QualType FieldBaseElementType =
4346     SemaRef.Context.getBaseElementType(Field->getType());
4347 
4348   if (FieldBaseElementType->isRecordType()) {
4349     InitializedEntity InitEntity =
4350         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4351                                                        /*Implicit*/ true)
4352                  : InitializedEntity::InitializeMember(Field, nullptr,
4353                                                        /*Implicit*/ true);
4354     InitializationKind InitKind =
4355       InitializationKind::CreateDefault(Loc);
4356 
4357     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4358     ExprResult MemberInit =
4359       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4360 
4361     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4362     if (MemberInit.isInvalid())
4363       return true;
4364 
4365     if (Indirect)
4366       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4367                                                                Indirect, Loc,
4368                                                                Loc,
4369                                                                MemberInit.get(),
4370                                                                Loc);
4371     else
4372       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4373                                                                Field, Loc, Loc,
4374                                                                MemberInit.get(),
4375                                                                Loc);
4376     return false;
4377   }
4378 
4379   if (!Field->getParent()->isUnion()) {
4380     if (FieldBaseElementType->isReferenceType()) {
4381       SemaRef.Diag(Constructor->getLocation(),
4382                    diag::err_uninitialized_member_in_ctor)
4383       << (int)Constructor->isImplicit()
4384       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4385       << 0 << Field->getDeclName();
4386       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4387       return true;
4388     }
4389 
4390     if (FieldBaseElementType.isConstQualified()) {
4391       SemaRef.Diag(Constructor->getLocation(),
4392                    diag::err_uninitialized_member_in_ctor)
4393       << (int)Constructor->isImplicit()
4394       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4395       << 1 << Field->getDeclName();
4396       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4397       return true;
4398     }
4399   }
4400 
4401   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
4402       FieldBaseElementType->isObjCRetainableType() &&
4403       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
4404       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
4405     // ARC:
4406     //   Default-initialize Objective-C pointers to NULL.
4407     CXXMemberInit
4408       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4409                                                  Loc, Loc,
4410                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4411                                                  Loc);
4412     return false;
4413   }
4414 
4415   // Nothing to initialize.
4416   CXXMemberInit = nullptr;
4417   return false;
4418 }
4419 
4420 namespace {
4421 struct BaseAndFieldInfo {
4422   Sema &S;
4423   CXXConstructorDecl *Ctor;
4424   bool AnyErrorsInInits;
4425   ImplicitInitializerKind IIK;
4426   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4427   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4428   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4429 
4430   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4431     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4432     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4433     if (Ctor->getInheritedConstructor())
4434       IIK = IIK_Inherit;
4435     else if (Generated && Ctor->isCopyConstructor())
4436       IIK = IIK_Copy;
4437     else if (Generated && Ctor->isMoveConstructor())
4438       IIK = IIK_Move;
4439     else
4440       IIK = IIK_Default;
4441   }
4442 
4443   bool isImplicitCopyOrMove() const {
4444     switch (IIK) {
4445     case IIK_Copy:
4446     case IIK_Move:
4447       return true;
4448 
4449     case IIK_Default:
4450     case IIK_Inherit:
4451       return false;
4452     }
4453 
4454     llvm_unreachable("Invalid ImplicitInitializerKind!");
4455   }
4456 
4457   bool addFieldInitializer(CXXCtorInitializer *Init) {
4458     AllToInit.push_back(Init);
4459 
4460     // Check whether this initializer makes the field "used".
4461     if (Init->getInit()->HasSideEffects(S.Context))
4462       S.UnusedPrivateFields.remove(Init->getAnyMember());
4463 
4464     return false;
4465   }
4466 
4467   bool isInactiveUnionMember(FieldDecl *Field) {
4468     RecordDecl *Record = Field->getParent();
4469     if (!Record->isUnion())
4470       return false;
4471 
4472     if (FieldDecl *Active =
4473             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4474       return Active != Field->getCanonicalDecl();
4475 
4476     // In an implicit copy or move constructor, ignore any in-class initializer.
4477     if (isImplicitCopyOrMove())
4478       return true;
4479 
4480     // If there's no explicit initialization, the field is active only if it
4481     // has an in-class initializer...
4482     if (Field->hasInClassInitializer())
4483       return false;
4484     // ... or it's an anonymous struct or union whose class has an in-class
4485     // initializer.
4486     if (!Field->isAnonymousStructOrUnion())
4487       return true;
4488     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4489     return !FieldRD->hasInClassInitializer();
4490   }
4491 
4492   /// \brief Determine whether the given field is, or is within, a union member
4493   /// that is inactive (because there was an initializer given for a different
4494   /// member of the union, or because the union was not initialized at all).
4495   bool isWithinInactiveUnionMember(FieldDecl *Field,
4496                                    IndirectFieldDecl *Indirect) {
4497     if (!Indirect)
4498       return isInactiveUnionMember(Field);
4499 
4500     for (auto *C : Indirect->chain()) {
4501       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4502       if (Field && isInactiveUnionMember(Field))
4503         return true;
4504     }
4505     return false;
4506   }
4507 };
4508 }
4509 
4510 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
4511 /// array type.
4512 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4513   if (T->isIncompleteArrayType())
4514     return true;
4515 
4516   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4517     if (!ArrayT->getSize())
4518       return true;
4519 
4520     T = ArrayT->getElementType();
4521   }
4522 
4523   return false;
4524 }
4525 
4526 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4527                                     FieldDecl *Field,
4528                                     IndirectFieldDecl *Indirect = nullptr) {
4529   if (Field->isInvalidDecl())
4530     return false;
4531 
4532   // Overwhelmingly common case: we have a direct initializer for this field.
4533   if (CXXCtorInitializer *Init =
4534           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4535     return Info.addFieldInitializer(Init);
4536 
4537   // C++11 [class.base.init]p8:
4538   //   if the entity is a non-static data member that has a
4539   //   brace-or-equal-initializer and either
4540   //   -- the constructor's class is a union and no other variant member of that
4541   //      union is designated by a mem-initializer-id or
4542   //   -- the constructor's class is not a union, and, if the entity is a member
4543   //      of an anonymous union, no other member of that union is designated by
4544   //      a mem-initializer-id,
4545   //   the entity is initialized as specified in [dcl.init].
4546   //
4547   // We also apply the same rules to handle anonymous structs within anonymous
4548   // unions.
4549   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4550     return false;
4551 
4552   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4553     ExprResult DIE =
4554         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4555     if (DIE.isInvalid())
4556       return true;
4557     CXXCtorInitializer *Init;
4558     if (Indirect)
4559       Init = new (SemaRef.Context)
4560           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4561                              SourceLocation(), DIE.get(), SourceLocation());
4562     else
4563       Init = new (SemaRef.Context)
4564           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4565                              SourceLocation(), DIE.get(), SourceLocation());
4566     return Info.addFieldInitializer(Init);
4567   }
4568 
4569   // Don't initialize incomplete or zero-length arrays.
4570   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4571     return false;
4572 
4573   // Don't try to build an implicit initializer if there were semantic
4574   // errors in any of the initializers (and therefore we might be
4575   // missing some that the user actually wrote).
4576   if (Info.AnyErrorsInInits)
4577     return false;
4578 
4579   CXXCtorInitializer *Init = nullptr;
4580   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4581                                      Indirect, Init))
4582     return true;
4583 
4584   if (!Init)
4585     return false;
4586 
4587   return Info.addFieldInitializer(Init);
4588 }
4589 
4590 bool
4591 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4592                                CXXCtorInitializer *Initializer) {
4593   assert(Initializer->isDelegatingInitializer());
4594   Constructor->setNumCtorInitializers(1);
4595   CXXCtorInitializer **initializer =
4596     new (Context) CXXCtorInitializer*[1];
4597   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4598   Constructor->setCtorInitializers(initializer);
4599 
4600   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4601     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4602     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4603   }
4604 
4605   DelegatingCtorDecls.push_back(Constructor);
4606 
4607   DiagnoseUninitializedFields(*this, Constructor);
4608 
4609   return false;
4610 }
4611 
4612 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4613                                ArrayRef<CXXCtorInitializer *> Initializers) {
4614   if (Constructor->isDependentContext()) {
4615     // Just store the initializers as written, they will be checked during
4616     // instantiation.
4617     if (!Initializers.empty()) {
4618       Constructor->setNumCtorInitializers(Initializers.size());
4619       CXXCtorInitializer **baseOrMemberInitializers =
4620         new (Context) CXXCtorInitializer*[Initializers.size()];
4621       memcpy(baseOrMemberInitializers, Initializers.data(),
4622              Initializers.size() * sizeof(CXXCtorInitializer*));
4623       Constructor->setCtorInitializers(baseOrMemberInitializers);
4624     }
4625 
4626     // Let template instantiation know whether we had errors.
4627     if (AnyErrors)
4628       Constructor->setInvalidDecl();
4629 
4630     return false;
4631   }
4632 
4633   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4634 
4635   // We need to build the initializer AST according to order of construction
4636   // and not what user specified in the Initializers list.
4637   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4638   if (!ClassDecl)
4639     return true;
4640 
4641   bool HadError = false;
4642 
4643   for (unsigned i = 0; i < Initializers.size(); i++) {
4644     CXXCtorInitializer *Member = Initializers[i];
4645 
4646     if (Member->isBaseInitializer())
4647       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4648     else {
4649       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4650 
4651       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4652         for (auto *C : F->chain()) {
4653           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4654           if (FD && FD->getParent()->isUnion())
4655             Info.ActiveUnionMember.insert(std::make_pair(
4656                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4657         }
4658       } else if (FieldDecl *FD = Member->getMember()) {
4659         if (FD->getParent()->isUnion())
4660           Info.ActiveUnionMember.insert(std::make_pair(
4661               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4662       }
4663     }
4664   }
4665 
4666   // Keep track of the direct virtual bases.
4667   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4668   for (auto &I : ClassDecl->bases()) {
4669     if (I.isVirtual())
4670       DirectVBases.insert(&I);
4671   }
4672 
4673   // Push virtual bases before others.
4674   for (auto &VBase : ClassDecl->vbases()) {
4675     if (CXXCtorInitializer *Value
4676         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4677       // [class.base.init]p7, per DR257:
4678       //   A mem-initializer where the mem-initializer-id names a virtual base
4679       //   class is ignored during execution of a constructor of any class that
4680       //   is not the most derived class.
4681       if (ClassDecl->isAbstract()) {
4682         // FIXME: Provide a fixit to remove the base specifier. This requires
4683         // tracking the location of the associated comma for a base specifier.
4684         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4685           << VBase.getType() << ClassDecl;
4686         DiagnoseAbstractType(ClassDecl);
4687       }
4688 
4689       Info.AllToInit.push_back(Value);
4690     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4691       // [class.base.init]p8, per DR257:
4692       //   If a given [...] base class is not named by a mem-initializer-id
4693       //   [...] and the entity is not a virtual base class of an abstract
4694       //   class, then [...] the entity is default-initialized.
4695       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4696       CXXCtorInitializer *CXXBaseInit;
4697       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4698                                        &VBase, IsInheritedVirtualBase,
4699                                        CXXBaseInit)) {
4700         HadError = true;
4701         continue;
4702       }
4703 
4704       Info.AllToInit.push_back(CXXBaseInit);
4705     }
4706   }
4707 
4708   // Non-virtual bases.
4709   for (auto &Base : ClassDecl->bases()) {
4710     // Virtuals are in the virtual base list and already constructed.
4711     if (Base.isVirtual())
4712       continue;
4713 
4714     if (CXXCtorInitializer *Value
4715           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4716       Info.AllToInit.push_back(Value);
4717     } else if (!AnyErrors) {
4718       CXXCtorInitializer *CXXBaseInit;
4719       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4720                                        &Base, /*IsInheritedVirtualBase=*/false,
4721                                        CXXBaseInit)) {
4722         HadError = true;
4723         continue;
4724       }
4725 
4726       Info.AllToInit.push_back(CXXBaseInit);
4727     }
4728   }
4729 
4730   // Fields.
4731   for (auto *Mem : ClassDecl->decls()) {
4732     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4733       // C++ [class.bit]p2:
4734       //   A declaration for a bit-field that omits the identifier declares an
4735       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4736       //   initialized.
4737       if (F->isUnnamedBitfield())
4738         continue;
4739 
4740       // If we're not generating the implicit copy/move constructor, then we'll
4741       // handle anonymous struct/union fields based on their individual
4742       // indirect fields.
4743       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4744         continue;
4745 
4746       if (CollectFieldInitializer(*this, Info, F))
4747         HadError = true;
4748       continue;
4749     }
4750 
4751     // Beyond this point, we only consider default initialization.
4752     if (Info.isImplicitCopyOrMove())
4753       continue;
4754 
4755     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4756       if (F->getType()->isIncompleteArrayType()) {
4757         assert(ClassDecl->hasFlexibleArrayMember() &&
4758                "Incomplete array type is not valid");
4759         continue;
4760       }
4761 
4762       // Initialize each field of an anonymous struct individually.
4763       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4764         HadError = true;
4765 
4766       continue;
4767     }
4768   }
4769 
4770   unsigned NumInitializers = Info.AllToInit.size();
4771   if (NumInitializers > 0) {
4772     Constructor->setNumCtorInitializers(NumInitializers);
4773     CXXCtorInitializer **baseOrMemberInitializers =
4774       new (Context) CXXCtorInitializer*[NumInitializers];
4775     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4776            NumInitializers * sizeof(CXXCtorInitializer*));
4777     Constructor->setCtorInitializers(baseOrMemberInitializers);
4778 
4779     // Constructors implicitly reference the base and member
4780     // destructors.
4781     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4782                                            Constructor->getParent());
4783   }
4784 
4785   return HadError;
4786 }
4787 
4788 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4789   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4790     const RecordDecl *RD = RT->getDecl();
4791     if (RD->isAnonymousStructOrUnion()) {
4792       for (auto *Field : RD->fields())
4793         PopulateKeysForFields(Field, IdealInits);
4794       return;
4795     }
4796   }
4797   IdealInits.push_back(Field->getCanonicalDecl());
4798 }
4799 
4800 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4801   return Context.getCanonicalType(BaseType).getTypePtr();
4802 }
4803 
4804 static const void *GetKeyForMember(ASTContext &Context,
4805                                    CXXCtorInitializer *Member) {
4806   if (!Member->isAnyMemberInitializer())
4807     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4808 
4809   return Member->getAnyMember()->getCanonicalDecl();
4810 }
4811 
4812 static void DiagnoseBaseOrMemInitializerOrder(
4813     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4814     ArrayRef<CXXCtorInitializer *> Inits) {
4815   if (Constructor->getDeclContext()->isDependentContext())
4816     return;
4817 
4818   // Don't check initializers order unless the warning is enabled at the
4819   // location of at least one initializer.
4820   bool ShouldCheckOrder = false;
4821   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4822     CXXCtorInitializer *Init = Inits[InitIndex];
4823     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4824                                  Init->getSourceLocation())) {
4825       ShouldCheckOrder = true;
4826       break;
4827     }
4828   }
4829   if (!ShouldCheckOrder)
4830     return;
4831 
4832   // Build the list of bases and members in the order that they'll
4833   // actually be initialized.  The explicit initializers should be in
4834   // this same order but may be missing things.
4835   SmallVector<const void*, 32> IdealInitKeys;
4836 
4837   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4838 
4839   // 1. Virtual bases.
4840   for (const auto &VBase : ClassDecl->vbases())
4841     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4842 
4843   // 2. Non-virtual bases.
4844   for (const auto &Base : ClassDecl->bases()) {
4845     if (Base.isVirtual())
4846       continue;
4847     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4848   }
4849 
4850   // 3. Direct fields.
4851   for (auto *Field : ClassDecl->fields()) {
4852     if (Field->isUnnamedBitfield())
4853       continue;
4854 
4855     PopulateKeysForFields(Field, IdealInitKeys);
4856   }
4857 
4858   unsigned NumIdealInits = IdealInitKeys.size();
4859   unsigned IdealIndex = 0;
4860 
4861   CXXCtorInitializer *PrevInit = nullptr;
4862   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4863     CXXCtorInitializer *Init = Inits[InitIndex];
4864     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4865 
4866     // Scan forward to try to find this initializer in the idealized
4867     // initializers list.
4868     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4869       if (InitKey == IdealInitKeys[IdealIndex])
4870         break;
4871 
4872     // If we didn't find this initializer, it must be because we
4873     // scanned past it on a previous iteration.  That can only
4874     // happen if we're out of order;  emit a warning.
4875     if (IdealIndex == NumIdealInits && PrevInit) {
4876       Sema::SemaDiagnosticBuilder D =
4877         SemaRef.Diag(PrevInit->getSourceLocation(),
4878                      diag::warn_initializer_out_of_order);
4879 
4880       if (PrevInit->isAnyMemberInitializer())
4881         D << 0 << PrevInit->getAnyMember()->getDeclName();
4882       else
4883         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4884 
4885       if (Init->isAnyMemberInitializer())
4886         D << 0 << Init->getAnyMember()->getDeclName();
4887       else
4888         D << 1 << Init->getTypeSourceInfo()->getType();
4889 
4890       // Move back to the initializer's location in the ideal list.
4891       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4892         if (InitKey == IdealInitKeys[IdealIndex])
4893           break;
4894 
4895       assert(IdealIndex < NumIdealInits &&
4896              "initializer not found in initializer list");
4897     }
4898 
4899     PrevInit = Init;
4900   }
4901 }
4902 
4903 namespace {
4904 bool CheckRedundantInit(Sema &S,
4905                         CXXCtorInitializer *Init,
4906                         CXXCtorInitializer *&PrevInit) {
4907   if (!PrevInit) {
4908     PrevInit = Init;
4909     return false;
4910   }
4911 
4912   if (FieldDecl *Field = Init->getAnyMember())
4913     S.Diag(Init->getSourceLocation(),
4914            diag::err_multiple_mem_initialization)
4915       << Field->getDeclName()
4916       << Init->getSourceRange();
4917   else {
4918     const Type *BaseClass = Init->getBaseClass();
4919     assert(BaseClass && "neither field nor base");
4920     S.Diag(Init->getSourceLocation(),
4921            diag::err_multiple_base_initialization)
4922       << QualType(BaseClass, 0)
4923       << Init->getSourceRange();
4924   }
4925   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4926     << 0 << PrevInit->getSourceRange();
4927 
4928   return true;
4929 }
4930 
4931 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4932 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4933 
4934 bool CheckRedundantUnionInit(Sema &S,
4935                              CXXCtorInitializer *Init,
4936                              RedundantUnionMap &Unions) {
4937   FieldDecl *Field = Init->getAnyMember();
4938   RecordDecl *Parent = Field->getParent();
4939   NamedDecl *Child = Field;
4940 
4941   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4942     if (Parent->isUnion()) {
4943       UnionEntry &En = Unions[Parent];
4944       if (En.first && En.first != Child) {
4945         S.Diag(Init->getSourceLocation(),
4946                diag::err_multiple_mem_union_initialization)
4947           << Field->getDeclName()
4948           << Init->getSourceRange();
4949         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4950           << 0 << En.second->getSourceRange();
4951         return true;
4952       }
4953       if (!En.first) {
4954         En.first = Child;
4955         En.second = Init;
4956       }
4957       if (!Parent->isAnonymousStructOrUnion())
4958         return false;
4959     }
4960 
4961     Child = Parent;
4962     Parent = cast<RecordDecl>(Parent->getDeclContext());
4963   }
4964 
4965   return false;
4966 }
4967 }
4968 
4969 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4970 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4971                                 SourceLocation ColonLoc,
4972                                 ArrayRef<CXXCtorInitializer*> MemInits,
4973                                 bool AnyErrors) {
4974   if (!ConstructorDecl)
4975     return;
4976 
4977   AdjustDeclIfTemplate(ConstructorDecl);
4978 
4979   CXXConstructorDecl *Constructor
4980     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4981 
4982   if (!Constructor) {
4983     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4984     return;
4985   }
4986 
4987   // Mapping for the duplicate initializers check.
4988   // For member initializers, this is keyed with a FieldDecl*.
4989   // For base initializers, this is keyed with a Type*.
4990   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4991 
4992   // Mapping for the inconsistent anonymous-union initializers check.
4993   RedundantUnionMap MemberUnions;
4994 
4995   bool HadError = false;
4996   for (unsigned i = 0; i < MemInits.size(); i++) {
4997     CXXCtorInitializer *Init = MemInits[i];
4998 
4999     // Set the source order index.
5000     Init->setSourceOrder(i);
5001 
5002     if (Init->isAnyMemberInitializer()) {
5003       const void *Key = GetKeyForMember(Context, Init);
5004       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5005           CheckRedundantUnionInit(*this, Init, MemberUnions))
5006         HadError = true;
5007     } else if (Init->isBaseInitializer()) {
5008       const void *Key = GetKeyForMember(Context, Init);
5009       if (CheckRedundantInit(*this, Init, Members[Key]))
5010         HadError = true;
5011     } else {
5012       assert(Init->isDelegatingInitializer());
5013       // This must be the only initializer
5014       if (MemInits.size() != 1) {
5015         Diag(Init->getSourceLocation(),
5016              diag::err_delegating_initializer_alone)
5017           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5018         // We will treat this as being the only initializer.
5019       }
5020       SetDelegatingInitializer(Constructor, MemInits[i]);
5021       // Return immediately as the initializer is set.
5022       return;
5023     }
5024   }
5025 
5026   if (HadError)
5027     return;
5028 
5029   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5030 
5031   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5032 
5033   DiagnoseUninitializedFields(*this, Constructor);
5034 }
5035 
5036 void
5037 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5038                                              CXXRecordDecl *ClassDecl) {
5039   // Ignore dependent contexts. Also ignore unions, since their members never
5040   // have destructors implicitly called.
5041   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5042     return;
5043 
5044   // FIXME: all the access-control diagnostics are positioned on the
5045   // field/base declaration.  That's probably good; that said, the
5046   // user might reasonably want to know why the destructor is being
5047   // emitted, and we currently don't say.
5048 
5049   // Non-static data members.
5050   for (auto *Field : ClassDecl->fields()) {
5051     if (Field->isInvalidDecl())
5052       continue;
5053 
5054     // Don't destroy incomplete or zero-length arrays.
5055     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5056       continue;
5057 
5058     QualType FieldType = Context.getBaseElementType(Field->getType());
5059 
5060     const RecordType* RT = FieldType->getAs<RecordType>();
5061     if (!RT)
5062       continue;
5063 
5064     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5065     if (FieldClassDecl->isInvalidDecl())
5066       continue;
5067     if (FieldClassDecl->hasIrrelevantDestructor())
5068       continue;
5069     // The destructor for an implicit anonymous union member is never invoked.
5070     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5071       continue;
5072 
5073     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5074     assert(Dtor && "No dtor found for FieldClassDecl!");
5075     CheckDestructorAccess(Field->getLocation(), Dtor,
5076                           PDiag(diag::err_access_dtor_field)
5077                             << Field->getDeclName()
5078                             << FieldType);
5079 
5080     MarkFunctionReferenced(Location, Dtor);
5081     DiagnoseUseOfDecl(Dtor, Location);
5082   }
5083 
5084   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5085 
5086   // Bases.
5087   for (const auto &Base : ClassDecl->bases()) {
5088     // Bases are always records in a well-formed non-dependent class.
5089     const RecordType *RT = Base.getType()->getAs<RecordType>();
5090 
5091     // Remember direct virtual bases.
5092     if (Base.isVirtual())
5093       DirectVirtualBases.insert(RT);
5094 
5095     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5096     // If our base class is invalid, we probably can't get its dtor anyway.
5097     if (BaseClassDecl->isInvalidDecl())
5098       continue;
5099     if (BaseClassDecl->hasIrrelevantDestructor())
5100       continue;
5101 
5102     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5103     assert(Dtor && "No dtor found for BaseClassDecl!");
5104 
5105     // FIXME: caret should be on the start of the class name
5106     CheckDestructorAccess(Base.getLocStart(), Dtor,
5107                           PDiag(diag::err_access_dtor_base)
5108                             << Base.getType()
5109                             << Base.getSourceRange(),
5110                           Context.getTypeDeclType(ClassDecl));
5111 
5112     MarkFunctionReferenced(Location, Dtor);
5113     DiagnoseUseOfDecl(Dtor, Location);
5114   }
5115 
5116   // Virtual bases.
5117   for (const auto &VBase : ClassDecl->vbases()) {
5118     // Bases are always records in a well-formed non-dependent class.
5119     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5120 
5121     // Ignore direct virtual bases.
5122     if (DirectVirtualBases.count(RT))
5123       continue;
5124 
5125     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5126     // If our base class is invalid, we probably can't get its dtor anyway.
5127     if (BaseClassDecl->isInvalidDecl())
5128       continue;
5129     if (BaseClassDecl->hasIrrelevantDestructor())
5130       continue;
5131 
5132     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5133     assert(Dtor && "No dtor found for BaseClassDecl!");
5134     if (CheckDestructorAccess(
5135             ClassDecl->getLocation(), Dtor,
5136             PDiag(diag::err_access_dtor_vbase)
5137                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5138             Context.getTypeDeclType(ClassDecl)) ==
5139         AR_accessible) {
5140       CheckDerivedToBaseConversion(
5141           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5142           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5143           SourceRange(), DeclarationName(), nullptr);
5144     }
5145 
5146     MarkFunctionReferenced(Location, Dtor);
5147     DiagnoseUseOfDecl(Dtor, Location);
5148   }
5149 }
5150 
5151 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5152   if (!CDtorDecl)
5153     return;
5154 
5155   if (CXXConstructorDecl *Constructor
5156       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5157     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5158     DiagnoseUninitializedFields(*this, Constructor);
5159   }
5160 }
5161 
5162 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5163   if (!getLangOpts().CPlusPlus)
5164     return false;
5165 
5166   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5167   if (!RD)
5168     return false;
5169 
5170   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5171   // class template specialization here, but doing so breaks a lot of code.
5172 
5173   // We can't answer whether something is abstract until it has a
5174   // definition. If it's currently being defined, we'll walk back
5175   // over all the declarations when we have a full definition.
5176   const CXXRecordDecl *Def = RD->getDefinition();
5177   if (!Def || Def->isBeingDefined())
5178     return false;
5179 
5180   return RD->isAbstract();
5181 }
5182 
5183 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5184                                   TypeDiagnoser &Diagnoser) {
5185   if (!isAbstractType(Loc, T))
5186     return false;
5187 
5188   T = Context.getBaseElementType(T);
5189   Diagnoser.diagnose(*this, Loc, T);
5190   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5191   return true;
5192 }
5193 
5194 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5195   // Check if we've already emitted the list of pure virtual functions
5196   // for this class.
5197   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5198     return;
5199 
5200   // If the diagnostic is suppressed, don't emit the notes. We're only
5201   // going to emit them once, so try to attach them to a diagnostic we're
5202   // actually going to show.
5203   if (Diags.isLastDiagnosticIgnored())
5204     return;
5205 
5206   CXXFinalOverriderMap FinalOverriders;
5207   RD->getFinalOverriders(FinalOverriders);
5208 
5209   // Keep a set of seen pure methods so we won't diagnose the same method
5210   // more than once.
5211   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5212 
5213   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5214                                    MEnd = FinalOverriders.end();
5215        M != MEnd;
5216        ++M) {
5217     for (OverridingMethods::iterator SO = M->second.begin(),
5218                                   SOEnd = M->second.end();
5219          SO != SOEnd; ++SO) {
5220       // C++ [class.abstract]p4:
5221       //   A class is abstract if it contains or inherits at least one
5222       //   pure virtual function for which the final overrider is pure
5223       //   virtual.
5224 
5225       //
5226       if (SO->second.size() != 1)
5227         continue;
5228 
5229       if (!SO->second.front().Method->isPure())
5230         continue;
5231 
5232       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5233         continue;
5234 
5235       Diag(SO->second.front().Method->getLocation(),
5236            diag::note_pure_virtual_function)
5237         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5238     }
5239   }
5240 
5241   if (!PureVirtualClassDiagSet)
5242     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5243   PureVirtualClassDiagSet->insert(RD);
5244 }
5245 
5246 namespace {
5247 struct AbstractUsageInfo {
5248   Sema &S;
5249   CXXRecordDecl *Record;
5250   CanQualType AbstractType;
5251   bool Invalid;
5252 
5253   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5254     : S(S), Record(Record),
5255       AbstractType(S.Context.getCanonicalType(
5256                    S.Context.getTypeDeclType(Record))),
5257       Invalid(false) {}
5258 
5259   void DiagnoseAbstractType() {
5260     if (Invalid) return;
5261     S.DiagnoseAbstractType(Record);
5262     Invalid = true;
5263   }
5264 
5265   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5266 };
5267 
5268 struct CheckAbstractUsage {
5269   AbstractUsageInfo &Info;
5270   const NamedDecl *Ctx;
5271 
5272   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5273     : Info(Info), Ctx(Ctx) {}
5274 
5275   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5276     switch (TL.getTypeLocClass()) {
5277 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5278 #define TYPELOC(CLASS, PARENT) \
5279     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5280 #include "clang/AST/TypeLocNodes.def"
5281     }
5282   }
5283 
5284   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5285     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5286     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5287       if (!TL.getParam(I))
5288         continue;
5289 
5290       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5291       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5292     }
5293   }
5294 
5295   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5296     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5297   }
5298 
5299   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5300     // Visit the type parameters from a permissive context.
5301     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5302       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5303       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5304         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5305           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5306       // TODO: other template argument types?
5307     }
5308   }
5309 
5310   // Visit pointee types from a permissive context.
5311 #define CheckPolymorphic(Type) \
5312   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5313     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5314   }
5315   CheckPolymorphic(PointerTypeLoc)
5316   CheckPolymorphic(ReferenceTypeLoc)
5317   CheckPolymorphic(MemberPointerTypeLoc)
5318   CheckPolymorphic(BlockPointerTypeLoc)
5319   CheckPolymorphic(AtomicTypeLoc)
5320 
5321   /// Handle all the types we haven't given a more specific
5322   /// implementation for above.
5323   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5324     // Every other kind of type that we haven't called out already
5325     // that has an inner type is either (1) sugar or (2) contains that
5326     // inner type in some way as a subobject.
5327     if (TypeLoc Next = TL.getNextTypeLoc())
5328       return Visit(Next, Sel);
5329 
5330     // If there's no inner type and we're in a permissive context,
5331     // don't diagnose.
5332     if (Sel == Sema::AbstractNone) return;
5333 
5334     // Check whether the type matches the abstract type.
5335     QualType T = TL.getType();
5336     if (T->isArrayType()) {
5337       Sel = Sema::AbstractArrayType;
5338       T = Info.S.Context.getBaseElementType(T);
5339     }
5340     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5341     if (CT != Info.AbstractType) return;
5342 
5343     // It matched; do some magic.
5344     if (Sel == Sema::AbstractArrayType) {
5345       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5346         << T << TL.getSourceRange();
5347     } else {
5348       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5349         << Sel << T << TL.getSourceRange();
5350     }
5351     Info.DiagnoseAbstractType();
5352   }
5353 };
5354 
5355 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5356                                   Sema::AbstractDiagSelID Sel) {
5357   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5358 }
5359 
5360 }
5361 
5362 /// Check for invalid uses of an abstract type in a method declaration.
5363 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5364                                     CXXMethodDecl *MD) {
5365   // No need to do the check on definitions, which require that
5366   // the return/param types be complete.
5367   if (MD->doesThisDeclarationHaveABody())
5368     return;
5369 
5370   // For safety's sake, just ignore it if we don't have type source
5371   // information.  This should never happen for non-implicit methods,
5372   // but...
5373   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5374     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5375 }
5376 
5377 /// Check for invalid uses of an abstract type within a class definition.
5378 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5379                                     CXXRecordDecl *RD) {
5380   for (auto *D : RD->decls()) {
5381     if (D->isImplicit()) continue;
5382 
5383     // Methods and method templates.
5384     if (isa<CXXMethodDecl>(D)) {
5385       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5386     } else if (isa<FunctionTemplateDecl>(D)) {
5387       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5388       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5389 
5390     // Fields and static variables.
5391     } else if (isa<FieldDecl>(D)) {
5392       FieldDecl *FD = cast<FieldDecl>(D);
5393       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5394         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5395     } else if (isa<VarDecl>(D)) {
5396       VarDecl *VD = cast<VarDecl>(D);
5397       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5398         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5399 
5400     // Nested classes and class templates.
5401     } else if (isa<CXXRecordDecl>(D)) {
5402       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5403     } else if (isa<ClassTemplateDecl>(D)) {
5404       CheckAbstractClassUsage(Info,
5405                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5406     }
5407   }
5408 }
5409 
5410 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5411   Attr *ClassAttr = getDLLAttr(Class);
5412   if (!ClassAttr)
5413     return;
5414 
5415   assert(ClassAttr->getKind() == attr::DLLExport);
5416 
5417   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5418 
5419   if (TSK == TSK_ExplicitInstantiationDeclaration)
5420     // Don't go any further if this is just an explicit instantiation
5421     // declaration.
5422     return;
5423 
5424   for (Decl *Member : Class->decls()) {
5425     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5426     if (!MD)
5427       continue;
5428 
5429     if (Member->getAttr<DLLExportAttr>()) {
5430       if (MD->isUserProvided()) {
5431         // Instantiate non-default class member functions ...
5432 
5433         // .. except for certain kinds of template specializations.
5434         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5435           continue;
5436 
5437         S.MarkFunctionReferenced(Class->getLocation(), MD);
5438 
5439         // The function will be passed to the consumer when its definition is
5440         // encountered.
5441       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5442                  MD->isCopyAssignmentOperator() ||
5443                  MD->isMoveAssignmentOperator()) {
5444         // Synthesize and instantiate non-trivial implicit methods, explicitly
5445         // defaulted methods, and the copy and move assignment operators. The
5446         // latter are exported even if they are trivial, because the address of
5447         // an operator can be taken and should compare equal accross libraries.
5448         DiagnosticErrorTrap Trap(S.Diags);
5449         S.MarkFunctionReferenced(Class->getLocation(), MD);
5450         if (Trap.hasErrorOccurred()) {
5451           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5452               << Class->getName() << !S.getLangOpts().CPlusPlus11;
5453           break;
5454         }
5455 
5456         // There is no later point when we will see the definition of this
5457         // function, so pass it to the consumer now.
5458         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5459       }
5460     }
5461   }
5462 }
5463 
5464 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5465                                                         CXXRecordDecl *Class) {
5466   // Only the MS ABI has default constructor closures, so we don't need to do
5467   // this semantic checking anywhere else.
5468   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5469     return;
5470 
5471   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5472   for (Decl *Member : Class->decls()) {
5473     // Look for exported default constructors.
5474     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5475     if (!CD || !CD->isDefaultConstructor())
5476       continue;
5477     auto *Attr = CD->getAttr<DLLExportAttr>();
5478     if (!Attr)
5479       continue;
5480 
5481     // If the class is non-dependent, mark the default arguments as ODR-used so
5482     // that we can properly codegen the constructor closure.
5483     if (!Class->isDependentContext()) {
5484       for (ParmVarDecl *PD : CD->parameters()) {
5485         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5486         S.DiscardCleanupsInEvaluationContext();
5487       }
5488     }
5489 
5490     if (LastExportedDefaultCtor) {
5491       S.Diag(LastExportedDefaultCtor->getLocation(),
5492              diag::err_attribute_dll_ambiguous_default_ctor)
5493           << Class;
5494       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5495           << CD->getDeclName();
5496       return;
5497     }
5498     LastExportedDefaultCtor = CD;
5499   }
5500 }
5501 
5502 /// \brief Check class-level dllimport/dllexport attribute.
5503 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5504   Attr *ClassAttr = getDLLAttr(Class);
5505 
5506   // MSVC inherits DLL attributes to partial class template specializations.
5507   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5508     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5509       if (Attr *TemplateAttr =
5510               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5511         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5512         A->setInherited(true);
5513         ClassAttr = A;
5514       }
5515     }
5516   }
5517 
5518   if (!ClassAttr)
5519     return;
5520 
5521   if (!Class->isExternallyVisible()) {
5522     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5523         << Class << ClassAttr;
5524     return;
5525   }
5526 
5527   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5528       !ClassAttr->isInherited()) {
5529     // Diagnose dll attributes on members of class with dll attribute.
5530     for (Decl *Member : Class->decls()) {
5531       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5532         continue;
5533       InheritableAttr *MemberAttr = getDLLAttr(Member);
5534       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5535         continue;
5536 
5537       Diag(MemberAttr->getLocation(),
5538              diag::err_attribute_dll_member_of_dll_class)
5539           << MemberAttr << ClassAttr;
5540       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5541       Member->setInvalidDecl();
5542     }
5543   }
5544 
5545   if (Class->getDescribedClassTemplate())
5546     // Don't inherit dll attribute until the template is instantiated.
5547     return;
5548 
5549   // The class is either imported or exported.
5550   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5551 
5552   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5553 
5554   // Ignore explicit dllexport on explicit class template instantiation declarations.
5555   if (ClassExported && !ClassAttr->isInherited() &&
5556       TSK == TSK_ExplicitInstantiationDeclaration) {
5557     Class->dropAttr<DLLExportAttr>();
5558     return;
5559   }
5560 
5561   // Force declaration of implicit members so they can inherit the attribute.
5562   ForceDeclarationOfImplicitMembers(Class);
5563 
5564   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5565   // seem to be true in practice?
5566 
5567   for (Decl *Member : Class->decls()) {
5568     VarDecl *VD = dyn_cast<VarDecl>(Member);
5569     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5570 
5571     // Only methods and static fields inherit the attributes.
5572     if (!VD && !MD)
5573       continue;
5574 
5575     if (MD) {
5576       // Don't process deleted methods.
5577       if (MD->isDeleted())
5578         continue;
5579 
5580       if (MD->isInlined()) {
5581         // MinGW does not import or export inline methods.
5582         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5583             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5584           continue;
5585 
5586         // MSVC versions before 2015 don't export the move assignment operators
5587         // and move constructor, so don't attempt to import/export them if
5588         // we have a definition.
5589         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5590         if ((MD->isMoveAssignmentOperator() ||
5591              (Ctor && Ctor->isMoveConstructor())) &&
5592             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5593           continue;
5594 
5595         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5596         // operator is exported anyway.
5597         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5598             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5599           continue;
5600       }
5601     }
5602 
5603     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5604       continue;
5605 
5606     if (!getDLLAttr(Member)) {
5607       auto *NewAttr =
5608           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5609       NewAttr->setInherited(true);
5610       Member->addAttr(NewAttr);
5611     }
5612   }
5613 
5614   if (ClassExported)
5615     DelayedDllExportClasses.push_back(Class);
5616 }
5617 
5618 /// \brief Perform propagation of DLL attributes from a derived class to a
5619 /// templated base class for MS compatibility.
5620 void Sema::propagateDLLAttrToBaseClassTemplate(
5621     CXXRecordDecl *Class, Attr *ClassAttr,
5622     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5623   if (getDLLAttr(
5624           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5625     // If the base class template has a DLL attribute, don't try to change it.
5626     return;
5627   }
5628 
5629   auto TSK = BaseTemplateSpec->getSpecializationKind();
5630   if (!getDLLAttr(BaseTemplateSpec) &&
5631       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5632        TSK == TSK_ImplicitInstantiation)) {
5633     // The template hasn't been instantiated yet (or it has, but only as an
5634     // explicit instantiation declaration or implicit instantiation, which means
5635     // we haven't codegenned any members yet), so propagate the attribute.
5636     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5637     NewAttr->setInherited(true);
5638     BaseTemplateSpec->addAttr(NewAttr);
5639 
5640     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5641     // needs to be run again to work see the new attribute. Otherwise this will
5642     // get run whenever the template is instantiated.
5643     if (TSK != TSK_Undeclared)
5644       checkClassLevelDLLAttribute(BaseTemplateSpec);
5645 
5646     return;
5647   }
5648 
5649   if (getDLLAttr(BaseTemplateSpec)) {
5650     // The template has already been specialized or instantiated with an
5651     // attribute, explicitly or through propagation. We should not try to change
5652     // it.
5653     return;
5654   }
5655 
5656   // The template was previously instantiated or explicitly specialized without
5657   // a dll attribute, It's too late for us to add an attribute, so warn that
5658   // this is unsupported.
5659   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5660       << BaseTemplateSpec->isExplicitSpecialization();
5661   Diag(ClassAttr->getLocation(), diag::note_attribute);
5662   if (BaseTemplateSpec->isExplicitSpecialization()) {
5663     Diag(BaseTemplateSpec->getLocation(),
5664            diag::note_template_class_explicit_specialization_was_here)
5665         << BaseTemplateSpec;
5666   } else {
5667     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5668            diag::note_template_class_instantiation_was_here)
5669         << BaseTemplateSpec;
5670   }
5671 }
5672 
5673 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5674                                         SourceLocation DefaultLoc) {
5675   switch (S.getSpecialMember(MD)) {
5676   case Sema::CXXDefaultConstructor:
5677     S.DefineImplicitDefaultConstructor(DefaultLoc,
5678                                        cast<CXXConstructorDecl>(MD));
5679     break;
5680   case Sema::CXXCopyConstructor:
5681     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5682     break;
5683   case Sema::CXXCopyAssignment:
5684     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5685     break;
5686   case Sema::CXXDestructor:
5687     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5688     break;
5689   case Sema::CXXMoveConstructor:
5690     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5691     break;
5692   case Sema::CXXMoveAssignment:
5693     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5694     break;
5695   case Sema::CXXInvalid:
5696     llvm_unreachable("Invalid special member.");
5697   }
5698 }
5699 
5700 /// \brief Perform semantic checks on a class definition that has been
5701 /// completing, introducing implicitly-declared members, checking for
5702 /// abstract types, etc.
5703 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5704   if (!Record)
5705     return;
5706 
5707   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5708     AbstractUsageInfo Info(*this, Record);
5709     CheckAbstractClassUsage(Info, Record);
5710   }
5711 
5712   // If this is not an aggregate type and has no user-declared constructor,
5713   // complain about any non-static data members of reference or const scalar
5714   // type, since they will never get initializers.
5715   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5716       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5717       !Record->isLambda()) {
5718     bool Complained = false;
5719     for (const auto *F : Record->fields()) {
5720       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5721         continue;
5722 
5723       if (F->getType()->isReferenceType() ||
5724           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5725         if (!Complained) {
5726           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5727             << Record->getTagKind() << Record;
5728           Complained = true;
5729         }
5730 
5731         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5732           << F->getType()->isReferenceType()
5733           << F->getDeclName();
5734       }
5735     }
5736   }
5737 
5738   if (Record->getIdentifier()) {
5739     // C++ [class.mem]p13:
5740     //   If T is the name of a class, then each of the following shall have a
5741     //   name different from T:
5742     //     - every member of every anonymous union that is a member of class T.
5743     //
5744     // C++ [class.mem]p14:
5745     //   In addition, if class T has a user-declared constructor (12.1), every
5746     //   non-static data member of class T shall have a name different from T.
5747     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5748     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5749          ++I) {
5750       NamedDecl *D = *I;
5751       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5752           isa<IndirectFieldDecl>(D)) {
5753         Diag(D->getLocation(), diag::err_member_name_of_class)
5754           << D->getDeclName();
5755         break;
5756       }
5757     }
5758   }
5759 
5760   // Warn if the class has virtual methods but non-virtual public destructor.
5761   if (Record->isPolymorphic() && !Record->isDependentType()) {
5762     CXXDestructorDecl *dtor = Record->getDestructor();
5763     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5764         !Record->hasAttr<FinalAttr>())
5765       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5766            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5767   }
5768 
5769   if (Record->isAbstract()) {
5770     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5771       Diag(Record->getLocation(), diag::warn_abstract_final_class)
5772         << FA->isSpelledAsSealed();
5773       DiagnoseAbstractType(Record);
5774     }
5775   }
5776 
5777   bool HasMethodWithOverrideControl = false,
5778        HasOverridingMethodWithoutOverrideControl = false;
5779   if (!Record->isDependentType()) {
5780     for (auto *M : Record->methods()) {
5781       // See if a method overloads virtual methods in a base
5782       // class without overriding any.
5783       if (!M->isStatic())
5784         DiagnoseHiddenVirtualMethods(M);
5785       if (M->hasAttr<OverrideAttr>())
5786         HasMethodWithOverrideControl = true;
5787       else if (M->size_overridden_methods() > 0)
5788         HasOverridingMethodWithoutOverrideControl = true;
5789       // Check whether the explicitly-defaulted special members are valid.
5790       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
5791         CheckExplicitlyDefaultedSpecialMember(M);
5792 
5793       // For an explicitly defaulted or deleted special member, we defer
5794       // determining triviality until the class is complete. That time is now!
5795       CXXSpecialMember CSM = getSpecialMember(M);
5796       if (!M->isImplicit() && !M->isUserProvided()) {
5797         if (CSM != CXXInvalid) {
5798           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
5799 
5800           // Inform the class that we've finished declaring this member.
5801           Record->finishedDefaultedOrDeletedMember(M);
5802         }
5803       }
5804 
5805       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5806           M->hasAttr<DLLExportAttr>()) {
5807         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5808             M->isTrivial() &&
5809             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5810              CSM == CXXDestructor))
5811           M->dropAttr<DLLExportAttr>();
5812 
5813         if (M->hasAttr<DLLExportAttr>()) {
5814           DefineImplicitSpecialMember(*this, M, M->getLocation());
5815           ActOnFinishInlineFunctionDef(M);
5816         }
5817       }
5818     }
5819   }
5820 
5821   if (HasMethodWithOverrideControl &&
5822       HasOverridingMethodWithoutOverrideControl) {
5823     // At least one method has the 'override' control declared.
5824     // Diagnose all other overridden methods which do not have 'override' specified on them.
5825     for (auto *M : Record->methods())
5826       DiagnoseAbsenceOfOverrideControl(M);
5827   }
5828 
5829   // ms_struct is a request to use the same ABI rules as MSVC.  Check
5830   // whether this class uses any C++ features that are implemented
5831   // completely differently in MSVC, and if so, emit a diagnostic.
5832   // That diagnostic defaults to an error, but we allow projects to
5833   // map it down to a warning (or ignore it).  It's a fairly common
5834   // practice among users of the ms_struct pragma to mass-annotate
5835   // headers, sweeping up a bunch of types that the project doesn't
5836   // really rely on MSVC-compatible layout for.  We must therefore
5837   // support "ms_struct except for C++ stuff" as a secondary ABI.
5838   if (Record->isMsStruct(Context) &&
5839       (Record->isPolymorphic() || Record->getNumBases())) {
5840     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5841   }
5842 
5843   checkClassLevelDLLAttribute(Record);
5844 }
5845 
5846 /// Look up the special member function that would be called by a special
5847 /// member function for a subobject of class type.
5848 ///
5849 /// \param Class The class type of the subobject.
5850 /// \param CSM The kind of special member function.
5851 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5852 /// \param ConstRHS True if this is a copy operation with a const object
5853 ///        on its RHS, that is, if the argument to the outer special member
5854 ///        function is 'const' and this is not a field marked 'mutable'.
5855 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
5856     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5857     unsigned FieldQuals, bool ConstRHS) {
5858   unsigned LHSQuals = 0;
5859   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5860     LHSQuals = FieldQuals;
5861 
5862   unsigned RHSQuals = FieldQuals;
5863   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5864     RHSQuals = 0;
5865   else if (ConstRHS)
5866     RHSQuals |= Qualifiers::Const;
5867 
5868   return S.LookupSpecialMember(Class, CSM,
5869                                RHSQuals & Qualifiers::Const,
5870                                RHSQuals & Qualifiers::Volatile,
5871                                false,
5872                                LHSQuals & Qualifiers::Const,
5873                                LHSQuals & Qualifiers::Volatile);
5874 }
5875 
5876 class Sema::InheritedConstructorInfo {
5877   Sema &S;
5878   SourceLocation UseLoc;
5879 
5880   /// A mapping from the base classes through which the constructor was
5881   /// inherited to the using shadow declaration in that base class (or a null
5882   /// pointer if the constructor was declared in that base class).
5883   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5884       InheritedFromBases;
5885 
5886 public:
5887   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5888                            ConstructorUsingShadowDecl *Shadow)
5889       : S(S), UseLoc(UseLoc) {
5890     bool DiagnosedMultipleConstructedBases = false;
5891     CXXRecordDecl *ConstructedBase = nullptr;
5892     UsingDecl *ConstructedBaseUsing = nullptr;
5893 
5894     // Find the set of such base class subobjects and check that there's a
5895     // unique constructed subobject.
5896     for (auto *D : Shadow->redecls()) {
5897       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5898       auto *DNominatedBase = DShadow->getNominatedBaseClass();
5899       auto *DConstructedBase = DShadow->getConstructedBaseClass();
5900 
5901       InheritedFromBases.insert(
5902           std::make_pair(DNominatedBase->getCanonicalDecl(),
5903                          DShadow->getNominatedBaseClassShadowDecl()));
5904       if (DShadow->constructsVirtualBase())
5905         InheritedFromBases.insert(
5906             std::make_pair(DConstructedBase->getCanonicalDecl(),
5907                            DShadow->getConstructedBaseClassShadowDecl()));
5908       else
5909         assert(DNominatedBase == DConstructedBase);
5910 
5911       // [class.inhctor.init]p2:
5912       //   If the constructor was inherited from multiple base class subobjects
5913       //   of type B, the program is ill-formed.
5914       if (!ConstructedBase) {
5915         ConstructedBase = DConstructedBase;
5916         ConstructedBaseUsing = D->getUsingDecl();
5917       } else if (ConstructedBase != DConstructedBase &&
5918                  !Shadow->isInvalidDecl()) {
5919         if (!DiagnosedMultipleConstructedBases) {
5920           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5921               << Shadow->getTargetDecl();
5922           S.Diag(ConstructedBaseUsing->getLocation(),
5923                diag::note_ambiguous_inherited_constructor_using)
5924               << ConstructedBase;
5925           DiagnosedMultipleConstructedBases = true;
5926         }
5927         S.Diag(D->getUsingDecl()->getLocation(),
5928                diag::note_ambiguous_inherited_constructor_using)
5929             << DConstructedBase;
5930       }
5931     }
5932 
5933     if (DiagnosedMultipleConstructedBases)
5934       Shadow->setInvalidDecl();
5935   }
5936 
5937   /// Find the constructor to use for inherited construction of a base class,
5938   /// and whether that base class constructor inherits the constructor from a
5939   /// virtual base class (in which case it won't actually invoke it).
5940   std::pair<CXXConstructorDecl *, bool>
5941   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5942     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5943     if (It == InheritedFromBases.end())
5944       return std::make_pair(nullptr, false);
5945 
5946     // This is an intermediary class.
5947     if (It->second)
5948       return std::make_pair(
5949           S.findInheritingConstructor(UseLoc, Ctor, It->second),
5950           It->second->constructsVirtualBase());
5951 
5952     // This is the base class from which the constructor was inherited.
5953     return std::make_pair(Ctor, false);
5954   }
5955 };
5956 
5957 /// Is the special member function which would be selected to perform the
5958 /// specified operation on the specified class type a constexpr constructor?
5959 static bool
5960 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5961                          Sema::CXXSpecialMember CSM, unsigned Quals,
5962                          bool ConstRHS,
5963                          CXXConstructorDecl *InheritedCtor = nullptr,
5964                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
5965   // If we're inheriting a constructor, see if we need to call it for this base
5966   // class.
5967   if (InheritedCtor) {
5968     assert(CSM == Sema::CXXDefaultConstructor);
5969     auto BaseCtor =
5970         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5971     if (BaseCtor)
5972       return BaseCtor->isConstexpr();
5973   }
5974 
5975   if (CSM == Sema::CXXDefaultConstructor)
5976     return ClassDecl->hasConstexprDefaultConstructor();
5977 
5978   Sema::SpecialMemberOverloadResult SMOR =
5979       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5980   if (!SMOR.getMethod())
5981     // A constructor we wouldn't select can't be "involved in initializing"
5982     // anything.
5983     return true;
5984   return SMOR.getMethod()->isConstexpr();
5985 }
5986 
5987 /// Determine whether the specified special member function would be constexpr
5988 /// if it were implicitly defined.
5989 static bool defaultedSpecialMemberIsConstexpr(
5990     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
5991     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
5992     Sema::InheritedConstructorInfo *Inherited = nullptr) {
5993   if (!S.getLangOpts().CPlusPlus11)
5994     return false;
5995 
5996   // C++11 [dcl.constexpr]p4:
5997   // In the definition of a constexpr constructor [...]
5998   bool Ctor = true;
5999   switch (CSM) {
6000   case Sema::CXXDefaultConstructor:
6001     if (Inherited)
6002       break;
6003     // Since default constructor lookup is essentially trivial (and cannot
6004     // involve, for instance, template instantiation), we compute whether a
6005     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6006     //
6007     // This is important for performance; we need to know whether the default
6008     // constructor is constexpr to determine whether the type is a literal type.
6009     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6010 
6011   case Sema::CXXCopyConstructor:
6012   case Sema::CXXMoveConstructor:
6013     // For copy or move constructors, we need to perform overload resolution.
6014     break;
6015 
6016   case Sema::CXXCopyAssignment:
6017   case Sema::CXXMoveAssignment:
6018     if (!S.getLangOpts().CPlusPlus14)
6019       return false;
6020     // In C++1y, we need to perform overload resolution.
6021     Ctor = false;
6022     break;
6023 
6024   case Sema::CXXDestructor:
6025   case Sema::CXXInvalid:
6026     return false;
6027   }
6028 
6029   //   -- if the class is a non-empty union, or for each non-empty anonymous
6030   //      union member of a non-union class, exactly one non-static data member
6031   //      shall be initialized; [DR1359]
6032   //
6033   // If we squint, this is guaranteed, since exactly one non-static data member
6034   // will be initialized (if the constructor isn't deleted), we just don't know
6035   // which one.
6036   if (Ctor && ClassDecl->isUnion())
6037     return CSM == Sema::CXXDefaultConstructor
6038                ? ClassDecl->hasInClassInitializer() ||
6039                      !ClassDecl->hasVariantMembers()
6040                : true;
6041 
6042   //   -- the class shall not have any virtual base classes;
6043   if (Ctor && ClassDecl->getNumVBases())
6044     return false;
6045 
6046   // C++1y [class.copy]p26:
6047   //   -- [the class] is a literal type, and
6048   if (!Ctor && !ClassDecl->isLiteral())
6049     return false;
6050 
6051   //   -- every constructor involved in initializing [...] base class
6052   //      sub-objects shall be a constexpr constructor;
6053   //   -- the assignment operator selected to copy/move each direct base
6054   //      class is a constexpr function, and
6055   for (const auto &B : ClassDecl->bases()) {
6056     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6057     if (!BaseType) continue;
6058 
6059     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6060     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6061                                   InheritedCtor, Inherited))
6062       return false;
6063   }
6064 
6065   //   -- every constructor involved in initializing non-static data members
6066   //      [...] shall be a constexpr constructor;
6067   //   -- every non-static data member and base class sub-object shall be
6068   //      initialized
6069   //   -- for each non-static data member of X that is of class type (or array
6070   //      thereof), the assignment operator selected to copy/move that member is
6071   //      a constexpr function
6072   for (const auto *F : ClassDecl->fields()) {
6073     if (F->isInvalidDecl())
6074       continue;
6075     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6076       continue;
6077     QualType BaseType = S.Context.getBaseElementType(F->getType());
6078     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6079       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6080       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6081                                     BaseType.getCVRQualifiers(),
6082                                     ConstArg && !F->isMutable()))
6083         return false;
6084     } else if (CSM == Sema::CXXDefaultConstructor) {
6085       return false;
6086     }
6087   }
6088 
6089   // All OK, it's constexpr!
6090   return true;
6091 }
6092 
6093 static Sema::ImplicitExceptionSpecification
6094 ComputeDefaultedSpecialMemberExceptionSpec(
6095     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6096     Sema::InheritedConstructorInfo *ICI);
6097 
6098 static Sema::ImplicitExceptionSpecification
6099 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6100   auto CSM = S.getSpecialMember(MD);
6101   if (CSM != Sema::CXXInvalid)
6102     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6103 
6104   auto *CD = cast<CXXConstructorDecl>(MD);
6105   assert(CD->getInheritedConstructor() &&
6106          "only special members have implicit exception specs");
6107   Sema::InheritedConstructorInfo ICI(
6108       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6109   return ComputeDefaultedSpecialMemberExceptionSpec(
6110       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6111 }
6112 
6113 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6114                                                             CXXMethodDecl *MD) {
6115   FunctionProtoType::ExtProtoInfo EPI;
6116 
6117   // Build an exception specification pointing back at this member.
6118   EPI.ExceptionSpec.Type = EST_Unevaluated;
6119   EPI.ExceptionSpec.SourceDecl = MD;
6120 
6121   // Set the calling convention to the default for C++ instance methods.
6122   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6123       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6124                                             /*IsCXXMethod=*/true));
6125   return EPI;
6126 }
6127 
6128 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6129   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6130   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6131     return;
6132 
6133   // Evaluate the exception specification.
6134   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6135   auto ESI = IES.getExceptionSpec();
6136 
6137   // Update the type of the special member to use it.
6138   UpdateExceptionSpec(MD, ESI);
6139 
6140   // A user-provided destructor can be defined outside the class. When that
6141   // happens, be sure to update the exception specification on both
6142   // declarations.
6143   const FunctionProtoType *CanonicalFPT =
6144     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6145   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6146     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6147 }
6148 
6149 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6150   CXXRecordDecl *RD = MD->getParent();
6151   CXXSpecialMember CSM = getSpecialMember(MD);
6152 
6153   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6154          "not an explicitly-defaulted special member");
6155 
6156   // Whether this was the first-declared instance of the constructor.
6157   // This affects whether we implicitly add an exception spec and constexpr.
6158   bool First = MD == MD->getCanonicalDecl();
6159 
6160   bool HadError = false;
6161 
6162   // C++11 [dcl.fct.def.default]p1:
6163   //   A function that is explicitly defaulted shall
6164   //     -- be a special member function (checked elsewhere),
6165   //     -- have the same type (except for ref-qualifiers, and except that a
6166   //        copy operation can take a non-const reference) as an implicit
6167   //        declaration, and
6168   //     -- not have default arguments.
6169   unsigned ExpectedParams = 1;
6170   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6171     ExpectedParams = 0;
6172   if (MD->getNumParams() != ExpectedParams) {
6173     // This also checks for default arguments: a copy or move constructor with a
6174     // default argument is classified as a default constructor, and assignment
6175     // operations and destructors can't have default arguments.
6176     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6177       << CSM << MD->getSourceRange();
6178     HadError = true;
6179   } else if (MD->isVariadic()) {
6180     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6181       << CSM << MD->getSourceRange();
6182     HadError = true;
6183   }
6184 
6185   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6186 
6187   bool CanHaveConstParam = false;
6188   if (CSM == CXXCopyConstructor)
6189     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6190   else if (CSM == CXXCopyAssignment)
6191     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6192 
6193   QualType ReturnType = Context.VoidTy;
6194   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6195     // Check for return type matching.
6196     ReturnType = Type->getReturnType();
6197     QualType ExpectedReturnType =
6198         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6199     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6200       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6201         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6202       HadError = true;
6203     }
6204 
6205     // A defaulted special member cannot have cv-qualifiers.
6206     if (Type->getTypeQuals()) {
6207       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6208         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6209       HadError = true;
6210     }
6211   }
6212 
6213   // Check for parameter type matching.
6214   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6215   bool HasConstParam = false;
6216   if (ExpectedParams && ArgType->isReferenceType()) {
6217     // Argument must be reference to possibly-const T.
6218     QualType ReferentType = ArgType->getPointeeType();
6219     HasConstParam = ReferentType.isConstQualified();
6220 
6221     if (ReferentType.isVolatileQualified()) {
6222       Diag(MD->getLocation(),
6223            diag::err_defaulted_special_member_volatile_param) << CSM;
6224       HadError = true;
6225     }
6226 
6227     if (HasConstParam && !CanHaveConstParam) {
6228       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6229         Diag(MD->getLocation(),
6230              diag::err_defaulted_special_member_copy_const_param)
6231           << (CSM == CXXCopyAssignment);
6232         // FIXME: Explain why this special member can't be const.
6233       } else {
6234         Diag(MD->getLocation(),
6235              diag::err_defaulted_special_member_move_const_param)
6236           << (CSM == CXXMoveAssignment);
6237       }
6238       HadError = true;
6239     }
6240   } else if (ExpectedParams) {
6241     // A copy assignment operator can take its argument by value, but a
6242     // defaulted one cannot.
6243     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6244     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6245     HadError = true;
6246   }
6247 
6248   // C++11 [dcl.fct.def.default]p2:
6249   //   An explicitly-defaulted function may be declared constexpr only if it
6250   //   would have been implicitly declared as constexpr,
6251   // Do not apply this rule to members of class templates, since core issue 1358
6252   // makes such functions always instantiate to constexpr functions. For
6253   // functions which cannot be constexpr (for non-constructors in C++11 and for
6254   // destructors in C++1y), this is checked elsewhere.
6255   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6256                                                      HasConstParam);
6257   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6258                                  : isa<CXXConstructorDecl>(MD)) &&
6259       MD->isConstexpr() && !Constexpr &&
6260       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6261     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6262     // FIXME: Explain why the special member can't be constexpr.
6263     HadError = true;
6264   }
6265 
6266   //   and may have an explicit exception-specification only if it is compatible
6267   //   with the exception-specification on the implicit declaration.
6268   if (Type->hasExceptionSpec()) {
6269     // Delay the check if this is the first declaration of the special member,
6270     // since we may not have parsed some necessary in-class initializers yet.
6271     if (First) {
6272       // If the exception specification needs to be instantiated, do so now,
6273       // before we clobber it with an EST_Unevaluated specification below.
6274       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6275         InstantiateExceptionSpec(MD->getLocStart(), MD);
6276         Type = MD->getType()->getAs<FunctionProtoType>();
6277       }
6278       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6279     } else
6280       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6281   }
6282 
6283   //   If a function is explicitly defaulted on its first declaration,
6284   if (First) {
6285     //  -- it is implicitly considered to be constexpr if the implicit
6286     //     definition would be,
6287     MD->setConstexpr(Constexpr);
6288 
6289     //  -- it is implicitly considered to have the same exception-specification
6290     //     as if it had been implicitly declared,
6291     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6292     EPI.ExceptionSpec.Type = EST_Unevaluated;
6293     EPI.ExceptionSpec.SourceDecl = MD;
6294     MD->setType(Context.getFunctionType(ReturnType,
6295                                         llvm::makeArrayRef(&ArgType,
6296                                                            ExpectedParams),
6297                                         EPI));
6298   }
6299 
6300   if (ShouldDeleteSpecialMember(MD, CSM)) {
6301     if (First) {
6302       SetDeclDeleted(MD, MD->getLocation());
6303     } else {
6304       // C++11 [dcl.fct.def.default]p4:
6305       //   [For a] user-provided explicitly-defaulted function [...] if such a
6306       //   function is implicitly defined as deleted, the program is ill-formed.
6307       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6308       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6309       HadError = true;
6310     }
6311   }
6312 
6313   if (HadError)
6314     MD->setInvalidDecl();
6315 }
6316 
6317 /// Check whether the exception specification provided for an
6318 /// explicitly-defaulted special member matches the exception specification
6319 /// that would have been generated for an implicit special member, per
6320 /// C++11 [dcl.fct.def.default]p2.
6321 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6322     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6323   // If the exception specification was explicitly specified but hadn't been
6324   // parsed when the method was defaulted, grab it now.
6325   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6326     SpecifiedType =
6327         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6328 
6329   // Compute the implicit exception specification.
6330   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6331                                                        /*IsCXXMethod=*/true);
6332   FunctionProtoType::ExtProtoInfo EPI(CC);
6333   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6334   EPI.ExceptionSpec = IES.getExceptionSpec();
6335   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6336     Context.getFunctionType(Context.VoidTy, None, EPI));
6337 
6338   // Ensure that it matches.
6339   CheckEquivalentExceptionSpec(
6340     PDiag(diag::err_incorrect_defaulted_exception_spec)
6341       << getSpecialMember(MD), PDiag(),
6342     ImplicitType, SourceLocation(),
6343     SpecifiedType, MD->getLocation());
6344 }
6345 
6346 void Sema::CheckDelayedMemberExceptionSpecs() {
6347   decltype(DelayedExceptionSpecChecks) Checks;
6348   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6349 
6350   std::swap(Checks, DelayedExceptionSpecChecks);
6351   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6352 
6353   // Perform any deferred checking of exception specifications for virtual
6354   // destructors.
6355   for (auto &Check : Checks)
6356     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6357 
6358   // Check that any explicitly-defaulted methods have exception specifications
6359   // compatible with their implicit exception specifications.
6360   for (auto &Spec : Specs)
6361     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6362 }
6363 
6364 namespace {
6365 /// CRTP base class for visiting operations performed by a special member
6366 /// function (or inherited constructor).
6367 template<typename Derived>
6368 struct SpecialMemberVisitor {
6369   Sema &S;
6370   CXXMethodDecl *MD;
6371   Sema::CXXSpecialMember CSM;
6372   Sema::InheritedConstructorInfo *ICI;
6373 
6374   bool ConstArg = false;
6375 
6376   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6377                        Sema::InheritedConstructorInfo *ICI)
6378       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6379     if (MD->getNumParams()) {
6380       if (const ReferenceType *RT =
6381               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6382         ConstArg = RT->getPointeeType().isConstQualified();
6383     }
6384   }
6385 
6386   /// Look up the corresponding special member in the given class.
6387   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6388                                              unsigned Quals, bool IsMutable) {
6389     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6390                                        ConstArg && !IsMutable);
6391   }
6392 
6393   /// A base or member subobject.
6394   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6395 
6396   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6397     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6398       return B->getBaseTypeLoc();
6399     else
6400       return Subobj.get<FieldDecl*>()->getLocation();
6401   }
6402 
6403 };
6404 }
6405 
6406 namespace {
6407 struct SpecialMemberDeletionInfo
6408     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6409   bool Diagnose;
6410 
6411   // Properties of the special member, computed for convenience.
6412   bool IsConstructor, IsAssignment, IsMove;
6413   SourceLocation Loc;
6414 
6415   bool AllFieldsAreConst;
6416 
6417   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6418                             Sema::CXXSpecialMember CSM,
6419                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6420       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6421         IsConstructor(false), IsAssignment(false), IsMove(false),
6422         Loc(MD->getLocation()), AllFieldsAreConst(true) {
6423     switch (CSM) {
6424       case Sema::CXXDefaultConstructor:
6425       case Sema::CXXCopyConstructor:
6426         IsConstructor = true;
6427         break;
6428       case Sema::CXXMoveConstructor:
6429         IsConstructor = true;
6430         IsMove = true;
6431         break;
6432       case Sema::CXXCopyAssignment:
6433         IsAssignment = true;
6434         break;
6435       case Sema::CXXMoveAssignment:
6436         IsAssignment = true;
6437         IsMove = true;
6438         break;
6439       case Sema::CXXDestructor:
6440         break;
6441       case Sema::CXXInvalid:
6442         llvm_unreachable("invalid special member kind");
6443     }
6444   }
6445 
6446   bool inUnion() const { return MD->getParent()->isUnion(); }
6447 
6448   Sema::CXXSpecialMember getEffectiveCSM() {
6449     return ICI ? Sema::CXXInvalid : CSM;
6450   }
6451 
6452   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6453   bool shouldDeleteForField(FieldDecl *FD);
6454   bool shouldDeleteForAllConstMembers();
6455 
6456   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6457                                      unsigned Quals);
6458   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6459                                     Sema::SpecialMemberOverloadResult SMOR,
6460                                     bool IsDtorCallInCtor);
6461 
6462   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6463 };
6464 }
6465 
6466 /// Is the given special member inaccessible when used on the given
6467 /// sub-object.
6468 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6469                                              CXXMethodDecl *target) {
6470   /// If we're operating on a base class, the object type is the
6471   /// type of this special member.
6472   QualType objectTy;
6473   AccessSpecifier access = target->getAccess();
6474   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6475     objectTy = S.Context.getTypeDeclType(MD->getParent());
6476     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6477 
6478   // If we're operating on a field, the object type is the type of the field.
6479   } else {
6480     objectTy = S.Context.getTypeDeclType(target->getParent());
6481   }
6482 
6483   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6484 }
6485 
6486 /// Check whether we should delete a special member due to the implicit
6487 /// definition containing a call to a special member of a subobject.
6488 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6489     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6490     bool IsDtorCallInCtor) {
6491   CXXMethodDecl *Decl = SMOR.getMethod();
6492   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6493 
6494   int DiagKind = -1;
6495 
6496   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6497     DiagKind = !Decl ? 0 : 1;
6498   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6499     DiagKind = 2;
6500   else if (!isAccessible(Subobj, Decl))
6501     DiagKind = 3;
6502   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6503            !Decl->isTrivial()) {
6504     // A member of a union must have a trivial corresponding special member.
6505     // As a weird special case, a destructor call from a union's constructor
6506     // must be accessible and non-deleted, but need not be trivial. Such a
6507     // destructor is never actually called, but is semantically checked as
6508     // if it were.
6509     DiagKind = 4;
6510   }
6511 
6512   if (DiagKind == -1)
6513     return false;
6514 
6515   if (Diagnose) {
6516     if (Field) {
6517       S.Diag(Field->getLocation(),
6518              diag::note_deleted_special_member_class_subobject)
6519         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6520         << Field << DiagKind << IsDtorCallInCtor;
6521     } else {
6522       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6523       S.Diag(Base->getLocStart(),
6524              diag::note_deleted_special_member_class_subobject)
6525         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6526         << Base->getType() << DiagKind << IsDtorCallInCtor;
6527     }
6528 
6529     if (DiagKind == 1)
6530       S.NoteDeletedFunction(Decl);
6531     // FIXME: Explain inaccessibility if DiagKind == 3.
6532   }
6533 
6534   return true;
6535 }
6536 
6537 /// Check whether we should delete a special member function due to having a
6538 /// direct or virtual base class or non-static data member of class type M.
6539 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6540     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6541   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6542   bool IsMutable = Field && Field->isMutable();
6543 
6544   // C++11 [class.ctor]p5:
6545   // -- any direct or virtual base class, or non-static data member with no
6546   //    brace-or-equal-initializer, has class type M (or array thereof) and
6547   //    either M has no default constructor or overload resolution as applied
6548   //    to M's default constructor results in an ambiguity or in a function
6549   //    that is deleted or inaccessible
6550   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6551   // -- a direct or virtual base class B that cannot be copied/moved because
6552   //    overload resolution, as applied to B's corresponding special member,
6553   //    results in an ambiguity or a function that is deleted or inaccessible
6554   //    from the defaulted special member
6555   // C++11 [class.dtor]p5:
6556   // -- any direct or virtual base class [...] has a type with a destructor
6557   //    that is deleted or inaccessible
6558   if (!(CSM == Sema::CXXDefaultConstructor &&
6559         Field && Field->hasInClassInitializer()) &&
6560       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6561                                    false))
6562     return true;
6563 
6564   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6565   // -- any direct or virtual base class or non-static data member has a
6566   //    type with a destructor that is deleted or inaccessible
6567   if (IsConstructor) {
6568     Sema::SpecialMemberOverloadResult SMOR =
6569         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6570                               false, false, false, false, false);
6571     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6572       return true;
6573   }
6574 
6575   return false;
6576 }
6577 
6578 /// Check whether we should delete a special member function due to the class
6579 /// having a particular direct or virtual base class.
6580 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6581   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6582   // If program is correct, BaseClass cannot be null, but if it is, the error
6583   // must be reported elsewhere.
6584   if (!BaseClass)
6585     return false;
6586   // If we have an inheriting constructor, check whether we're calling an
6587   // inherited constructor instead of a default constructor.
6588   if (ICI) {
6589     assert(CSM == Sema::CXXDefaultConstructor);
6590     auto *BaseCtor =
6591         ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD)
6592                                                    ->getInheritedConstructor()
6593                                                    .getConstructor())
6594             .first;
6595     if (BaseCtor) {
6596       if (BaseCtor->isDeleted() && Diagnose) {
6597         S.Diag(Base->getLocStart(),
6598                diag::note_deleted_special_member_class_subobject)
6599           << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6600           << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6601         S.NoteDeletedFunction(BaseCtor);
6602       }
6603       return BaseCtor->isDeleted();
6604     }
6605   }
6606   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6607 }
6608 
6609 /// Check whether we should delete a special member function due to the class
6610 /// having a particular non-static data member.
6611 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6612   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6613   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6614 
6615   if (CSM == Sema::CXXDefaultConstructor) {
6616     // For a default constructor, all references must be initialized in-class
6617     // and, if a union, it must have a non-const member.
6618     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6619       if (Diagnose)
6620         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6621           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6622       return true;
6623     }
6624     // C++11 [class.ctor]p5: any non-variant non-static data member of
6625     // const-qualified type (or array thereof) with no
6626     // brace-or-equal-initializer does not have a user-provided default
6627     // constructor.
6628     if (!inUnion() && FieldType.isConstQualified() &&
6629         !FD->hasInClassInitializer() &&
6630         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6631       if (Diagnose)
6632         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6633           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6634       return true;
6635     }
6636 
6637     if (inUnion() && !FieldType.isConstQualified())
6638       AllFieldsAreConst = false;
6639   } else if (CSM == Sema::CXXCopyConstructor) {
6640     // For a copy constructor, data members must not be of rvalue reference
6641     // type.
6642     if (FieldType->isRValueReferenceType()) {
6643       if (Diagnose)
6644         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6645           << MD->getParent() << FD << FieldType;
6646       return true;
6647     }
6648   } else if (IsAssignment) {
6649     // For an assignment operator, data members must not be of reference type.
6650     if (FieldType->isReferenceType()) {
6651       if (Diagnose)
6652         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6653           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
6654       return true;
6655     }
6656     if (!FieldRecord && FieldType.isConstQualified()) {
6657       // C++11 [class.copy]p23:
6658       // -- a non-static data member of const non-class type (or array thereof)
6659       if (Diagnose)
6660         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6661           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
6662       return true;
6663     }
6664   }
6665 
6666   if (FieldRecord) {
6667     // Some additional restrictions exist on the variant members.
6668     if (!inUnion() && FieldRecord->isUnion() &&
6669         FieldRecord->isAnonymousStructOrUnion()) {
6670       bool AllVariantFieldsAreConst = true;
6671 
6672       // FIXME: Handle anonymous unions declared within anonymous unions.
6673       for (auto *UI : FieldRecord->fields()) {
6674         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
6675 
6676         if (!UnionFieldType.isConstQualified())
6677           AllVariantFieldsAreConst = false;
6678 
6679         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6680         if (UnionFieldRecord &&
6681             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
6682                                           UnionFieldType.getCVRQualifiers()))
6683           return true;
6684       }
6685 
6686       // At least one member in each anonymous union must be non-const
6687       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
6688           !FieldRecord->field_empty()) {
6689         if (Diagnose)
6690           S.Diag(FieldRecord->getLocation(),
6691                  diag::note_deleted_default_ctor_all_const)
6692             << !!ICI << MD->getParent() << /*anonymous union*/1;
6693         return true;
6694       }
6695 
6696       // Don't check the implicit member of the anonymous union type.
6697       // This is technically non-conformant, but sanity demands it.
6698       return false;
6699     }
6700 
6701     if (shouldDeleteForClassSubobject(FieldRecord, FD,
6702                                       FieldType.getCVRQualifiers()))
6703       return true;
6704   }
6705 
6706   return false;
6707 }
6708 
6709 /// C++11 [class.ctor] p5:
6710 ///   A defaulted default constructor for a class X is defined as deleted if
6711 /// X is a union and all of its variant members are of const-qualified type.
6712 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
6713   // This is a silly definition, because it gives an empty union a deleted
6714   // default constructor. Don't do that.
6715   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
6716     bool AnyFields = false;
6717     for (auto *F : MD->getParent()->fields())
6718       if ((AnyFields = !F->isUnnamedBitfield()))
6719         break;
6720     if (!AnyFields)
6721       return false;
6722     if (Diagnose)
6723       S.Diag(MD->getParent()->getLocation(),
6724              diag::note_deleted_default_ctor_all_const)
6725         << !!ICI << MD->getParent() << /*not anonymous union*/0;
6726     return true;
6727   }
6728   return false;
6729 }
6730 
6731 /// Determine whether a defaulted special member function should be defined as
6732 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6733 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
6734 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6735                                      InheritedConstructorInfo *ICI,
6736                                      bool Diagnose) {
6737   if (MD->isInvalidDecl())
6738     return false;
6739   CXXRecordDecl *RD = MD->getParent();
6740   assert(!RD->isDependentType() && "do deletion after instantiation");
6741   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
6742     return false;
6743 
6744   // C++11 [expr.lambda.prim]p19:
6745   //   The closure type associated with a lambda-expression has a
6746   //   deleted (8.4.3) default constructor and a deleted copy
6747   //   assignment operator.
6748   if (RD->isLambda() &&
6749       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6750     if (Diagnose)
6751       Diag(RD->getLocation(), diag::note_lambda_decl);
6752     return true;
6753   }
6754 
6755   // For an anonymous struct or union, the copy and assignment special members
6756   // will never be used, so skip the check. For an anonymous union declared at
6757   // namespace scope, the constructor and destructor are used.
6758   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6759       RD->isAnonymousStructOrUnion())
6760     return false;
6761 
6762   // C++11 [class.copy]p7, p18:
6763   //   If the class definition declares a move constructor or move assignment
6764   //   operator, an implicitly declared copy constructor or copy assignment
6765   //   operator is defined as deleted.
6766   if (MD->isImplicit() &&
6767       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
6768     CXXMethodDecl *UserDeclaredMove = nullptr;
6769 
6770     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
6771     // deletion of the corresponding copy operation, not both copy operations.
6772     // MSVC 2015 has adopted the standards conforming behavior.
6773     bool DeletesOnlyMatchingCopy =
6774         getLangOpts().MSVCCompat &&
6775         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
6776 
6777     if (RD->hasUserDeclaredMoveConstructor() &&
6778         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
6779       if (!Diagnose) return true;
6780 
6781       // Find any user-declared move constructor.
6782       for (auto *I : RD->ctors()) {
6783         if (I->isMoveConstructor()) {
6784           UserDeclaredMove = I;
6785           break;
6786         }
6787       }
6788       assert(UserDeclaredMove);
6789     } else if (RD->hasUserDeclaredMoveAssignment() &&
6790                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
6791       if (!Diagnose) return true;
6792 
6793       // Find any user-declared move assignment operator.
6794       for (auto *I : RD->methods()) {
6795         if (I->isMoveAssignmentOperator()) {
6796           UserDeclaredMove = I;
6797           break;
6798         }
6799       }
6800       assert(UserDeclaredMove);
6801     }
6802 
6803     if (UserDeclaredMove) {
6804       Diag(UserDeclaredMove->getLocation(),
6805            diag::note_deleted_copy_user_declared_move)
6806         << (CSM == CXXCopyAssignment) << RD
6807         << UserDeclaredMove->isMoveAssignmentOperator();
6808       return true;
6809     }
6810   }
6811 
6812   // Do access control from the special member function
6813   ContextRAII MethodContext(*this, MD);
6814 
6815   // C++11 [class.dtor]p5:
6816   // -- for a virtual destructor, lookup of the non-array deallocation function
6817   //    results in an ambiguity or in a function that is deleted or inaccessible
6818   if (CSM == CXXDestructor && MD->isVirtual()) {
6819     FunctionDecl *OperatorDelete = nullptr;
6820     DeclarationName Name =
6821       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6822     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
6823                                  OperatorDelete, /*Diagnose*/false)) {
6824       if (Diagnose)
6825         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
6826       return true;
6827     }
6828   }
6829 
6830   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
6831 
6832   for (auto &BI : RD->bases())
6833     if ((SMI.IsAssignment || !BI.isVirtual()) &&
6834         SMI.shouldDeleteForBase(&BI))
6835       return true;
6836 
6837   // Per DR1611, do not consider virtual bases of constructors of abstract
6838   // classes, since we are not going to construct them. For assignment
6839   // operators, we only assign (and thus only consider) direct bases.
6840   if ((!RD->isAbstract() || !SMI.IsConstructor) && !SMI.IsAssignment) {
6841     for (auto &BI : RD->vbases())
6842       if (SMI.shouldDeleteForBase(&BI))
6843         return true;
6844   }
6845 
6846   for (auto *FI : RD->fields())
6847     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
6848         SMI.shouldDeleteForField(FI))
6849       return true;
6850 
6851   if (SMI.shouldDeleteForAllConstMembers())
6852     return true;
6853 
6854   if (getLangOpts().CUDA) {
6855     // We should delete the special member in CUDA mode if target inference
6856     // failed.
6857     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6858                                                    Diagnose);
6859   }
6860 
6861   return false;
6862 }
6863 
6864 /// Perform lookup for a special member of the specified kind, and determine
6865 /// whether it is trivial. If the triviality can be determined without the
6866 /// lookup, skip it. This is intended for use when determining whether a
6867 /// special member of a containing object is trivial, and thus does not ever
6868 /// perform overload resolution for default constructors.
6869 ///
6870 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6871 /// member that was most likely to be intended to be trivial, if any.
6872 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6873                                      Sema::CXXSpecialMember CSM, unsigned Quals,
6874                                      bool ConstRHS, CXXMethodDecl **Selected) {
6875   if (Selected)
6876     *Selected = nullptr;
6877 
6878   switch (CSM) {
6879   case Sema::CXXInvalid:
6880     llvm_unreachable("not a special member");
6881 
6882   case Sema::CXXDefaultConstructor:
6883     // C++11 [class.ctor]p5:
6884     //   A default constructor is trivial if:
6885     //    - all the [direct subobjects] have trivial default constructors
6886     //
6887     // Note, no overload resolution is performed in this case.
6888     if (RD->hasTrivialDefaultConstructor())
6889       return true;
6890 
6891     if (Selected) {
6892       // If there's a default constructor which could have been trivial, dig it
6893       // out. Otherwise, if there's any user-provided default constructor, point
6894       // to that as an example of why there's not a trivial one.
6895       CXXConstructorDecl *DefCtor = nullptr;
6896       if (RD->needsImplicitDefaultConstructor())
6897         S.DeclareImplicitDefaultConstructor(RD);
6898       for (auto *CI : RD->ctors()) {
6899         if (!CI->isDefaultConstructor())
6900           continue;
6901         DefCtor = CI;
6902         if (!DefCtor->isUserProvided())
6903           break;
6904       }
6905 
6906       *Selected = DefCtor;
6907     }
6908 
6909     return false;
6910 
6911   case Sema::CXXDestructor:
6912     // C++11 [class.dtor]p5:
6913     //   A destructor is trivial if:
6914     //    - all the direct [subobjects] have trivial destructors
6915     if (RD->hasTrivialDestructor())
6916       return true;
6917 
6918     if (Selected) {
6919       if (RD->needsImplicitDestructor())
6920         S.DeclareImplicitDestructor(RD);
6921       *Selected = RD->getDestructor();
6922     }
6923 
6924     return false;
6925 
6926   case Sema::CXXCopyConstructor:
6927     // C++11 [class.copy]p12:
6928     //   A copy constructor is trivial if:
6929     //    - the constructor selected to copy each direct [subobject] is trivial
6930     if (RD->hasTrivialCopyConstructor()) {
6931       if (Quals == Qualifiers::Const)
6932         // We must either select the trivial copy constructor or reach an
6933         // ambiguity; no need to actually perform overload resolution.
6934         return true;
6935     } else if (!Selected) {
6936       return false;
6937     }
6938     // In C++98, we are not supposed to perform overload resolution here, but we
6939     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6940     // cases like B as having a non-trivial copy constructor:
6941     //   struct A { template<typename T> A(T&); };
6942     //   struct B { mutable A a; };
6943     goto NeedOverloadResolution;
6944 
6945   case Sema::CXXCopyAssignment:
6946     // C++11 [class.copy]p25:
6947     //   A copy assignment operator is trivial if:
6948     //    - the assignment operator selected to copy each direct [subobject] is
6949     //      trivial
6950     if (RD->hasTrivialCopyAssignment()) {
6951       if (Quals == Qualifiers::Const)
6952         return true;
6953     } else if (!Selected) {
6954       return false;
6955     }
6956     // In C++98, we are not supposed to perform overload resolution here, but we
6957     // treat that as a language defect.
6958     goto NeedOverloadResolution;
6959 
6960   case Sema::CXXMoveConstructor:
6961   case Sema::CXXMoveAssignment:
6962   NeedOverloadResolution:
6963     Sema::SpecialMemberOverloadResult SMOR =
6964         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
6965 
6966     // The standard doesn't describe how to behave if the lookup is ambiguous.
6967     // We treat it as not making the member non-trivial, just like the standard
6968     // mandates for the default constructor. This should rarely matter, because
6969     // the member will also be deleted.
6970     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6971       return true;
6972 
6973     if (!SMOR.getMethod()) {
6974       assert(SMOR.getKind() ==
6975              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
6976       return false;
6977     }
6978 
6979     // We deliberately don't check if we found a deleted special member. We're
6980     // not supposed to!
6981     if (Selected)
6982       *Selected = SMOR.getMethod();
6983     return SMOR.getMethod()->isTrivial();
6984   }
6985 
6986   llvm_unreachable("unknown special method kind");
6987 }
6988 
6989 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
6990   for (auto *CI : RD->ctors())
6991     if (!CI->isImplicit())
6992       return CI;
6993 
6994   // Look for constructor templates.
6995   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6996   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6997     if (CXXConstructorDecl *CD =
6998           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6999       return CD;
7000   }
7001 
7002   return nullptr;
7003 }
7004 
7005 /// The kind of subobject we are checking for triviality. The values of this
7006 /// enumeration are used in diagnostics.
7007 enum TrivialSubobjectKind {
7008   /// The subobject is a base class.
7009   TSK_BaseClass,
7010   /// The subobject is a non-static data member.
7011   TSK_Field,
7012   /// The object is actually the complete object.
7013   TSK_CompleteObject
7014 };
7015 
7016 /// Check whether the special member selected for a given type would be trivial.
7017 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7018                                       QualType SubType, bool ConstRHS,
7019                                       Sema::CXXSpecialMember CSM,
7020                                       TrivialSubobjectKind Kind,
7021                                       bool Diagnose) {
7022   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7023   if (!SubRD)
7024     return true;
7025 
7026   CXXMethodDecl *Selected;
7027   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7028                                ConstRHS, Diagnose ? &Selected : nullptr))
7029     return true;
7030 
7031   if (Diagnose) {
7032     if (ConstRHS)
7033       SubType.addConst();
7034 
7035     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7036       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7037         << Kind << SubType.getUnqualifiedType();
7038       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7039         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7040     } else if (!Selected)
7041       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7042         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7043     else if (Selected->isUserProvided()) {
7044       if (Kind == TSK_CompleteObject)
7045         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7046           << Kind << SubType.getUnqualifiedType() << CSM;
7047       else {
7048         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7049           << Kind << SubType.getUnqualifiedType() << CSM;
7050         S.Diag(Selected->getLocation(), diag::note_declared_at);
7051       }
7052     } else {
7053       if (Kind != TSK_CompleteObject)
7054         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7055           << Kind << SubType.getUnqualifiedType() << CSM;
7056 
7057       // Explain why the defaulted or deleted special member isn't trivial.
7058       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
7059     }
7060   }
7061 
7062   return false;
7063 }
7064 
7065 /// Check whether the members of a class type allow a special member to be
7066 /// trivial.
7067 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7068                                      Sema::CXXSpecialMember CSM,
7069                                      bool ConstArg, bool Diagnose) {
7070   for (const auto *FI : RD->fields()) {
7071     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7072       continue;
7073 
7074     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7075 
7076     // Pretend anonymous struct or union members are members of this class.
7077     if (FI->isAnonymousStructOrUnion()) {
7078       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7079                                     CSM, ConstArg, Diagnose))
7080         return false;
7081       continue;
7082     }
7083 
7084     // C++11 [class.ctor]p5:
7085     //   A default constructor is trivial if [...]
7086     //    -- no non-static data member of its class has a
7087     //       brace-or-equal-initializer
7088     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7089       if (Diagnose)
7090         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7091       return false;
7092     }
7093 
7094     // Objective C ARC 4.3.5:
7095     //   [...] nontrivally ownership-qualified types are [...] not trivially
7096     //   default constructible, copy constructible, move constructible, copy
7097     //   assignable, move assignable, or destructible [...]
7098     if (S.getLangOpts().ObjCAutoRefCount &&
7099         FieldType.hasNonTrivialObjCLifetime()) {
7100       if (Diagnose)
7101         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7102           << RD << FieldType.getObjCLifetime();
7103       return false;
7104     }
7105 
7106     bool ConstRHS = ConstArg && !FI->isMutable();
7107     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7108                                    CSM, TSK_Field, Diagnose))
7109       return false;
7110   }
7111 
7112   return true;
7113 }
7114 
7115 /// Diagnose why the specified class does not have a trivial special member of
7116 /// the given kind.
7117 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7118   QualType Ty = Context.getRecordType(RD);
7119 
7120   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7121   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7122                             TSK_CompleteObject, /*Diagnose*/true);
7123 }
7124 
7125 /// Determine whether a defaulted or deleted special member function is trivial,
7126 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7127 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7128 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7129                                   bool Diagnose) {
7130   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7131 
7132   CXXRecordDecl *RD = MD->getParent();
7133 
7134   bool ConstArg = false;
7135 
7136   // C++11 [class.copy]p12, p25: [DR1593]
7137   //   A [special member] is trivial if [...] its parameter-type-list is
7138   //   equivalent to the parameter-type-list of an implicit declaration [...]
7139   switch (CSM) {
7140   case CXXDefaultConstructor:
7141   case CXXDestructor:
7142     // Trivial default constructors and destructors cannot have parameters.
7143     break;
7144 
7145   case CXXCopyConstructor:
7146   case CXXCopyAssignment: {
7147     // Trivial copy operations always have const, non-volatile parameter types.
7148     ConstArg = true;
7149     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7150     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7151     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7152       if (Diagnose)
7153         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7154           << Param0->getSourceRange() << Param0->getType()
7155           << Context.getLValueReferenceType(
7156                Context.getRecordType(RD).withConst());
7157       return false;
7158     }
7159     break;
7160   }
7161 
7162   case CXXMoveConstructor:
7163   case CXXMoveAssignment: {
7164     // Trivial move operations always have non-cv-qualified parameters.
7165     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7166     const RValueReferenceType *RT =
7167       Param0->getType()->getAs<RValueReferenceType>();
7168     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7169       if (Diagnose)
7170         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7171           << Param0->getSourceRange() << Param0->getType()
7172           << Context.getRValueReferenceType(Context.getRecordType(RD));
7173       return false;
7174     }
7175     break;
7176   }
7177 
7178   case CXXInvalid:
7179     llvm_unreachable("not a special member");
7180   }
7181 
7182   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7183     if (Diagnose)
7184       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7185            diag::note_nontrivial_default_arg)
7186         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7187     return false;
7188   }
7189   if (MD->isVariadic()) {
7190     if (Diagnose)
7191       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7192     return false;
7193   }
7194 
7195   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7196   //   A copy/move [constructor or assignment operator] is trivial if
7197   //    -- the [member] selected to copy/move each direct base class subobject
7198   //       is trivial
7199   //
7200   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7201   //   A [default constructor or destructor] is trivial if
7202   //    -- all the direct base classes have trivial [default constructors or
7203   //       destructors]
7204   for (const auto &BI : RD->bases())
7205     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7206                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
7207       return false;
7208 
7209   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7210   //   A copy/move [constructor or assignment operator] for a class X is
7211   //   trivial if
7212   //    -- for each non-static data member of X that is of class type (or array
7213   //       thereof), the constructor selected to copy/move that member is
7214   //       trivial
7215   //
7216   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7217   //   A [default constructor or destructor] is trivial if
7218   //    -- for all of the non-static data members of its class that are of class
7219   //       type (or array thereof), each such class has a trivial [default
7220   //       constructor or destructor]
7221   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7222     return false;
7223 
7224   // C++11 [class.dtor]p5:
7225   //   A destructor is trivial if [...]
7226   //    -- the destructor is not virtual
7227   if (CSM == CXXDestructor && MD->isVirtual()) {
7228     if (Diagnose)
7229       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7230     return false;
7231   }
7232 
7233   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7234   //   A [special member] for class X is trivial if [...]
7235   //    -- class X has no virtual functions and no virtual base classes
7236   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7237     if (!Diagnose)
7238       return false;
7239 
7240     if (RD->getNumVBases()) {
7241       // Check for virtual bases. We already know that the corresponding
7242       // member in all bases is trivial, so vbases must all be direct.
7243       CXXBaseSpecifier &BS = *RD->vbases_begin();
7244       assert(BS.isVirtual());
7245       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7246       return false;
7247     }
7248 
7249     // Must have a virtual method.
7250     for (const auto *MI : RD->methods()) {
7251       if (MI->isVirtual()) {
7252         SourceLocation MLoc = MI->getLocStart();
7253         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7254         return false;
7255       }
7256     }
7257 
7258     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7259   }
7260 
7261   // Looks like it's trivial!
7262   return true;
7263 }
7264 
7265 namespace {
7266 struct FindHiddenVirtualMethod {
7267   Sema *S;
7268   CXXMethodDecl *Method;
7269   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7270   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7271 
7272 private:
7273   /// Check whether any most overriden method from MD in Methods
7274   static bool CheckMostOverridenMethods(
7275       const CXXMethodDecl *MD,
7276       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7277     if (MD->size_overridden_methods() == 0)
7278       return Methods.count(MD->getCanonicalDecl());
7279     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7280                                         E = MD->end_overridden_methods();
7281          I != E; ++I)
7282       if (CheckMostOverridenMethods(*I, Methods))
7283         return true;
7284     return false;
7285   }
7286 
7287 public:
7288   /// Member lookup function that determines whether a given C++
7289   /// method overloads virtual methods in a base class without overriding any,
7290   /// to be used with CXXRecordDecl::lookupInBases().
7291   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7292     RecordDecl *BaseRecord =
7293         Specifier->getType()->getAs<RecordType>()->getDecl();
7294 
7295     DeclarationName Name = Method->getDeclName();
7296     assert(Name.getNameKind() == DeclarationName::Identifier);
7297 
7298     bool foundSameNameMethod = false;
7299     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7300     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7301          Path.Decls = Path.Decls.slice(1)) {
7302       NamedDecl *D = Path.Decls.front();
7303       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7304         MD = MD->getCanonicalDecl();
7305         foundSameNameMethod = true;
7306         // Interested only in hidden virtual methods.
7307         if (!MD->isVirtual())
7308           continue;
7309         // If the method we are checking overrides a method from its base
7310         // don't warn about the other overloaded methods. Clang deviates from
7311         // GCC by only diagnosing overloads of inherited virtual functions that
7312         // do not override any other virtual functions in the base. GCC's
7313         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7314         // function from a base class. These cases may be better served by a
7315         // warning (not specific to virtual functions) on call sites when the
7316         // call would select a different function from the base class, were it
7317         // visible.
7318         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7319         if (!S->IsOverload(Method, MD, false))
7320           return true;
7321         // Collect the overload only if its hidden.
7322         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7323           overloadedMethods.push_back(MD);
7324       }
7325     }
7326 
7327     if (foundSameNameMethod)
7328       OverloadedMethods.append(overloadedMethods.begin(),
7329                                overloadedMethods.end());
7330     return foundSameNameMethod;
7331   }
7332 };
7333 } // end anonymous namespace
7334 
7335 /// \brief Add the most overriden methods from MD to Methods
7336 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7337                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7338   if (MD->size_overridden_methods() == 0)
7339     Methods.insert(MD->getCanonicalDecl());
7340   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7341                                       E = MD->end_overridden_methods();
7342        I != E; ++I)
7343     AddMostOverridenMethods(*I, Methods);
7344 }
7345 
7346 /// \brief Check if a method overloads virtual methods in a base class without
7347 /// overriding any.
7348 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7349                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7350   if (!MD->getDeclName().isIdentifier())
7351     return;
7352 
7353   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7354                      /*bool RecordPaths=*/false,
7355                      /*bool DetectVirtual=*/false);
7356   FindHiddenVirtualMethod FHVM;
7357   FHVM.Method = MD;
7358   FHVM.S = this;
7359 
7360   // Keep the base methods that were overriden or introduced in the subclass
7361   // by 'using' in a set. A base method not in this set is hidden.
7362   CXXRecordDecl *DC = MD->getParent();
7363   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7364   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7365     NamedDecl *ND = *I;
7366     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7367       ND = shad->getTargetDecl();
7368     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7369       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7370   }
7371 
7372   if (DC->lookupInBases(FHVM, Paths))
7373     OverloadedMethods = FHVM.OverloadedMethods;
7374 }
7375 
7376 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7377                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7378   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7379     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7380     PartialDiagnostic PD = PDiag(
7381          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7382     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7383     Diag(overloadedMD->getLocation(), PD);
7384   }
7385 }
7386 
7387 /// \brief Diagnose methods which overload virtual methods in a base class
7388 /// without overriding any.
7389 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7390   if (MD->isInvalidDecl())
7391     return;
7392 
7393   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7394     return;
7395 
7396   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7397   FindHiddenVirtualMethods(MD, OverloadedMethods);
7398   if (!OverloadedMethods.empty()) {
7399     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7400       << MD << (OverloadedMethods.size() > 1);
7401 
7402     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7403   }
7404 }
7405 
7406 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7407                                              Decl *TagDecl,
7408                                              SourceLocation LBrac,
7409                                              SourceLocation RBrac,
7410                                              AttributeList *AttrList) {
7411   if (!TagDecl)
7412     return;
7413 
7414   AdjustDeclIfTemplate(TagDecl);
7415 
7416   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7417     if (l->getKind() != AttributeList::AT_Visibility)
7418       continue;
7419     l->setInvalid();
7420     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7421       l->getName();
7422   }
7423 
7424   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7425               // strict aliasing violation!
7426               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7427               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7428 
7429   CheckCompletedCXXClass(
7430                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
7431 }
7432 
7433 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7434 /// special functions, such as the default constructor, copy
7435 /// constructor, or destructor, to the given C++ class (C++
7436 /// [special]p1).  This routine can only be executed just before the
7437 /// definition of the class is complete.
7438 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7439   if (ClassDecl->needsImplicitDefaultConstructor()) {
7440     ++ASTContext::NumImplicitDefaultConstructors;
7441 
7442     if (ClassDecl->hasInheritedConstructor())
7443       DeclareImplicitDefaultConstructor(ClassDecl);
7444   }
7445 
7446   if (ClassDecl->needsImplicitCopyConstructor()) {
7447     ++ASTContext::NumImplicitCopyConstructors;
7448 
7449     // If the properties or semantics of the copy constructor couldn't be
7450     // determined while the class was being declared, force a declaration
7451     // of it now.
7452     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7453         ClassDecl->hasInheritedConstructor())
7454       DeclareImplicitCopyConstructor(ClassDecl);
7455     // For the MS ABI we need to know whether the copy ctor is deleted. A
7456     // prerequisite for deleting the implicit copy ctor is that the class has a
7457     // move ctor or move assignment that is either user-declared or whose
7458     // semantics are inherited from a subobject. FIXME: We should provide a more
7459     // direct way for CodeGen to ask whether the constructor was deleted.
7460     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7461              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7462               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7463               ClassDecl->hasUserDeclaredMoveAssignment() ||
7464               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7465       DeclareImplicitCopyConstructor(ClassDecl);
7466   }
7467 
7468   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7469     ++ASTContext::NumImplicitMoveConstructors;
7470 
7471     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7472         ClassDecl->hasInheritedConstructor())
7473       DeclareImplicitMoveConstructor(ClassDecl);
7474   }
7475 
7476   if (ClassDecl->needsImplicitCopyAssignment()) {
7477     ++ASTContext::NumImplicitCopyAssignmentOperators;
7478 
7479     // If we have a dynamic class, then the copy assignment operator may be
7480     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7481     // it shows up in the right place in the vtable and that we diagnose
7482     // problems with the implicit exception specification.
7483     if (ClassDecl->isDynamicClass() ||
7484         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7485         ClassDecl->hasInheritedAssignment())
7486       DeclareImplicitCopyAssignment(ClassDecl);
7487   }
7488 
7489   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7490     ++ASTContext::NumImplicitMoveAssignmentOperators;
7491 
7492     // Likewise for the move assignment operator.
7493     if (ClassDecl->isDynamicClass() ||
7494         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7495         ClassDecl->hasInheritedAssignment())
7496       DeclareImplicitMoveAssignment(ClassDecl);
7497   }
7498 
7499   if (ClassDecl->needsImplicitDestructor()) {
7500     ++ASTContext::NumImplicitDestructors;
7501 
7502     // If we have a dynamic class, then the destructor may be virtual, so we
7503     // have to declare the destructor immediately. This ensures that, e.g., it
7504     // shows up in the right place in the vtable and that we diagnose problems
7505     // with the implicit exception specification.
7506     if (ClassDecl->isDynamicClass() ||
7507         ClassDecl->needsOverloadResolutionForDestructor())
7508       DeclareImplicitDestructor(ClassDecl);
7509   }
7510 }
7511 
7512 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7513   if (!D)
7514     return 0;
7515 
7516   // The order of template parameters is not important here. All names
7517   // get added to the same scope.
7518   SmallVector<TemplateParameterList *, 4> ParameterLists;
7519 
7520   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7521     D = TD->getTemplatedDecl();
7522 
7523   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7524     ParameterLists.push_back(PSD->getTemplateParameters());
7525 
7526   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7527     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7528       ParameterLists.push_back(DD->getTemplateParameterList(i));
7529 
7530     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7531       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7532         ParameterLists.push_back(FTD->getTemplateParameters());
7533     }
7534   }
7535 
7536   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7537     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7538       ParameterLists.push_back(TD->getTemplateParameterList(i));
7539 
7540     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7541       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7542         ParameterLists.push_back(CTD->getTemplateParameters());
7543     }
7544   }
7545 
7546   unsigned Count = 0;
7547   for (TemplateParameterList *Params : ParameterLists) {
7548     if (Params->size() > 0)
7549       // Ignore explicit specializations; they don't contribute to the template
7550       // depth.
7551       ++Count;
7552     for (NamedDecl *Param : *Params) {
7553       if (Param->getDeclName()) {
7554         S->AddDecl(Param);
7555         IdResolver.AddDecl(Param);
7556       }
7557     }
7558   }
7559 
7560   return Count;
7561 }
7562 
7563 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7564   if (!RecordD) return;
7565   AdjustDeclIfTemplate(RecordD);
7566   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7567   PushDeclContext(S, Record);
7568 }
7569 
7570 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7571   if (!RecordD) return;
7572   PopDeclContext();
7573 }
7574 
7575 /// This is used to implement the constant expression evaluation part of the
7576 /// attribute enable_if extension. There is nothing in standard C++ which would
7577 /// require reentering parameters.
7578 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7579   if (!Param)
7580     return;
7581 
7582   S->AddDecl(Param);
7583   if (Param->getDeclName())
7584     IdResolver.AddDecl(Param);
7585 }
7586 
7587 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7588 /// parsing a top-level (non-nested) C++ class, and we are now
7589 /// parsing those parts of the given Method declaration that could
7590 /// not be parsed earlier (C++ [class.mem]p2), such as default
7591 /// arguments. This action should enter the scope of the given
7592 /// Method declaration as if we had just parsed the qualified method
7593 /// name. However, it should not bring the parameters into scope;
7594 /// that will be performed by ActOnDelayedCXXMethodParameter.
7595 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7596 }
7597 
7598 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
7599 /// C++ method declaration. We're (re-)introducing the given
7600 /// function parameter into scope for use in parsing later parts of
7601 /// the method declaration. For example, we could see an
7602 /// ActOnParamDefaultArgument event for this parameter.
7603 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7604   if (!ParamD)
7605     return;
7606 
7607   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7608 
7609   // If this parameter has an unparsed default argument, clear it out
7610   // to make way for the parsed default argument.
7611   if (Param->hasUnparsedDefaultArg())
7612     Param->setDefaultArg(nullptr);
7613 
7614   S->AddDecl(Param);
7615   if (Param->getDeclName())
7616     IdResolver.AddDecl(Param);
7617 }
7618 
7619 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7620 /// processing the delayed method declaration for Method. The method
7621 /// declaration is now considered finished. There may be a separate
7622 /// ActOnStartOfFunctionDef action later (not necessarily
7623 /// immediately!) for this method, if it was also defined inside the
7624 /// class body.
7625 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7626   if (!MethodD)
7627     return;
7628 
7629   AdjustDeclIfTemplate(MethodD);
7630 
7631   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
7632 
7633   // Now that we have our default arguments, check the constructor
7634   // again. It could produce additional diagnostics or affect whether
7635   // the class has implicitly-declared destructors, among other
7636   // things.
7637   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7638     CheckConstructor(Constructor);
7639 
7640   // Check the default arguments, which we may have added.
7641   if (!Method->isInvalidDecl())
7642     CheckCXXDefaultArguments(Method);
7643 }
7644 
7645 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
7646 /// the well-formedness of the constructor declarator @p D with type @p
7647 /// R. If there are any errors in the declarator, this routine will
7648 /// emit diagnostics and set the invalid bit to true.  In any case, the type
7649 /// will be updated to reflect a well-formed type for the constructor and
7650 /// returned.
7651 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
7652                                           StorageClass &SC) {
7653   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7654 
7655   // C++ [class.ctor]p3:
7656   //   A constructor shall not be virtual (10.3) or static (9.4). A
7657   //   constructor can be invoked for a const, volatile or const
7658   //   volatile object. A constructor shall not be declared const,
7659   //   volatile, or const volatile (9.3.2).
7660   if (isVirtual) {
7661     if (!D.isInvalidType())
7662       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7663         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7664         << SourceRange(D.getIdentifierLoc());
7665     D.setInvalidType();
7666   }
7667   if (SC == SC_Static) {
7668     if (!D.isInvalidType())
7669       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7670         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7671         << SourceRange(D.getIdentifierLoc());
7672     D.setInvalidType();
7673     SC = SC_None;
7674   }
7675 
7676   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7677     diagnoseIgnoredQualifiers(
7678         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7679         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7680         D.getDeclSpec().getRestrictSpecLoc(),
7681         D.getDeclSpec().getAtomicSpecLoc());
7682     D.setInvalidType();
7683   }
7684 
7685   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7686   if (FTI.TypeQuals != 0) {
7687     if (FTI.TypeQuals & Qualifiers::Const)
7688       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7689         << "const" << SourceRange(D.getIdentifierLoc());
7690     if (FTI.TypeQuals & Qualifiers::Volatile)
7691       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7692         << "volatile" << SourceRange(D.getIdentifierLoc());
7693     if (FTI.TypeQuals & Qualifiers::Restrict)
7694       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7695         << "restrict" << SourceRange(D.getIdentifierLoc());
7696     D.setInvalidType();
7697   }
7698 
7699   // C++0x [class.ctor]p4:
7700   //   A constructor shall not be declared with a ref-qualifier.
7701   if (FTI.hasRefQualifier()) {
7702     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7703       << FTI.RefQualifierIsLValueRef
7704       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7705     D.setInvalidType();
7706   }
7707 
7708   // Rebuild the function type "R" without any type qualifiers (in
7709   // case any of the errors above fired) and with "void" as the
7710   // return type, since constructors don't have return types.
7711   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7712   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
7713     return R;
7714 
7715   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7716   EPI.TypeQuals = 0;
7717   EPI.RefQualifier = RQ_None;
7718 
7719   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
7720 }
7721 
7722 /// CheckConstructor - Checks a fully-formed constructor for
7723 /// well-formedness, issuing any diagnostics required. Returns true if
7724 /// the constructor declarator is invalid.
7725 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
7726   CXXRecordDecl *ClassDecl
7727     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7728   if (!ClassDecl)
7729     return Constructor->setInvalidDecl();
7730 
7731   // C++ [class.copy]p3:
7732   //   A declaration of a constructor for a class X is ill-formed if
7733   //   its first parameter is of type (optionally cv-qualified) X and
7734   //   either there are no other parameters or else all other
7735   //   parameters have default arguments.
7736   if (!Constructor->isInvalidDecl() &&
7737       ((Constructor->getNumParams() == 1) ||
7738        (Constructor->getNumParams() > 1 &&
7739         Constructor->getParamDecl(1)->hasDefaultArg())) &&
7740       Constructor->getTemplateSpecializationKind()
7741                                               != TSK_ImplicitInstantiation) {
7742     QualType ParamType = Constructor->getParamDecl(0)->getType();
7743     QualType ClassTy = Context.getTagDeclType(ClassDecl);
7744     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
7745       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
7746       const char *ConstRef
7747         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7748                                                         : " const &";
7749       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
7750         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
7751 
7752       // FIXME: Rather that making the constructor invalid, we should endeavor
7753       // to fix the type.
7754       Constructor->setInvalidDecl();
7755     }
7756   }
7757 }
7758 
7759 /// CheckDestructor - Checks a fully-formed destructor definition for
7760 /// well-formedness, issuing any diagnostics required.  Returns true
7761 /// on error.
7762 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
7763   CXXRecordDecl *RD = Destructor->getParent();
7764 
7765   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
7766     SourceLocation Loc;
7767 
7768     if (!Destructor->isImplicit())
7769       Loc = Destructor->getLocation();
7770     else
7771       Loc = RD->getLocation();
7772 
7773     // If we have a virtual destructor, look up the deallocation function
7774     if (FunctionDecl *OperatorDelete =
7775             FindDeallocationFunctionForDestructor(Loc, RD)) {
7776       MarkFunctionReferenced(Loc, OperatorDelete);
7777       Destructor->setOperatorDelete(OperatorDelete);
7778     }
7779   }
7780 
7781   return false;
7782 }
7783 
7784 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7785 /// the well-formednes of the destructor declarator @p D with type @p
7786 /// R. If there are any errors in the declarator, this routine will
7787 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
7788 /// will be updated to reflect a well-formed type for the destructor and
7789 /// returned.
7790 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
7791                                          StorageClass& SC) {
7792   // C++ [class.dtor]p1:
7793   //   [...] A typedef-name that names a class is a class-name
7794   //   (7.1.3); however, a typedef-name that names a class shall not
7795   //   be used as the identifier in the declarator for a destructor
7796   //   declaration.
7797   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
7798   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
7799     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7800       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
7801   else if (const TemplateSpecializationType *TST =
7802              DeclaratorType->getAs<TemplateSpecializationType>())
7803     if (TST->isTypeAlias())
7804       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7805         << DeclaratorType << 1;
7806 
7807   // C++ [class.dtor]p2:
7808   //   A destructor is used to destroy objects of its class type. A
7809   //   destructor takes no parameters, and no return type can be
7810   //   specified for it (not even void). The address of a destructor
7811   //   shall not be taken. A destructor shall not be static. A
7812   //   destructor can be invoked for a const, volatile or const
7813   //   volatile object. A destructor shall not be declared const,
7814   //   volatile or const volatile (9.3.2).
7815   if (SC == SC_Static) {
7816     if (!D.isInvalidType())
7817       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7818         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7819         << SourceRange(D.getIdentifierLoc())
7820         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7821 
7822     SC = SC_None;
7823   }
7824   if (!D.isInvalidType()) {
7825     // Destructors don't have return types, but the parser will
7826     // happily parse something like:
7827     //
7828     //   class X {
7829     //     float ~X();
7830     //   };
7831     //
7832     // The return type will be eliminated later.
7833     if (D.getDeclSpec().hasTypeSpecifier())
7834       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7835         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7836         << SourceRange(D.getIdentifierLoc());
7837     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7838       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7839                                 SourceLocation(),
7840                                 D.getDeclSpec().getConstSpecLoc(),
7841                                 D.getDeclSpec().getVolatileSpecLoc(),
7842                                 D.getDeclSpec().getRestrictSpecLoc(),
7843                                 D.getDeclSpec().getAtomicSpecLoc());
7844       D.setInvalidType();
7845     }
7846   }
7847 
7848   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7849   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
7850     if (FTI.TypeQuals & Qualifiers::Const)
7851       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7852         << "const" << SourceRange(D.getIdentifierLoc());
7853     if (FTI.TypeQuals & Qualifiers::Volatile)
7854       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7855         << "volatile" << SourceRange(D.getIdentifierLoc());
7856     if (FTI.TypeQuals & Qualifiers::Restrict)
7857       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7858         << "restrict" << SourceRange(D.getIdentifierLoc());
7859     D.setInvalidType();
7860   }
7861 
7862   // C++0x [class.dtor]p2:
7863   //   A destructor shall not be declared with a ref-qualifier.
7864   if (FTI.hasRefQualifier()) {
7865     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7866       << FTI.RefQualifierIsLValueRef
7867       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7868     D.setInvalidType();
7869   }
7870 
7871   // Make sure we don't have any parameters.
7872   if (FTIHasNonVoidParameters(FTI)) {
7873     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7874 
7875     // Delete the parameters.
7876     FTI.freeParams();
7877     D.setInvalidType();
7878   }
7879 
7880   // Make sure the destructor isn't variadic.
7881   if (FTI.isVariadic) {
7882     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
7883     D.setInvalidType();
7884   }
7885 
7886   // Rebuild the function type "R" without any type qualifiers or
7887   // parameters (in case any of the errors above fired) and with
7888   // "void" as the return type, since destructors don't have return
7889   // types.
7890   if (!D.isInvalidType())
7891     return R;
7892 
7893   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7894   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7895   EPI.Variadic = false;
7896   EPI.TypeQuals = 0;
7897   EPI.RefQualifier = RQ_None;
7898   return Context.getFunctionType(Context.VoidTy, None, EPI);
7899 }
7900 
7901 static void extendLeft(SourceRange &R, SourceRange Before) {
7902   if (Before.isInvalid())
7903     return;
7904   R.setBegin(Before.getBegin());
7905   if (R.getEnd().isInvalid())
7906     R.setEnd(Before.getEnd());
7907 }
7908 
7909 static void extendRight(SourceRange &R, SourceRange After) {
7910   if (After.isInvalid())
7911     return;
7912   if (R.getBegin().isInvalid())
7913     R.setBegin(After.getBegin());
7914   R.setEnd(After.getEnd());
7915 }
7916 
7917 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7918 /// well-formednes of the conversion function declarator @p D with
7919 /// type @p R. If there are any errors in the declarator, this routine
7920 /// will emit diagnostics and return true. Otherwise, it will return
7921 /// false. Either way, the type @p R will be updated to reflect a
7922 /// well-formed type for the conversion operator.
7923 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
7924                                      StorageClass& SC) {
7925   // C++ [class.conv.fct]p1:
7926   //   Neither parameter types nor return type can be specified. The
7927   //   type of a conversion function (8.3.5) is "function taking no
7928   //   parameter returning conversion-type-id."
7929   if (SC == SC_Static) {
7930     if (!D.isInvalidType())
7931       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
7932         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7933         << D.getName().getSourceRange();
7934     D.setInvalidType();
7935     SC = SC_None;
7936   }
7937 
7938   TypeSourceInfo *ConvTSI = nullptr;
7939   QualType ConvType =
7940       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
7941 
7942   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
7943     // Conversion functions don't have return types, but the parser will
7944     // happily parse something like:
7945     //
7946     //   class X {
7947     //     float operator bool();
7948     //   };
7949     //
7950     // The return type will be changed later anyway.
7951     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
7952       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7953       << SourceRange(D.getIdentifierLoc());
7954     D.setInvalidType();
7955   }
7956 
7957   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7958 
7959   // Make sure we don't have any parameters.
7960   if (Proto->getNumParams() > 0) {
7961     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
7962 
7963     // Delete the parameters.
7964     D.getFunctionTypeInfo().freeParams();
7965     D.setInvalidType();
7966   } else if (Proto->isVariadic()) {
7967     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
7968     D.setInvalidType();
7969   }
7970 
7971   // Diagnose "&operator bool()" and other such nonsense.  This
7972   // is actually a gcc extension which we don't support.
7973   if (Proto->getReturnType() != ConvType) {
7974     bool NeedsTypedef = false;
7975     SourceRange Before, After;
7976 
7977     // Walk the chunks and extract information on them for our diagnostic.
7978     bool PastFunctionChunk = false;
7979     for (auto &Chunk : D.type_objects()) {
7980       switch (Chunk.Kind) {
7981       case DeclaratorChunk::Function:
7982         if (!PastFunctionChunk) {
7983           if (Chunk.Fun.HasTrailingReturnType) {
7984             TypeSourceInfo *TRT = nullptr;
7985             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7986             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7987           }
7988           PastFunctionChunk = true;
7989           break;
7990         }
7991         // Fall through.
7992       case DeclaratorChunk::Array:
7993         NeedsTypedef = true;
7994         extendRight(After, Chunk.getSourceRange());
7995         break;
7996 
7997       case DeclaratorChunk::Pointer:
7998       case DeclaratorChunk::BlockPointer:
7999       case DeclaratorChunk::Reference:
8000       case DeclaratorChunk::MemberPointer:
8001       case DeclaratorChunk::Pipe:
8002         extendLeft(Before, Chunk.getSourceRange());
8003         break;
8004 
8005       case DeclaratorChunk::Paren:
8006         extendLeft(Before, Chunk.Loc);
8007         extendRight(After, Chunk.EndLoc);
8008         break;
8009       }
8010     }
8011 
8012     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8013                          After.isValid()  ? After.getBegin() :
8014                                             D.getIdentifierLoc();
8015     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8016     DB << Before << After;
8017 
8018     if (!NeedsTypedef) {
8019       DB << /*don't need a typedef*/0;
8020 
8021       // If we can provide a correct fix-it hint, do so.
8022       if (After.isInvalid() && ConvTSI) {
8023         SourceLocation InsertLoc =
8024             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
8025         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8026            << FixItHint::CreateInsertionFromRange(
8027                   InsertLoc, CharSourceRange::getTokenRange(Before))
8028            << FixItHint::CreateRemoval(Before);
8029       }
8030     } else if (!Proto->getReturnType()->isDependentType()) {
8031       DB << /*typedef*/1 << Proto->getReturnType();
8032     } else if (getLangOpts().CPlusPlus11) {
8033       DB << /*alias template*/2 << Proto->getReturnType();
8034     } else {
8035       DB << /*might not be fixable*/3;
8036     }
8037 
8038     // Recover by incorporating the other type chunks into the result type.
8039     // Note, this does *not* change the name of the function. This is compatible
8040     // with the GCC extension:
8041     //   struct S { &operator int(); } s;
8042     //   int &r = s.operator int(); // ok in GCC
8043     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8044     ConvType = Proto->getReturnType();
8045   }
8046 
8047   // C++ [class.conv.fct]p4:
8048   //   The conversion-type-id shall not represent a function type nor
8049   //   an array type.
8050   if (ConvType->isArrayType()) {
8051     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8052     ConvType = Context.getPointerType(ConvType);
8053     D.setInvalidType();
8054   } else if (ConvType->isFunctionType()) {
8055     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8056     ConvType = Context.getPointerType(ConvType);
8057     D.setInvalidType();
8058   }
8059 
8060   // Rebuild the function type "R" without any parameters (in case any
8061   // of the errors above fired) and with the conversion type as the
8062   // return type.
8063   if (D.isInvalidType())
8064     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8065 
8066   // C++0x explicit conversion operators.
8067   if (D.getDeclSpec().isExplicitSpecified())
8068     Diag(D.getDeclSpec().getExplicitSpecLoc(),
8069          getLangOpts().CPlusPlus11 ?
8070            diag::warn_cxx98_compat_explicit_conversion_functions :
8071            diag::ext_explicit_conversion_functions)
8072       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
8073 }
8074 
8075 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8076 /// the declaration of the given C++ conversion function. This routine
8077 /// is responsible for recording the conversion function in the C++
8078 /// class, if possible.
8079 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8080   assert(Conversion && "Expected to receive a conversion function declaration");
8081 
8082   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8083 
8084   // Make sure we aren't redeclaring the conversion function.
8085   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8086 
8087   // C++ [class.conv.fct]p1:
8088   //   [...] A conversion function is never used to convert a
8089   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8090   //   same object type (or a reference to it), to a (possibly
8091   //   cv-qualified) base class of that type (or a reference to it),
8092   //   or to (possibly cv-qualified) void.
8093   // FIXME: Suppress this warning if the conversion function ends up being a
8094   // virtual function that overrides a virtual function in a base class.
8095   QualType ClassType
8096     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8097   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8098     ConvType = ConvTypeRef->getPointeeType();
8099   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8100       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8101     /* Suppress diagnostics for instantiations. */;
8102   else if (ConvType->isRecordType()) {
8103     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8104     if (ConvType == ClassType)
8105       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8106         << ClassType;
8107     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8108       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8109         <<  ClassType << ConvType;
8110   } else if (ConvType->isVoidType()) {
8111     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8112       << ClassType << ConvType;
8113   }
8114 
8115   if (FunctionTemplateDecl *ConversionTemplate
8116                                 = Conversion->getDescribedFunctionTemplate())
8117     return ConversionTemplate;
8118 
8119   return Conversion;
8120 }
8121 
8122 namespace {
8123 /// Utility class to accumulate and print a diagnostic listing the invalid
8124 /// specifier(s) on a declaration.
8125 struct BadSpecifierDiagnoser {
8126   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8127       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8128   ~BadSpecifierDiagnoser() {
8129     Diagnostic << Specifiers;
8130   }
8131 
8132   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8133     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8134   }
8135   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8136     return check(SpecLoc,
8137                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8138   }
8139   void check(SourceLocation SpecLoc, const char *Spec) {
8140     if (SpecLoc.isInvalid()) return;
8141     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8142     if (!Specifiers.empty()) Specifiers += " ";
8143     Specifiers += Spec;
8144   }
8145 
8146   Sema &S;
8147   Sema::SemaDiagnosticBuilder Diagnostic;
8148   std::string Specifiers;
8149 };
8150 }
8151 
8152 /// Check the validity of a declarator that we parsed for a deduction-guide.
8153 /// These aren't actually declarators in the grammar, so we need to check that
8154 /// the user didn't specify any pieces that are not part of the deduction-guide
8155 /// grammar.
8156 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8157                                          StorageClass &SC) {
8158   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8159   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8160   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8161 
8162   // C++ [temp.deduct.guide]p3:
8163   //   A deduction-gide shall be declared in the same scope as the
8164   //   corresponding class template.
8165   if (!CurContext->getRedeclContext()->Equals(
8166           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8167     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8168       << GuidedTemplateDecl;
8169     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8170   }
8171 
8172   auto &DS = D.getMutableDeclSpec();
8173   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8174   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8175       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8176       DS.isNoreturnSpecified() || DS.isConstexprSpecified() ||
8177       DS.isConceptSpecified()) {
8178     BadSpecifierDiagnoser Diagnoser(
8179         *this, D.getIdentifierLoc(),
8180         diag::err_deduction_guide_invalid_specifier);
8181 
8182     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8183     DS.ClearStorageClassSpecs();
8184     SC = SC_None;
8185 
8186     // 'explicit' is permitted.
8187     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8188     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8189     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8190     Diagnoser.check(DS.getConceptSpecLoc(), "concept");
8191     DS.ClearConstexprSpec();
8192     DS.ClearConceptSpec();
8193 
8194     Diagnoser.check(DS.getConstSpecLoc(), "const");
8195     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8196     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8197     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8198     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8199     DS.ClearTypeQualifiers();
8200 
8201     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8202     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8203     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8204     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8205     DS.ClearTypeSpecType();
8206   }
8207 
8208   if (D.isInvalidType())
8209     return;
8210 
8211   // Check the declarator is simple enough.
8212   bool FoundFunction = false;
8213   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8214     if (Chunk.Kind == DeclaratorChunk::Paren)
8215       continue;
8216     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8217       Diag(D.getDeclSpec().getLocStart(),
8218           diag::err_deduction_guide_with_complex_decl)
8219         << D.getSourceRange();
8220       break;
8221     }
8222     if (!Chunk.Fun.hasTrailingReturnType()) {
8223       Diag(D.getName().getLocStart(),
8224            diag::err_deduction_guide_no_trailing_return_type);
8225       break;
8226     }
8227 
8228     // Check that the return type is written as a specialization of
8229     // the template specified as the deduction-guide's name.
8230     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8231     TypeSourceInfo *TSI = nullptr;
8232     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8233     assert(TSI && "deduction guide has valid type but invalid return type?");
8234     bool AcceptableReturnType = false;
8235     bool MightInstantiateToSpecialization = false;
8236     if (auto RetTST =
8237             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8238       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8239       bool TemplateMatches =
8240           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8241       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8242         AcceptableReturnType = true;
8243       else {
8244         // This could still instantiate to the right type, unless we know it
8245         // names the wrong class template.
8246         auto *TD = SpecifiedName.getAsTemplateDecl();
8247         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8248                                              !TemplateMatches);
8249       }
8250     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8251       MightInstantiateToSpecialization = true;
8252     }
8253 
8254     if (!AcceptableReturnType) {
8255       Diag(TSI->getTypeLoc().getLocStart(),
8256            diag::err_deduction_guide_bad_trailing_return_type)
8257         << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8258         << TSI->getTypeLoc().getSourceRange();
8259     }
8260 
8261     // Keep going to check that we don't have any inner declarator pieces (we
8262     // could still have a function returning a pointer to a function).
8263     FoundFunction = true;
8264   }
8265 
8266   if (D.isFunctionDefinition())
8267     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8268 }
8269 
8270 //===----------------------------------------------------------------------===//
8271 // Namespace Handling
8272 //===----------------------------------------------------------------------===//
8273 
8274 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8275 /// reopened.
8276 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8277                                             SourceLocation Loc,
8278                                             IdentifierInfo *II, bool *IsInline,
8279                                             NamespaceDecl *PrevNS) {
8280   assert(*IsInline != PrevNS->isInline());
8281 
8282   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8283   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8284   // inline namespaces, with the intention of bringing names into namespace std.
8285   //
8286   // We support this just well enough to get that case working; this is not
8287   // sufficient to support reopening namespaces as inline in general.
8288   if (*IsInline && II && II->getName().startswith("__atomic") &&
8289       S.getSourceManager().isInSystemHeader(Loc)) {
8290     // Mark all prior declarations of the namespace as inline.
8291     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8292          NS = NS->getPreviousDecl())
8293       NS->setInline(*IsInline);
8294     // Patch up the lookup table for the containing namespace. This isn't really
8295     // correct, but it's good enough for this particular case.
8296     for (auto *I : PrevNS->decls())
8297       if (auto *ND = dyn_cast<NamedDecl>(I))
8298         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8299     return;
8300   }
8301 
8302   if (PrevNS->isInline())
8303     // The user probably just forgot the 'inline', so suggest that it
8304     // be added back.
8305     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8306       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8307   else
8308     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8309 
8310   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8311   *IsInline = PrevNS->isInline();
8312 }
8313 
8314 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8315 /// definition.
8316 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8317                                    SourceLocation InlineLoc,
8318                                    SourceLocation NamespaceLoc,
8319                                    SourceLocation IdentLoc,
8320                                    IdentifierInfo *II,
8321                                    SourceLocation LBrace,
8322                                    AttributeList *AttrList,
8323                                    UsingDirectiveDecl *&UD) {
8324   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8325   // For anonymous namespace, take the location of the left brace.
8326   SourceLocation Loc = II ? IdentLoc : LBrace;
8327   bool IsInline = InlineLoc.isValid();
8328   bool IsInvalid = false;
8329   bool IsStd = false;
8330   bool AddToKnown = false;
8331   Scope *DeclRegionScope = NamespcScope->getParent();
8332 
8333   NamespaceDecl *PrevNS = nullptr;
8334   if (II) {
8335     // C++ [namespace.def]p2:
8336     //   The identifier in an original-namespace-definition shall not
8337     //   have been previously defined in the declarative region in
8338     //   which the original-namespace-definition appears. The
8339     //   identifier in an original-namespace-definition is the name of
8340     //   the namespace. Subsequently in that declarative region, it is
8341     //   treated as an original-namespace-name.
8342     //
8343     // Since namespace names are unique in their scope, and we don't
8344     // look through using directives, just look for any ordinary names
8345     // as if by qualified name lookup.
8346     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8347     LookupQualifiedName(R, CurContext->getRedeclContext());
8348     NamedDecl *PrevDecl =
8349         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8350     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8351 
8352     if (PrevNS) {
8353       // This is an extended namespace definition.
8354       if (IsInline != PrevNS->isInline())
8355         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8356                                         &IsInline, PrevNS);
8357     } else if (PrevDecl) {
8358       // This is an invalid name redefinition.
8359       Diag(Loc, diag::err_redefinition_different_kind)
8360         << II;
8361       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8362       IsInvalid = true;
8363       // Continue on to push Namespc as current DeclContext and return it.
8364     } else if (II->isStr("std") &&
8365                CurContext->getRedeclContext()->isTranslationUnit()) {
8366       // This is the first "real" definition of the namespace "std", so update
8367       // our cache of the "std" namespace to point at this definition.
8368       PrevNS = getStdNamespace();
8369       IsStd = true;
8370       AddToKnown = !IsInline;
8371     } else {
8372       // We've seen this namespace for the first time.
8373       AddToKnown = !IsInline;
8374     }
8375   } else {
8376     // Anonymous namespaces.
8377 
8378     // Determine whether the parent already has an anonymous namespace.
8379     DeclContext *Parent = CurContext->getRedeclContext();
8380     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8381       PrevNS = TU->getAnonymousNamespace();
8382     } else {
8383       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8384       PrevNS = ND->getAnonymousNamespace();
8385     }
8386 
8387     if (PrevNS && IsInline != PrevNS->isInline())
8388       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8389                                       &IsInline, PrevNS);
8390   }
8391 
8392   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8393                                                  StartLoc, Loc, II, PrevNS);
8394   if (IsInvalid)
8395     Namespc->setInvalidDecl();
8396 
8397   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8398 
8399   // FIXME: Should we be merging attributes?
8400   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8401     PushNamespaceVisibilityAttr(Attr, Loc);
8402 
8403   if (IsStd)
8404     StdNamespace = Namespc;
8405   if (AddToKnown)
8406     KnownNamespaces[Namespc] = false;
8407 
8408   if (II) {
8409     PushOnScopeChains(Namespc, DeclRegionScope);
8410   } else {
8411     // Link the anonymous namespace into its parent.
8412     DeclContext *Parent = CurContext->getRedeclContext();
8413     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8414       TU->setAnonymousNamespace(Namespc);
8415     } else {
8416       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8417     }
8418 
8419     CurContext->addDecl(Namespc);
8420 
8421     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8422     //   behaves as if it were replaced by
8423     //     namespace unique { /* empty body */ }
8424     //     using namespace unique;
8425     //     namespace unique { namespace-body }
8426     //   where all occurrences of 'unique' in a translation unit are
8427     //   replaced by the same identifier and this identifier differs
8428     //   from all other identifiers in the entire program.
8429 
8430     // We just create the namespace with an empty name and then add an
8431     // implicit using declaration, just like the standard suggests.
8432     //
8433     // CodeGen enforces the "universally unique" aspect by giving all
8434     // declarations semantically contained within an anonymous
8435     // namespace internal linkage.
8436 
8437     if (!PrevNS) {
8438       UD = UsingDirectiveDecl::Create(Context, Parent,
8439                                       /* 'using' */ LBrace,
8440                                       /* 'namespace' */ SourceLocation(),
8441                                       /* qualifier */ NestedNameSpecifierLoc(),
8442                                       /* identifier */ SourceLocation(),
8443                                       Namespc,
8444                                       /* Ancestor */ Parent);
8445       UD->setImplicit();
8446       Parent->addDecl(UD);
8447     }
8448   }
8449 
8450   ActOnDocumentableDecl(Namespc);
8451 
8452   // Although we could have an invalid decl (i.e. the namespace name is a
8453   // redefinition), push it as current DeclContext and try to continue parsing.
8454   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8455   // for the namespace has the declarations that showed up in that particular
8456   // namespace definition.
8457   PushDeclContext(NamespcScope, Namespc);
8458   return Namespc;
8459 }
8460 
8461 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8462 /// is a namespace alias, returns the namespace it points to.
8463 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8464   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8465     return AD->getNamespace();
8466   return dyn_cast_or_null<NamespaceDecl>(D);
8467 }
8468 
8469 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8470 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8471 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8472   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8473   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8474   Namespc->setRBraceLoc(RBrace);
8475   PopDeclContext();
8476   if (Namespc->hasAttr<VisibilityAttr>())
8477     PopPragmaVisibility(true, RBrace);
8478 }
8479 
8480 CXXRecordDecl *Sema::getStdBadAlloc() const {
8481   return cast_or_null<CXXRecordDecl>(
8482                                   StdBadAlloc.get(Context.getExternalSource()));
8483 }
8484 
8485 EnumDecl *Sema::getStdAlignValT() const {
8486   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8487 }
8488 
8489 NamespaceDecl *Sema::getStdNamespace() const {
8490   return cast_or_null<NamespaceDecl>(
8491                                  StdNamespace.get(Context.getExternalSource()));
8492 }
8493 
8494 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8495   if (!StdExperimentalNamespaceCache) {
8496     if (auto Std = getStdNamespace()) {
8497       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8498                           SourceLocation(), LookupNamespaceName);
8499       if (!LookupQualifiedName(Result, Std) ||
8500           !(StdExperimentalNamespaceCache =
8501                 Result.getAsSingle<NamespaceDecl>()))
8502         Result.suppressDiagnostics();
8503     }
8504   }
8505   return StdExperimentalNamespaceCache;
8506 }
8507 
8508 /// \brief Retrieve the special "std" namespace, which may require us to
8509 /// implicitly define the namespace.
8510 NamespaceDecl *Sema::getOrCreateStdNamespace() {
8511   if (!StdNamespace) {
8512     // The "std" namespace has not yet been defined, so build one implicitly.
8513     StdNamespace = NamespaceDecl::Create(Context,
8514                                          Context.getTranslationUnitDecl(),
8515                                          /*Inline=*/false,
8516                                          SourceLocation(), SourceLocation(),
8517                                          &PP.getIdentifierTable().get("std"),
8518                                          /*PrevDecl=*/nullptr);
8519     getStdNamespace()->setImplicit(true);
8520   }
8521 
8522   return getStdNamespace();
8523 }
8524 
8525 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
8526   assert(getLangOpts().CPlusPlus &&
8527          "Looking for std::initializer_list outside of C++.");
8528 
8529   // We're looking for implicit instantiations of
8530   // template <typename E> class std::initializer_list.
8531 
8532   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8533     return false;
8534 
8535   ClassTemplateDecl *Template = nullptr;
8536   const TemplateArgument *Arguments = nullptr;
8537 
8538   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8539 
8540     ClassTemplateSpecializationDecl *Specialization =
8541         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8542     if (!Specialization)
8543       return false;
8544 
8545     Template = Specialization->getSpecializedTemplate();
8546     Arguments = Specialization->getTemplateArgs().data();
8547   } else if (const TemplateSpecializationType *TST =
8548                  Ty->getAs<TemplateSpecializationType>()) {
8549     Template = dyn_cast_or_null<ClassTemplateDecl>(
8550         TST->getTemplateName().getAsTemplateDecl());
8551     Arguments = TST->getArgs();
8552   }
8553   if (!Template)
8554     return false;
8555 
8556   if (!StdInitializerList) {
8557     // Haven't recognized std::initializer_list yet, maybe this is it.
8558     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8559     if (TemplateClass->getIdentifier() !=
8560             &PP.getIdentifierTable().get("initializer_list") ||
8561         !getStdNamespace()->InEnclosingNamespaceSetOf(
8562             TemplateClass->getDeclContext()))
8563       return false;
8564     // This is a template called std::initializer_list, but is it the right
8565     // template?
8566     TemplateParameterList *Params = Template->getTemplateParameters();
8567     if (Params->getMinRequiredArguments() != 1)
8568       return false;
8569     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8570       return false;
8571 
8572     // It's the right template.
8573     StdInitializerList = Template;
8574   }
8575 
8576   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
8577     return false;
8578 
8579   // This is an instance of std::initializer_list. Find the argument type.
8580   if (Element)
8581     *Element = Arguments[0].getAsType();
8582   return true;
8583 }
8584 
8585 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8586   NamespaceDecl *Std = S.getStdNamespace();
8587   if (!Std) {
8588     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8589     return nullptr;
8590   }
8591 
8592   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8593                       Loc, Sema::LookupOrdinaryName);
8594   if (!S.LookupQualifiedName(Result, Std)) {
8595     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8596     return nullptr;
8597   }
8598   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8599   if (!Template) {
8600     Result.suppressDiagnostics();
8601     // We found something weird. Complain about the first thing we found.
8602     NamedDecl *Found = *Result.begin();
8603     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
8604     return nullptr;
8605   }
8606 
8607   // We found some template called std::initializer_list. Now verify that it's
8608   // correct.
8609   TemplateParameterList *Params = Template->getTemplateParameters();
8610   if (Params->getMinRequiredArguments() != 1 ||
8611       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
8612     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
8613     return nullptr;
8614   }
8615 
8616   return Template;
8617 }
8618 
8619 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8620   if (!StdInitializerList) {
8621     StdInitializerList = LookupStdInitializerList(*this, Loc);
8622     if (!StdInitializerList)
8623       return QualType();
8624   }
8625 
8626   TemplateArgumentListInfo Args(Loc, Loc);
8627   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8628                                        Context.getTrivialTypeSourceInfo(Element,
8629                                                                         Loc)));
8630   return Context.getCanonicalType(
8631       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8632 }
8633 
8634 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
8635   // C++ [dcl.init.list]p2:
8636   //   A constructor is an initializer-list constructor if its first parameter
8637   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
8638   //   std::initializer_list<E> for some type E, and either there are no other
8639   //   parameters or else all other parameters have default arguments.
8640   if (Ctor->getNumParams() < 1 ||
8641       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8642     return false;
8643 
8644   QualType ArgType = Ctor->getParamDecl(0)->getType();
8645   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8646     ArgType = RT->getPointeeType().getUnqualifiedType();
8647 
8648   return isStdInitializerList(ArgType, nullptr);
8649 }
8650 
8651 /// \brief Determine whether a using statement is in a context where it will be
8652 /// apply in all contexts.
8653 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8654   switch (CurContext->getDeclKind()) {
8655     case Decl::TranslationUnit:
8656       return true;
8657     case Decl::LinkageSpec:
8658       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8659     default:
8660       return false;
8661   }
8662 }
8663 
8664 namespace {
8665 
8666 // Callback to only accept typo corrections that are namespaces.
8667 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
8668 public:
8669   bool ValidateCandidate(const TypoCorrection &candidate) override {
8670     if (NamedDecl *ND = candidate.getCorrectionDecl())
8671       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
8672     return false;
8673   }
8674 };
8675 
8676 }
8677 
8678 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8679                                        CXXScopeSpec &SS,
8680                                        SourceLocation IdentLoc,
8681                                        IdentifierInfo *Ident) {
8682   R.clear();
8683   if (TypoCorrection Corrected =
8684           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8685                         llvm::make_unique<NamespaceValidatorCCC>(),
8686                         Sema::CTK_ErrorRecovery)) {
8687     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
8688       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8689       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
8690                               Ident->getName().equals(CorrectedStr);
8691       S.diagnoseTypo(Corrected,
8692                      S.PDiag(diag::err_using_directive_member_suggest)
8693                        << Ident << DC << DroppedSpecifier << SS.getRange(),
8694                      S.PDiag(diag::note_namespace_defined_here));
8695     } else {
8696       S.diagnoseTypo(Corrected,
8697                      S.PDiag(diag::err_using_directive_suggest) << Ident,
8698                      S.PDiag(diag::note_namespace_defined_here));
8699     }
8700     R.addDecl(Corrected.getFoundDecl());
8701     return true;
8702   }
8703   return false;
8704 }
8705 
8706 Decl *Sema::ActOnUsingDirective(Scope *S,
8707                                           SourceLocation UsingLoc,
8708                                           SourceLocation NamespcLoc,
8709                                           CXXScopeSpec &SS,
8710                                           SourceLocation IdentLoc,
8711                                           IdentifierInfo *NamespcName,
8712                                           AttributeList *AttrList) {
8713   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8714   assert(NamespcName && "Invalid NamespcName.");
8715   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
8716 
8717   // This can only happen along a recovery path.
8718   while (S->isTemplateParamScope())
8719     S = S->getParent();
8720   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8721 
8722   UsingDirectiveDecl *UDir = nullptr;
8723   NestedNameSpecifier *Qualifier = nullptr;
8724   if (SS.isSet())
8725     Qualifier = SS.getScopeRep();
8726 
8727   // Lookup namespace name.
8728   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8729   LookupParsedName(R, S, &SS);
8730   if (R.isAmbiguous())
8731     return nullptr;
8732 
8733   if (R.empty()) {
8734     R.clear();
8735     // Allow "using namespace std;" or "using namespace ::std;" even if
8736     // "std" hasn't been defined yet, for GCC compatibility.
8737     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8738         NamespcName->isStr("std")) {
8739       Diag(IdentLoc, diag::ext_using_undefined_std);
8740       R.addDecl(getOrCreateStdNamespace());
8741       R.resolveKind();
8742     }
8743     // Otherwise, attempt typo correction.
8744     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
8745   }
8746 
8747   if (!R.empty()) {
8748     NamedDecl *Named = R.getRepresentativeDecl();
8749     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8750     assert(NS && "expected namespace decl");
8751 
8752     // The use of a nested name specifier may trigger deprecation warnings.
8753     DiagnoseUseOfDecl(Named, IdentLoc);
8754 
8755     // C++ [namespace.udir]p1:
8756     //   A using-directive specifies that the names in the nominated
8757     //   namespace can be used in the scope in which the
8758     //   using-directive appears after the using-directive. During
8759     //   unqualified name lookup (3.4.1), the names appear as if they
8760     //   were declared in the nearest enclosing namespace which
8761     //   contains both the using-directive and the nominated
8762     //   namespace. [Note: in this context, "contains" means "contains
8763     //   directly or indirectly". ]
8764 
8765     // Find enclosing context containing both using-directive and
8766     // nominated namespace.
8767     DeclContext *CommonAncestor = cast<DeclContext>(NS);
8768     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8769       CommonAncestor = CommonAncestor->getParent();
8770 
8771     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
8772                                       SS.getWithLocInContext(Context),
8773                                       IdentLoc, Named, CommonAncestor);
8774 
8775     if (IsUsingDirectiveInToplevelContext(CurContext) &&
8776         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
8777       Diag(IdentLoc, diag::warn_using_directive_in_header);
8778     }
8779 
8780     PushUsingDirective(S, UDir);
8781   } else {
8782     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8783   }
8784 
8785   if (UDir)
8786     ProcessDeclAttributeList(S, UDir, AttrList);
8787 
8788   return UDir;
8789 }
8790 
8791 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
8792   // If the scope has an associated entity and the using directive is at
8793   // namespace or translation unit scope, add the UsingDirectiveDecl into
8794   // its lookup structure so qualified name lookup can find it.
8795   DeclContext *Ctx = S->getEntity();
8796   if (Ctx && !Ctx->isFunctionOrMethod())
8797     Ctx->addDecl(UDir);
8798   else
8799     // Otherwise, it is at block scope. The using-directives will affect lookup
8800     // only to the end of the scope.
8801     S->PushUsingDirective(UDir);
8802 }
8803 
8804 
8805 Decl *Sema::ActOnUsingDeclaration(Scope *S,
8806                                   AccessSpecifier AS,
8807                                   SourceLocation UsingLoc,
8808                                   SourceLocation TypenameLoc,
8809                                   CXXScopeSpec &SS,
8810                                   UnqualifiedId &Name,
8811                                   SourceLocation EllipsisLoc,
8812                                   AttributeList *AttrList) {
8813   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8814 
8815   if (SS.isEmpty()) {
8816     Diag(Name.getLocStart(), diag::err_using_requires_qualname);
8817     return nullptr;
8818   }
8819 
8820   switch (Name.getKind()) {
8821   case UnqualifiedId::IK_ImplicitSelfParam:
8822   case UnqualifiedId::IK_Identifier:
8823   case UnqualifiedId::IK_OperatorFunctionId:
8824   case UnqualifiedId::IK_LiteralOperatorId:
8825   case UnqualifiedId::IK_ConversionFunctionId:
8826     break;
8827 
8828   case UnqualifiedId::IK_ConstructorName:
8829   case UnqualifiedId::IK_ConstructorTemplateId:
8830     // C++11 inheriting constructors.
8831     Diag(Name.getLocStart(),
8832          getLangOpts().CPlusPlus11 ?
8833            diag::warn_cxx98_compat_using_decl_constructor :
8834            diag::err_using_decl_constructor)
8835       << SS.getRange();
8836 
8837     if (getLangOpts().CPlusPlus11) break;
8838 
8839     return nullptr;
8840 
8841   case UnqualifiedId::IK_DestructorName:
8842     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
8843       << SS.getRange();
8844     return nullptr;
8845 
8846   case UnqualifiedId::IK_TemplateId:
8847     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
8848       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
8849     return nullptr;
8850 
8851   case UnqualifiedId::IK_DeductionGuideName:
8852     llvm_unreachable("cannot parse qualified deduction guide name");
8853   }
8854 
8855   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8856   DeclarationName TargetName = TargetNameInfo.getName();
8857   if (!TargetName)
8858     return nullptr;
8859 
8860   // Warn about access declarations.
8861   if (UsingLoc.isInvalid()) {
8862     Diag(Name.getLocStart(),
8863          getLangOpts().CPlusPlus11 ? diag::err_access_decl
8864                                    : diag::warn_access_decl_deprecated)
8865       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
8866   }
8867 
8868   if (EllipsisLoc.isInvalid()) {
8869     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8870         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
8871       return nullptr;
8872   } else {
8873     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
8874         !TargetNameInfo.containsUnexpandedParameterPack()) {
8875       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
8876         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
8877       EllipsisLoc = SourceLocation();
8878     }
8879   }
8880 
8881   NamedDecl *UD =
8882       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
8883                             SS, TargetNameInfo, EllipsisLoc, AttrList,
8884                             /*IsInstantiation*/false);
8885   if (UD)
8886     PushOnScopeChains(UD, S, /*AddToContext*/ false);
8887 
8888   return UD;
8889 }
8890 
8891 /// \brief Determine whether a using declaration considers the given
8892 /// declarations as "equivalent", e.g., if they are redeclarations of
8893 /// the same entity or are both typedefs of the same type.
8894 static bool
8895 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
8896   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
8897     return true;
8898 
8899   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
8900     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
8901       return Context.hasSameType(TD1->getUnderlyingType(),
8902                                  TD2->getUnderlyingType());
8903 
8904   return false;
8905 }
8906 
8907 
8908 /// Determines whether to create a using shadow decl for a particular
8909 /// decl, given the set of decls existing prior to this using lookup.
8910 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
8911                                 const LookupResult &Previous,
8912                                 UsingShadowDecl *&PrevShadow) {
8913   // Diagnose finding a decl which is not from a base class of the
8914   // current class.  We do this now because there are cases where this
8915   // function will silently decide not to build a shadow decl, which
8916   // will pre-empt further diagnostics.
8917   //
8918   // We don't need to do this in C++11 because we do the check once on
8919   // the qualifier.
8920   //
8921   // FIXME: diagnose the following if we care enough:
8922   //   struct A { int foo; };
8923   //   struct B : A { using A::foo; };
8924   //   template <class T> struct C : A {};
8925   //   template <class T> struct D : C<T> { using B::foo; } // <---
8926   // This is invalid (during instantiation) in C++03 because B::foo
8927   // resolves to the using decl in B, which is not a base class of D<T>.
8928   // We can't diagnose it immediately because C<T> is an unknown
8929   // specialization.  The UsingShadowDecl in D<T> then points directly
8930   // to A::foo, which will look well-formed when we instantiate.
8931   // The right solution is to not collapse the shadow-decl chain.
8932   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
8933     DeclContext *OrigDC = Orig->getDeclContext();
8934 
8935     // Handle enums and anonymous structs.
8936     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
8937     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
8938     while (OrigRec->isAnonymousStructOrUnion())
8939       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
8940 
8941     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
8942       if (OrigDC == CurContext) {
8943         Diag(Using->getLocation(),
8944              diag::err_using_decl_nested_name_specifier_is_current_class)
8945           << Using->getQualifierLoc().getSourceRange();
8946         Diag(Orig->getLocation(), diag::note_using_decl_target);
8947         Using->setInvalidDecl();
8948         return true;
8949       }
8950 
8951       Diag(Using->getQualifierLoc().getBeginLoc(),
8952            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8953         << Using->getQualifier()
8954         << cast<CXXRecordDecl>(CurContext)
8955         << Using->getQualifierLoc().getSourceRange();
8956       Diag(Orig->getLocation(), diag::note_using_decl_target);
8957       Using->setInvalidDecl();
8958       return true;
8959     }
8960   }
8961 
8962   if (Previous.empty()) return false;
8963 
8964   NamedDecl *Target = Orig;
8965   if (isa<UsingShadowDecl>(Target))
8966     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8967 
8968   // If the target happens to be one of the previous declarations, we
8969   // don't have a conflict.
8970   //
8971   // FIXME: but we might be increasing its access, in which case we
8972   // should redeclare it.
8973   NamedDecl *NonTag = nullptr, *Tag = nullptr;
8974   bool FoundEquivalentDecl = false;
8975   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8976          I != E; ++I) {
8977     NamedDecl *D = (*I)->getUnderlyingDecl();
8978     // We can have UsingDecls in our Previous results because we use the same
8979     // LookupResult for checking whether the UsingDecl itself is a valid
8980     // redeclaration.
8981     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
8982       continue;
8983 
8984     if (IsEquivalentForUsingDecl(Context, D, Target)) {
8985       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
8986         PrevShadow = Shadow;
8987       FoundEquivalentDecl = true;
8988     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
8989       // We don't conflict with an existing using shadow decl of an equivalent
8990       // declaration, but we're not a redeclaration of it.
8991       FoundEquivalentDecl = true;
8992     }
8993 
8994     if (isVisible(D))
8995       (isa<TagDecl>(D) ? Tag : NonTag) = D;
8996   }
8997 
8998   if (FoundEquivalentDecl)
8999     return false;
9000 
9001   if (FunctionDecl *FD = Target->getAsFunction()) {
9002     NamedDecl *OldDecl = nullptr;
9003     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9004                           /*IsForUsingDecl*/ true)) {
9005     case Ovl_Overload:
9006       return false;
9007 
9008     case Ovl_NonFunction:
9009       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9010       break;
9011 
9012     // We found a decl with the exact signature.
9013     case Ovl_Match:
9014       // If we're in a record, we want to hide the target, so we
9015       // return true (without a diagnostic) to tell the caller not to
9016       // build a shadow decl.
9017       if (CurContext->isRecord())
9018         return true;
9019 
9020       // If we're not in a record, this is an error.
9021       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9022       break;
9023     }
9024 
9025     Diag(Target->getLocation(), diag::note_using_decl_target);
9026     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9027     Using->setInvalidDecl();
9028     return true;
9029   }
9030 
9031   // Target is not a function.
9032 
9033   if (isa<TagDecl>(Target)) {
9034     // No conflict between a tag and a non-tag.
9035     if (!Tag) return false;
9036 
9037     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9038     Diag(Target->getLocation(), diag::note_using_decl_target);
9039     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9040     Using->setInvalidDecl();
9041     return true;
9042   }
9043 
9044   // No conflict between a tag and a non-tag.
9045   if (!NonTag) return false;
9046 
9047   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9048   Diag(Target->getLocation(), diag::note_using_decl_target);
9049   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9050   Using->setInvalidDecl();
9051   return true;
9052 }
9053 
9054 /// Determine whether a direct base class is a virtual base class.
9055 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9056   if (!Derived->getNumVBases())
9057     return false;
9058   for (auto &B : Derived->bases())
9059     if (B.getType()->getAsCXXRecordDecl() == Base)
9060       return B.isVirtual();
9061   llvm_unreachable("not a direct base class");
9062 }
9063 
9064 /// Builds a shadow declaration corresponding to a 'using' declaration.
9065 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9066                                             UsingDecl *UD,
9067                                             NamedDecl *Orig,
9068                                             UsingShadowDecl *PrevDecl) {
9069   // If we resolved to another shadow declaration, just coalesce them.
9070   NamedDecl *Target = Orig;
9071   if (isa<UsingShadowDecl>(Target)) {
9072     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9073     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9074   }
9075 
9076   NamedDecl *NonTemplateTarget = Target;
9077   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9078     NonTemplateTarget = TargetTD->getTemplatedDecl();
9079 
9080   UsingShadowDecl *Shadow;
9081   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9082     bool IsVirtualBase =
9083         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9084                             UD->getQualifier()->getAsRecordDecl());
9085     Shadow = ConstructorUsingShadowDecl::Create(
9086         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9087   } else {
9088     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9089                                      Target);
9090   }
9091   UD->addShadowDecl(Shadow);
9092 
9093   Shadow->setAccess(UD->getAccess());
9094   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9095     Shadow->setInvalidDecl();
9096 
9097   Shadow->setPreviousDecl(PrevDecl);
9098 
9099   if (S)
9100     PushOnScopeChains(Shadow, S);
9101   else
9102     CurContext->addDecl(Shadow);
9103 
9104 
9105   return Shadow;
9106 }
9107 
9108 /// Hides a using shadow declaration.  This is required by the current
9109 /// using-decl implementation when a resolvable using declaration in a
9110 /// class is followed by a declaration which would hide or override
9111 /// one or more of the using decl's targets; for example:
9112 ///
9113 ///   struct Base { void foo(int); };
9114 ///   struct Derived : Base {
9115 ///     using Base::foo;
9116 ///     void foo(int);
9117 ///   };
9118 ///
9119 /// The governing language is C++03 [namespace.udecl]p12:
9120 ///
9121 ///   When a using-declaration brings names from a base class into a
9122 ///   derived class scope, member functions in the derived class
9123 ///   override and/or hide member functions with the same name and
9124 ///   parameter types in a base class (rather than conflicting).
9125 ///
9126 /// There are two ways to implement this:
9127 ///   (1) optimistically create shadow decls when they're not hidden
9128 ///       by existing declarations, or
9129 ///   (2) don't create any shadow decls (or at least don't make them
9130 ///       visible) until we've fully parsed/instantiated the class.
9131 /// The problem with (1) is that we might have to retroactively remove
9132 /// a shadow decl, which requires several O(n) operations because the
9133 /// decl structures are (very reasonably) not designed for removal.
9134 /// (2) avoids this but is very fiddly and phase-dependent.
9135 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9136   if (Shadow->getDeclName().getNameKind() ==
9137         DeclarationName::CXXConversionFunctionName)
9138     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9139 
9140   // Remove it from the DeclContext...
9141   Shadow->getDeclContext()->removeDecl(Shadow);
9142 
9143   // ...and the scope, if applicable...
9144   if (S) {
9145     S->RemoveDecl(Shadow);
9146     IdResolver.RemoveDecl(Shadow);
9147   }
9148 
9149   // ...and the using decl.
9150   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9151 
9152   // TODO: complain somehow if Shadow was used.  It shouldn't
9153   // be possible for this to happen, because...?
9154 }
9155 
9156 /// Find the base specifier for a base class with the given type.
9157 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9158                                                 QualType DesiredBase,
9159                                                 bool &AnyDependentBases) {
9160   // Check whether the named type is a direct base class.
9161   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9162   for (auto &Base : Derived->bases()) {
9163     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9164     if (CanonicalDesiredBase == BaseType)
9165       return &Base;
9166     if (BaseType->isDependentType())
9167       AnyDependentBases = true;
9168   }
9169   return nullptr;
9170 }
9171 
9172 namespace {
9173 class UsingValidatorCCC : public CorrectionCandidateCallback {
9174 public:
9175   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9176                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9177       : HasTypenameKeyword(HasTypenameKeyword),
9178         IsInstantiation(IsInstantiation), OldNNS(NNS),
9179         RequireMemberOf(RequireMemberOf) {}
9180 
9181   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9182     NamedDecl *ND = Candidate.getCorrectionDecl();
9183 
9184     // Keywords are not valid here.
9185     if (!ND || isa<NamespaceDecl>(ND))
9186       return false;
9187 
9188     // Completely unqualified names are invalid for a 'using' declaration.
9189     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9190       return false;
9191 
9192     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9193     // reject.
9194 
9195     if (RequireMemberOf) {
9196       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9197       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9198         // No-one ever wants a using-declaration to name an injected-class-name
9199         // of a base class, unless they're declaring an inheriting constructor.
9200         ASTContext &Ctx = ND->getASTContext();
9201         if (!Ctx.getLangOpts().CPlusPlus11)
9202           return false;
9203         QualType FoundType = Ctx.getRecordType(FoundRecord);
9204 
9205         // Check that the injected-class-name is named as a member of its own
9206         // type; we don't want to suggest 'using Derived::Base;', since that
9207         // means something else.
9208         NestedNameSpecifier *Specifier =
9209             Candidate.WillReplaceSpecifier()
9210                 ? Candidate.getCorrectionSpecifier()
9211                 : OldNNS;
9212         if (!Specifier->getAsType() ||
9213             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9214           return false;
9215 
9216         // Check that this inheriting constructor declaration actually names a
9217         // direct base class of the current class.
9218         bool AnyDependentBases = false;
9219         if (!findDirectBaseWithType(RequireMemberOf,
9220                                     Ctx.getRecordType(FoundRecord),
9221                                     AnyDependentBases) &&
9222             !AnyDependentBases)
9223           return false;
9224       } else {
9225         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9226         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9227           return false;
9228 
9229         // FIXME: Check that the base class member is accessible?
9230       }
9231     } else {
9232       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9233       if (FoundRecord && FoundRecord->isInjectedClassName())
9234         return false;
9235     }
9236 
9237     if (isa<TypeDecl>(ND))
9238       return HasTypenameKeyword || !IsInstantiation;
9239 
9240     return !HasTypenameKeyword;
9241   }
9242 
9243 private:
9244   bool HasTypenameKeyword;
9245   bool IsInstantiation;
9246   NestedNameSpecifier *OldNNS;
9247   CXXRecordDecl *RequireMemberOf;
9248 };
9249 } // end anonymous namespace
9250 
9251 /// Builds a using declaration.
9252 ///
9253 /// \param IsInstantiation - Whether this call arises from an
9254 ///   instantiation of an unresolved using declaration.  We treat
9255 ///   the lookup differently for these declarations.
9256 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9257                                        SourceLocation UsingLoc,
9258                                        bool HasTypenameKeyword,
9259                                        SourceLocation TypenameLoc,
9260                                        CXXScopeSpec &SS,
9261                                        DeclarationNameInfo NameInfo,
9262                                        SourceLocation EllipsisLoc,
9263                                        AttributeList *AttrList,
9264                                        bool IsInstantiation) {
9265   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9266   SourceLocation IdentLoc = NameInfo.getLoc();
9267   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9268 
9269   // FIXME: We ignore attributes for now.
9270 
9271   // For an inheriting constructor declaration, the name of the using
9272   // declaration is the name of a constructor in this class, not in the
9273   // base class.
9274   DeclarationNameInfo UsingName = NameInfo;
9275   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9276     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9277       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9278           Context.getCanonicalType(Context.getRecordType(RD))));
9279 
9280   // Do the redeclaration lookup in the current scope.
9281   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9282                         ForRedeclaration);
9283   Previous.setHideTags(false);
9284   if (S) {
9285     LookupName(Previous, S);
9286 
9287     // It is really dumb that we have to do this.
9288     LookupResult::Filter F = Previous.makeFilter();
9289     while (F.hasNext()) {
9290       NamedDecl *D = F.next();
9291       if (!isDeclInScope(D, CurContext, S))
9292         F.erase();
9293       // If we found a local extern declaration that's not ordinarily visible,
9294       // and this declaration is being added to a non-block scope, ignore it.
9295       // We're only checking for scope conflicts here, not also for violations
9296       // of the linkage rules.
9297       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9298                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9299         F.erase();
9300     }
9301     F.done();
9302   } else {
9303     assert(IsInstantiation && "no scope in non-instantiation");
9304     if (CurContext->isRecord())
9305       LookupQualifiedName(Previous, CurContext);
9306     else {
9307       // No redeclaration check is needed here; in non-member contexts we
9308       // diagnosed all possible conflicts with other using-declarations when
9309       // building the template:
9310       //
9311       // For a dependent non-type using declaration, the only valid case is
9312       // if we instantiate to a single enumerator. We check for conflicts
9313       // between shadow declarations we introduce, and we check in the template
9314       // definition for conflicts between a non-type using declaration and any
9315       // other declaration, which together covers all cases.
9316       //
9317       // A dependent typename using declaration will never successfully
9318       // instantiate, since it will always name a class member, so we reject
9319       // that in the template definition.
9320     }
9321   }
9322 
9323   // Check for invalid redeclarations.
9324   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9325                                   SS, IdentLoc, Previous))
9326     return nullptr;
9327 
9328   // Check for bad qualifiers.
9329   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9330                               IdentLoc))
9331     return nullptr;
9332 
9333   DeclContext *LookupContext = computeDeclContext(SS);
9334   NamedDecl *D;
9335   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9336   if (!LookupContext || EllipsisLoc.isValid()) {
9337     if (HasTypenameKeyword) {
9338       // FIXME: not all declaration name kinds are legal here
9339       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9340                                               UsingLoc, TypenameLoc,
9341                                               QualifierLoc,
9342                                               IdentLoc, NameInfo.getName(),
9343                                               EllipsisLoc);
9344     } else {
9345       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9346                                            QualifierLoc, NameInfo, EllipsisLoc);
9347     }
9348     D->setAccess(AS);
9349     CurContext->addDecl(D);
9350     return D;
9351   }
9352 
9353   auto Build = [&](bool Invalid) {
9354     UsingDecl *UD =
9355         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9356                           UsingName, HasTypenameKeyword);
9357     UD->setAccess(AS);
9358     CurContext->addDecl(UD);
9359     UD->setInvalidDecl(Invalid);
9360     return UD;
9361   };
9362   auto BuildInvalid = [&]{ return Build(true); };
9363   auto BuildValid = [&]{ return Build(false); };
9364 
9365   if (RequireCompleteDeclContext(SS, LookupContext))
9366     return BuildInvalid();
9367 
9368   // Look up the target name.
9369   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9370 
9371   // Unlike most lookups, we don't always want to hide tag
9372   // declarations: tag names are visible through the using declaration
9373   // even if hidden by ordinary names, *except* in a dependent context
9374   // where it's important for the sanity of two-phase lookup.
9375   if (!IsInstantiation)
9376     R.setHideTags(false);
9377 
9378   // For the purposes of this lookup, we have a base object type
9379   // equal to that of the current context.
9380   if (CurContext->isRecord()) {
9381     R.setBaseObjectType(
9382                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9383   }
9384 
9385   LookupQualifiedName(R, LookupContext);
9386 
9387   // Try to correct typos if possible. If constructor name lookup finds no
9388   // results, that means the named class has no explicit constructors, and we
9389   // suppressed declaring implicit ones (probably because it's dependent or
9390   // invalid).
9391   if (R.empty() &&
9392       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9393     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9394     // it will believe that glibc provides a ::gets in cases where it does not,
9395     // and will try to pull it into namespace std with a using-declaration.
9396     // Just ignore the using-declaration in that case.
9397     auto *II = NameInfo.getName().getAsIdentifierInfo();
9398     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9399         CurContext->isStdNamespace() &&
9400         isa<TranslationUnitDecl>(LookupContext) &&
9401         getSourceManager().isInSystemHeader(UsingLoc))
9402       return nullptr;
9403     if (TypoCorrection Corrected = CorrectTypo(
9404             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9405             llvm::make_unique<UsingValidatorCCC>(
9406                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9407                 dyn_cast<CXXRecordDecl>(CurContext)),
9408             CTK_ErrorRecovery)) {
9409       // We reject candidates where DroppedSpecifier == true, hence the
9410       // literal '0' below.
9411       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9412                                 << NameInfo.getName() << LookupContext << 0
9413                                 << SS.getRange());
9414 
9415       // If we picked a correction with no attached Decl we can't do anything
9416       // useful with it, bail out.
9417       NamedDecl *ND = Corrected.getCorrectionDecl();
9418       if (!ND)
9419         return BuildInvalid();
9420 
9421       // If we corrected to an inheriting constructor, handle it as one.
9422       auto *RD = dyn_cast<CXXRecordDecl>(ND);
9423       if (RD && RD->isInjectedClassName()) {
9424         // The parent of the injected class name is the class itself.
9425         RD = cast<CXXRecordDecl>(RD->getParent());
9426 
9427         // Fix up the information we'll use to build the using declaration.
9428         if (Corrected.WillReplaceSpecifier()) {
9429           NestedNameSpecifierLocBuilder Builder;
9430           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9431                               QualifierLoc.getSourceRange());
9432           QualifierLoc = Builder.getWithLocInContext(Context);
9433         }
9434 
9435         // In this case, the name we introduce is the name of a derived class
9436         // constructor.
9437         auto *CurClass = cast<CXXRecordDecl>(CurContext);
9438         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9439             Context.getCanonicalType(Context.getRecordType(CurClass))));
9440         UsingName.setNamedTypeInfo(nullptr);
9441         for (auto *Ctor : LookupConstructors(RD))
9442           R.addDecl(Ctor);
9443         R.resolveKind();
9444       } else {
9445         // FIXME: Pick up all the declarations if we found an overloaded
9446         // function.
9447         UsingName.setName(ND->getDeclName());
9448         R.addDecl(ND);
9449       }
9450     } else {
9451       Diag(IdentLoc, diag::err_no_member)
9452         << NameInfo.getName() << LookupContext << SS.getRange();
9453       return BuildInvalid();
9454     }
9455   }
9456 
9457   if (R.isAmbiguous())
9458     return BuildInvalid();
9459 
9460   if (HasTypenameKeyword) {
9461     // If we asked for a typename and got a non-type decl, error out.
9462     if (!R.getAsSingle<TypeDecl>()) {
9463       Diag(IdentLoc, diag::err_using_typename_non_type);
9464       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9465         Diag((*I)->getUnderlyingDecl()->getLocation(),
9466              diag::note_using_decl_target);
9467       return BuildInvalid();
9468     }
9469   } else {
9470     // If we asked for a non-typename and we got a type, error out,
9471     // but only if this is an instantiation of an unresolved using
9472     // decl.  Otherwise just silently find the type name.
9473     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
9474       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9475       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
9476       return BuildInvalid();
9477     }
9478   }
9479 
9480   // C++14 [namespace.udecl]p6:
9481   // A using-declaration shall not name a namespace.
9482   if (R.getAsSingle<NamespaceDecl>()) {
9483     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9484       << SS.getRange();
9485     return BuildInvalid();
9486   }
9487 
9488   // C++14 [namespace.udecl]p7:
9489   // A using-declaration shall not name a scoped enumerator.
9490   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9491     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9492       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9493         << SS.getRange();
9494       return BuildInvalid();
9495     }
9496   }
9497 
9498   UsingDecl *UD = BuildValid();
9499 
9500   // Some additional rules apply to inheriting constructors.
9501   if (UsingName.getName().getNameKind() ==
9502         DeclarationName::CXXConstructorName) {
9503     // Suppress access diagnostics; the access check is instead performed at the
9504     // point of use for an inheriting constructor.
9505     R.suppressDiagnostics();
9506     if (CheckInheritingConstructorUsingDecl(UD))
9507       return UD;
9508   }
9509 
9510   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9511     UsingShadowDecl *PrevDecl = nullptr;
9512     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9513       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
9514   }
9515 
9516   return UD;
9517 }
9518 
9519 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
9520                                     ArrayRef<NamedDecl *> Expansions) {
9521   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
9522          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
9523          isa<UsingPackDecl>(InstantiatedFrom));
9524 
9525   auto *UPD =
9526       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
9527   UPD->setAccess(InstantiatedFrom->getAccess());
9528   CurContext->addDecl(UPD);
9529   return UPD;
9530 }
9531 
9532 /// Additional checks for a using declaration referring to a constructor name.
9533 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
9534   assert(!UD->hasTypename() && "expecting a constructor name");
9535 
9536   const Type *SourceType = UD->getQualifier()->getAsType();
9537   assert(SourceType &&
9538          "Using decl naming constructor doesn't have type in scope spec.");
9539   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9540 
9541   // Check whether the named type is a direct base class.
9542   bool AnyDependentBases = false;
9543   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9544                                       AnyDependentBases);
9545   if (!Base && !AnyDependentBases) {
9546     Diag(UD->getUsingLoc(),
9547          diag::err_using_decl_constructor_not_in_direct_base)
9548       << UD->getNameInfo().getSourceRange()
9549       << QualType(SourceType, 0) << TargetClass;
9550     UD->setInvalidDecl();
9551     return true;
9552   }
9553 
9554   if (Base)
9555     Base->setInheritConstructors();
9556 
9557   return false;
9558 }
9559 
9560 /// Checks that the given using declaration is not an invalid
9561 /// redeclaration.  Note that this is checking only for the using decl
9562 /// itself, not for any ill-formedness among the UsingShadowDecls.
9563 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
9564                                        bool HasTypenameKeyword,
9565                                        const CXXScopeSpec &SS,
9566                                        SourceLocation NameLoc,
9567                                        const LookupResult &Prev) {
9568   NestedNameSpecifier *Qual = SS.getScopeRep();
9569 
9570   // C++03 [namespace.udecl]p8:
9571   // C++0x [namespace.udecl]p10:
9572   //   A using-declaration is a declaration and can therefore be used
9573   //   repeatedly where (and only where) multiple declarations are
9574   //   allowed.
9575   //
9576   // That's in non-member contexts.
9577   if (!CurContext->getRedeclContext()->isRecord()) {
9578     // A dependent qualifier outside a class can only ever resolve to an
9579     // enumeration type. Therefore it conflicts with any other non-type
9580     // declaration in the same scope.
9581     // FIXME: How should we check for dependent type-type conflicts at block
9582     // scope?
9583     if (Qual->isDependent() && !HasTypenameKeyword) {
9584       for (auto *D : Prev) {
9585         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
9586           bool OldCouldBeEnumerator =
9587               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
9588           Diag(NameLoc,
9589                OldCouldBeEnumerator ? diag::err_redefinition
9590                                     : diag::err_redefinition_different_kind)
9591               << Prev.getLookupName();
9592           Diag(D->getLocation(), diag::note_previous_definition);
9593           return true;
9594         }
9595       }
9596     }
9597     return false;
9598   }
9599 
9600   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9601     NamedDecl *D = *I;
9602 
9603     bool DTypename;
9604     NestedNameSpecifier *DQual;
9605     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
9606       DTypename = UD->hasTypename();
9607       DQual = UD->getQualifier();
9608     } else if (UnresolvedUsingValueDecl *UD
9609                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9610       DTypename = false;
9611       DQual = UD->getQualifier();
9612     } else if (UnresolvedUsingTypenameDecl *UD
9613                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9614       DTypename = true;
9615       DQual = UD->getQualifier();
9616     } else continue;
9617 
9618     // using decls differ if one says 'typename' and the other doesn't.
9619     // FIXME: non-dependent using decls?
9620     if (HasTypenameKeyword != DTypename) continue;
9621 
9622     // using decls differ if they name different scopes (but note that
9623     // template instantiation can cause this check to trigger when it
9624     // didn't before instantiation).
9625     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9626         Context.getCanonicalNestedNameSpecifier(DQual))
9627       continue;
9628 
9629     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
9630     Diag(D->getLocation(), diag::note_using_decl) << 1;
9631     return true;
9632   }
9633 
9634   return false;
9635 }
9636 
9637 
9638 /// Checks that the given nested-name qualifier used in a using decl
9639 /// in the current context is appropriately related to the current
9640 /// scope.  If an error is found, diagnoses it and returns true.
9641 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
9642                                    bool HasTypename,
9643                                    const CXXScopeSpec &SS,
9644                                    const DeclarationNameInfo &NameInfo,
9645                                    SourceLocation NameLoc) {
9646   DeclContext *NamedContext = computeDeclContext(SS);
9647 
9648   if (!CurContext->isRecord()) {
9649     // C++03 [namespace.udecl]p3:
9650     // C++0x [namespace.udecl]p8:
9651     //   A using-declaration for a class member shall be a member-declaration.
9652 
9653     // If we weren't able to compute a valid scope, it might validly be a
9654     // dependent class scope or a dependent enumeration unscoped scope. If
9655     // we have a 'typename' keyword, the scope must resolve to a class type.
9656     if ((HasTypename && !NamedContext) ||
9657         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
9658       auto *RD = NamedContext
9659                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9660                      : nullptr;
9661       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
9662         RD = nullptr;
9663 
9664       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9665         << SS.getRange();
9666 
9667       // If we have a complete, non-dependent source type, try to suggest a
9668       // way to get the same effect.
9669       if (!RD)
9670         return true;
9671 
9672       // Find what this using-declaration was referring to.
9673       LookupResult R(*this, NameInfo, LookupOrdinaryName);
9674       R.setHideTags(false);
9675       R.suppressDiagnostics();
9676       LookupQualifiedName(R, RD);
9677 
9678       if (R.getAsSingle<TypeDecl>()) {
9679         if (getLangOpts().CPlusPlus11) {
9680           // Convert 'using X::Y;' to 'using Y = X::Y;'.
9681           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9682             << 0 // alias declaration
9683             << FixItHint::CreateInsertion(SS.getBeginLoc(),
9684                                           NameInfo.getName().getAsString() +
9685                                               " = ");
9686         } else {
9687           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9688           SourceLocation InsertLoc =
9689               getLocForEndOfToken(NameInfo.getLocEnd());
9690           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9691             << 1 // typedef declaration
9692             << FixItHint::CreateReplacement(UsingLoc, "typedef")
9693             << FixItHint::CreateInsertion(
9694                    InsertLoc, " " + NameInfo.getName().getAsString());
9695         }
9696       } else if (R.getAsSingle<VarDecl>()) {
9697         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9698         // repeating the type of the static data member here.
9699         FixItHint FixIt;
9700         if (getLangOpts().CPlusPlus11) {
9701           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9702           FixIt = FixItHint::CreateReplacement(
9703               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9704         }
9705 
9706         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9707           << 2 // reference declaration
9708           << FixIt;
9709       } else if (R.getAsSingle<EnumConstantDecl>()) {
9710         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9711         // repeating the type of the enumeration here, and we can't do so if
9712         // the type is anonymous.
9713         FixItHint FixIt;
9714         if (getLangOpts().CPlusPlus11) {
9715           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9716           FixIt = FixItHint::CreateReplacement(
9717               UsingLoc,
9718               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
9719         }
9720 
9721         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9722           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9723           << FixIt;
9724       }
9725       return true;
9726     }
9727 
9728     // Otherwise, this might be valid.
9729     return false;
9730   }
9731 
9732   // The current scope is a record.
9733 
9734   // If the named context is dependent, we can't decide much.
9735   if (!NamedContext) {
9736     // FIXME: in C++0x, we can diagnose if we can prove that the
9737     // nested-name-specifier does not refer to a base class, which is
9738     // still possible in some cases.
9739 
9740     // Otherwise we have to conservatively report that things might be
9741     // okay.
9742     return false;
9743   }
9744 
9745   if (!NamedContext->isRecord()) {
9746     // Ideally this would point at the last name in the specifier,
9747     // but we don't have that level of source info.
9748     Diag(SS.getRange().getBegin(),
9749          diag::err_using_decl_nested_name_specifier_is_not_class)
9750       << SS.getScopeRep() << SS.getRange();
9751     return true;
9752   }
9753 
9754   if (!NamedContext->isDependentContext() &&
9755       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9756     return true;
9757 
9758   if (getLangOpts().CPlusPlus11) {
9759     // C++11 [namespace.udecl]p3:
9760     //   In a using-declaration used as a member-declaration, the
9761     //   nested-name-specifier shall name a base class of the class
9762     //   being defined.
9763 
9764     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9765                                  cast<CXXRecordDecl>(NamedContext))) {
9766       if (CurContext == NamedContext) {
9767         Diag(NameLoc,
9768              diag::err_using_decl_nested_name_specifier_is_current_class)
9769           << SS.getRange();
9770         return true;
9771       }
9772 
9773       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
9774         Diag(SS.getRange().getBegin(),
9775              diag::err_using_decl_nested_name_specifier_is_not_base_class)
9776           << SS.getScopeRep()
9777           << cast<CXXRecordDecl>(CurContext)
9778           << SS.getRange();
9779       }
9780       return true;
9781     }
9782 
9783     return false;
9784   }
9785 
9786   // C++03 [namespace.udecl]p4:
9787   //   A using-declaration used as a member-declaration shall refer
9788   //   to a member of a base class of the class being defined [etc.].
9789 
9790   // Salient point: SS doesn't have to name a base class as long as
9791   // lookup only finds members from base classes.  Therefore we can
9792   // diagnose here only if we can prove that that can't happen,
9793   // i.e. if the class hierarchies provably don't intersect.
9794 
9795   // TODO: it would be nice if "definitely valid" results were cached
9796   // in the UsingDecl and UsingShadowDecl so that these checks didn't
9797   // need to be repeated.
9798 
9799   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9800   auto Collect = [&Bases](const CXXRecordDecl *Base) {
9801     Bases.insert(Base);
9802     return true;
9803   };
9804 
9805   // Collect all bases. Return false if we find a dependent base.
9806   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
9807     return false;
9808 
9809   // Returns true if the base is dependent or is one of the accumulated base
9810   // classes.
9811   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9812     return !Bases.count(Base);
9813   };
9814 
9815   // Return false if the class has a dependent base or if it or one
9816   // of its bases is present in the base set of the current context.
9817   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9818       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
9819     return false;
9820 
9821   Diag(SS.getRange().getBegin(),
9822        diag::err_using_decl_nested_name_specifier_is_not_base_class)
9823     << SS.getScopeRep()
9824     << cast<CXXRecordDecl>(CurContext)
9825     << SS.getRange();
9826 
9827   return true;
9828 }
9829 
9830 Decl *Sema::ActOnAliasDeclaration(Scope *S,
9831                                   AccessSpecifier AS,
9832                                   MultiTemplateParamsArg TemplateParamLists,
9833                                   SourceLocation UsingLoc,
9834                                   UnqualifiedId &Name,
9835                                   AttributeList *AttrList,
9836                                   TypeResult Type,
9837                                   Decl *DeclFromDeclSpec) {
9838   // Skip up to the relevant declaration scope.
9839   while (S->isTemplateParamScope())
9840     S = S->getParent();
9841   assert((S->getFlags() & Scope::DeclScope) &&
9842          "got alias-declaration outside of declaration scope");
9843 
9844   if (Type.isInvalid())
9845     return nullptr;
9846 
9847   bool Invalid = false;
9848   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
9849   TypeSourceInfo *TInfo = nullptr;
9850   GetTypeFromParser(Type.get(), &TInfo);
9851 
9852   if (DiagnoseClassNameShadow(CurContext, NameInfo))
9853     return nullptr;
9854 
9855   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
9856                                       UPPC_DeclarationType)) {
9857     Invalid = true;
9858     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9859                                              TInfo->getTypeLoc().getBeginLoc());
9860   }
9861 
9862   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9863   LookupName(Previous, S);
9864 
9865   // Warn about shadowing the name of a template parameter.
9866   if (Previous.isSingleResult() &&
9867       Previous.getFoundDecl()->isTemplateParameter()) {
9868     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
9869     Previous.clear();
9870   }
9871 
9872   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9873          "name in alias declaration must be an identifier");
9874   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9875                                                Name.StartLocation,
9876                                                Name.Identifier, TInfo);
9877 
9878   NewTD->setAccess(AS);
9879 
9880   if (Invalid)
9881     NewTD->setInvalidDecl();
9882 
9883   ProcessDeclAttributeList(S, NewTD, AttrList);
9884 
9885   CheckTypedefForVariablyModifiedType(S, NewTD);
9886   Invalid |= NewTD->isInvalidDecl();
9887 
9888   bool Redeclaration = false;
9889 
9890   NamedDecl *NewND;
9891   if (TemplateParamLists.size()) {
9892     TypeAliasTemplateDecl *OldDecl = nullptr;
9893     TemplateParameterList *OldTemplateParams = nullptr;
9894 
9895     if (TemplateParamLists.size() != 1) {
9896       Diag(UsingLoc, diag::err_alias_template_extra_headers)
9897         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
9898          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
9899     }
9900     TemplateParameterList *TemplateParams = TemplateParamLists[0];
9901 
9902     // Check that we can declare a template here.
9903     if (CheckTemplateDeclScope(S, TemplateParams))
9904       return nullptr;
9905 
9906     // Only consider previous declarations in the same scope.
9907     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
9908                          /*ExplicitInstantiationOrSpecialization*/false);
9909     if (!Previous.empty()) {
9910       Redeclaration = true;
9911 
9912       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
9913       if (!OldDecl && !Invalid) {
9914         Diag(UsingLoc, diag::err_redefinition_different_kind)
9915           << Name.Identifier;
9916 
9917         NamedDecl *OldD = Previous.getRepresentativeDecl();
9918         if (OldD->getLocation().isValid())
9919           Diag(OldD->getLocation(), diag::note_previous_definition);
9920 
9921         Invalid = true;
9922       }
9923 
9924       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
9925         if (TemplateParameterListsAreEqual(TemplateParams,
9926                                            OldDecl->getTemplateParameters(),
9927                                            /*Complain=*/true,
9928                                            TPL_TemplateMatch))
9929           OldTemplateParams = OldDecl->getTemplateParameters();
9930         else
9931           Invalid = true;
9932 
9933         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
9934         if (!Invalid &&
9935             !Context.hasSameType(OldTD->getUnderlyingType(),
9936                                  NewTD->getUnderlyingType())) {
9937           // FIXME: The C++0x standard does not clearly say this is ill-formed,
9938           // but we can't reasonably accept it.
9939           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
9940             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
9941           if (OldTD->getLocation().isValid())
9942             Diag(OldTD->getLocation(), diag::note_previous_definition);
9943           Invalid = true;
9944         }
9945       }
9946     }
9947 
9948     // Merge any previous default template arguments into our parameters,
9949     // and check the parameter list.
9950     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
9951                                    TPC_TypeAliasTemplate))
9952       return nullptr;
9953 
9954     TypeAliasTemplateDecl *NewDecl =
9955       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
9956                                     Name.Identifier, TemplateParams,
9957                                     NewTD);
9958     NewTD->setDescribedAliasTemplate(NewDecl);
9959 
9960     NewDecl->setAccess(AS);
9961 
9962     if (Invalid)
9963       NewDecl->setInvalidDecl();
9964     else if (OldDecl)
9965       NewDecl->setPreviousDecl(OldDecl);
9966 
9967     NewND = NewDecl;
9968   } else {
9969     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
9970       setTagNameForLinkagePurposes(TD, NewTD);
9971       handleTagNumbering(TD, S);
9972     }
9973     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
9974     NewND = NewTD;
9975   }
9976 
9977   PushOnScopeChains(NewND, S);
9978   ActOnDocumentableDecl(NewND);
9979   return NewND;
9980 }
9981 
9982 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
9983                                    SourceLocation AliasLoc,
9984                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
9985                                    SourceLocation IdentLoc,
9986                                    IdentifierInfo *Ident) {
9987 
9988   // Lookup the namespace name.
9989   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
9990   LookupParsedName(R, S, &SS);
9991 
9992   if (R.isAmbiguous())
9993     return nullptr;
9994 
9995   if (R.empty()) {
9996     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
9997       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9998       return nullptr;
9999     }
10000   }
10001   assert(!R.isAmbiguous() && !R.empty());
10002   NamedDecl *ND = R.getRepresentativeDecl();
10003 
10004   // Check if we have a previous declaration with the same name.
10005   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10006                      ForRedeclaration);
10007   LookupName(PrevR, S);
10008 
10009   // Check we're not shadowing a template parameter.
10010   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10011     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10012     PrevR.clear();
10013   }
10014 
10015   // Filter out any other lookup result from an enclosing scope.
10016   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10017                        /*AllowInlineNamespace*/false);
10018 
10019   // Find the previous declaration and check that we can redeclare it.
10020   NamespaceAliasDecl *Prev = nullptr;
10021   if (PrevR.isSingleResult()) {
10022     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10023     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10024       // We already have an alias with the same name that points to the same
10025       // namespace; check that it matches.
10026       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10027         Prev = AD;
10028       } else if (isVisible(PrevDecl)) {
10029         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10030           << Alias;
10031         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10032           << AD->getNamespace();
10033         return nullptr;
10034       }
10035     } else if (isVisible(PrevDecl)) {
10036       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10037                             ? diag::err_redefinition
10038                             : diag::err_redefinition_different_kind;
10039       Diag(AliasLoc, DiagID) << Alias;
10040       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10041       return nullptr;
10042     }
10043   }
10044 
10045   // The use of a nested name specifier may trigger deprecation warnings.
10046   DiagnoseUseOfDecl(ND, IdentLoc);
10047 
10048   NamespaceAliasDecl *AliasDecl =
10049     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10050                                Alias, SS.getWithLocInContext(Context),
10051                                IdentLoc, ND);
10052   if (Prev)
10053     AliasDecl->setPreviousDecl(Prev);
10054 
10055   PushOnScopeChains(AliasDecl, S);
10056   return AliasDecl;
10057 }
10058 
10059 namespace {
10060 struct SpecialMemberExceptionSpecInfo
10061     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10062   SourceLocation Loc;
10063   Sema::ImplicitExceptionSpecification ExceptSpec;
10064 
10065   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10066                                  Sema::CXXSpecialMember CSM,
10067                                  Sema::InheritedConstructorInfo *ICI,
10068                                  SourceLocation Loc)
10069       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10070 
10071   void visitBase(CXXBaseSpecifier *Base);
10072   void visitField(FieldDecl *FD);
10073 
10074   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10075                            unsigned Quals);
10076 
10077   void visitSubobjectCall(Subobject Subobj,
10078                           Sema::SpecialMemberOverloadResult SMOR);
10079 };
10080 }
10081 
10082 void SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10083   auto *RT = Base->getType()->getAs<RecordType>();
10084   if (!RT)
10085     return;
10086 
10087   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10088   if (ICI) {
10089     assert(CSM == Sema::CXXDefaultConstructor);
10090     if (auto *BaseCtor = ICI->findConstructorForBase(
10091                                 BaseClass, cast<CXXConstructorDecl>(MD)
10092                                                ->getInheritedConstructor()
10093                                                .getConstructor())
10094                              .first)
10095       return visitSubobjectCall(Base, BaseCtor);
10096   }
10097 
10098   visitClassSubobject(BaseClass, Base, 0);
10099 }
10100 
10101 void SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10102   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10103     Expr *E = FD->getInClassInitializer();
10104     if (!E)
10105       // FIXME: It's a little wasteful to build and throw away a
10106       // CXXDefaultInitExpr here.
10107       // FIXME: We should have a single context note pointing at Loc, and
10108       // this location should be MD->getLocation() instead, since that's
10109       // the location where we actually use the default init expression.
10110       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10111     if (E)
10112       ExceptSpec.CalledExpr(E);
10113   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10114                             ->getAs<RecordType>()) {
10115     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10116                         FD->getType().getCVRQualifiers());
10117   }
10118 }
10119 
10120 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10121                                                          Subobject Subobj,
10122                                                          unsigned Quals) {
10123   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10124   bool IsMutable = Field && Field->isMutable();
10125   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10126 }
10127 
10128 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10129     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10130   // Note, if lookup fails, it doesn't matter what exception specification we
10131   // choose because the special member will be deleted.
10132   if (CXXMethodDecl *MD = SMOR.getMethod())
10133     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10134 }
10135 
10136 static Sema::ImplicitExceptionSpecification
10137 ComputeDefaultedSpecialMemberExceptionSpec(
10138     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10139     Sema::InheritedConstructorInfo *ICI) {
10140   CXXRecordDecl *ClassDecl = MD->getParent();
10141 
10142   // C++ [except.spec]p14:
10143   //   An implicitly declared special member function (Clause 12) shall have an
10144   //   exception-specification. [...]
10145   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc);
10146   if (ClassDecl->isInvalidDecl())
10147     return Info.ExceptSpec;
10148 
10149   // Direct base-class constructors.
10150   for (auto &B : ClassDecl->bases())
10151     if (!B.isVirtual()) // Handled below.
10152       Info.visitBase(&B);
10153 
10154   // Virtual base-class constructors.
10155   // FIXME: Implement potentially-constructed subobjects rule.
10156   for (auto &B : ClassDecl->vbases())
10157     Info.visitBase(&B);
10158 
10159   // Field constructors.
10160   for (auto *F : ClassDecl->fields())
10161     Info.visitField(F);
10162 
10163   return Info.ExceptSpec;
10164 }
10165 
10166 namespace {
10167 /// RAII object to register a special member as being currently declared.
10168 struct DeclaringSpecialMember {
10169   Sema &S;
10170   Sema::SpecialMemberDecl D;
10171   Sema::ContextRAII SavedContext;
10172   bool WasAlreadyBeingDeclared;
10173 
10174   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10175       : S(S), D(RD, CSM), SavedContext(S, RD) {
10176     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10177     if (WasAlreadyBeingDeclared)
10178       // This almost never happens, but if it does, ensure that our cache
10179       // doesn't contain a stale result.
10180       S.SpecialMemberCache.clear();
10181     else {
10182       // Register a note to be produced if we encounter an error while
10183       // declaring the special member.
10184       Sema::CodeSynthesisContext Ctx;
10185       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10186       // FIXME: We don't have a location to use here. Using the class's
10187       // location maintains the fiction that we declare all special members
10188       // with the class, but (1) it's not clear that lying about that helps our
10189       // users understand what's going on, and (2) there may be outer contexts
10190       // on the stack (some of which are relevant) and printing them exposes
10191       // our lies.
10192       Ctx.PointOfInstantiation = RD->getLocation();
10193       Ctx.Entity = RD;
10194       Ctx.SpecialMember = CSM;
10195       S.pushCodeSynthesisContext(Ctx);
10196     }
10197   }
10198   ~DeclaringSpecialMember() {
10199     if (!WasAlreadyBeingDeclared) {
10200       S.SpecialMembersBeingDeclared.erase(D);
10201       S.popCodeSynthesisContext();
10202     }
10203   }
10204 
10205   /// \brief Are we already trying to declare this special member?
10206   bool isAlreadyBeingDeclared() const {
10207     return WasAlreadyBeingDeclared;
10208   }
10209 };
10210 }
10211 
10212 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10213   // Look up any existing declarations, but don't trigger declaration of all
10214   // implicit special members with this name.
10215   DeclarationName Name = FD->getDeclName();
10216   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10217                  ForRedeclaration);
10218   for (auto *D : FD->getParent()->lookup(Name))
10219     if (auto *Acceptable = R.getAcceptableDecl(D))
10220       R.addDecl(Acceptable);
10221   R.resolveKind();
10222   R.suppressDiagnostics();
10223 
10224   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10225 }
10226 
10227 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10228                                                      CXXRecordDecl *ClassDecl) {
10229   // C++ [class.ctor]p5:
10230   //   A default constructor for a class X is a constructor of class X
10231   //   that can be called without an argument. If there is no
10232   //   user-declared constructor for class X, a default constructor is
10233   //   implicitly declared. An implicitly-declared default constructor
10234   //   is an inline public member of its class.
10235   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10236          "Should not build implicit default constructor!");
10237 
10238   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10239   if (DSM.isAlreadyBeingDeclared())
10240     return nullptr;
10241 
10242   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10243                                                      CXXDefaultConstructor,
10244                                                      false);
10245 
10246   // Create the actual constructor declaration.
10247   CanQualType ClassType
10248     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10249   SourceLocation ClassLoc = ClassDecl->getLocation();
10250   DeclarationName Name
10251     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10252   DeclarationNameInfo NameInfo(Name, ClassLoc);
10253   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10254       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10255       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10256       /*isImplicitlyDeclared=*/true, Constexpr);
10257   DefaultCon->setAccess(AS_public);
10258   DefaultCon->setDefaulted();
10259 
10260   if (getLangOpts().CUDA) {
10261     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10262                                             DefaultCon,
10263                                             /* ConstRHS */ false,
10264                                             /* Diagnose */ false);
10265   }
10266 
10267   // Build an exception specification pointing back at this constructor.
10268   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10269   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10270 
10271   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10272   // constructors is easy to compute.
10273   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10274 
10275   // Note that we have declared this constructor.
10276   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10277 
10278   Scope *S = getScopeForContext(ClassDecl);
10279   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10280 
10281   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10282     SetDeclDeleted(DefaultCon, ClassLoc);
10283 
10284   if (S)
10285     PushOnScopeChains(DefaultCon, S, false);
10286   ClassDecl->addDecl(DefaultCon);
10287 
10288   return DefaultCon;
10289 }
10290 
10291 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10292                                             CXXConstructorDecl *Constructor) {
10293   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10294           !Constructor->doesThisDeclarationHaveABody() &&
10295           !Constructor->isDeleted()) &&
10296     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10297 
10298   CXXRecordDecl *ClassDecl = Constructor->getParent();
10299   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10300 
10301   SynthesizedFunctionScope Scope(*this, Constructor);
10302   DiagnosticErrorTrap Trap(Diags);
10303   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
10304       Trap.hasErrorOccurred()) {
10305     Diag(CurrentLocation, diag::note_member_synthesized_at)
10306       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
10307     Constructor->setInvalidDecl();
10308     return;
10309   }
10310 
10311   // The exception specification is needed because we are defining the
10312   // function.
10313   ResolveExceptionSpec(CurrentLocation,
10314                        Constructor->getType()->castAs<FunctionProtoType>());
10315 
10316   SourceLocation Loc = Constructor->getLocEnd().isValid()
10317                            ? Constructor->getLocEnd()
10318                            : Constructor->getLocation();
10319   Constructor->setBody(new (Context) CompoundStmt(Loc));
10320 
10321   Constructor->markUsed(Context);
10322   MarkVTableUsed(CurrentLocation, ClassDecl);
10323 
10324   if (ASTMutationListener *L = getASTMutationListener()) {
10325     L->CompletedImplicitDefinition(Constructor);
10326   }
10327 
10328   DiagnoseUninitializedFields(*this, Constructor);
10329 }
10330 
10331 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10332   // Perform any delayed checks on exception specifications.
10333   CheckDelayedMemberExceptionSpecs();
10334 }
10335 
10336 /// Find or create the fake constructor we synthesize to model constructing an
10337 /// object of a derived class via a constructor of a base class.
10338 CXXConstructorDecl *
10339 Sema::findInheritingConstructor(SourceLocation Loc,
10340                                 CXXConstructorDecl *BaseCtor,
10341                                 ConstructorUsingShadowDecl *Shadow) {
10342   CXXRecordDecl *Derived = Shadow->getParent();
10343   SourceLocation UsingLoc = Shadow->getLocation();
10344 
10345   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10346   // For now we use the name of the base class constructor as a member of the
10347   // derived class to indicate a (fake) inherited constructor name.
10348   DeclarationName Name = BaseCtor->getDeclName();
10349 
10350   // Check to see if we already have a fake constructor for this inherited
10351   // constructor call.
10352   for (NamedDecl *Ctor : Derived->lookup(Name))
10353     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10354                                ->getInheritedConstructor()
10355                                .getConstructor(),
10356                            BaseCtor))
10357       return cast<CXXConstructorDecl>(Ctor);
10358 
10359   DeclarationNameInfo NameInfo(Name, UsingLoc);
10360   TypeSourceInfo *TInfo =
10361       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10362   FunctionProtoTypeLoc ProtoLoc =
10363       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10364 
10365   // Check the inherited constructor is valid and find the list of base classes
10366   // from which it was inherited.
10367   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10368 
10369   bool Constexpr =
10370       BaseCtor->isConstexpr() &&
10371       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10372                                         false, BaseCtor, &ICI);
10373 
10374   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10375       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10376       BaseCtor->isExplicit(), /*Inline=*/true,
10377       /*ImplicitlyDeclared=*/true, Constexpr,
10378       InheritedConstructor(Shadow, BaseCtor));
10379   if (Shadow->isInvalidDecl())
10380     DerivedCtor->setInvalidDecl();
10381 
10382   // Build an unevaluated exception specification for this fake constructor.
10383   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10384   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10385   EPI.ExceptionSpec.Type = EST_Unevaluated;
10386   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10387   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10388                                                FPT->getParamTypes(), EPI));
10389 
10390   // Build the parameter declarations.
10391   SmallVector<ParmVarDecl *, 16> ParamDecls;
10392   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10393     TypeSourceInfo *TInfo =
10394         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10395     ParmVarDecl *PD = ParmVarDecl::Create(
10396         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10397         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10398     PD->setScopeInfo(0, I);
10399     PD->setImplicit();
10400     // Ensure attributes are propagated onto parameters (this matters for
10401     // format, pass_object_size, ...).
10402     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10403     ParamDecls.push_back(PD);
10404     ProtoLoc.setParam(I, PD);
10405   }
10406 
10407   // Set up the new constructor.
10408   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10409   DerivedCtor->setAccess(BaseCtor->getAccess());
10410   DerivedCtor->setParams(ParamDecls);
10411   Derived->addDecl(DerivedCtor);
10412 
10413   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10414     SetDeclDeleted(DerivedCtor, UsingLoc);
10415 
10416   return DerivedCtor;
10417 }
10418 
10419 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10420   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10421                                Ctor->getInheritedConstructor().getShadowDecl());
10422   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10423                             /*Diagnose*/true);
10424 }
10425 
10426 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10427                                        CXXConstructorDecl *Constructor) {
10428   CXXRecordDecl *ClassDecl = Constructor->getParent();
10429   assert(Constructor->getInheritedConstructor() &&
10430          !Constructor->doesThisDeclarationHaveABody() &&
10431          !Constructor->isDeleted());
10432   if (Constructor->isInvalidDecl())
10433     return;
10434 
10435   ConstructorUsingShadowDecl *Shadow =
10436       Constructor->getInheritedConstructor().getShadowDecl();
10437   CXXConstructorDecl *InheritedCtor =
10438       Constructor->getInheritedConstructor().getConstructor();
10439 
10440   // [class.inhctor.init]p1:
10441   //   initialization proceeds as if a defaulted default constructor is used to
10442   //   initialize the D object and each base class subobject from which the
10443   //   constructor was inherited
10444 
10445   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10446   CXXRecordDecl *RD = Shadow->getParent();
10447   SourceLocation InitLoc = Shadow->getLocation();
10448 
10449   // Initializations are performed "as if by a defaulted default constructor",
10450   // so enter the appropriate scope.
10451   SynthesizedFunctionScope Scope(*this, Constructor);
10452   DiagnosticErrorTrap Trap(Diags);
10453 
10454   // Build explicit initializers for all base classes from which the
10455   // constructor was inherited.
10456   SmallVector<CXXCtorInitializer*, 8> Inits;
10457   for (bool VBase : {false, true}) {
10458     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10459       if (B.isVirtual() != VBase)
10460         continue;
10461 
10462       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10463       if (!BaseRD)
10464         continue;
10465 
10466       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10467       if (!BaseCtor.first)
10468         continue;
10469 
10470       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10471       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10472           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10473 
10474       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10475       Inits.push_back(new (Context) CXXCtorInitializer(
10476           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10477           SourceLocation()));
10478     }
10479   }
10480 
10481   // We now proceed as if for a defaulted default constructor, with the relevant
10482   // initializers replaced.
10483 
10484   bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
10485   if (HadError || Trap.hasErrorOccurred()) {
10486     Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
10487     Constructor->setInvalidDecl();
10488     return;
10489   }
10490 
10491   // The exception specification is needed because we are defining the
10492   // function.
10493   ResolveExceptionSpec(CurrentLocation,
10494                        Constructor->getType()->castAs<FunctionProtoType>());
10495 
10496   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
10497 
10498   Constructor->markUsed(Context);
10499   MarkVTableUsed(CurrentLocation, ClassDecl);
10500 
10501   if (ASTMutationListener *L = getASTMutationListener()) {
10502     L->CompletedImplicitDefinition(Constructor);
10503   }
10504 
10505   DiagnoseUninitializedFields(*this, Constructor);
10506 }
10507 
10508 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10509   // C++ [class.dtor]p2:
10510   //   If a class has no user-declared destructor, a destructor is
10511   //   declared implicitly. An implicitly-declared destructor is an
10512   //   inline public member of its class.
10513   assert(ClassDecl->needsImplicitDestructor());
10514 
10515   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10516   if (DSM.isAlreadyBeingDeclared())
10517     return nullptr;
10518 
10519   // Create the actual destructor declaration.
10520   CanQualType ClassType
10521     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10522   SourceLocation ClassLoc = ClassDecl->getLocation();
10523   DeclarationName Name
10524     = Context.DeclarationNames.getCXXDestructorName(ClassType);
10525   DeclarationNameInfo NameInfo(Name, ClassLoc);
10526   CXXDestructorDecl *Destructor
10527       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
10528                                   QualType(), nullptr, /*isInline=*/true,
10529                                   /*isImplicitlyDeclared=*/true);
10530   Destructor->setAccess(AS_public);
10531   Destructor->setDefaulted();
10532 
10533   if (getLangOpts().CUDA) {
10534     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10535                                             Destructor,
10536                                             /* ConstRHS */ false,
10537                                             /* Diagnose */ false);
10538   }
10539 
10540   // Build an exception specification pointing back at this destructor.
10541   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
10542   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10543 
10544   // We don't need to use SpecialMemberIsTrivial here; triviality for
10545   // destructors is easy to compute.
10546   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10547 
10548   // Note that we have declared this destructor.
10549   ++ASTContext::NumImplicitDestructorsDeclared;
10550 
10551   Scope *S = getScopeForContext(ClassDecl);
10552   CheckImplicitSpecialMemberDeclaration(S, Destructor);
10553 
10554   // We can't check whether an implicit destructor is deleted before we complete
10555   // the definition of the class, because its validity depends on the alignment
10556   // of the class. We'll check this from ActOnFields once the class is complete.
10557   if (ClassDecl->isCompleteDefinition() &&
10558       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
10559     SetDeclDeleted(Destructor, ClassLoc);
10560 
10561   // Introduce this destructor into its scope.
10562   if (S)
10563     PushOnScopeChains(Destructor, S, false);
10564   ClassDecl->addDecl(Destructor);
10565 
10566   return Destructor;
10567 }
10568 
10569 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
10570                                     CXXDestructorDecl *Destructor) {
10571   assert((Destructor->isDefaulted() &&
10572           !Destructor->doesThisDeclarationHaveABody() &&
10573           !Destructor->isDeleted()) &&
10574          "DefineImplicitDestructor - call it for implicit default dtor");
10575   CXXRecordDecl *ClassDecl = Destructor->getParent();
10576   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
10577 
10578   if (Destructor->isInvalidDecl())
10579     return;
10580 
10581   SynthesizedFunctionScope Scope(*this, Destructor);
10582 
10583   DiagnosticErrorTrap Trap(Diags);
10584   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10585                                          Destructor->getParent());
10586 
10587   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
10588     Diag(CurrentLocation, diag::note_member_synthesized_at)
10589       << CXXDestructor << Context.getTagDeclType(ClassDecl);
10590 
10591     Destructor->setInvalidDecl();
10592     return;
10593   }
10594 
10595   // The exception specification is needed because we are defining the
10596   // function.
10597   ResolveExceptionSpec(CurrentLocation,
10598                        Destructor->getType()->castAs<FunctionProtoType>());
10599 
10600   SourceLocation Loc = Destructor->getLocEnd().isValid()
10601                            ? Destructor->getLocEnd()
10602                            : Destructor->getLocation();
10603   Destructor->setBody(new (Context) CompoundStmt(Loc));
10604   Destructor->markUsed(Context);
10605   MarkVTableUsed(CurrentLocation, ClassDecl);
10606 
10607   if (ASTMutationListener *L = getASTMutationListener()) {
10608     L->CompletedImplicitDefinition(Destructor);
10609   }
10610 }
10611 
10612 /// \brief Perform any semantic analysis which needs to be delayed until all
10613 /// pending class member declarations have been parsed.
10614 void Sema::ActOnFinishCXXMemberDecls() {
10615   // If the context is an invalid C++ class, just suppress these checks.
10616   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10617     if (Record->isInvalidDecl()) {
10618       DelayedDefaultedMemberExceptionSpecs.clear();
10619       DelayedExceptionSpecChecks.clear();
10620       return;
10621     }
10622     checkForMultipleExportedDefaultConstructors(*this, Record);
10623   }
10624 }
10625 
10626 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
10627   referenceDLLExportedClassMethods();
10628 }
10629 
10630 void Sema::referenceDLLExportedClassMethods() {
10631   if (!DelayedDllExportClasses.empty()) {
10632     // Calling ReferenceDllExportedMethods might cause the current function to
10633     // be called again, so use a local copy of DelayedDllExportClasses.
10634     SmallVector<CXXRecordDecl *, 4> WorkList;
10635     std::swap(DelayedDllExportClasses, WorkList);
10636     for (CXXRecordDecl *Class : WorkList)
10637       ReferenceDllExportedMethods(*this, Class);
10638   }
10639 }
10640 
10641 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10642                                          CXXDestructorDecl *Destructor) {
10643   assert(getLangOpts().CPlusPlus11 &&
10644          "adjusting dtor exception specs was introduced in c++11");
10645 
10646   // C++11 [class.dtor]p3:
10647   //   A declaration of a destructor that does not have an exception-
10648   //   specification is implicitly considered to have the same exception-
10649   //   specification as an implicit declaration.
10650   const FunctionProtoType *DtorType = Destructor->getType()->
10651                                         getAs<FunctionProtoType>();
10652   if (DtorType->hasExceptionSpec())
10653     return;
10654 
10655   // Replace the destructor's type, building off the existing one. Fortunately,
10656   // the only thing of interest in the destructor type is its extended info.
10657   // The return and arguments are fixed.
10658   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
10659   EPI.ExceptionSpec.Type = EST_Unevaluated;
10660   EPI.ExceptionSpec.SourceDecl = Destructor;
10661   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10662 
10663   // FIXME: If the destructor has a body that could throw, and the newly created
10664   // spec doesn't allow exceptions, we should emit a warning, because this
10665   // change in behavior can break conforming C++03 programs at runtime.
10666   // However, we don't have a body or an exception specification yet, so it
10667   // needs to be done somewhere else.
10668 }
10669 
10670 namespace {
10671 /// \brief An abstract base class for all helper classes used in building the
10672 //  copy/move operators. These classes serve as factory functions and help us
10673 //  avoid using the same Expr* in the AST twice.
10674 class ExprBuilder {
10675   ExprBuilder(const ExprBuilder&) = delete;
10676   ExprBuilder &operator=(const ExprBuilder&) = delete;
10677 
10678 protected:
10679   static Expr *assertNotNull(Expr *E) {
10680     assert(E && "Expression construction must not fail.");
10681     return E;
10682   }
10683 
10684 public:
10685   ExprBuilder() {}
10686   virtual ~ExprBuilder() {}
10687 
10688   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10689 };
10690 
10691 class RefBuilder: public ExprBuilder {
10692   VarDecl *Var;
10693   QualType VarType;
10694 
10695 public:
10696   Expr *build(Sema &S, SourceLocation Loc) const override {
10697     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
10698   }
10699 
10700   RefBuilder(VarDecl *Var, QualType VarType)
10701       : Var(Var), VarType(VarType) {}
10702 };
10703 
10704 class ThisBuilder: public ExprBuilder {
10705 public:
10706   Expr *build(Sema &S, SourceLocation Loc) const override {
10707     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
10708   }
10709 };
10710 
10711 class CastBuilder: public ExprBuilder {
10712   const ExprBuilder &Builder;
10713   QualType Type;
10714   ExprValueKind Kind;
10715   const CXXCastPath &Path;
10716 
10717 public:
10718   Expr *build(Sema &S, SourceLocation Loc) const override {
10719     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10720                                              CK_UncheckedDerivedToBase, Kind,
10721                                              &Path).get());
10722   }
10723 
10724   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10725               const CXXCastPath &Path)
10726       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10727 };
10728 
10729 class DerefBuilder: public ExprBuilder {
10730   const ExprBuilder &Builder;
10731 
10732 public:
10733   Expr *build(Sema &S, SourceLocation Loc) const override {
10734     return assertNotNull(
10735         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
10736   }
10737 
10738   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10739 };
10740 
10741 class MemberBuilder: public ExprBuilder {
10742   const ExprBuilder &Builder;
10743   QualType Type;
10744   CXXScopeSpec SS;
10745   bool IsArrow;
10746   LookupResult &MemberLookup;
10747 
10748 public:
10749   Expr *build(Sema &S, SourceLocation Loc) const override {
10750     return assertNotNull(S.BuildMemberReferenceExpr(
10751         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
10752         nullptr, MemberLookup, nullptr, nullptr).get());
10753   }
10754 
10755   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10756                 LookupResult &MemberLookup)
10757       : Builder(Builder), Type(Type), IsArrow(IsArrow),
10758         MemberLookup(MemberLookup) {}
10759 };
10760 
10761 class MoveCastBuilder: public ExprBuilder {
10762   const ExprBuilder &Builder;
10763 
10764 public:
10765   Expr *build(Sema &S, SourceLocation Loc) const override {
10766     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10767   }
10768 
10769   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10770 };
10771 
10772 class LvalueConvBuilder: public ExprBuilder {
10773   const ExprBuilder &Builder;
10774 
10775 public:
10776   Expr *build(Sema &S, SourceLocation Loc) const override {
10777     return assertNotNull(
10778         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
10779   }
10780 
10781   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10782 };
10783 
10784 class SubscriptBuilder: public ExprBuilder {
10785   const ExprBuilder &Base;
10786   const ExprBuilder &Index;
10787 
10788 public:
10789   Expr *build(Sema &S, SourceLocation Loc) const override {
10790     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
10791         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
10792   }
10793 
10794   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10795       : Base(Base), Index(Index) {}
10796 };
10797 
10798 } // end anonymous namespace
10799 
10800 /// When generating a defaulted copy or move assignment operator, if a field
10801 /// should be copied with __builtin_memcpy rather than via explicit assignments,
10802 /// do so. This optimization only applies for arrays of scalars, and for arrays
10803 /// of class type where the selected copy/move-assignment operator is trivial.
10804 static StmtResult
10805 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
10806                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
10807   // Compute the size of the memory buffer to be copied.
10808   QualType SizeType = S.Context.getSizeType();
10809   llvm::APInt Size(S.Context.getTypeSize(SizeType),
10810                    S.Context.getTypeSizeInChars(T).getQuantity());
10811 
10812   // Take the address of the field references for "from" and "to". We
10813   // directly construct UnaryOperators here because semantic analysis
10814   // does not permit us to take the address of an xvalue.
10815   Expr *From = FromB.build(S, Loc);
10816   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10817                          S.Context.getPointerType(From->getType()),
10818                          VK_RValue, OK_Ordinary, Loc);
10819   Expr *To = ToB.build(S, Loc);
10820   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10821                        S.Context.getPointerType(To->getType()),
10822                        VK_RValue, OK_Ordinary, Loc);
10823 
10824   const Type *E = T->getBaseElementTypeUnsafe();
10825   bool NeedsCollectableMemCpy =
10826     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10827 
10828   // Create a reference to the __builtin_objc_memmove_collectable function
10829   StringRef MemCpyName = NeedsCollectableMemCpy ?
10830     "__builtin_objc_memmove_collectable" :
10831     "__builtin_memcpy";
10832   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10833                  Sema::LookupOrdinaryName);
10834   S.LookupName(R, S.TUScope, true);
10835 
10836   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10837   if (!MemCpy)
10838     // Something went horribly wrong earlier, and we will have complained
10839     // about it.
10840     return StmtError();
10841 
10842   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
10843                                             VK_RValue, Loc, nullptr);
10844   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10845 
10846   Expr *CallArgs[] = {
10847     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10848   };
10849   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
10850                                     Loc, CallArgs, Loc);
10851 
10852   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
10853   return Call.getAs<Stmt>();
10854 }
10855 
10856 /// \brief Builds a statement that copies/moves the given entity from \p From to
10857 /// \c To.
10858 ///
10859 /// This routine is used to copy/move the members of a class with an
10860 /// implicitly-declared copy/move assignment operator. When the entities being
10861 /// copied are arrays, this routine builds for loops to copy them.
10862 ///
10863 /// \param S The Sema object used for type-checking.
10864 ///
10865 /// \param Loc The location where the implicit copy/move is being generated.
10866 ///
10867 /// \param T The type of the expressions being copied/moved. Both expressions
10868 /// must have this type.
10869 ///
10870 /// \param To The expression we are copying/moving to.
10871 ///
10872 /// \param From The expression we are copying/moving from.
10873 ///
10874 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
10875 /// Otherwise, it's a non-static member subobject.
10876 ///
10877 /// \param Copying Whether we're copying or moving.
10878 ///
10879 /// \param Depth Internal parameter recording the depth of the recursion.
10880 ///
10881 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
10882 /// if a memcpy should be used instead.
10883 static StmtResult
10884 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
10885                                  const ExprBuilder &To, const ExprBuilder &From,
10886                                  bool CopyingBaseSubobject, bool Copying,
10887                                  unsigned Depth = 0) {
10888   // C++11 [class.copy]p28:
10889   //   Each subobject is assigned in the manner appropriate to its type:
10890   //
10891   //     - if the subobject is of class type, as if by a call to operator= with
10892   //       the subobject as the object expression and the corresponding
10893   //       subobject of x as a single function argument (as if by explicit
10894   //       qualification; that is, ignoring any possible virtual overriding
10895   //       functions in more derived classes);
10896   //
10897   // C++03 [class.copy]p13:
10898   //     - if the subobject is of class type, the copy assignment operator for
10899   //       the class is used (as if by explicit qualification; that is,
10900   //       ignoring any possible virtual overriding functions in more derived
10901   //       classes);
10902   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
10903     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
10904 
10905     // Look for operator=.
10906     DeclarationName Name
10907       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10908     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
10909     S.LookupQualifiedName(OpLookup, ClassDecl, false);
10910 
10911     // Prior to C++11, filter out any result that isn't a copy/move-assignment
10912     // operator.
10913     if (!S.getLangOpts().CPlusPlus11) {
10914       LookupResult::Filter F = OpLookup.makeFilter();
10915       while (F.hasNext()) {
10916         NamedDecl *D = F.next();
10917         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
10918           if (Method->isCopyAssignmentOperator() ||
10919               (!Copying && Method->isMoveAssignmentOperator()))
10920             continue;
10921 
10922         F.erase();
10923       }
10924       F.done();
10925     }
10926 
10927     // Suppress the protected check (C++ [class.protected]) for each of the
10928     // assignment operators we found. This strange dance is required when
10929     // we're assigning via a base classes's copy-assignment operator. To
10930     // ensure that we're getting the right base class subobject (without
10931     // ambiguities), we need to cast "this" to that subobject type; to
10932     // ensure that we don't go through the virtual call mechanism, we need
10933     // to qualify the operator= name with the base class (see below). However,
10934     // this means that if the base class has a protected copy assignment
10935     // operator, the protected member access check will fail. So, we
10936     // rewrite "protected" access to "public" access in this case, since we
10937     // know by construction that we're calling from a derived class.
10938     if (CopyingBaseSubobject) {
10939       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
10940            L != LEnd; ++L) {
10941         if (L.getAccess() == AS_protected)
10942           L.setAccess(AS_public);
10943       }
10944     }
10945 
10946     // Create the nested-name-specifier that will be used to qualify the
10947     // reference to operator=; this is required to suppress the virtual
10948     // call mechanism.
10949     CXXScopeSpec SS;
10950     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
10951     SS.MakeTrivial(S.Context,
10952                    NestedNameSpecifier::Create(S.Context, nullptr, false,
10953                                                CanonicalT),
10954                    Loc);
10955 
10956     // Create the reference to operator=.
10957     ExprResult OpEqualRef
10958       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
10959                                    SS, /*TemplateKWLoc=*/SourceLocation(),
10960                                    /*FirstQualifierInScope=*/nullptr,
10961                                    OpLookup,
10962                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
10963                                    /*SuppressQualifierCheck=*/true);
10964     if (OpEqualRef.isInvalid())
10965       return StmtError();
10966 
10967     // Build the call to the assignment operator.
10968 
10969     Expr *FromInst = From.build(S, Loc);
10970     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
10971                                                   OpEqualRef.getAs<Expr>(),
10972                                                   Loc, FromInst, Loc);
10973     if (Call.isInvalid())
10974       return StmtError();
10975 
10976     // If we built a call to a trivial 'operator=' while copying an array,
10977     // bail out. We'll replace the whole shebang with a memcpy.
10978     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
10979     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
10980       return StmtResult((Stmt*)nullptr);
10981 
10982     // Convert to an expression-statement, and clean up any produced
10983     // temporaries.
10984     return S.ActOnExprStmt(Call);
10985   }
10986 
10987   //     - if the subobject is of scalar type, the built-in assignment
10988   //       operator is used.
10989   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
10990   if (!ArrayTy) {
10991     ExprResult Assignment = S.CreateBuiltinBinOp(
10992         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
10993     if (Assignment.isInvalid())
10994       return StmtError();
10995     return S.ActOnExprStmt(Assignment);
10996   }
10997 
10998   //     - if the subobject is an array, each element is assigned, in the
10999   //       manner appropriate to the element type;
11000 
11001   // Construct a loop over the array bounds, e.g.,
11002   //
11003   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11004   //
11005   // that will copy each of the array elements.
11006   QualType SizeType = S.Context.getSizeType();
11007 
11008   // Create the iteration variable.
11009   IdentifierInfo *IterationVarName = nullptr;
11010   {
11011     SmallString<8> Str;
11012     llvm::raw_svector_ostream OS(Str);
11013     OS << "__i" << Depth;
11014     IterationVarName = &S.Context.Idents.get(OS.str());
11015   }
11016   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11017                                           IterationVarName, SizeType,
11018                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11019                                           SC_None);
11020 
11021   // Initialize the iteration variable to zero.
11022   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11023   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11024 
11025   // Creates a reference to the iteration variable.
11026   RefBuilder IterationVarRef(IterationVar, SizeType);
11027   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11028 
11029   // Create the DeclStmt that holds the iteration variable.
11030   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11031 
11032   // Subscript the "from" and "to" expressions with the iteration variable.
11033   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11034   MoveCastBuilder FromIndexMove(FromIndexCopy);
11035   const ExprBuilder *FromIndex;
11036   if (Copying)
11037     FromIndex = &FromIndexCopy;
11038   else
11039     FromIndex = &FromIndexMove;
11040 
11041   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11042 
11043   // Build the copy/move for an individual element of the array.
11044   StmtResult Copy =
11045     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11046                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11047                                      Copying, Depth + 1);
11048   // Bail out if copying fails or if we determined that we should use memcpy.
11049   if (Copy.isInvalid() || !Copy.get())
11050     return Copy;
11051 
11052   // Create the comparison against the array bound.
11053   llvm::APInt Upper
11054     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11055   Expr *Comparison
11056     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11057                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11058                                      BO_NE, S.Context.BoolTy,
11059                                      VK_RValue, OK_Ordinary, Loc, false);
11060 
11061   // Create the pre-increment of the iteration variable.
11062   Expr *Increment
11063     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
11064                                     SizeType, VK_LValue, OK_Ordinary, Loc);
11065 
11066   // Construct the loop that copies all elements of this array.
11067   return S.ActOnForStmt(
11068       Loc, Loc, InitStmt,
11069       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11070       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11071 }
11072 
11073 static StmtResult
11074 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11075                       const ExprBuilder &To, const ExprBuilder &From,
11076                       bool CopyingBaseSubobject, bool Copying) {
11077   // Maybe we should use a memcpy?
11078   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11079       T.isTriviallyCopyableType(S.Context))
11080     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11081 
11082   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11083                                                      CopyingBaseSubobject,
11084                                                      Copying, 0));
11085 
11086   // If we ended up picking a trivial assignment operator for an array of a
11087   // non-trivially-copyable class type, just emit a memcpy.
11088   if (!Result.isInvalid() && !Result.get())
11089     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11090 
11091   return Result;
11092 }
11093 
11094 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11095   // Note: The following rules are largely analoguous to the copy
11096   // constructor rules. Note that virtual bases are not taken into account
11097   // for determining the argument type of the operator. Note also that
11098   // operators taking an object instead of a reference are allowed.
11099   assert(ClassDecl->needsImplicitCopyAssignment());
11100 
11101   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11102   if (DSM.isAlreadyBeingDeclared())
11103     return nullptr;
11104 
11105   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11106   QualType RetType = Context.getLValueReferenceType(ArgType);
11107   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11108   if (Const)
11109     ArgType = ArgType.withConst();
11110   ArgType = Context.getLValueReferenceType(ArgType);
11111 
11112   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11113                                                      CXXCopyAssignment,
11114                                                      Const);
11115 
11116   //   An implicitly-declared copy assignment operator is an inline public
11117   //   member of its class.
11118   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11119   SourceLocation ClassLoc = ClassDecl->getLocation();
11120   DeclarationNameInfo NameInfo(Name, ClassLoc);
11121   CXXMethodDecl *CopyAssignment =
11122       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11123                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11124                             /*isInline=*/true, Constexpr, SourceLocation());
11125   CopyAssignment->setAccess(AS_public);
11126   CopyAssignment->setDefaulted();
11127   CopyAssignment->setImplicit();
11128 
11129   if (getLangOpts().CUDA) {
11130     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11131                                             CopyAssignment,
11132                                             /* ConstRHS */ Const,
11133                                             /* Diagnose */ false);
11134   }
11135 
11136   // Build an exception specification pointing back at this member.
11137   FunctionProtoType::ExtProtoInfo EPI =
11138       getImplicitMethodEPI(*this, CopyAssignment);
11139   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11140 
11141   // Add the parameter to the operator.
11142   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11143                                                ClassLoc, ClassLoc,
11144                                                /*Id=*/nullptr, ArgType,
11145                                                /*TInfo=*/nullptr, SC_None,
11146                                                nullptr);
11147   CopyAssignment->setParams(FromParam);
11148 
11149   CopyAssignment->setTrivial(
11150     ClassDecl->needsOverloadResolutionForCopyAssignment()
11151       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11152       : ClassDecl->hasTrivialCopyAssignment());
11153 
11154   // Note that we have added this copy-assignment operator.
11155   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11156 
11157   Scope *S = getScopeForContext(ClassDecl);
11158   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11159 
11160   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11161     SetDeclDeleted(CopyAssignment, ClassLoc);
11162 
11163   if (S)
11164     PushOnScopeChains(CopyAssignment, S, false);
11165   ClassDecl->addDecl(CopyAssignment);
11166 
11167   return CopyAssignment;
11168 }
11169 
11170 /// Diagnose an implicit copy operation for a class which is odr-used, but
11171 /// which is deprecated because the class has a user-declared copy constructor,
11172 /// copy assignment operator, or destructor.
11173 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
11174                                             SourceLocation UseLoc) {
11175   assert(CopyOp->isImplicit());
11176 
11177   CXXRecordDecl *RD = CopyOp->getParent();
11178   CXXMethodDecl *UserDeclaredOperation = nullptr;
11179 
11180   // In Microsoft mode, assignment operations don't affect constructors and
11181   // vice versa.
11182   if (RD->hasUserDeclaredDestructor()) {
11183     UserDeclaredOperation = RD->getDestructor();
11184   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11185              RD->hasUserDeclaredCopyConstructor() &&
11186              !S.getLangOpts().MSVCCompat) {
11187     // Find any user-declared copy constructor.
11188     for (auto *I : RD->ctors()) {
11189       if (I->isCopyConstructor()) {
11190         UserDeclaredOperation = I;
11191         break;
11192       }
11193     }
11194     assert(UserDeclaredOperation);
11195   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11196              RD->hasUserDeclaredCopyAssignment() &&
11197              !S.getLangOpts().MSVCCompat) {
11198     // Find any user-declared move assignment operator.
11199     for (auto *I : RD->methods()) {
11200       if (I->isCopyAssignmentOperator()) {
11201         UserDeclaredOperation = I;
11202         break;
11203       }
11204     }
11205     assert(UserDeclaredOperation);
11206   }
11207 
11208   if (UserDeclaredOperation) {
11209     S.Diag(UserDeclaredOperation->getLocation(),
11210          diag::warn_deprecated_copy_operation)
11211       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11212       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11213     S.Diag(UseLoc, diag::note_member_synthesized_at)
11214       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
11215                                           : Sema::CXXCopyAssignment)
11216       << RD;
11217   }
11218 }
11219 
11220 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11221                                         CXXMethodDecl *CopyAssignOperator) {
11222   assert((CopyAssignOperator->isDefaulted() &&
11223           CopyAssignOperator->isOverloadedOperator() &&
11224           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11225           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11226           !CopyAssignOperator->isDeleted()) &&
11227          "DefineImplicitCopyAssignment called for wrong function");
11228 
11229   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11230 
11231   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
11232     CopyAssignOperator->setInvalidDecl();
11233     return;
11234   }
11235 
11236   // C++11 [class.copy]p18:
11237   //   The [definition of an implicitly declared copy assignment operator] is
11238   //   deprecated if the class has a user-declared copy constructor or a
11239   //   user-declared destructor.
11240   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11241     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
11242 
11243   CopyAssignOperator->markUsed(Context);
11244 
11245   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11246   DiagnosticErrorTrap Trap(Diags);
11247 
11248   // C++0x [class.copy]p30:
11249   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11250   //   for a non-union class X performs memberwise copy assignment of its
11251   //   subobjects. The direct base classes of X are assigned first, in the
11252   //   order of their declaration in the base-specifier-list, and then the
11253   //   immediate non-static data members of X are assigned, in the order in
11254   //   which they were declared in the class definition.
11255 
11256   // The statements that form the synthesized function body.
11257   SmallVector<Stmt*, 8> Statements;
11258 
11259   // The parameter for the "other" object, which we are copying from.
11260   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11261   Qualifiers OtherQuals = Other->getType().getQualifiers();
11262   QualType OtherRefType = Other->getType();
11263   if (const LValueReferenceType *OtherRef
11264                                 = OtherRefType->getAs<LValueReferenceType>()) {
11265     OtherRefType = OtherRef->getPointeeType();
11266     OtherQuals = OtherRefType.getQualifiers();
11267   }
11268 
11269   // Our location for everything implicitly-generated.
11270   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11271                            ? CopyAssignOperator->getLocEnd()
11272                            : CopyAssignOperator->getLocation();
11273 
11274   // Builds a DeclRefExpr for the "other" object.
11275   RefBuilder OtherRef(Other, OtherRefType);
11276 
11277   // Builds the "this" pointer.
11278   ThisBuilder This;
11279 
11280   // Assign base classes.
11281   bool Invalid = false;
11282   for (auto &Base : ClassDecl->bases()) {
11283     // Form the assignment:
11284     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11285     QualType BaseType = Base.getType().getUnqualifiedType();
11286     if (!BaseType->isRecordType()) {
11287       Invalid = true;
11288       continue;
11289     }
11290 
11291     CXXCastPath BasePath;
11292     BasePath.push_back(&Base);
11293 
11294     // Construct the "from" expression, which is an implicit cast to the
11295     // appropriately-qualified base type.
11296     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11297                      VK_LValue, BasePath);
11298 
11299     // Dereference "this".
11300     DerefBuilder DerefThis(This);
11301     CastBuilder To(DerefThis,
11302                    Context.getCVRQualifiedType(
11303                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11304                    VK_LValue, BasePath);
11305 
11306     // Build the copy.
11307     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11308                                             To, From,
11309                                             /*CopyingBaseSubobject=*/true,
11310                                             /*Copying=*/true);
11311     if (Copy.isInvalid()) {
11312       Diag(CurrentLocation, diag::note_member_synthesized_at)
11313         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11314       CopyAssignOperator->setInvalidDecl();
11315       return;
11316     }
11317 
11318     // Success! Record the copy.
11319     Statements.push_back(Copy.getAs<Expr>());
11320   }
11321 
11322   // Assign non-static members.
11323   for (auto *Field : ClassDecl->fields()) {
11324     // FIXME: We should form some kind of AST representation for the implied
11325     // memcpy in a union copy operation.
11326     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11327       continue;
11328 
11329     if (Field->isInvalidDecl()) {
11330       Invalid = true;
11331       continue;
11332     }
11333 
11334     // Check for members of reference type; we can't copy those.
11335     if (Field->getType()->isReferenceType()) {
11336       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11337         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11338       Diag(Field->getLocation(), diag::note_declared_at);
11339       Diag(CurrentLocation, diag::note_member_synthesized_at)
11340         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11341       Invalid = true;
11342       continue;
11343     }
11344 
11345     // Check for members of const-qualified, non-class type.
11346     QualType BaseType = Context.getBaseElementType(Field->getType());
11347     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11348       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11349         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11350       Diag(Field->getLocation(), diag::note_declared_at);
11351       Diag(CurrentLocation, diag::note_member_synthesized_at)
11352         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11353       Invalid = true;
11354       continue;
11355     }
11356 
11357     // Suppress assigning zero-width bitfields.
11358     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11359       continue;
11360 
11361     QualType FieldType = Field->getType().getNonReferenceType();
11362     if (FieldType->isIncompleteArrayType()) {
11363       assert(ClassDecl->hasFlexibleArrayMember() &&
11364              "Incomplete array type is not valid");
11365       continue;
11366     }
11367 
11368     // Build references to the field in the object we're copying from and to.
11369     CXXScopeSpec SS; // Intentionally empty
11370     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11371                               LookupMemberName);
11372     MemberLookup.addDecl(Field);
11373     MemberLookup.resolveKind();
11374 
11375     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11376 
11377     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11378 
11379     // Build the copy of this field.
11380     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11381                                             To, From,
11382                                             /*CopyingBaseSubobject=*/false,
11383                                             /*Copying=*/true);
11384     if (Copy.isInvalid()) {
11385       Diag(CurrentLocation, diag::note_member_synthesized_at)
11386         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11387       CopyAssignOperator->setInvalidDecl();
11388       return;
11389     }
11390 
11391     // Success! Record the copy.
11392     Statements.push_back(Copy.getAs<Stmt>());
11393   }
11394 
11395   if (!Invalid) {
11396     // Add a "return *this;"
11397     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11398 
11399     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11400     if (Return.isInvalid())
11401       Invalid = true;
11402     else {
11403       Statements.push_back(Return.getAs<Stmt>());
11404 
11405       if (Trap.hasErrorOccurred()) {
11406         Diag(CurrentLocation, diag::note_member_synthesized_at)
11407           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11408         Invalid = true;
11409       }
11410     }
11411   }
11412 
11413   // The exception specification is needed because we are defining the
11414   // function.
11415   ResolveExceptionSpec(CurrentLocation,
11416                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11417 
11418   if (Invalid) {
11419     CopyAssignOperator->setInvalidDecl();
11420     return;
11421   }
11422 
11423   StmtResult Body;
11424   {
11425     CompoundScopeRAII CompoundScope(*this);
11426     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11427                              /*isStmtExpr=*/false);
11428     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11429   }
11430   CopyAssignOperator->setBody(Body.getAs<Stmt>());
11431 
11432   if (ASTMutationListener *L = getASTMutationListener()) {
11433     L->CompletedImplicitDefinition(CopyAssignOperator);
11434   }
11435 }
11436 
11437 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11438   assert(ClassDecl->needsImplicitMoveAssignment());
11439 
11440   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11441   if (DSM.isAlreadyBeingDeclared())
11442     return nullptr;
11443 
11444   // Note: The following rules are largely analoguous to the move
11445   // constructor rules.
11446 
11447   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11448   QualType RetType = Context.getLValueReferenceType(ArgType);
11449   ArgType = Context.getRValueReferenceType(ArgType);
11450 
11451   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11452                                                      CXXMoveAssignment,
11453                                                      false);
11454 
11455   //   An implicitly-declared move assignment operator is an inline public
11456   //   member of its class.
11457   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11458   SourceLocation ClassLoc = ClassDecl->getLocation();
11459   DeclarationNameInfo NameInfo(Name, ClassLoc);
11460   CXXMethodDecl *MoveAssignment =
11461       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11462                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11463                             /*isInline=*/true, Constexpr, SourceLocation());
11464   MoveAssignment->setAccess(AS_public);
11465   MoveAssignment->setDefaulted();
11466   MoveAssignment->setImplicit();
11467 
11468   if (getLangOpts().CUDA) {
11469     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11470                                             MoveAssignment,
11471                                             /* ConstRHS */ false,
11472                                             /* Diagnose */ false);
11473   }
11474 
11475   // Build an exception specification pointing back at this member.
11476   FunctionProtoType::ExtProtoInfo EPI =
11477       getImplicitMethodEPI(*this, MoveAssignment);
11478   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11479 
11480   // Add the parameter to the operator.
11481   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
11482                                                ClassLoc, ClassLoc,
11483                                                /*Id=*/nullptr, ArgType,
11484                                                /*TInfo=*/nullptr, SC_None,
11485                                                nullptr);
11486   MoveAssignment->setParams(FromParam);
11487 
11488   MoveAssignment->setTrivial(
11489     ClassDecl->needsOverloadResolutionForMoveAssignment()
11490       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11491       : ClassDecl->hasTrivialMoveAssignment());
11492 
11493   // Note that we have added this copy-assignment operator.
11494   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11495 
11496   Scope *S = getScopeForContext(ClassDecl);
11497   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11498 
11499   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
11500     ClassDecl->setImplicitMoveAssignmentIsDeleted();
11501     SetDeclDeleted(MoveAssignment, ClassLoc);
11502   }
11503 
11504   if (S)
11505     PushOnScopeChains(MoveAssignment, S, false);
11506   ClassDecl->addDecl(MoveAssignment);
11507 
11508   return MoveAssignment;
11509 }
11510 
11511 /// Check if we're implicitly defining a move assignment operator for a class
11512 /// with virtual bases. Such a move assignment might move-assign the virtual
11513 /// base multiple times.
11514 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11515                                                SourceLocation CurrentLocation) {
11516   assert(!Class->isDependentContext() && "should not define dependent move");
11517 
11518   // Only a virtual base could get implicitly move-assigned multiple times.
11519   // Only a non-trivial move assignment can observe this. We only want to
11520   // diagnose if we implicitly define an assignment operator that assigns
11521   // two base classes, both of which move-assign the same virtual base.
11522   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11523       Class->getNumBases() < 2)
11524     return;
11525 
11526   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11527   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11528   VBaseMap VBases;
11529 
11530   for (auto &BI : Class->bases()) {
11531     Worklist.push_back(&BI);
11532     while (!Worklist.empty()) {
11533       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11534       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11535 
11536       // If the base has no non-trivial move assignment operators,
11537       // we don't care about moves from it.
11538       if (!Base->hasNonTrivialMoveAssignment())
11539         continue;
11540 
11541       // If there's nothing virtual here, skip it.
11542       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11543         continue;
11544 
11545       // If we're not actually going to call a move assignment for this base,
11546       // or the selected move assignment is trivial, skip it.
11547       Sema::SpecialMemberOverloadResult SMOR =
11548         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11549                               /*ConstArg*/false, /*VolatileArg*/false,
11550                               /*RValueThis*/true, /*ConstThis*/false,
11551                               /*VolatileThis*/false);
11552       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
11553           !SMOR.getMethod()->isMoveAssignmentOperator())
11554         continue;
11555 
11556       if (BaseSpec->isVirtual()) {
11557         // We're going to move-assign this virtual base, and its move
11558         // assignment operator is not trivial. If this can happen for
11559         // multiple distinct direct bases of Class, diagnose it. (If it
11560         // only happens in one base, we'll diagnose it when synthesizing
11561         // that base class's move assignment operator.)
11562         CXXBaseSpecifier *&Existing =
11563             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
11564                 .first->second;
11565         if (Existing && Existing != &BI) {
11566           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11567             << Class << Base;
11568           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11569             << (Base->getCanonicalDecl() ==
11570                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11571             << Base << Existing->getType() << Existing->getSourceRange();
11572           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
11573             << (Base->getCanonicalDecl() ==
11574                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11575             << Base << BI.getType() << BaseSpec->getSourceRange();
11576 
11577           // Only diagnose each vbase once.
11578           Existing = nullptr;
11579         }
11580       } else {
11581         // Only walk over bases that have defaulted move assignment operators.
11582         // We assume that any user-provided move assignment operator handles
11583         // the multiple-moves-of-vbase case itself somehow.
11584         if (!SMOR.getMethod()->isDefaulted())
11585           continue;
11586 
11587         // We're going to move the base classes of Base. Add them to the list.
11588         for (auto &BI : Base->bases())
11589           Worklist.push_back(&BI);
11590       }
11591     }
11592   }
11593 }
11594 
11595 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11596                                         CXXMethodDecl *MoveAssignOperator) {
11597   assert((MoveAssignOperator->isDefaulted() &&
11598           MoveAssignOperator->isOverloadedOperator() &&
11599           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
11600           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11601           !MoveAssignOperator->isDeleted()) &&
11602          "DefineImplicitMoveAssignment called for wrong function");
11603 
11604   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11605 
11606   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
11607     MoveAssignOperator->setInvalidDecl();
11608     return;
11609   }
11610 
11611   MoveAssignOperator->markUsed(Context);
11612 
11613   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
11614   DiagnosticErrorTrap Trap(Diags);
11615 
11616   // C++0x [class.copy]p28:
11617   //   The implicitly-defined or move assignment operator for a non-union class
11618   //   X performs memberwise move assignment of its subobjects. The direct base
11619   //   classes of X are assigned first, in the order of their declaration in the
11620   //   base-specifier-list, and then the immediate non-static data members of X
11621   //   are assigned, in the order in which they were declared in the class
11622   //   definition.
11623 
11624   // Issue a warning if our implicit move assignment operator will move
11625   // from a virtual base more than once.
11626   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
11627 
11628   // The statements that form the synthesized function body.
11629   SmallVector<Stmt*, 8> Statements;
11630 
11631   // The parameter for the "other" object, which we are move from.
11632   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11633   QualType OtherRefType = Other->getType()->
11634       getAs<RValueReferenceType>()->getPointeeType();
11635   assert(!OtherRefType.getQualifiers() &&
11636          "Bad argument type of defaulted move assignment");
11637 
11638   // Our location for everything implicitly-generated.
11639   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11640                            ? MoveAssignOperator->getLocEnd()
11641                            : MoveAssignOperator->getLocation();
11642 
11643   // Builds a reference to the "other" object.
11644   RefBuilder OtherRef(Other, OtherRefType);
11645   // Cast to rvalue.
11646   MoveCastBuilder MoveOther(OtherRef);
11647 
11648   // Builds the "this" pointer.
11649   ThisBuilder This;
11650 
11651   // Assign base classes.
11652   bool Invalid = false;
11653   for (auto &Base : ClassDecl->bases()) {
11654     // C++11 [class.copy]p28:
11655     //   It is unspecified whether subobjects representing virtual base classes
11656     //   are assigned more than once by the implicitly-defined copy assignment
11657     //   operator.
11658     // FIXME: Do not assign to a vbase that will be assigned by some other base
11659     // class. For a move-assignment, this can result in the vbase being moved
11660     // multiple times.
11661 
11662     // Form the assignment:
11663     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
11664     QualType BaseType = Base.getType().getUnqualifiedType();
11665     if (!BaseType->isRecordType()) {
11666       Invalid = true;
11667       continue;
11668     }
11669 
11670     CXXCastPath BasePath;
11671     BasePath.push_back(&Base);
11672 
11673     // Construct the "from" expression, which is an implicit cast to the
11674     // appropriately-qualified base type.
11675     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
11676 
11677     // Dereference "this".
11678     DerefBuilder DerefThis(This);
11679 
11680     // Implicitly cast "this" to the appropriately-qualified base type.
11681     CastBuilder To(DerefThis,
11682                    Context.getCVRQualifiedType(
11683                        BaseType, MoveAssignOperator->getTypeQualifiers()),
11684                    VK_LValue, BasePath);
11685 
11686     // Build the move.
11687     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
11688                                             To, From,
11689                                             /*CopyingBaseSubobject=*/true,
11690                                             /*Copying=*/false);
11691     if (Move.isInvalid()) {
11692       Diag(CurrentLocation, diag::note_member_synthesized_at)
11693         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11694       MoveAssignOperator->setInvalidDecl();
11695       return;
11696     }
11697 
11698     // Success! Record the move.
11699     Statements.push_back(Move.getAs<Expr>());
11700   }
11701 
11702   // Assign non-static members.
11703   for (auto *Field : ClassDecl->fields()) {
11704     // FIXME: We should form some kind of AST representation for the implied
11705     // memcpy in a union copy operation.
11706     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11707       continue;
11708 
11709     if (Field->isInvalidDecl()) {
11710       Invalid = true;
11711       continue;
11712     }
11713 
11714     // Check for members of reference type; we can't move those.
11715     if (Field->getType()->isReferenceType()) {
11716       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11717         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11718       Diag(Field->getLocation(), diag::note_declared_at);
11719       Diag(CurrentLocation, diag::note_member_synthesized_at)
11720         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11721       Invalid = true;
11722       continue;
11723     }
11724 
11725     // Check for members of const-qualified, non-class type.
11726     QualType BaseType = Context.getBaseElementType(Field->getType());
11727     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11728       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11729         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11730       Diag(Field->getLocation(), diag::note_declared_at);
11731       Diag(CurrentLocation, diag::note_member_synthesized_at)
11732         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11733       Invalid = true;
11734       continue;
11735     }
11736 
11737     // Suppress assigning zero-width bitfields.
11738     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11739       continue;
11740 
11741     QualType FieldType = Field->getType().getNonReferenceType();
11742     if (FieldType->isIncompleteArrayType()) {
11743       assert(ClassDecl->hasFlexibleArrayMember() &&
11744              "Incomplete array type is not valid");
11745       continue;
11746     }
11747 
11748     // Build references to the field in the object we're copying from and to.
11749     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11750                               LookupMemberName);
11751     MemberLookup.addDecl(Field);
11752     MemberLookup.resolveKind();
11753     MemberBuilder From(MoveOther, OtherRefType,
11754                        /*IsArrow=*/false, MemberLookup);
11755     MemberBuilder To(This, getCurrentThisType(),
11756                      /*IsArrow=*/true, MemberLookup);
11757 
11758     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
11759         "Member reference with rvalue base must be rvalue except for reference "
11760         "members, which aren't allowed for move assignment.");
11761 
11762     // Build the move of this field.
11763     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
11764                                             To, From,
11765                                             /*CopyingBaseSubobject=*/false,
11766                                             /*Copying=*/false);
11767     if (Move.isInvalid()) {
11768       Diag(CurrentLocation, diag::note_member_synthesized_at)
11769         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11770       MoveAssignOperator->setInvalidDecl();
11771       return;
11772     }
11773 
11774     // Success! Record the copy.
11775     Statements.push_back(Move.getAs<Stmt>());
11776   }
11777 
11778   if (!Invalid) {
11779     // Add a "return *this;"
11780     ExprResult ThisObj =
11781         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11782 
11783     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11784     if (Return.isInvalid())
11785       Invalid = true;
11786     else {
11787       Statements.push_back(Return.getAs<Stmt>());
11788 
11789       if (Trap.hasErrorOccurred()) {
11790         Diag(CurrentLocation, diag::note_member_synthesized_at)
11791           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11792         Invalid = true;
11793       }
11794     }
11795   }
11796 
11797   // The exception specification is needed because we are defining the
11798   // function.
11799   ResolveExceptionSpec(CurrentLocation,
11800                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11801 
11802   if (Invalid) {
11803     MoveAssignOperator->setInvalidDecl();
11804     return;
11805   }
11806 
11807   StmtResult Body;
11808   {
11809     CompoundScopeRAII CompoundScope(*this);
11810     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11811                              /*isStmtExpr=*/false);
11812     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11813   }
11814   MoveAssignOperator->setBody(Body.getAs<Stmt>());
11815 
11816   if (ASTMutationListener *L = getASTMutationListener()) {
11817     L->CompletedImplicitDefinition(MoveAssignOperator);
11818   }
11819 }
11820 
11821 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11822                                                     CXXRecordDecl *ClassDecl) {
11823   // C++ [class.copy]p4:
11824   //   If the class definition does not explicitly declare a copy
11825   //   constructor, one is declared implicitly.
11826   assert(ClassDecl->needsImplicitCopyConstructor());
11827 
11828   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11829   if (DSM.isAlreadyBeingDeclared())
11830     return nullptr;
11831 
11832   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11833   QualType ArgType = ClassType;
11834   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
11835   if (Const)
11836     ArgType = ArgType.withConst();
11837   ArgType = Context.getLValueReferenceType(ArgType);
11838 
11839   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11840                                                      CXXCopyConstructor,
11841                                                      Const);
11842 
11843   DeclarationName Name
11844     = Context.DeclarationNames.getCXXConstructorName(
11845                                            Context.getCanonicalType(ClassType));
11846   SourceLocation ClassLoc = ClassDecl->getLocation();
11847   DeclarationNameInfo NameInfo(Name, ClassLoc);
11848 
11849   //   An implicitly-declared copy constructor is an inline public
11850   //   member of its class.
11851   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
11852       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11853       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11854       Constexpr);
11855   CopyConstructor->setAccess(AS_public);
11856   CopyConstructor->setDefaulted();
11857 
11858   if (getLangOpts().CUDA) {
11859     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11860                                             CopyConstructor,
11861                                             /* ConstRHS */ Const,
11862                                             /* Diagnose */ false);
11863   }
11864 
11865   // Build an exception specification pointing back at this member.
11866   FunctionProtoType::ExtProtoInfo EPI =
11867       getImplicitMethodEPI(*this, CopyConstructor);
11868   CopyConstructor->setType(
11869       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11870 
11871   // Add the parameter to the constructor.
11872   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
11873                                                ClassLoc, ClassLoc,
11874                                                /*IdentifierInfo=*/nullptr,
11875                                                ArgType, /*TInfo=*/nullptr,
11876                                                SC_None, nullptr);
11877   CopyConstructor->setParams(FromParam);
11878 
11879   CopyConstructor->setTrivial(
11880     ClassDecl->needsOverloadResolutionForCopyConstructor()
11881       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11882       : ClassDecl->hasTrivialCopyConstructor());
11883 
11884   // Note that we have declared this constructor.
11885   ++ASTContext::NumImplicitCopyConstructorsDeclared;
11886 
11887   Scope *S = getScopeForContext(ClassDecl);
11888   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11889 
11890   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11891     SetDeclDeleted(CopyConstructor, ClassLoc);
11892 
11893   if (S)
11894     PushOnScopeChains(CopyConstructor, S, false);
11895   ClassDecl->addDecl(CopyConstructor);
11896 
11897   return CopyConstructor;
11898 }
11899 
11900 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
11901                                    CXXConstructorDecl *CopyConstructor) {
11902   assert((CopyConstructor->isDefaulted() &&
11903           CopyConstructor->isCopyConstructor() &&
11904           !CopyConstructor->doesThisDeclarationHaveABody() &&
11905           !CopyConstructor->isDeleted()) &&
11906          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
11907 
11908   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
11909   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
11910 
11911   // C++11 [class.copy]p7:
11912   //   The [definition of an implicitly declared copy constructor] is
11913   //   deprecated if the class has a user-declared copy assignment operator
11914   //   or a user-declared destructor.
11915   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11916     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11917 
11918   SynthesizedFunctionScope Scope(*this, CopyConstructor);
11919   DiagnosticErrorTrap Trap(Diags);
11920 
11921   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
11922       Trap.hasErrorOccurred()) {
11923     Diag(CurrentLocation, diag::note_member_synthesized_at)
11924       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
11925     CopyConstructor->setInvalidDecl();
11926   }  else {
11927     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11928                              ? CopyConstructor->getLocEnd()
11929                              : CopyConstructor->getLocation();
11930     Sema::CompoundScopeRAII CompoundScope(*this);
11931     CopyConstructor->setBody(
11932         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
11933   }
11934 
11935   // The exception specification is needed because we are defining the
11936   // function.
11937   ResolveExceptionSpec(CurrentLocation,
11938                        CopyConstructor->getType()->castAs<FunctionProtoType>());
11939 
11940   CopyConstructor->markUsed(Context);
11941   MarkVTableUsed(CurrentLocation, ClassDecl);
11942 
11943   if (ASTMutationListener *L = getASTMutationListener()) {
11944     L->CompletedImplicitDefinition(CopyConstructor);
11945   }
11946 }
11947 
11948 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11949                                                     CXXRecordDecl *ClassDecl) {
11950   assert(ClassDecl->needsImplicitMoveConstructor());
11951 
11952   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11953   if (DSM.isAlreadyBeingDeclared())
11954     return nullptr;
11955 
11956   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11957   QualType ArgType = Context.getRValueReferenceType(ClassType);
11958 
11959   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11960                                                      CXXMoveConstructor,
11961                                                      false);
11962 
11963   DeclarationName Name
11964     = Context.DeclarationNames.getCXXConstructorName(
11965                                            Context.getCanonicalType(ClassType));
11966   SourceLocation ClassLoc = ClassDecl->getLocation();
11967   DeclarationNameInfo NameInfo(Name, ClassLoc);
11968 
11969   // C++11 [class.copy]p11:
11970   //   An implicitly-declared copy/move constructor is an inline public
11971   //   member of its class.
11972   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
11973       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11974       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11975       Constexpr);
11976   MoveConstructor->setAccess(AS_public);
11977   MoveConstructor->setDefaulted();
11978 
11979   if (getLangOpts().CUDA) {
11980     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11981                                             MoveConstructor,
11982                                             /* ConstRHS */ false,
11983                                             /* Diagnose */ false);
11984   }
11985 
11986   // Build an exception specification pointing back at this member.
11987   FunctionProtoType::ExtProtoInfo EPI =
11988       getImplicitMethodEPI(*this, MoveConstructor);
11989   MoveConstructor->setType(
11990       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11991 
11992   // Add the parameter to the constructor.
11993   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11994                                                ClassLoc, ClassLoc,
11995                                                /*IdentifierInfo=*/nullptr,
11996                                                ArgType, /*TInfo=*/nullptr,
11997                                                SC_None, nullptr);
11998   MoveConstructor->setParams(FromParam);
11999 
12000   MoveConstructor->setTrivial(
12001     ClassDecl->needsOverloadResolutionForMoveConstructor()
12002       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12003       : ClassDecl->hasTrivialMoveConstructor());
12004 
12005   // Note that we have declared this constructor.
12006   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12007 
12008   Scope *S = getScopeForContext(ClassDecl);
12009   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12010 
12011   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12012     ClassDecl->setImplicitMoveConstructorIsDeleted();
12013     SetDeclDeleted(MoveConstructor, ClassLoc);
12014   }
12015 
12016   if (S)
12017     PushOnScopeChains(MoveConstructor, S, false);
12018   ClassDecl->addDecl(MoveConstructor);
12019 
12020   return MoveConstructor;
12021 }
12022 
12023 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12024                                    CXXConstructorDecl *MoveConstructor) {
12025   assert((MoveConstructor->isDefaulted() &&
12026           MoveConstructor->isMoveConstructor() &&
12027           !MoveConstructor->doesThisDeclarationHaveABody() &&
12028           !MoveConstructor->isDeleted()) &&
12029          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12030 
12031   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12032   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12033 
12034   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12035   DiagnosticErrorTrap Trap(Diags);
12036 
12037   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
12038       Trap.hasErrorOccurred()) {
12039     Diag(CurrentLocation, diag::note_member_synthesized_at)
12040       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
12041     MoveConstructor->setInvalidDecl();
12042   }  else {
12043     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12044                              ? MoveConstructor->getLocEnd()
12045                              : MoveConstructor->getLocation();
12046     Sema::CompoundScopeRAII CompoundScope(*this);
12047     MoveConstructor->setBody(ActOnCompoundStmt(
12048         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12049   }
12050 
12051   // The exception specification is needed because we are defining the
12052   // function.
12053   ResolveExceptionSpec(CurrentLocation,
12054                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12055 
12056   MoveConstructor->markUsed(Context);
12057   MarkVTableUsed(CurrentLocation, ClassDecl);
12058 
12059   if (ASTMutationListener *L = getASTMutationListener()) {
12060     L->CompletedImplicitDefinition(MoveConstructor);
12061   }
12062 }
12063 
12064 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12065   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12066 }
12067 
12068 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12069                             SourceLocation CurrentLocation,
12070                             CXXConversionDecl *Conv) {
12071   CXXRecordDecl *Lambda = Conv->getParent();
12072   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12073   // If we are defining a specialization of a conversion to function-ptr
12074   // cache the deduced template arguments for this specialization
12075   // so that we can use them to retrieve the corresponding call-operator
12076   // and static-invoker.
12077   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12078 
12079   // Retrieve the corresponding call-operator specialization.
12080   if (Lambda->isGenericLambda()) {
12081     assert(Conv->isFunctionTemplateSpecialization());
12082     FunctionTemplateDecl *CallOpTemplate =
12083         CallOp->getDescribedFunctionTemplate();
12084     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
12085     void *InsertPos = nullptr;
12086     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
12087                                                 DeducedTemplateArgs->asArray(),
12088                                                 InsertPos);
12089     assert(CallOpSpec &&
12090           "Conversion operator must have a corresponding call operator");
12091     CallOp = cast<CXXMethodDecl>(CallOpSpec);
12092   }
12093   // Mark the call operator referenced (and add to pending instantiations
12094   // if necessary).
12095   // For both the conversion and static-invoker template specializations
12096   // we construct their body's in this function, so no need to add them
12097   // to the PendingInstantiations.
12098   MarkFunctionReferenced(CurrentLocation, CallOp);
12099 
12100   SynthesizedFunctionScope Scope(*this, Conv);
12101   DiagnosticErrorTrap Trap(Diags);
12102 
12103   // Retrieve the static invoker...
12104   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12105   // ... and get the corresponding specialization for a generic lambda.
12106   if (Lambda->isGenericLambda()) {
12107     assert(DeducedTemplateArgs &&
12108       "Must have deduced template arguments from Conversion Operator");
12109     FunctionTemplateDecl *InvokeTemplate =
12110                           Invoker->getDescribedFunctionTemplate();
12111     void *InsertPos = nullptr;
12112     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
12113                                                 DeducedTemplateArgs->asArray(),
12114                                                 InsertPos);
12115     assert(InvokeSpec &&
12116       "Must have a corresponding static invoker specialization");
12117     Invoker = cast<CXXMethodDecl>(InvokeSpec);
12118   }
12119   // Construct the body of the conversion function { return __invoke; }.
12120   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12121                                         VK_LValue, Conv->getLocation()).get();
12122    assert(FunctionRef && "Can't refer to __invoke function?");
12123    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12124    Conv->setBody(new (Context) CompoundStmt(Context, Return,
12125                                             Conv->getLocation(),
12126                                             Conv->getLocation()));
12127 
12128   Conv->markUsed(Context);
12129   Conv->setReferenced();
12130 
12131   // Fill in the __invoke function with a dummy implementation. IR generation
12132   // will fill in the actual details.
12133   Invoker->markUsed(Context);
12134   Invoker->setReferenced();
12135   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12136 
12137   if (ASTMutationListener *L = getASTMutationListener()) {
12138     L->CompletedImplicitDefinition(Conv);
12139     L->CompletedImplicitDefinition(Invoker);
12140    }
12141 }
12142 
12143 
12144 
12145 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12146        SourceLocation CurrentLocation,
12147        CXXConversionDecl *Conv)
12148 {
12149   assert(!Conv->getParent()->isGenericLambda());
12150 
12151   Conv->markUsed(Context);
12152 
12153   SynthesizedFunctionScope Scope(*this, Conv);
12154   DiagnosticErrorTrap Trap(Diags);
12155 
12156   // Copy-initialize the lambda object as needed to capture it.
12157   Expr *This = ActOnCXXThis(CurrentLocation).get();
12158   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12159 
12160   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12161                                                         Conv->getLocation(),
12162                                                         Conv, DerefThis);
12163 
12164   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12165   // behavior.  Note that only the general conversion function does this
12166   // (since it's unusable otherwise); in the case where we inline the
12167   // block literal, it has block literal lifetime semantics.
12168   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12169     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12170                                           CK_CopyAndAutoreleaseBlockObject,
12171                                           BuildBlock.get(), nullptr, VK_RValue);
12172 
12173   if (BuildBlock.isInvalid()) {
12174     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12175     Conv->setInvalidDecl();
12176     return;
12177   }
12178 
12179   // Create the return statement that returns the block from the conversion
12180   // function.
12181   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12182   if (Return.isInvalid()) {
12183     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12184     Conv->setInvalidDecl();
12185     return;
12186   }
12187 
12188   // Set the body of the conversion function.
12189   Stmt *ReturnS = Return.get();
12190   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
12191                                            Conv->getLocation(),
12192                                            Conv->getLocation()));
12193 
12194   // We're done; notify the mutation listener, if any.
12195   if (ASTMutationListener *L = getASTMutationListener()) {
12196     L->CompletedImplicitDefinition(Conv);
12197   }
12198 }
12199 
12200 /// \brief Determine whether the given list arguments contains exactly one
12201 /// "real" (non-default) argument.
12202 static bool hasOneRealArgument(MultiExprArg Args) {
12203   switch (Args.size()) {
12204   case 0:
12205     return false;
12206 
12207   default:
12208     if (!Args[1]->isDefaultArgument())
12209       return false;
12210 
12211     // fall through
12212   case 1:
12213     return !Args[0]->isDefaultArgument();
12214   }
12215 
12216   return false;
12217 }
12218 
12219 ExprResult
12220 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12221                             NamedDecl *FoundDecl,
12222                             CXXConstructorDecl *Constructor,
12223                             MultiExprArg ExprArgs,
12224                             bool HadMultipleCandidates,
12225                             bool IsListInitialization,
12226                             bool IsStdInitListInitialization,
12227                             bool RequiresZeroInit,
12228                             unsigned ConstructKind,
12229                             SourceRange ParenRange) {
12230   bool Elidable = false;
12231 
12232   // C++0x [class.copy]p34:
12233   //   When certain criteria are met, an implementation is allowed to
12234   //   omit the copy/move construction of a class object, even if the
12235   //   copy/move constructor and/or destructor for the object have
12236   //   side effects. [...]
12237   //     - when a temporary class object that has not been bound to a
12238   //       reference (12.2) would be copied/moved to a class object
12239   //       with the same cv-unqualified type, the copy/move operation
12240   //       can be omitted by constructing the temporary object
12241   //       directly into the target of the omitted copy/move
12242   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12243       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12244     Expr *SubExpr = ExprArgs[0];
12245     Elidable = SubExpr->isTemporaryObject(
12246         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12247   }
12248 
12249   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12250                                FoundDecl, Constructor,
12251                                Elidable, ExprArgs, HadMultipleCandidates,
12252                                IsListInitialization,
12253                                IsStdInitListInitialization, RequiresZeroInit,
12254                                ConstructKind, ParenRange);
12255 }
12256 
12257 ExprResult
12258 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12259                             NamedDecl *FoundDecl,
12260                             CXXConstructorDecl *Constructor,
12261                             bool Elidable,
12262                             MultiExprArg ExprArgs,
12263                             bool HadMultipleCandidates,
12264                             bool IsListInitialization,
12265                             bool IsStdInitListInitialization,
12266                             bool RequiresZeroInit,
12267                             unsigned ConstructKind,
12268                             SourceRange ParenRange) {
12269   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12270     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12271     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12272       return ExprError();
12273   }
12274 
12275   return BuildCXXConstructExpr(
12276       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12277       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12278       RequiresZeroInit, ConstructKind, ParenRange);
12279 }
12280 
12281 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12282 /// including handling of its default argument expressions.
12283 ExprResult
12284 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12285                             CXXConstructorDecl *Constructor,
12286                             bool Elidable,
12287                             MultiExprArg ExprArgs,
12288                             bool HadMultipleCandidates,
12289                             bool IsListInitialization,
12290                             bool IsStdInitListInitialization,
12291                             bool RequiresZeroInit,
12292                             unsigned ConstructKind,
12293                             SourceRange ParenRange) {
12294   assert(declaresSameEntity(
12295              Constructor->getParent(),
12296              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12297          "given constructor for wrong type");
12298   MarkFunctionReferenced(ConstructLoc, Constructor);
12299   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12300     return ExprError();
12301 
12302   return CXXConstructExpr::Create(
12303       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12304       ExprArgs, HadMultipleCandidates, IsListInitialization,
12305       IsStdInitListInitialization, RequiresZeroInit,
12306       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12307       ParenRange);
12308 }
12309 
12310 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12311   assert(Field->hasInClassInitializer());
12312 
12313   // If we already have the in-class initializer nothing needs to be done.
12314   if (Field->getInClassInitializer())
12315     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12316 
12317   // If we might have already tried and failed to instantiate, don't try again.
12318   if (Field->isInvalidDecl())
12319     return ExprError();
12320 
12321   // Maybe we haven't instantiated the in-class initializer. Go check the
12322   // pattern FieldDecl to see if it has one.
12323   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12324 
12325   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12326     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12327     DeclContext::lookup_result Lookup =
12328         ClassPattern->lookup(Field->getDeclName());
12329 
12330     // Lookup can return at most two results: the pattern for the field, or the
12331     // injected class name of the parent record. No other member can have the
12332     // same name as the field.
12333     // In modules mode, lookup can return multiple results (coming from
12334     // different modules).
12335     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12336            "more than two lookup results for field name");
12337     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12338     if (!Pattern) {
12339       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12340              "cannot have other non-field member with same name");
12341       for (auto L : Lookup)
12342         if (isa<FieldDecl>(L)) {
12343           Pattern = cast<FieldDecl>(L);
12344           break;
12345         }
12346       assert(Pattern && "We must have set the Pattern!");
12347     }
12348 
12349     if (InstantiateInClassInitializer(Loc, Field, Pattern,
12350                                       getTemplateInstantiationArgs(Field))) {
12351       // Don't diagnose this again.
12352       Field->setInvalidDecl();
12353       return ExprError();
12354     }
12355     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12356   }
12357 
12358   // DR1351:
12359   //   If the brace-or-equal-initializer of a non-static data member
12360   //   invokes a defaulted default constructor of its class or of an
12361   //   enclosing class in a potentially evaluated subexpression, the
12362   //   program is ill-formed.
12363   //
12364   // This resolution is unworkable: the exception specification of the
12365   // default constructor can be needed in an unevaluated context, in
12366   // particular, in the operand of a noexcept-expression, and we can be
12367   // unable to compute an exception specification for an enclosed class.
12368   //
12369   // Any attempt to resolve the exception specification of a defaulted default
12370   // constructor before the initializer is lexically complete will ultimately
12371   // come here at which point we can diagnose it.
12372   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12373   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12374       << OutermostClass << Field;
12375   Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
12376   // Recover by marking the field invalid, unless we're in a SFINAE context.
12377   if (!isSFINAEContext())
12378     Field->setInvalidDecl();
12379   return ExprError();
12380 }
12381 
12382 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12383   if (VD->isInvalidDecl()) return;
12384 
12385   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12386   if (ClassDecl->isInvalidDecl()) return;
12387   if (ClassDecl->hasIrrelevantDestructor()) return;
12388   if (ClassDecl->isDependentContext()) return;
12389 
12390   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12391   MarkFunctionReferenced(VD->getLocation(), Destructor);
12392   CheckDestructorAccess(VD->getLocation(), Destructor,
12393                         PDiag(diag::err_access_dtor_var)
12394                         << VD->getDeclName()
12395                         << VD->getType());
12396   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12397 
12398   if (Destructor->isTrivial()) return;
12399   if (!VD->hasGlobalStorage()) return;
12400 
12401   // Emit warning for non-trivial dtor in global scope (a real global,
12402   // class-static, function-static).
12403   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12404 
12405   // TODO: this should be re-enabled for static locals by !CXAAtExit
12406   if (!VD->isStaticLocal())
12407     Diag(VD->getLocation(), diag::warn_global_destructor);
12408 }
12409 
12410 /// \brief Given a constructor and the set of arguments provided for the
12411 /// constructor, convert the arguments and add any required default arguments
12412 /// to form a proper call to this constructor.
12413 ///
12414 /// \returns true if an error occurred, false otherwise.
12415 bool
12416 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12417                               MultiExprArg ArgsPtr,
12418                               SourceLocation Loc,
12419                               SmallVectorImpl<Expr*> &ConvertedArgs,
12420                               bool AllowExplicit,
12421                               bool IsListInitialization) {
12422   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12423   unsigned NumArgs = ArgsPtr.size();
12424   Expr **Args = ArgsPtr.data();
12425 
12426   const FunctionProtoType *Proto
12427     = Constructor->getType()->getAs<FunctionProtoType>();
12428   assert(Proto && "Constructor without a prototype?");
12429   unsigned NumParams = Proto->getNumParams();
12430 
12431   // If too few arguments are available, we'll fill in the rest with defaults.
12432   if (NumArgs < NumParams)
12433     ConvertedArgs.reserve(NumParams);
12434   else
12435     ConvertedArgs.reserve(NumArgs);
12436 
12437   VariadicCallType CallType =
12438     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12439   SmallVector<Expr *, 8> AllArgs;
12440   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12441                                         Proto, 0,
12442                                         llvm::makeArrayRef(Args, NumArgs),
12443                                         AllArgs,
12444                                         CallType, AllowExplicit,
12445                                         IsListInitialization);
12446   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12447 
12448   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12449 
12450   CheckConstructorCall(Constructor,
12451                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12452                        Proto, Loc);
12453 
12454   return Invalid;
12455 }
12456 
12457 static inline bool
12458 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12459                                        const FunctionDecl *FnDecl) {
12460   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12461   if (isa<NamespaceDecl>(DC)) {
12462     return SemaRef.Diag(FnDecl->getLocation(),
12463                         diag::err_operator_new_delete_declared_in_namespace)
12464       << FnDecl->getDeclName();
12465   }
12466 
12467   if (isa<TranslationUnitDecl>(DC) &&
12468       FnDecl->getStorageClass() == SC_Static) {
12469     return SemaRef.Diag(FnDecl->getLocation(),
12470                         diag::err_operator_new_delete_declared_static)
12471       << FnDecl->getDeclName();
12472   }
12473 
12474   return false;
12475 }
12476 
12477 static inline bool
12478 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12479                             CanQualType ExpectedResultType,
12480                             CanQualType ExpectedFirstParamType,
12481                             unsigned DependentParamTypeDiag,
12482                             unsigned InvalidParamTypeDiag) {
12483   QualType ResultType =
12484       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
12485 
12486   // Check that the result type is not dependent.
12487   if (ResultType->isDependentType())
12488     return SemaRef.Diag(FnDecl->getLocation(),
12489                         diag::err_operator_new_delete_dependent_result_type)
12490     << FnDecl->getDeclName() << ExpectedResultType;
12491 
12492   // Check that the result type is what we expect.
12493   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12494     return SemaRef.Diag(FnDecl->getLocation(),
12495                         diag::err_operator_new_delete_invalid_result_type)
12496     << FnDecl->getDeclName() << ExpectedResultType;
12497 
12498   // A function template must have at least 2 parameters.
12499   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12500     return SemaRef.Diag(FnDecl->getLocation(),
12501                       diag::err_operator_new_delete_template_too_few_parameters)
12502         << FnDecl->getDeclName();
12503 
12504   // The function decl must have at least 1 parameter.
12505   if (FnDecl->getNumParams() == 0)
12506     return SemaRef.Diag(FnDecl->getLocation(),
12507                         diag::err_operator_new_delete_too_few_parameters)
12508       << FnDecl->getDeclName();
12509 
12510   // Check the first parameter type is not dependent.
12511   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12512   if (FirstParamType->isDependentType())
12513     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12514       << FnDecl->getDeclName() << ExpectedFirstParamType;
12515 
12516   // Check that the first parameter type is what we expect.
12517   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
12518       ExpectedFirstParamType)
12519     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12520     << FnDecl->getDeclName() << ExpectedFirstParamType;
12521 
12522   return false;
12523 }
12524 
12525 static bool
12526 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
12527   // C++ [basic.stc.dynamic.allocation]p1:
12528   //   A program is ill-formed if an allocation function is declared in a
12529   //   namespace scope other than global scope or declared static in global
12530   //   scope.
12531   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12532     return true;
12533 
12534   CanQualType SizeTy =
12535     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12536 
12537   // C++ [basic.stc.dynamic.allocation]p1:
12538   //  The return type shall be void*. The first parameter shall have type
12539   //  std::size_t.
12540   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12541                                   SizeTy,
12542                                   diag::err_operator_new_dependent_param_type,
12543                                   diag::err_operator_new_param_type))
12544     return true;
12545 
12546   // C++ [basic.stc.dynamic.allocation]p1:
12547   //  The first parameter shall not have an associated default argument.
12548   if (FnDecl->getParamDecl(0)->hasDefaultArg())
12549     return SemaRef.Diag(FnDecl->getLocation(),
12550                         diag::err_operator_new_default_arg)
12551       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12552 
12553   return false;
12554 }
12555 
12556 static bool
12557 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
12558   // C++ [basic.stc.dynamic.deallocation]p1:
12559   //   A program is ill-formed if deallocation functions are declared in a
12560   //   namespace scope other than global scope or declared static in global
12561   //   scope.
12562   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12563     return true;
12564 
12565   // C++ [basic.stc.dynamic.deallocation]p2:
12566   //   Each deallocation function shall return void and its first parameter
12567   //   shall be void*.
12568   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
12569                                   SemaRef.Context.VoidPtrTy,
12570                                  diag::err_operator_delete_dependent_param_type,
12571                                  diag::err_operator_delete_param_type))
12572     return true;
12573 
12574   return false;
12575 }
12576 
12577 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
12578 /// of this overloaded operator is well-formed. If so, returns false;
12579 /// otherwise, emits appropriate diagnostics and returns true.
12580 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
12581   assert(FnDecl && FnDecl->isOverloadedOperator() &&
12582          "Expected an overloaded operator declaration");
12583 
12584   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12585 
12586   // C++ [over.oper]p5:
12587   //   The allocation and deallocation functions, operator new,
12588   //   operator new[], operator delete and operator delete[], are
12589   //   described completely in 3.7.3. The attributes and restrictions
12590   //   found in the rest of this subclause do not apply to them unless
12591   //   explicitly stated in 3.7.3.
12592   if (Op == OO_Delete || Op == OO_Array_Delete)
12593     return CheckOperatorDeleteDeclaration(*this, FnDecl);
12594 
12595   if (Op == OO_New || Op == OO_Array_New)
12596     return CheckOperatorNewDeclaration(*this, FnDecl);
12597 
12598   // C++ [over.oper]p6:
12599   //   An operator function shall either be a non-static member
12600   //   function or be a non-member function and have at least one
12601   //   parameter whose type is a class, a reference to a class, an
12602   //   enumeration, or a reference to an enumeration.
12603   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12604     if (MethodDecl->isStatic())
12605       return Diag(FnDecl->getLocation(),
12606                   diag::err_operator_overload_static) << FnDecl->getDeclName();
12607   } else {
12608     bool ClassOrEnumParam = false;
12609     for (auto Param : FnDecl->parameters()) {
12610       QualType ParamType = Param->getType().getNonReferenceType();
12611       if (ParamType->isDependentType() || ParamType->isRecordType() ||
12612           ParamType->isEnumeralType()) {
12613         ClassOrEnumParam = true;
12614         break;
12615       }
12616     }
12617 
12618     if (!ClassOrEnumParam)
12619       return Diag(FnDecl->getLocation(),
12620                   diag::err_operator_overload_needs_class_or_enum)
12621         << FnDecl->getDeclName();
12622   }
12623 
12624   // C++ [over.oper]p8:
12625   //   An operator function cannot have default arguments (8.3.6),
12626   //   except where explicitly stated below.
12627   //
12628   // Only the function-call operator allows default arguments
12629   // (C++ [over.call]p1).
12630   if (Op != OO_Call) {
12631     for (auto Param : FnDecl->parameters()) {
12632       if (Param->hasDefaultArg())
12633         return Diag(Param->getLocation(),
12634                     diag::err_operator_overload_default_arg)
12635           << FnDecl->getDeclName() << Param->getDefaultArgRange();
12636     }
12637   }
12638 
12639   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12640     { false, false, false }
12641 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12642     , { Unary, Binary, MemberOnly }
12643 #include "clang/Basic/OperatorKinds.def"
12644   };
12645 
12646   bool CanBeUnaryOperator = OperatorUses[Op][0];
12647   bool CanBeBinaryOperator = OperatorUses[Op][1];
12648   bool MustBeMemberOperator = OperatorUses[Op][2];
12649 
12650   // C++ [over.oper]p8:
12651   //   [...] Operator functions cannot have more or fewer parameters
12652   //   than the number required for the corresponding operator, as
12653   //   described in the rest of this subclause.
12654   unsigned NumParams = FnDecl->getNumParams()
12655                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
12656   if (Op != OO_Call &&
12657       ((NumParams == 1 && !CanBeUnaryOperator) ||
12658        (NumParams == 2 && !CanBeBinaryOperator) ||
12659        (NumParams < 1) || (NumParams > 2))) {
12660     // We have the wrong number of parameters.
12661     unsigned ErrorKind;
12662     if (CanBeUnaryOperator && CanBeBinaryOperator) {
12663       ErrorKind = 2;  // 2 -> unary or binary.
12664     } else if (CanBeUnaryOperator) {
12665       ErrorKind = 0;  // 0 -> unary
12666     } else {
12667       assert(CanBeBinaryOperator &&
12668              "All non-call overloaded operators are unary or binary!");
12669       ErrorKind = 1;  // 1 -> binary
12670     }
12671 
12672     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
12673       << FnDecl->getDeclName() << NumParams << ErrorKind;
12674   }
12675 
12676   // Overloaded operators other than operator() cannot be variadic.
12677   if (Op != OO_Call &&
12678       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
12679     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
12680       << FnDecl->getDeclName();
12681   }
12682 
12683   // Some operators must be non-static member functions.
12684   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12685     return Diag(FnDecl->getLocation(),
12686                 diag::err_operator_overload_must_be_member)
12687       << FnDecl->getDeclName();
12688   }
12689 
12690   // C++ [over.inc]p1:
12691   //   The user-defined function called operator++ implements the
12692   //   prefix and postfix ++ operator. If this function is a member
12693   //   function with no parameters, or a non-member function with one
12694   //   parameter of class or enumeration type, it defines the prefix
12695   //   increment operator ++ for objects of that type. If the function
12696   //   is a member function with one parameter (which shall be of type
12697   //   int) or a non-member function with two parameters (the second
12698   //   of which shall be of type int), it defines the postfix
12699   //   increment operator ++ for objects of that type.
12700   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12701     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
12702     QualType ParamType = LastParam->getType();
12703 
12704     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12705         !ParamType->isDependentType())
12706       return Diag(LastParam->getLocation(),
12707                   diag::err_operator_overload_post_incdec_must_be_int)
12708         << LastParam->getType() << (Op == OO_MinusMinus);
12709   }
12710 
12711   return false;
12712 }
12713 
12714 static bool
12715 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12716                                           FunctionTemplateDecl *TpDecl) {
12717   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12718 
12719   // Must have one or two template parameters.
12720   if (TemplateParams->size() == 1) {
12721     NonTypeTemplateParmDecl *PmDecl =
12722         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12723 
12724     // The template parameter must be a char parameter pack.
12725     if (PmDecl && PmDecl->isTemplateParameterPack() &&
12726         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12727       return false;
12728 
12729   } else if (TemplateParams->size() == 2) {
12730     TemplateTypeParmDecl *PmType =
12731         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12732     NonTypeTemplateParmDecl *PmArgs =
12733         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12734 
12735     // The second template parameter must be a parameter pack with the
12736     // first template parameter as its type.
12737     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12738         PmArgs->isTemplateParameterPack()) {
12739       const TemplateTypeParmType *TArgs =
12740           PmArgs->getType()->getAs<TemplateTypeParmType>();
12741       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12742           TArgs->getIndex() == PmType->getIndex()) {
12743         if (!SemaRef.inTemplateInstantiation())
12744           SemaRef.Diag(TpDecl->getLocation(),
12745                        diag::ext_string_literal_operator_template);
12746         return false;
12747       }
12748     }
12749   }
12750 
12751   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12752                diag::err_literal_operator_template)
12753       << TpDecl->getTemplateParameters()->getSourceRange();
12754   return true;
12755 }
12756 
12757 /// CheckLiteralOperatorDeclaration - Check whether the declaration
12758 /// of this literal operator function is well-formed. If so, returns
12759 /// false; otherwise, emits appropriate diagnostics and returns true.
12760 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
12761   if (isa<CXXMethodDecl>(FnDecl)) {
12762     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12763       << FnDecl->getDeclName();
12764     return true;
12765   }
12766 
12767   if (FnDecl->isExternC()) {
12768     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
12769     if (const LinkageSpecDecl *LSD =
12770             FnDecl->getDeclContext()->getExternCContext())
12771       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
12772     return true;
12773   }
12774 
12775   // This might be the definition of a literal operator template.
12776   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
12777 
12778   // This might be a specialization of a literal operator template.
12779   if (!TpDecl)
12780     TpDecl = FnDecl->getPrimaryTemplate();
12781 
12782   // template <char...> type operator "" name() and
12783   // template <class T, T...> type operator "" name() are the only valid
12784   // template signatures, and the only valid signatures with no parameters.
12785   if (TpDecl) {
12786     if (FnDecl->param_size() != 0) {
12787       Diag(FnDecl->getLocation(),
12788            diag::err_literal_operator_template_with_params);
12789       return true;
12790     }
12791 
12792     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12793       return true;
12794 
12795   } else if (FnDecl->param_size() == 1) {
12796     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12797 
12798     QualType ParamType = Param->getType().getUnqualifiedType();
12799 
12800     // Only unsigned long long int, long double, any character type, and const
12801     // char * are allowed as the only parameters.
12802     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12803         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12804         Context.hasSameType(ParamType, Context.CharTy) ||
12805         Context.hasSameType(ParamType, Context.WideCharTy) ||
12806         Context.hasSameType(ParamType, Context.Char16Ty) ||
12807         Context.hasSameType(ParamType, Context.Char32Ty)) {
12808     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12809       QualType InnerType = Ptr->getPointeeType();
12810 
12811       // Pointer parameter must be a const char *.
12812       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12813                                 Context.CharTy) &&
12814             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12815         Diag(Param->getSourceRange().getBegin(),
12816              diag::err_literal_operator_param)
12817             << ParamType << "'const char *'" << Param->getSourceRange();
12818         return true;
12819       }
12820 
12821     } else if (ParamType->isRealFloatingType()) {
12822       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12823           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12824       return true;
12825 
12826     } else if (ParamType->isIntegerType()) {
12827       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12828           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12829       return true;
12830 
12831     } else {
12832       Diag(Param->getSourceRange().getBegin(),
12833            diag::err_literal_operator_invalid_param)
12834           << ParamType << Param->getSourceRange();
12835       return true;
12836     }
12837 
12838   } else if (FnDecl->param_size() == 2) {
12839     FunctionDecl::param_iterator Param = FnDecl->param_begin();
12840 
12841     // First, verify that the first parameter is correct.
12842 
12843     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12844 
12845     // Two parameter function must have a pointer to const as a
12846     // first parameter; let's strip those qualifiers.
12847     const PointerType *PT = FirstParamType->getAs<PointerType>();
12848 
12849     if (!PT) {
12850       Diag((*Param)->getSourceRange().getBegin(),
12851            diag::err_literal_operator_param)
12852           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12853       return true;
12854     }
12855 
12856     QualType PointeeType = PT->getPointeeType();
12857     // First parameter must be const
12858     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12859       Diag((*Param)->getSourceRange().getBegin(),
12860            diag::err_literal_operator_param)
12861           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12862       return true;
12863     }
12864 
12865     QualType InnerType = PointeeType.getUnqualifiedType();
12866     // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12867     // are allowed as the first parameter to a two-parameter function
12868     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12869           Context.hasSameType(InnerType, Context.WideCharTy) ||
12870           Context.hasSameType(InnerType, Context.Char16Ty) ||
12871           Context.hasSameType(InnerType, Context.Char32Ty))) {
12872       Diag((*Param)->getSourceRange().getBegin(),
12873            diag::err_literal_operator_param)
12874           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12875       return true;
12876     }
12877 
12878     // Move on to the second and final parameter.
12879     ++Param;
12880 
12881     // The second parameter must be a std::size_t.
12882     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12883     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12884       Diag((*Param)->getSourceRange().getBegin(),
12885            diag::err_literal_operator_param)
12886           << SecondParamType << Context.getSizeType()
12887           << (*Param)->getSourceRange();
12888       return true;
12889     }
12890   } else {
12891     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
12892     return true;
12893   }
12894 
12895   // Parameters are good.
12896 
12897   // A parameter-declaration-clause containing a default argument is not
12898   // equivalent to any of the permitted forms.
12899   for (auto Param : FnDecl->parameters()) {
12900     if (Param->hasDefaultArg()) {
12901       Diag(Param->getDefaultArgRange().getBegin(),
12902            diag::err_literal_operator_default_argument)
12903         << Param->getDefaultArgRange();
12904       break;
12905     }
12906   }
12907 
12908   StringRef LiteralName
12909     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12910   if (LiteralName[0] != '_') {
12911     // C++11 [usrlit.suffix]p1:
12912     //   Literal suffix identifiers that do not start with an underscore
12913     //   are reserved for future standardization.
12914     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
12915       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
12916   }
12917 
12918   return false;
12919 }
12920 
12921 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12922 /// linkage specification, including the language and (if present)
12923 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
12924 /// language string literal. LBraceLoc, if valid, provides the location of
12925 /// the '{' brace. Otherwise, this linkage specification does not
12926 /// have any braces.
12927 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
12928                                            Expr *LangStr,
12929                                            SourceLocation LBraceLoc) {
12930   StringLiteral *Lit = cast<StringLiteral>(LangStr);
12931   if (!Lit->isAscii()) {
12932     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12933       << LangStr->getSourceRange();
12934     return nullptr;
12935   }
12936 
12937   StringRef Lang = Lit->getString();
12938   LinkageSpecDecl::LanguageIDs Language;
12939   if (Lang == "C")
12940     Language = LinkageSpecDecl::lang_c;
12941   else if (Lang == "C++")
12942     Language = LinkageSpecDecl::lang_cxx;
12943   else {
12944     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12945       << LangStr->getSourceRange();
12946     return nullptr;
12947   }
12948 
12949   // FIXME: Add all the various semantics of linkage specifications
12950 
12951   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
12952                                                LangStr->getExprLoc(), Language,
12953                                                LBraceLoc.isValid());
12954   CurContext->addDecl(D);
12955   PushDeclContext(S, D);
12956   return D;
12957 }
12958 
12959 /// ActOnFinishLinkageSpecification - Complete the definition of
12960 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
12961 /// valid, it's the position of the closing '}' brace in a linkage
12962 /// specification that uses braces.
12963 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
12964                                             Decl *LinkageSpec,
12965                                             SourceLocation RBraceLoc) {
12966   if (RBraceLoc.isValid()) {
12967     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
12968     LSDecl->setRBraceLoc(RBraceLoc);
12969   }
12970   PopDeclContext();
12971   return LinkageSpec;
12972 }
12973 
12974 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
12975                                   AttributeList *AttrList,
12976                                   SourceLocation SemiLoc) {
12977   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
12978   // Attribute declarations appertain to empty declaration so we handle
12979   // them here.
12980   if (AttrList)
12981     ProcessDeclAttributeList(S, ED, AttrList);
12982 
12983   CurContext->addDecl(ED);
12984   return ED;
12985 }
12986 
12987 /// \brief Perform semantic analysis for the variable declaration that
12988 /// occurs within a C++ catch clause, returning the newly-created
12989 /// variable.
12990 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
12991                                          TypeSourceInfo *TInfo,
12992                                          SourceLocation StartLoc,
12993                                          SourceLocation Loc,
12994                                          IdentifierInfo *Name) {
12995   bool Invalid = false;
12996   QualType ExDeclType = TInfo->getType();
12997 
12998   // Arrays and functions decay.
12999   if (ExDeclType->isArrayType())
13000     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13001   else if (ExDeclType->isFunctionType())
13002     ExDeclType = Context.getPointerType(ExDeclType);
13003 
13004   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13005   // The exception-declaration shall not denote a pointer or reference to an
13006   // incomplete type, other than [cv] void*.
13007   // N2844 forbids rvalue references.
13008   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13009     Diag(Loc, diag::err_catch_rvalue_ref);
13010     Invalid = true;
13011   }
13012 
13013   if (ExDeclType->isVariablyModifiedType()) {
13014     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13015     Invalid = true;
13016   }
13017 
13018   QualType BaseType = ExDeclType;
13019   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13020   unsigned DK = diag::err_catch_incomplete;
13021   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13022     BaseType = Ptr->getPointeeType();
13023     Mode = 1;
13024     DK = diag::err_catch_incomplete_ptr;
13025   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13026     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13027     BaseType = Ref->getPointeeType();
13028     Mode = 2;
13029     DK = diag::err_catch_incomplete_ref;
13030   }
13031   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13032       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13033     Invalid = true;
13034 
13035   if (!Invalid && !ExDeclType->isDependentType() &&
13036       RequireNonAbstractType(Loc, ExDeclType,
13037                              diag::err_abstract_type_in_decl,
13038                              AbstractVariableType))
13039     Invalid = true;
13040 
13041   // Only the non-fragile NeXT runtime currently supports C++ catches
13042   // of ObjC types, and no runtime supports catching ObjC types by value.
13043   if (!Invalid && getLangOpts().ObjC1) {
13044     QualType T = ExDeclType;
13045     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13046       T = RT->getPointeeType();
13047 
13048     if (T->isObjCObjectType()) {
13049       Diag(Loc, diag::err_objc_object_catch);
13050       Invalid = true;
13051     } else if (T->isObjCObjectPointerType()) {
13052       // FIXME: should this be a test for macosx-fragile specifically?
13053       if (getLangOpts().ObjCRuntime.isFragile())
13054         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13055     }
13056   }
13057 
13058   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13059                                     ExDeclType, TInfo, SC_None);
13060   ExDecl->setExceptionVariable(true);
13061 
13062   // In ARC, infer 'retaining' for variables of retainable type.
13063   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13064     Invalid = true;
13065 
13066   if (!Invalid && !ExDeclType->isDependentType()) {
13067     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13068       // Insulate this from anything else we might currently be parsing.
13069       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
13070 
13071       // C++ [except.handle]p16:
13072       //   The object declared in an exception-declaration or, if the
13073       //   exception-declaration does not specify a name, a temporary (12.2) is
13074       //   copy-initialized (8.5) from the exception object. [...]
13075       //   The object is destroyed when the handler exits, after the destruction
13076       //   of any automatic objects initialized within the handler.
13077       //
13078       // We just pretend to initialize the object with itself, then make sure
13079       // it can be destroyed later.
13080       QualType initType = Context.getExceptionObjectType(ExDeclType);
13081 
13082       InitializedEntity entity =
13083         InitializedEntity::InitializeVariable(ExDecl);
13084       InitializationKind initKind =
13085         InitializationKind::CreateCopy(Loc, SourceLocation());
13086 
13087       Expr *opaqueValue =
13088         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13089       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13090       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13091       if (result.isInvalid())
13092         Invalid = true;
13093       else {
13094         // If the constructor used was non-trivial, set this as the
13095         // "initializer".
13096         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13097         if (!construct->getConstructor()->isTrivial()) {
13098           Expr *init = MaybeCreateExprWithCleanups(construct);
13099           ExDecl->setInit(init);
13100         }
13101 
13102         // And make sure it's destructable.
13103         FinalizeVarWithDestructor(ExDecl, recordType);
13104       }
13105     }
13106   }
13107 
13108   if (Invalid)
13109     ExDecl->setInvalidDecl();
13110 
13111   return ExDecl;
13112 }
13113 
13114 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13115 /// handler.
13116 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13117   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13118   bool Invalid = D.isInvalidType();
13119 
13120   // Check for unexpanded parameter packs.
13121   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13122                                       UPPC_ExceptionType)) {
13123     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13124                                              D.getIdentifierLoc());
13125     Invalid = true;
13126   }
13127 
13128   IdentifierInfo *II = D.getIdentifier();
13129   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13130                                              LookupOrdinaryName,
13131                                              ForRedeclaration)) {
13132     // The scope should be freshly made just for us. There is just no way
13133     // it contains any previous declaration, except for function parameters in
13134     // a function-try-block's catch statement.
13135     assert(!S->isDeclScope(PrevDecl));
13136     if (isDeclInScope(PrevDecl, CurContext, S)) {
13137       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13138         << D.getIdentifier();
13139       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13140       Invalid = true;
13141     } else if (PrevDecl->isTemplateParameter())
13142       // Maybe we will complain about the shadowed template parameter.
13143       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13144   }
13145 
13146   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13147     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13148       << D.getCXXScopeSpec().getRange();
13149     Invalid = true;
13150   }
13151 
13152   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13153                                               D.getLocStart(),
13154                                               D.getIdentifierLoc(),
13155                                               D.getIdentifier());
13156   if (Invalid)
13157     ExDecl->setInvalidDecl();
13158 
13159   // Add the exception declaration into this scope.
13160   if (II)
13161     PushOnScopeChains(ExDecl, S);
13162   else
13163     CurContext->addDecl(ExDecl);
13164 
13165   ProcessDeclAttributes(S, ExDecl, D);
13166   return ExDecl;
13167 }
13168 
13169 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13170                                          Expr *AssertExpr,
13171                                          Expr *AssertMessageExpr,
13172                                          SourceLocation RParenLoc) {
13173   StringLiteral *AssertMessage =
13174       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13175 
13176   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13177     return nullptr;
13178 
13179   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13180                                       AssertMessage, RParenLoc, false);
13181 }
13182 
13183 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13184                                          Expr *AssertExpr,
13185                                          StringLiteral *AssertMessage,
13186                                          SourceLocation RParenLoc,
13187                                          bool Failed) {
13188   assert(AssertExpr != nullptr && "Expected non-null condition");
13189   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13190       !Failed) {
13191     // In a static_assert-declaration, the constant-expression shall be a
13192     // constant expression that can be contextually converted to bool.
13193     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13194     if (Converted.isInvalid())
13195       Failed = true;
13196 
13197     llvm::APSInt Cond;
13198     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13199           diag::err_static_assert_expression_is_not_constant,
13200           /*AllowFold=*/false).isInvalid())
13201       Failed = true;
13202 
13203     if (!Failed && !Cond) {
13204       SmallString<256> MsgBuffer;
13205       llvm::raw_svector_ostream Msg(MsgBuffer);
13206       if (AssertMessage)
13207         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13208       Diag(StaticAssertLoc, diag::err_static_assert_failed)
13209         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13210       Failed = true;
13211     }
13212   }
13213 
13214   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13215                                         AssertExpr, AssertMessage, RParenLoc,
13216                                         Failed);
13217 
13218   CurContext->addDecl(Decl);
13219   return Decl;
13220 }
13221 
13222 /// \brief Perform semantic analysis of the given friend type declaration.
13223 ///
13224 /// \returns A friend declaration that.
13225 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13226                                       SourceLocation FriendLoc,
13227                                       TypeSourceInfo *TSInfo) {
13228   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13229 
13230   QualType T = TSInfo->getType();
13231   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13232 
13233   // C++03 [class.friend]p2:
13234   //   An elaborated-type-specifier shall be used in a friend declaration
13235   //   for a class.*
13236   //
13237   //   * The class-key of the elaborated-type-specifier is required.
13238   if (!CodeSynthesisContexts.empty()) {
13239     // Do not complain about the form of friend template types during any kind
13240     // of code synthesis. For template instantiation, we will have complained
13241     // when the template was defined.
13242   } else {
13243     if (!T->isElaboratedTypeSpecifier()) {
13244       // If we evaluated the type to a record type, suggest putting
13245       // a tag in front.
13246       if (const RecordType *RT = T->getAs<RecordType>()) {
13247         RecordDecl *RD = RT->getDecl();
13248 
13249         SmallString<16> InsertionText(" ");
13250         InsertionText += RD->getKindName();
13251 
13252         Diag(TypeRange.getBegin(),
13253              getLangOpts().CPlusPlus11 ?
13254                diag::warn_cxx98_compat_unelaborated_friend_type :
13255                diag::ext_unelaborated_friend_type)
13256           << (unsigned) RD->getTagKind()
13257           << T
13258           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13259                                         InsertionText);
13260       } else {
13261         Diag(FriendLoc,
13262              getLangOpts().CPlusPlus11 ?
13263                diag::warn_cxx98_compat_nonclass_type_friend :
13264                diag::ext_nonclass_type_friend)
13265           << T
13266           << TypeRange;
13267       }
13268     } else if (T->getAs<EnumType>()) {
13269       Diag(FriendLoc,
13270            getLangOpts().CPlusPlus11 ?
13271              diag::warn_cxx98_compat_enum_friend :
13272              diag::ext_enum_friend)
13273         << T
13274         << TypeRange;
13275     }
13276 
13277     // C++11 [class.friend]p3:
13278     //   A friend declaration that does not declare a function shall have one
13279     //   of the following forms:
13280     //     friend elaborated-type-specifier ;
13281     //     friend simple-type-specifier ;
13282     //     friend typename-specifier ;
13283     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13284       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13285   }
13286 
13287   //   If the type specifier in a friend declaration designates a (possibly
13288   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13289   //   the friend declaration is ignored.
13290   return FriendDecl::Create(Context, CurContext,
13291                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
13292                             FriendLoc);
13293 }
13294 
13295 /// Handle a friend tag declaration where the scope specifier was
13296 /// templated.
13297 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13298                                     unsigned TagSpec, SourceLocation TagLoc,
13299                                     CXXScopeSpec &SS,
13300                                     IdentifierInfo *Name,
13301                                     SourceLocation NameLoc,
13302                                     AttributeList *Attr,
13303                                     MultiTemplateParamsArg TempParamLists) {
13304   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13305 
13306   bool IsMemberSpecialization = false;
13307   bool Invalid = false;
13308 
13309   if (TemplateParameterList *TemplateParams =
13310           MatchTemplateParametersToScopeSpecifier(
13311               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13312               IsMemberSpecialization, Invalid)) {
13313     if (TemplateParams->size() > 0) {
13314       // This is a declaration of a class template.
13315       if (Invalid)
13316         return nullptr;
13317 
13318       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13319                                 NameLoc, Attr, TemplateParams, AS_public,
13320                                 /*ModulePrivateLoc=*/SourceLocation(),
13321                                 FriendLoc, TempParamLists.size() - 1,
13322                                 TempParamLists.data()).get();
13323     } else {
13324       // The "template<>" header is extraneous.
13325       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13326         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13327       IsMemberSpecialization = true;
13328     }
13329   }
13330 
13331   if (Invalid) return nullptr;
13332 
13333   bool isAllExplicitSpecializations = true;
13334   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13335     if (TempParamLists[I]->size()) {
13336       isAllExplicitSpecializations = false;
13337       break;
13338     }
13339   }
13340 
13341   // FIXME: don't ignore attributes.
13342 
13343   // If it's explicit specializations all the way down, just forget
13344   // about the template header and build an appropriate non-templated
13345   // friend.  TODO: for source fidelity, remember the headers.
13346   if (isAllExplicitSpecializations) {
13347     if (SS.isEmpty()) {
13348       bool Owned = false;
13349       bool IsDependent = false;
13350       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13351                       Attr, AS_public,
13352                       /*ModulePrivateLoc=*/SourceLocation(),
13353                       MultiTemplateParamsArg(), Owned, IsDependent,
13354                       /*ScopedEnumKWLoc=*/SourceLocation(),
13355                       /*ScopedEnumUsesClassTag=*/false,
13356                       /*UnderlyingType=*/TypeResult(),
13357                       /*IsTypeSpecifier=*/false);
13358     }
13359 
13360     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13361     ElaboratedTypeKeyword Keyword
13362       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13363     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13364                                    *Name, NameLoc);
13365     if (T.isNull())
13366       return nullptr;
13367 
13368     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13369     if (isa<DependentNameType>(T)) {
13370       DependentNameTypeLoc TL =
13371           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13372       TL.setElaboratedKeywordLoc(TagLoc);
13373       TL.setQualifierLoc(QualifierLoc);
13374       TL.setNameLoc(NameLoc);
13375     } else {
13376       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13377       TL.setElaboratedKeywordLoc(TagLoc);
13378       TL.setQualifierLoc(QualifierLoc);
13379       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13380     }
13381 
13382     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13383                                             TSI, FriendLoc, TempParamLists);
13384     Friend->setAccess(AS_public);
13385     CurContext->addDecl(Friend);
13386     return Friend;
13387   }
13388 
13389   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13390 
13391 
13392 
13393   // Handle the case of a templated-scope friend class.  e.g.
13394   //   template <class T> class A<T>::B;
13395   // FIXME: we don't support these right now.
13396   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13397     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13398   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13399   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13400   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13401   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13402   TL.setElaboratedKeywordLoc(TagLoc);
13403   TL.setQualifierLoc(SS.getWithLocInContext(Context));
13404   TL.setNameLoc(NameLoc);
13405 
13406   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13407                                           TSI, FriendLoc, TempParamLists);
13408   Friend->setAccess(AS_public);
13409   Friend->setUnsupportedFriend(true);
13410   CurContext->addDecl(Friend);
13411   return Friend;
13412 }
13413 
13414 
13415 /// Handle a friend type declaration.  This works in tandem with
13416 /// ActOnTag.
13417 ///
13418 /// Notes on friend class templates:
13419 ///
13420 /// We generally treat friend class declarations as if they were
13421 /// declaring a class.  So, for example, the elaborated type specifier
13422 /// in a friend declaration is required to obey the restrictions of a
13423 /// class-head (i.e. no typedefs in the scope chain), template
13424 /// parameters are required to match up with simple template-ids, &c.
13425 /// However, unlike when declaring a template specialization, it's
13426 /// okay to refer to a template specialization without an empty
13427 /// template parameter declaration, e.g.
13428 ///   friend class A<T>::B<unsigned>;
13429 /// We permit this as a special case; if there are any template
13430 /// parameters present at all, require proper matching, i.e.
13431 ///   template <> template \<class T> friend class A<int>::B;
13432 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
13433                                 MultiTemplateParamsArg TempParams) {
13434   SourceLocation Loc = DS.getLocStart();
13435 
13436   assert(DS.isFriendSpecified());
13437   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13438 
13439   // Try to convert the decl specifier to a type.  This works for
13440   // friend templates because ActOnTag never produces a ClassTemplateDecl
13441   // for a TUK_Friend.
13442   Declarator TheDeclarator(DS, Declarator::MemberContext);
13443   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13444   QualType T = TSI->getType();
13445   if (TheDeclarator.isInvalidType())
13446     return nullptr;
13447 
13448   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
13449     return nullptr;
13450 
13451   // This is definitely an error in C++98.  It's probably meant to
13452   // be forbidden in C++0x, too, but the specification is just
13453   // poorly written.
13454   //
13455   // The problem is with declarations like the following:
13456   //   template <T> friend A<T>::foo;
13457   // where deciding whether a class C is a friend or not now hinges
13458   // on whether there exists an instantiation of A that causes
13459   // 'foo' to equal C.  There are restrictions on class-heads
13460   // (which we declare (by fiat) elaborated friend declarations to
13461   // be) that makes this tractable.
13462   //
13463   // FIXME: handle "template <> friend class A<T>;", which
13464   // is possibly well-formed?  Who even knows?
13465   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
13466     Diag(Loc, diag::err_tagless_friend_type_template)
13467       << DS.getSourceRange();
13468     return nullptr;
13469   }
13470 
13471   // C++98 [class.friend]p1: A friend of a class is a function
13472   //   or class that is not a member of the class . . .
13473   // This is fixed in DR77, which just barely didn't make the C++03
13474   // deadline.  It's also a very silly restriction that seriously
13475   // affects inner classes and which nobody else seems to implement;
13476   // thus we never diagnose it, not even in -pedantic.
13477   //
13478   // But note that we could warn about it: it's always useless to
13479   // friend one of your own members (it's not, however, worthless to
13480   // friend a member of an arbitrary specialization of your template).
13481 
13482   Decl *D;
13483   if (!TempParams.empty())
13484     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
13485                                    TempParams,
13486                                    TSI,
13487                                    DS.getFriendSpecLoc());
13488   else
13489     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
13490 
13491   if (!D)
13492     return nullptr;
13493 
13494   D->setAccess(AS_public);
13495   CurContext->addDecl(D);
13496 
13497   return D;
13498 }
13499 
13500 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13501                                         MultiTemplateParamsArg TemplateParams) {
13502   const DeclSpec &DS = D.getDeclSpec();
13503 
13504   assert(DS.isFriendSpecified());
13505   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13506 
13507   SourceLocation Loc = D.getIdentifierLoc();
13508   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13509 
13510   // C++ [class.friend]p1
13511   //   A friend of a class is a function or class....
13512   // Note that this sees through typedefs, which is intended.
13513   // It *doesn't* see through dependent types, which is correct
13514   // according to [temp.arg.type]p3:
13515   //   If a declaration acquires a function type through a
13516   //   type dependent on a template-parameter and this causes
13517   //   a declaration that does not use the syntactic form of a
13518   //   function declarator to have a function type, the program
13519   //   is ill-formed.
13520   if (!TInfo->getType()->isFunctionType()) {
13521     Diag(Loc, diag::err_unexpected_friend);
13522 
13523     // It might be worthwhile to try to recover by creating an
13524     // appropriate declaration.
13525     return nullptr;
13526   }
13527 
13528   // C++ [namespace.memdef]p3
13529   //  - If a friend declaration in a non-local class first declares a
13530   //    class or function, the friend class or function is a member
13531   //    of the innermost enclosing namespace.
13532   //  - The name of the friend is not found by simple name lookup
13533   //    until a matching declaration is provided in that namespace
13534   //    scope (either before or after the class declaration granting
13535   //    friendship).
13536   //  - If a friend function is called, its name may be found by the
13537   //    name lookup that considers functions from namespaces and
13538   //    classes associated with the types of the function arguments.
13539   //  - When looking for a prior declaration of a class or a function
13540   //    declared as a friend, scopes outside the innermost enclosing
13541   //    namespace scope are not considered.
13542 
13543   CXXScopeSpec &SS = D.getCXXScopeSpec();
13544   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13545   DeclarationName Name = NameInfo.getName();
13546   assert(Name);
13547 
13548   // Check for unexpanded parameter packs.
13549   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13550       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13551       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
13552     return nullptr;
13553 
13554   // The context we found the declaration in, or in which we should
13555   // create the declaration.
13556   DeclContext *DC;
13557   Scope *DCScope = S;
13558   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13559                         ForRedeclaration);
13560 
13561   // There are five cases here.
13562   //   - There's no scope specifier and we're in a local class. Only look
13563   //     for functions declared in the immediately-enclosing block scope.
13564   // We recover from invalid scope qualifiers as if they just weren't there.
13565   FunctionDecl *FunctionContainingLocalClass = nullptr;
13566   if ((SS.isInvalid() || !SS.isSet()) &&
13567       (FunctionContainingLocalClass =
13568            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13569     // C++11 [class.friend]p11:
13570     //   If a friend declaration appears in a local class and the name
13571     //   specified is an unqualified name, a prior declaration is
13572     //   looked up without considering scopes that are outside the
13573     //   innermost enclosing non-class scope. For a friend function
13574     //   declaration, if there is no prior declaration, the program is
13575     //   ill-formed.
13576 
13577     // Find the innermost enclosing non-class scope. This is the block
13578     // scope containing the local class definition (or for a nested class,
13579     // the outer local class).
13580     DCScope = S->getFnParent();
13581 
13582     // Look up the function name in the scope.
13583     Previous.clear(LookupLocalFriendName);
13584     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13585 
13586     if (!Previous.empty()) {
13587       // All possible previous declarations must have the same context:
13588       // either they were declared at block scope or they are members of
13589       // one of the enclosing local classes.
13590       DC = Previous.getRepresentativeDecl()->getDeclContext();
13591     } else {
13592       // This is ill-formed, but provide the context that we would have
13593       // declared the function in, if we were permitted to, for error recovery.
13594       DC = FunctionContainingLocalClass;
13595     }
13596     adjustContextForLocalExternDecl(DC);
13597 
13598     // C++ [class.friend]p6:
13599     //   A function can be defined in a friend declaration of a class if and
13600     //   only if the class is a non-local class (9.8), the function name is
13601     //   unqualified, and the function has namespace scope.
13602     if (D.isFunctionDefinition()) {
13603       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13604     }
13605 
13606   //   - There's no scope specifier, in which case we just go to the
13607   //     appropriate scope and look for a function or function template
13608   //     there as appropriate.
13609   } else if (SS.isInvalid() || !SS.isSet()) {
13610     // C++11 [namespace.memdef]p3:
13611     //   If the name in a friend declaration is neither qualified nor
13612     //   a template-id and the declaration is a function or an
13613     //   elaborated-type-specifier, the lookup to determine whether
13614     //   the entity has been previously declared shall not consider
13615     //   any scopes outside the innermost enclosing namespace.
13616     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
13617 
13618     // Find the appropriate context according to the above.
13619     DC = CurContext;
13620 
13621     // Skip class contexts.  If someone can cite chapter and verse
13622     // for this behavior, that would be nice --- it's what GCC and
13623     // EDG do, and it seems like a reasonable intent, but the spec
13624     // really only says that checks for unqualified existing
13625     // declarations should stop at the nearest enclosing namespace,
13626     // not that they should only consider the nearest enclosing
13627     // namespace.
13628     while (DC->isRecord())
13629       DC = DC->getParent();
13630 
13631     DeclContext *LookupDC = DC;
13632     while (LookupDC->isTransparentContext())
13633       LookupDC = LookupDC->getParent();
13634 
13635     while (true) {
13636       LookupQualifiedName(Previous, LookupDC);
13637 
13638       if (!Previous.empty()) {
13639         DC = LookupDC;
13640         break;
13641       }
13642 
13643       if (isTemplateId) {
13644         if (isa<TranslationUnitDecl>(LookupDC)) break;
13645       } else {
13646         if (LookupDC->isFileContext()) break;
13647       }
13648       LookupDC = LookupDC->getParent();
13649     }
13650 
13651     DCScope = getScopeForDeclContext(S, DC);
13652 
13653   //   - There's a non-dependent scope specifier, in which case we
13654   //     compute it and do a previous lookup there for a function
13655   //     or function template.
13656   } else if (!SS.getScopeRep()->isDependent()) {
13657     DC = computeDeclContext(SS);
13658     if (!DC) return nullptr;
13659 
13660     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
13661 
13662     LookupQualifiedName(Previous, DC);
13663 
13664     // Ignore things found implicitly in the wrong scope.
13665     // TODO: better diagnostics for this case.  Suggesting the right
13666     // qualified scope would be nice...
13667     LookupResult::Filter F = Previous.makeFilter();
13668     while (F.hasNext()) {
13669       NamedDecl *D = F.next();
13670       if (!DC->InEnclosingNamespaceSetOf(
13671               D->getDeclContext()->getRedeclContext()))
13672         F.erase();
13673     }
13674     F.done();
13675 
13676     if (Previous.empty()) {
13677       D.setInvalidType();
13678       Diag(Loc, diag::err_qualified_friend_not_found)
13679           << Name << TInfo->getType();
13680       return nullptr;
13681     }
13682 
13683     // C++ [class.friend]p1: A friend of a class is a function or
13684     //   class that is not a member of the class . . .
13685     if (DC->Equals(CurContext))
13686       Diag(DS.getFriendSpecLoc(),
13687            getLangOpts().CPlusPlus11 ?
13688              diag::warn_cxx98_compat_friend_is_member :
13689              diag::err_friend_is_member);
13690 
13691     if (D.isFunctionDefinition()) {
13692       // C++ [class.friend]p6:
13693       //   A function can be defined in a friend declaration of a class if and
13694       //   only if the class is a non-local class (9.8), the function name is
13695       //   unqualified, and the function has namespace scope.
13696       SemaDiagnosticBuilder DB
13697         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13698 
13699       DB << SS.getScopeRep();
13700       if (DC->isFileContext())
13701         DB << FixItHint::CreateRemoval(SS.getRange());
13702       SS.clear();
13703     }
13704 
13705   //   - There's a scope specifier that does not match any template
13706   //     parameter lists, in which case we use some arbitrary context,
13707   //     create a method or method template, and wait for instantiation.
13708   //   - There's a scope specifier that does match some template
13709   //     parameter lists, which we don't handle right now.
13710   } else {
13711     if (D.isFunctionDefinition()) {
13712       // C++ [class.friend]p6:
13713       //   A function can be defined in a friend declaration of a class if and
13714       //   only if the class is a non-local class (9.8), the function name is
13715       //   unqualified, and the function has namespace scope.
13716       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13717         << SS.getScopeRep();
13718     }
13719 
13720     DC = CurContext;
13721     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
13722   }
13723 
13724   if (!DC->isRecord()) {
13725     int DiagArg = -1;
13726     switch (D.getName().getKind()) {
13727     case UnqualifiedId::IK_ConstructorTemplateId:
13728     case UnqualifiedId::IK_ConstructorName:
13729       DiagArg = 0;
13730       break;
13731     case UnqualifiedId::IK_DestructorName:
13732       DiagArg = 1;
13733       break;
13734     case UnqualifiedId::IK_ConversionFunctionId:
13735       DiagArg = 2;
13736       break;
13737     case UnqualifiedId::IK_DeductionGuideName:
13738       DiagArg = 3;
13739       break;
13740     case UnqualifiedId::IK_Identifier:
13741     case UnqualifiedId::IK_ImplicitSelfParam:
13742     case UnqualifiedId::IK_LiteralOperatorId:
13743     case UnqualifiedId::IK_OperatorFunctionId:
13744     case UnqualifiedId::IK_TemplateId:
13745       break;
13746     }
13747     // This implies that it has to be an operator or function.
13748     if (DiagArg >= 0) {
13749       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
13750       return nullptr;
13751     }
13752   }
13753 
13754   // FIXME: This is an egregious hack to cope with cases where the scope stack
13755   // does not contain the declaration context, i.e., in an out-of-line
13756   // definition of a class.
13757   Scope FakeDCScope(S, Scope::DeclScope, Diags);
13758   if (!DCScope) {
13759     FakeDCScope.setEntity(DC);
13760     DCScope = &FakeDCScope;
13761   }
13762 
13763   bool AddToScope = true;
13764   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
13765                                           TemplateParams, AddToScope);
13766   if (!ND) return nullptr;
13767 
13768   assert(ND->getLexicalDeclContext() == CurContext);
13769 
13770   // If we performed typo correction, we might have added a scope specifier
13771   // and changed the decl context.
13772   DC = ND->getDeclContext();
13773 
13774   // Add the function declaration to the appropriate lookup tables,
13775   // adjusting the redeclarations list as necessary.  We don't
13776   // want to do this yet if the friending class is dependent.
13777   //
13778   // Also update the scope-based lookup if the target context's
13779   // lookup context is in lexical scope.
13780   if (!CurContext->isDependentContext()) {
13781     DC = DC->getRedeclContext();
13782     DC->makeDeclVisibleInContext(ND);
13783     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13784       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
13785   }
13786 
13787   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
13788                                        D.getIdentifierLoc(), ND,
13789                                        DS.getFriendSpecLoc());
13790   FrD->setAccess(AS_public);
13791   CurContext->addDecl(FrD);
13792 
13793   if (ND->isInvalidDecl()) {
13794     FrD->setInvalidDecl();
13795   } else {
13796     if (DC->isRecord()) CheckFriendAccess(ND);
13797 
13798     FunctionDecl *FD;
13799     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13800       FD = FTD->getTemplatedDecl();
13801     else
13802       FD = cast<FunctionDecl>(ND);
13803 
13804     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13805     // default argument expression, that declaration shall be a definition
13806     // and shall be the only declaration of the function or function
13807     // template in the translation unit.
13808     if (functionDeclHasDefaultArgument(FD)) {
13809       // We can't look at FD->getPreviousDecl() because it may not have been set
13810       // if we're in a dependent context. If the function is known to be a
13811       // redeclaration, we will have narrowed Previous down to the right decl.
13812       if (D.isRedeclaration()) {
13813         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
13814         Diag(Previous.getRepresentativeDecl()->getLocation(),
13815              diag::note_previous_declaration);
13816       } else if (!D.isFunctionDefinition())
13817         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13818     }
13819 
13820     // Mark templated-scope function declarations as unsupported.
13821     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13822       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13823         << SS.getScopeRep() << SS.getRange()
13824         << cast<CXXRecordDecl>(CurContext);
13825       FrD->setUnsupportedFriend(true);
13826     }
13827   }
13828 
13829   return ND;
13830 }
13831 
13832 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13833   AdjustDeclIfTemplate(Dcl);
13834 
13835   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
13836   if (!Fn) {
13837     Diag(DelLoc, diag::err_deleted_non_function);
13838     return;
13839   }
13840 
13841   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
13842     // Don't consider the implicit declaration we generate for explicit
13843     // specializations. FIXME: Do not generate these implicit declarations.
13844     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13845          Prev->getPreviousDecl()) &&
13846         !Prev->isDefined()) {
13847       Diag(DelLoc, diag::err_deleted_decl_not_first);
13848       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13849            Prev->isImplicit() ? diag::note_previous_implicit_declaration
13850                               : diag::note_previous_declaration);
13851     }
13852     // If the declaration wasn't the first, we delete the function anyway for
13853     // recovery.
13854     Fn = Fn->getCanonicalDecl();
13855   }
13856 
13857   // dllimport/dllexport cannot be deleted.
13858   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13859     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13860     Fn->setInvalidDecl();
13861   }
13862 
13863   if (Fn->isDeleted())
13864     return;
13865 
13866   // See if we're deleting a function which is already known to override a
13867   // non-deleted virtual function.
13868   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
13869     bool IssuedDiagnostic = false;
13870     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13871                                         E = MD->end_overridden_methods();
13872          I != E; ++I) {
13873       if (!(*MD->begin_overridden_methods())->isDeleted()) {
13874         if (!IssuedDiagnostic) {
13875           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13876           IssuedDiagnostic = true;
13877         }
13878         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13879       }
13880     }
13881     // If this function was implicitly deleted because it was defaulted,
13882     // explain why it was deleted.
13883     if (IssuedDiagnostic && MD->isDefaulted())
13884       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
13885                                 /*Diagnose*/true);
13886   }
13887 
13888   // C++11 [basic.start.main]p3:
13889   //   A program that defines main as deleted [...] is ill-formed.
13890   if (Fn->isMain())
13891     Diag(DelLoc, diag::err_deleted_main);
13892 
13893   // C++11 [dcl.fct.def.delete]p4:
13894   //  A deleted function is implicitly inline.
13895   Fn->setImplicitlyInline();
13896   Fn->setDeletedAsWritten();
13897 }
13898 
13899 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
13900   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
13901 
13902   if (MD) {
13903     if (MD->getParent()->isDependentType()) {
13904       MD->setDefaulted();
13905       MD->setExplicitlyDefaulted();
13906       return;
13907     }
13908 
13909     CXXSpecialMember Member = getSpecialMember(MD);
13910     if (Member == CXXInvalid) {
13911       if (!MD->isInvalidDecl())
13912         Diag(DefaultLoc, diag::err_default_special_members);
13913       return;
13914     }
13915 
13916     MD->setDefaulted();
13917     MD->setExplicitlyDefaulted();
13918 
13919     // If this definition appears within the record, do the checking when
13920     // the record is complete.
13921     const FunctionDecl *Primary = MD;
13922     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
13923       // Ask the template instantiation pattern that actually had the
13924       // '= default' on it.
13925       Primary = Pattern;
13926 
13927     // If the method was defaulted on its first declaration, we will have
13928     // already performed the checking in CheckCompletedCXXClass. Such a
13929     // declaration doesn't trigger an implicit definition.
13930     if (Primary->getCanonicalDecl()->isDefaulted())
13931       return;
13932 
13933     CheckExplicitlyDefaultedSpecialMember(MD);
13934 
13935     if (!MD->isInvalidDecl())
13936       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
13937   } else {
13938     Diag(DefaultLoc, diag::err_default_special_members);
13939   }
13940 }
13941 
13942 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
13943   for (Stmt *SubStmt : S->children()) {
13944     if (!SubStmt)
13945       continue;
13946     if (isa<ReturnStmt>(SubStmt))
13947       Self.Diag(SubStmt->getLocStart(),
13948            diag::err_return_in_constructor_handler);
13949     if (!isa<Expr>(SubStmt))
13950       SearchForReturnInStmt(Self, SubStmt);
13951   }
13952 }
13953 
13954 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
13955   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
13956     CXXCatchStmt *Handler = TryBlock->getHandler(I);
13957     SearchForReturnInStmt(*this, Handler);
13958   }
13959 }
13960 
13961 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
13962                                              const CXXMethodDecl *Old) {
13963   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
13964   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
13965 
13966   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
13967 
13968   // If the calling conventions match, everything is fine
13969   if (NewCC == OldCC)
13970     return false;
13971 
13972   // If the calling conventions mismatch because the new function is static,
13973   // suppress the calling convention mismatch error; the error about static
13974   // function override (err_static_overrides_virtual from
13975   // Sema::CheckFunctionDeclaration) is more clear.
13976   if (New->getStorageClass() == SC_Static)
13977     return false;
13978 
13979   Diag(New->getLocation(),
13980        diag::err_conflicting_overriding_cc_attributes)
13981     << New->getDeclName() << New->getType() << Old->getType();
13982   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
13983   return true;
13984 }
13985 
13986 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
13987                                              const CXXMethodDecl *Old) {
13988   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
13989   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
13990 
13991   if (Context.hasSameType(NewTy, OldTy) ||
13992       NewTy->isDependentType() || OldTy->isDependentType())
13993     return false;
13994 
13995   // Check if the return types are covariant
13996   QualType NewClassTy, OldClassTy;
13997 
13998   /// Both types must be pointers or references to classes.
13999   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14000     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14001       NewClassTy = NewPT->getPointeeType();
14002       OldClassTy = OldPT->getPointeeType();
14003     }
14004   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14005     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14006       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14007         NewClassTy = NewRT->getPointeeType();
14008         OldClassTy = OldRT->getPointeeType();
14009       }
14010     }
14011   }
14012 
14013   // The return types aren't either both pointers or references to a class type.
14014   if (NewClassTy.isNull()) {
14015     Diag(New->getLocation(),
14016          diag::err_different_return_type_for_overriding_virtual_function)
14017         << New->getDeclName() << NewTy << OldTy
14018         << New->getReturnTypeSourceRange();
14019     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14020         << Old->getReturnTypeSourceRange();
14021 
14022     return true;
14023   }
14024 
14025   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14026     // C++14 [class.virtual]p8:
14027     //   If the class type in the covariant return type of D::f differs from
14028     //   that of B::f, the class type in the return type of D::f shall be
14029     //   complete at the point of declaration of D::f or shall be the class
14030     //   type D.
14031     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14032       if (!RT->isBeingDefined() &&
14033           RequireCompleteType(New->getLocation(), NewClassTy,
14034                               diag::err_covariant_return_incomplete,
14035                               New->getDeclName()))
14036         return true;
14037     }
14038 
14039     // Check if the new class derives from the old class.
14040     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14041       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14042           << New->getDeclName() << NewTy << OldTy
14043           << New->getReturnTypeSourceRange();
14044       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14045           << Old->getReturnTypeSourceRange();
14046       return true;
14047     }
14048 
14049     // Check if we the conversion from derived to base is valid.
14050     if (CheckDerivedToBaseConversion(
14051             NewClassTy, OldClassTy,
14052             diag::err_covariant_return_inaccessible_base,
14053             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14054             New->getLocation(), New->getReturnTypeSourceRange(),
14055             New->getDeclName(), nullptr)) {
14056       // FIXME: this note won't trigger for delayed access control
14057       // diagnostics, and it's impossible to get an undelayed error
14058       // here from access control during the original parse because
14059       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14060       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14061           << Old->getReturnTypeSourceRange();
14062       return true;
14063     }
14064   }
14065 
14066   // The qualifiers of the return types must be the same.
14067   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14068     Diag(New->getLocation(),
14069          diag::err_covariant_return_type_different_qualifications)
14070         << New->getDeclName() << NewTy << OldTy
14071         << New->getReturnTypeSourceRange();
14072     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14073         << Old->getReturnTypeSourceRange();
14074     return true;
14075   }
14076 
14077 
14078   // The new class type must have the same or less qualifiers as the old type.
14079   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14080     Diag(New->getLocation(),
14081          diag::err_covariant_return_type_class_type_more_qualified)
14082         << New->getDeclName() << NewTy << OldTy
14083         << New->getReturnTypeSourceRange();
14084     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14085         << Old->getReturnTypeSourceRange();
14086     return true;
14087   }
14088 
14089   return false;
14090 }
14091 
14092 /// \brief Mark the given method pure.
14093 ///
14094 /// \param Method the method to be marked pure.
14095 ///
14096 /// \param InitRange the source range that covers the "0" initializer.
14097 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14098   SourceLocation EndLoc = InitRange.getEnd();
14099   if (EndLoc.isValid())
14100     Method->setRangeEnd(EndLoc);
14101 
14102   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14103     Method->setPure();
14104     return false;
14105   }
14106 
14107   if (!Method->isInvalidDecl())
14108     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14109       << Method->getDeclName() << InitRange;
14110   return true;
14111 }
14112 
14113 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14114   if (D->getFriendObjectKind())
14115     Diag(D->getLocation(), diag::err_pure_friend);
14116   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14117     CheckPureMethod(M, ZeroLoc);
14118   else
14119     Diag(D->getLocation(), diag::err_illegal_initializer);
14120 }
14121 
14122 /// \brief Determine whether the given declaration is a static data member.
14123 static bool isStaticDataMember(const Decl *D) {
14124   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14125     return Var->isStaticDataMember();
14126 
14127   return false;
14128 }
14129 
14130 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
14131 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
14132 /// is a fresh scope pushed for just this purpose.
14133 ///
14134 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14135 /// static data member of class X, names should be looked up in the scope of
14136 /// class X.
14137 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14138   // If there is no declaration, there was an error parsing it.
14139   if (!D || D->isInvalidDecl())
14140     return;
14141 
14142   // We will always have a nested name specifier here, but this declaration
14143   // might not be out of line if the specifier names the current namespace:
14144   //   extern int n;
14145   //   int ::n = 0;
14146   if (D->isOutOfLine())
14147     EnterDeclaratorContext(S, D->getDeclContext());
14148 
14149   // If we are parsing the initializer for a static data member, push a
14150   // new expression evaluation context that is associated with this static
14151   // data member.
14152   if (isStaticDataMember(D))
14153     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
14154 }
14155 
14156 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
14157 /// initializer for the out-of-line declaration 'D'.
14158 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14159   // If there is no declaration, there was an error parsing it.
14160   if (!D || D->isInvalidDecl())
14161     return;
14162 
14163   if (isStaticDataMember(D))
14164     PopExpressionEvaluationContext();
14165 
14166   if (D->isOutOfLine())
14167     ExitDeclaratorContext(S);
14168 }
14169 
14170 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14171 /// C++ if/switch/while/for statement.
14172 /// e.g: "if (int x = f()) {...}"
14173 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14174   // C++ 6.4p2:
14175   // The declarator shall not specify a function or an array.
14176   // The type-specifier-seq shall not contain typedef and shall not declare a
14177   // new class or enumeration.
14178   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14179          "Parser allowed 'typedef' as storage class of condition decl.");
14180 
14181   Decl *Dcl = ActOnDeclarator(S, D);
14182   if (!Dcl)
14183     return true;
14184 
14185   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14186     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14187       << D.getSourceRange();
14188     return true;
14189   }
14190 
14191   return Dcl;
14192 }
14193 
14194 void Sema::LoadExternalVTableUses() {
14195   if (!ExternalSource)
14196     return;
14197 
14198   SmallVector<ExternalVTableUse, 4> VTables;
14199   ExternalSource->ReadUsedVTables(VTables);
14200   SmallVector<VTableUse, 4> NewUses;
14201   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14202     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14203       = VTablesUsed.find(VTables[I].Record);
14204     // Even if a definition wasn't required before, it may be required now.
14205     if (Pos != VTablesUsed.end()) {
14206       if (!Pos->second && VTables[I].DefinitionRequired)
14207         Pos->second = true;
14208       continue;
14209     }
14210 
14211     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14212     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14213   }
14214 
14215   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14216 }
14217 
14218 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14219                           bool DefinitionRequired) {
14220   // Ignore any vtable uses in unevaluated operands or for classes that do
14221   // not have a vtable.
14222   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14223       CurContext->isDependentContext() || isUnevaluatedContext())
14224     return;
14225 
14226   // Try to insert this class into the map.
14227   LoadExternalVTableUses();
14228   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14229   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14230     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14231   if (!Pos.second) {
14232     // If we already had an entry, check to see if we are promoting this vtable
14233     // to require a definition. If so, we need to reappend to the VTableUses
14234     // list, since we may have already processed the first entry.
14235     if (DefinitionRequired && !Pos.first->second) {
14236       Pos.first->second = true;
14237     } else {
14238       // Otherwise, we can early exit.
14239       return;
14240     }
14241   } else {
14242     // The Microsoft ABI requires that we perform the destructor body
14243     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14244     // the deleting destructor is emitted with the vtable, not with the
14245     // destructor definition as in the Itanium ABI.
14246     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14247       CXXDestructorDecl *DD = Class->getDestructor();
14248       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14249         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14250           // If this is an out-of-line declaration, marking it referenced will
14251           // not do anything. Manually call CheckDestructor to look up operator
14252           // delete().
14253           ContextRAII SavedContext(*this, DD);
14254           CheckDestructor(DD);
14255         } else {
14256           MarkFunctionReferenced(Loc, Class->getDestructor());
14257         }
14258       }
14259     }
14260   }
14261 
14262   // Local classes need to have their virtual members marked
14263   // immediately. For all other classes, we mark their virtual members
14264   // at the end of the translation unit.
14265   if (Class->isLocalClass())
14266     MarkVirtualMembersReferenced(Loc, Class);
14267   else
14268     VTableUses.push_back(std::make_pair(Class, Loc));
14269 }
14270 
14271 bool Sema::DefineUsedVTables() {
14272   LoadExternalVTableUses();
14273   if (VTableUses.empty())
14274     return false;
14275 
14276   // Note: The VTableUses vector could grow as a result of marking
14277   // the members of a class as "used", so we check the size each
14278   // time through the loop and prefer indices (which are stable) to
14279   // iterators (which are not).
14280   bool DefinedAnything = false;
14281   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14282     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14283     if (!Class)
14284       continue;
14285     TemplateSpecializationKind ClassTSK =
14286         Class->getTemplateSpecializationKind();
14287 
14288     SourceLocation Loc = VTableUses[I].second;
14289 
14290     bool DefineVTable = true;
14291 
14292     // If this class has a key function, but that key function is
14293     // defined in another translation unit, we don't need to emit the
14294     // vtable even though we're using it.
14295     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14296     if (KeyFunction && !KeyFunction->hasBody()) {
14297       // The key function is in another translation unit.
14298       DefineVTable = false;
14299       TemplateSpecializationKind TSK =
14300           KeyFunction->getTemplateSpecializationKind();
14301       assert(TSK != TSK_ExplicitInstantiationDefinition &&
14302              TSK != TSK_ImplicitInstantiation &&
14303              "Instantiations don't have key functions");
14304       (void)TSK;
14305     } else if (!KeyFunction) {
14306       // If we have a class with no key function that is the subject
14307       // of an explicit instantiation declaration, suppress the
14308       // vtable; it will live with the explicit instantiation
14309       // definition.
14310       bool IsExplicitInstantiationDeclaration =
14311           ClassTSK == TSK_ExplicitInstantiationDeclaration;
14312       for (auto R : Class->redecls()) {
14313         TemplateSpecializationKind TSK
14314           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14315         if (TSK == TSK_ExplicitInstantiationDeclaration)
14316           IsExplicitInstantiationDeclaration = true;
14317         else if (TSK == TSK_ExplicitInstantiationDefinition) {
14318           IsExplicitInstantiationDeclaration = false;
14319           break;
14320         }
14321       }
14322 
14323       if (IsExplicitInstantiationDeclaration)
14324         DefineVTable = false;
14325     }
14326 
14327     // The exception specifications for all virtual members may be needed even
14328     // if we are not providing an authoritative form of the vtable in this TU.
14329     // We may choose to emit it available_externally anyway.
14330     if (!DefineVTable) {
14331       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14332       continue;
14333     }
14334 
14335     // Mark all of the virtual members of this class as referenced, so
14336     // that we can build a vtable. Then, tell the AST consumer that a
14337     // vtable for this class is required.
14338     DefinedAnything = true;
14339     MarkVirtualMembersReferenced(Loc, Class);
14340     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14341     if (VTablesUsed[Canonical])
14342       Consumer.HandleVTable(Class);
14343 
14344     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14345     // no key function or the key function is inlined. Don't warn in C++ ABIs
14346     // that lack key functions, since the user won't be able to make one.
14347     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14348         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
14349       const FunctionDecl *KeyFunctionDef = nullptr;
14350       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14351                            KeyFunctionDef->isInlined())) {
14352         Diag(Class->getLocation(),
14353              ClassTSK == TSK_ExplicitInstantiationDefinition
14354                  ? diag::warn_weak_template_vtable
14355                  : diag::warn_weak_vtable)
14356             << Class;
14357       }
14358     }
14359   }
14360   VTableUses.clear();
14361 
14362   return DefinedAnything;
14363 }
14364 
14365 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14366                                                  const CXXRecordDecl *RD) {
14367   for (const auto *I : RD->methods())
14368     if (I->isVirtual() && !I->isPure())
14369       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
14370 }
14371 
14372 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14373                                         const CXXRecordDecl *RD) {
14374   // Mark all functions which will appear in RD's vtable as used.
14375   CXXFinalOverriderMap FinalOverriders;
14376   RD->getFinalOverriders(FinalOverriders);
14377   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14378                                             E = FinalOverriders.end();
14379        I != E; ++I) {
14380     for (OverridingMethods::const_iterator OI = I->second.begin(),
14381                                            OE = I->second.end();
14382          OI != OE; ++OI) {
14383       assert(OI->second.size() > 0 && "no final overrider");
14384       CXXMethodDecl *Overrider = OI->second.front().Method;
14385 
14386       // C++ [basic.def.odr]p2:
14387       //   [...] A virtual member function is used if it is not pure. [...]
14388       if (!Overrider->isPure())
14389         MarkFunctionReferenced(Loc, Overrider);
14390     }
14391   }
14392 
14393   // Only classes that have virtual bases need a VTT.
14394   if (RD->getNumVBases() == 0)
14395     return;
14396 
14397   for (const auto &I : RD->bases()) {
14398     const CXXRecordDecl *Base =
14399         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
14400     if (Base->getNumVBases() == 0)
14401       continue;
14402     MarkVirtualMembersReferenced(Loc, Base);
14403   }
14404 }
14405 
14406 /// SetIvarInitializers - This routine builds initialization ASTs for the
14407 /// Objective-C implementation whose ivars need be initialized.
14408 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
14409   if (!getLangOpts().CPlusPlus)
14410     return;
14411   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
14412     SmallVector<ObjCIvarDecl*, 8> ivars;
14413     CollectIvarsToConstructOrDestruct(OID, ivars);
14414     if (ivars.empty())
14415       return;
14416     SmallVector<CXXCtorInitializer*, 32> AllToInit;
14417     for (unsigned i = 0; i < ivars.size(); i++) {
14418       FieldDecl *Field = ivars[i];
14419       if (Field->isInvalidDecl())
14420         continue;
14421 
14422       CXXCtorInitializer *Member;
14423       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14424       InitializationKind InitKind =
14425         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
14426 
14427       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14428       ExprResult MemberInit =
14429         InitSeq.Perform(*this, InitEntity, InitKind, None);
14430       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
14431       // Note, MemberInit could actually come back empty if no initialization
14432       // is required (e.g., because it would call a trivial default constructor)
14433       if (!MemberInit.get() || MemberInit.isInvalid())
14434         continue;
14435 
14436       Member =
14437         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14438                                          SourceLocation(),
14439                                          MemberInit.getAs<Expr>(),
14440                                          SourceLocation());
14441       AllToInit.push_back(Member);
14442 
14443       // Be sure that the destructor is accessible and is marked as referenced.
14444       if (const RecordType *RecordTy =
14445               Context.getBaseElementType(Field->getType())
14446                   ->getAs<RecordType>()) {
14447         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
14448         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
14449           MarkFunctionReferenced(Field->getLocation(), Destructor);
14450           CheckDestructorAccess(Field->getLocation(), Destructor,
14451                             PDiag(diag::err_access_dtor_ivar)
14452                               << Context.getBaseElementType(Field->getType()));
14453         }
14454       }
14455     }
14456     ObjCImplementation->setIvarInitializers(Context,
14457                                             AllToInit.data(), AllToInit.size());
14458   }
14459 }
14460 
14461 static
14462 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14463                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14464                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14465                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14466                            Sema &S) {
14467   if (Ctor->isInvalidDecl())
14468     return;
14469 
14470   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14471 
14472   // Target may not be determinable yet, for instance if this is a dependent
14473   // call in an uninstantiated template.
14474   if (Target) {
14475     const FunctionDecl *FNTarget = nullptr;
14476     (void)Target->hasBody(FNTarget);
14477     Target = const_cast<CXXConstructorDecl*>(
14478       cast_or_null<CXXConstructorDecl>(FNTarget));
14479   }
14480 
14481   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14482                      // Avoid dereferencing a null pointer here.
14483                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
14484 
14485   if (!Current.insert(Canonical).second)
14486     return;
14487 
14488   // We know that beyond here, we aren't chaining into a cycle.
14489   if (!Target || !Target->isDelegatingConstructor() ||
14490       Target->isInvalidDecl() || Valid.count(TCanonical)) {
14491     Valid.insert(Current.begin(), Current.end());
14492     Current.clear();
14493   // We've hit a cycle.
14494   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14495              Current.count(TCanonical)) {
14496     // If we haven't diagnosed this cycle yet, do so now.
14497     if (!Invalid.count(TCanonical)) {
14498       S.Diag((*Ctor->init_begin())->getSourceLocation(),
14499              diag::warn_delegating_ctor_cycle)
14500         << Ctor;
14501 
14502       // Don't add a note for a function delegating directly to itself.
14503       if (TCanonical != Canonical)
14504         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14505 
14506       CXXConstructorDecl *C = Target;
14507       while (C->getCanonicalDecl() != Canonical) {
14508         const FunctionDecl *FNTarget = nullptr;
14509         (void)C->getTargetConstructor()->hasBody(FNTarget);
14510         assert(FNTarget && "Ctor cycle through bodiless function");
14511 
14512         C = const_cast<CXXConstructorDecl*>(
14513           cast<CXXConstructorDecl>(FNTarget));
14514         S.Diag(C->getLocation(), diag::note_which_delegates_to);
14515       }
14516     }
14517 
14518     Invalid.insert(Current.begin(), Current.end());
14519     Current.clear();
14520   } else {
14521     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14522   }
14523 }
14524 
14525 
14526 void Sema::CheckDelegatingCtorCycles() {
14527   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14528 
14529   for (DelegatingCtorDeclsType::iterator
14530          I = DelegatingCtorDecls.begin(ExternalSource),
14531          E = DelegatingCtorDecls.end();
14532        I != E; ++I)
14533     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
14534 
14535   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14536                                                          CE = Invalid.end();
14537        CI != CE; ++CI)
14538     (*CI)->setInvalidDecl();
14539 }
14540 
14541 namespace {
14542   /// \brief AST visitor that finds references to the 'this' expression.
14543   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14544     Sema &S;
14545 
14546   public:
14547     explicit FindCXXThisExpr(Sema &S) : S(S) { }
14548 
14549     bool VisitCXXThisExpr(CXXThisExpr *E) {
14550       S.Diag(E->getLocation(), diag::err_this_static_member_func)
14551         << E->isImplicit();
14552       return false;
14553     }
14554   };
14555 }
14556 
14557 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14558   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14559   if (!TSInfo)
14560     return false;
14561 
14562   TypeLoc TL = TSInfo->getTypeLoc();
14563   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14564   if (!ProtoTL)
14565     return false;
14566 
14567   // C++11 [expr.prim.general]p3:
14568   //   [The expression this] shall not appear before the optional
14569   //   cv-qualifier-seq and it shall not appear within the declaration of a
14570   //   static member function (although its type and value category are defined
14571   //   within a static member function as they are within a non-static member
14572   //   function). [ Note: this is because declaration matching does not occur
14573   //  until the complete declarator is known. - end note ]
14574   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14575   FindCXXThisExpr Finder(*this);
14576 
14577   // If the return type came after the cv-qualifier-seq, check it now.
14578   if (Proto->hasTrailingReturn() &&
14579       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
14580     return true;
14581 
14582   // Check the exception specification.
14583   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14584     return true;
14585 
14586   return checkThisInStaticMemberFunctionAttributes(Method);
14587 }
14588 
14589 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14590   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14591   if (!TSInfo)
14592     return false;
14593 
14594   TypeLoc TL = TSInfo->getTypeLoc();
14595   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14596   if (!ProtoTL)
14597     return false;
14598 
14599   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14600   FindCXXThisExpr Finder(*this);
14601 
14602   switch (Proto->getExceptionSpecType()) {
14603   case EST_Unparsed:
14604   case EST_Uninstantiated:
14605   case EST_Unevaluated:
14606   case EST_BasicNoexcept:
14607   case EST_DynamicNone:
14608   case EST_MSAny:
14609   case EST_None:
14610     break;
14611 
14612   case EST_ComputedNoexcept:
14613     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14614       return true;
14615 
14616   case EST_Dynamic:
14617     for (const auto &E : Proto->exceptions()) {
14618       if (!Finder.TraverseType(E))
14619         return true;
14620     }
14621     break;
14622   }
14623 
14624   return false;
14625 }
14626 
14627 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14628   FindCXXThisExpr Finder(*this);
14629 
14630   // Check attributes.
14631   for (const auto *A : Method->attrs()) {
14632     // FIXME: This should be emitted by tblgen.
14633     Expr *Arg = nullptr;
14634     ArrayRef<Expr *> Args;
14635     if (const auto *G = dyn_cast<GuardedByAttr>(A))
14636       Arg = G->getArg();
14637     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
14638       Arg = G->getArg();
14639     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
14640       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
14641     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
14642       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
14643     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
14644       Arg = ETLF->getSuccessValue();
14645       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
14646     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
14647       Arg = STLF->getSuccessValue();
14648       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
14649     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
14650       Arg = LR->getArg();
14651     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
14652       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
14653     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
14654       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14655     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
14656       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14657     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
14658       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14659     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
14660       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14661 
14662     if (Arg && !Finder.TraverseStmt(Arg))
14663       return true;
14664 
14665     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14666       if (!Finder.TraverseStmt(Args[I]))
14667         return true;
14668     }
14669   }
14670 
14671   return false;
14672 }
14673 
14674 void Sema::checkExceptionSpecification(
14675     bool IsTopLevel, ExceptionSpecificationType EST,
14676     ArrayRef<ParsedType> DynamicExceptions,
14677     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14678     SmallVectorImpl<QualType> &Exceptions,
14679     FunctionProtoType::ExceptionSpecInfo &ESI) {
14680   Exceptions.clear();
14681   ESI.Type = EST;
14682   if (EST == EST_Dynamic) {
14683     Exceptions.reserve(DynamicExceptions.size());
14684     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14685       // FIXME: Preserve type source info.
14686       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14687 
14688       if (IsTopLevel) {
14689         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14690         collectUnexpandedParameterPacks(ET, Unexpanded);
14691         if (!Unexpanded.empty()) {
14692           DiagnoseUnexpandedParameterPacks(
14693               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14694               Unexpanded);
14695           continue;
14696         }
14697       }
14698 
14699       // Check that the type is valid for an exception spec, and
14700       // drop it if not.
14701       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14702         Exceptions.push_back(ET);
14703     }
14704     ESI.Exceptions = Exceptions;
14705     return;
14706   }
14707 
14708   if (EST == EST_ComputedNoexcept) {
14709     // If an error occurred, there's no expression here.
14710     if (NoexceptExpr) {
14711       assert((NoexceptExpr->isTypeDependent() ||
14712               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14713               Context.BoolTy) &&
14714              "Parser should have made sure that the expression is boolean");
14715       if (IsTopLevel && NoexceptExpr &&
14716           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
14717         ESI.Type = EST_BasicNoexcept;
14718         return;
14719       }
14720 
14721       if (!NoexceptExpr->isValueDependent())
14722         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
14723                          diag::err_noexcept_needs_constant_expression,
14724                          /*AllowFold*/ false).get();
14725       ESI.NoexceptExpr = NoexceptExpr;
14726     }
14727     return;
14728   }
14729 }
14730 
14731 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14732              ExceptionSpecificationType EST,
14733              SourceRange SpecificationRange,
14734              ArrayRef<ParsedType> DynamicExceptions,
14735              ArrayRef<SourceRange> DynamicExceptionRanges,
14736              Expr *NoexceptExpr) {
14737   if (!MethodD)
14738     return;
14739 
14740   // Dig out the method we're referring to.
14741   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14742     MethodD = FunTmpl->getTemplatedDecl();
14743 
14744   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14745   if (!Method)
14746     return;
14747 
14748   // Check the exception specification.
14749   llvm::SmallVector<QualType, 4> Exceptions;
14750   FunctionProtoType::ExceptionSpecInfo ESI;
14751   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14752                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
14753                               ESI);
14754 
14755   // Update the exception specification on the function type.
14756   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14757 
14758   if (Method->isStatic())
14759     checkThisInStaticMemberFunctionExceptionSpec(Method);
14760 
14761   if (Method->isVirtual()) {
14762     // Check overrides, which we previously had to delay.
14763     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14764                                      OEnd = Method->end_overridden_methods();
14765          O != OEnd; ++O)
14766       CheckOverridingFunctionExceptionSpec(Method, *O);
14767   }
14768 }
14769 
14770 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14771 ///
14772 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14773                                        SourceLocation DeclStart,
14774                                        Declarator &D, Expr *BitWidth,
14775                                        InClassInitStyle InitStyle,
14776                                        AccessSpecifier AS,
14777                                        AttributeList *MSPropertyAttr) {
14778   IdentifierInfo *II = D.getIdentifier();
14779   if (!II) {
14780     Diag(DeclStart, diag::err_anonymous_property);
14781     return nullptr;
14782   }
14783   SourceLocation Loc = D.getIdentifierLoc();
14784 
14785   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14786   QualType T = TInfo->getType();
14787   if (getLangOpts().CPlusPlus) {
14788     CheckExtraCXXDefaultArguments(D);
14789 
14790     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14791                                         UPPC_DataMemberType)) {
14792       D.setInvalidType();
14793       T = Context.IntTy;
14794       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14795     }
14796   }
14797 
14798   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14799 
14800   if (D.getDeclSpec().isInlineSpecified())
14801     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14802         << getLangOpts().CPlusPlus1z;
14803   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14804     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14805          diag::err_invalid_thread)
14806       << DeclSpec::getSpecifierName(TSCS);
14807 
14808   // Check to see if this name was declared as a member previously
14809   NamedDecl *PrevDecl = nullptr;
14810   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14811   LookupName(Previous, S);
14812   switch (Previous.getResultKind()) {
14813   case LookupResult::Found:
14814   case LookupResult::FoundUnresolvedValue:
14815     PrevDecl = Previous.getAsSingle<NamedDecl>();
14816     break;
14817 
14818   case LookupResult::FoundOverloaded:
14819     PrevDecl = Previous.getRepresentativeDecl();
14820     break;
14821 
14822   case LookupResult::NotFound:
14823   case LookupResult::NotFoundInCurrentInstantiation:
14824   case LookupResult::Ambiguous:
14825     break;
14826   }
14827 
14828   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14829     // Maybe we will complain about the shadowed template parameter.
14830     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14831     // Just pretend that we didn't see the previous declaration.
14832     PrevDecl = nullptr;
14833   }
14834 
14835   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14836     PrevDecl = nullptr;
14837 
14838   SourceLocation TSSL = D.getLocStart();
14839   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
14840   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14841       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
14842   ProcessDeclAttributes(TUScope, NewPD, D);
14843   NewPD->setAccess(AS);
14844 
14845   if (NewPD->isInvalidDecl())
14846     Record->setInvalidDecl();
14847 
14848   if (D.getDeclSpec().isModulePrivateSpecified())
14849     NewPD->setModulePrivate();
14850 
14851   if (NewPD->isInvalidDecl() && PrevDecl) {
14852     // Don't introduce NewFD into scope; there's already something
14853     // with the same name in the same scope.
14854   } else if (II) {
14855     PushOnScopeChains(NewPD, S);
14856   } else
14857     Record->addDecl(NewPD);
14858 
14859   return NewPD;
14860 }
14861