]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Sema/SemaDeclCXX.cpp
Vendor import of clang trunk r300890:
[FreeBSD/FreeBSD.git] / lib / Sema / SemaDeclCXX.cpp
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       // sufficient, 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(
985       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
986
987   DeclarationName Value = S.PP.getIdentifierInfo("value");
988   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
989
990   // Form template argument list for tuple_size<T>.
991   TemplateArgumentListInfo Args(Loc, Loc);
992   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
993
994   // If there's no tuple_size specialization, it's not tuple-like.
995   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
996     return IsTupleLike::NotTupleLike;
997
998   // If we get this far, we've committed to the tuple interpretation, but
999   // we can still fail if there actually isn't a usable ::value.
1000
1001   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1002     LookupResult &R;
1003     TemplateArgumentListInfo &Args;
1004     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1005         : R(R), Args(Args) {}
1006     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1007       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1008           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1009     }
1010   } Diagnoser(R, Args);
1011
1012   if (R.empty()) {
1013     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1014     return IsTupleLike::Error;
1015   }
1016
1017   ExprResult E =
1018       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1019   if (E.isInvalid())
1020     return IsTupleLike::Error;
1021
1022   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1023   if (E.isInvalid())
1024     return IsTupleLike::Error;
1025
1026   return IsTupleLike::TupleLike;
1027 }
1028
1029 /// \return std::tuple_element<I, T>::type.
1030 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1031                                         unsigned I, QualType T) {
1032   // Form template argument list for tuple_element<I, T>.
1033   TemplateArgumentListInfo Args(Loc, Loc);
1034   Args.addArgument(
1035       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1036   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1037
1038   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1039   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1040   if (lookupStdTypeTraitMember(
1041           S, R, Loc, "tuple_element", Args,
1042           diag::err_decomp_decl_std_tuple_element_not_specialized))
1043     return QualType();
1044
1045   auto *TD = R.getAsSingle<TypeDecl>();
1046   if (!TD) {
1047     R.suppressDiagnostics();
1048     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1049       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1050     if (!R.empty())
1051       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1052     return QualType();
1053   }
1054
1055   return S.Context.getTypeDeclType(TD);
1056 }
1057
1058 namespace {
1059 struct BindingDiagnosticTrap {
1060   Sema &S;
1061   DiagnosticErrorTrap Trap;
1062   BindingDecl *BD;
1063
1064   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1065       : S(S), Trap(S.Diags), BD(BD) {}
1066   ~BindingDiagnosticTrap() {
1067     if (Trap.hasErrorOccurred())
1068       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1069   }
1070 };
1071 }
1072
1073 static bool checkTupleLikeDecomposition(Sema &S,
1074                                         ArrayRef<BindingDecl *> Bindings,
1075                                         VarDecl *Src, QualType DecompType,
1076                                         const llvm::APSInt &TupleSize) {
1077   if ((int64_t)Bindings.size() != TupleSize) {
1078     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1079         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1080         << (TupleSize < Bindings.size());
1081     return true;
1082   }
1083
1084   if (Bindings.empty())
1085     return false;
1086
1087   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1088
1089   // [dcl.decomp]p3:
1090   //   The unqualified-id get is looked up in the scope of E by class member
1091   //   access lookup
1092   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1093   bool UseMemberGet = false;
1094   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1095     if (auto *RD = DecompType->getAsCXXRecordDecl())
1096       S.LookupQualifiedName(MemberGet, RD);
1097     if (MemberGet.isAmbiguous())
1098       return true;
1099     UseMemberGet = !MemberGet.empty();
1100     S.FilterAcceptableTemplateNames(MemberGet);
1101   }
1102
1103   unsigned I = 0;
1104   for (auto *B : Bindings) {
1105     BindingDiagnosticTrap Trap(S, B);
1106     SourceLocation Loc = B->getLocation();
1107
1108     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1109     if (E.isInvalid())
1110       return true;
1111
1112     //   e is an lvalue if the type of the entity is an lvalue reference and
1113     //   an xvalue otherwise
1114     if (!Src->getType()->isLValueReferenceType())
1115       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1116                                    E.get(), nullptr, VK_XValue);
1117
1118     TemplateArgumentListInfo Args(Loc, Loc);
1119     Args.addArgument(
1120         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1121
1122     if (UseMemberGet) {
1123       //   if [lookup of member get] finds at least one declaration, the
1124       //   initializer is e.get<i-1>().
1125       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1126                                      CXXScopeSpec(), SourceLocation(), nullptr,
1127                                      MemberGet, &Args, nullptr);
1128       if (E.isInvalid())
1129         return true;
1130
1131       E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1132     } else {
1133       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1134       //   in the associated namespaces.
1135       Expr *Get = UnresolvedLookupExpr::Create(
1136           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1137           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1138           UnresolvedSetIterator(), UnresolvedSetIterator());
1139
1140       Expr *Arg = E.get();
1141       E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1142     }
1143     if (E.isInvalid())
1144       return true;
1145     Expr *Init = E.get();
1146
1147     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1148     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1149     if (T.isNull())
1150       return true;
1151
1152     //   each vi is a variable of type "reference to T" initialized with the
1153     //   initializer, where the reference is an lvalue reference if the
1154     //   initializer is an lvalue and an rvalue reference otherwise
1155     QualType RefType =
1156         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1157     if (RefType.isNull())
1158       return true;
1159     auto *RefVD = VarDecl::Create(
1160         S.Context, Src->getDeclContext(), Loc, Loc,
1161         B->getDeclName().getAsIdentifierInfo(), RefType,
1162         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1163     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1164     RefVD->setTSCSpec(Src->getTSCSpec());
1165     RefVD->setImplicit();
1166     if (Src->isInlineSpecified())
1167       RefVD->setInlineSpecified();
1168     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1169
1170     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1171     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1172     InitializationSequence Seq(S, Entity, Kind, Init);
1173     E = Seq.Perform(S, Entity, Kind, Init);
1174     if (E.isInvalid())
1175       return true;
1176     E = S.ActOnFinishFullExpr(E.get(), Loc);
1177     if (E.isInvalid())
1178       return true;
1179     RefVD->setInit(E.get());
1180     RefVD->checkInitIsICE();
1181
1182     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1183                                    DeclarationNameInfo(B->getDeclName(), Loc),
1184                                    RefVD);
1185     if (E.isInvalid())
1186       return true;
1187
1188     B->setBinding(T, E.get());
1189     I++;
1190   }
1191
1192   return false;
1193 }
1194
1195 /// Find the base class to decompose in a built-in decomposition of a class type.
1196 /// This base class search is, unfortunately, not quite like any other that we
1197 /// perform anywhere else in C++.
1198 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1199                                                       SourceLocation Loc,
1200                                                       const CXXRecordDecl *RD,
1201                                                       CXXCastPath &BasePath) {
1202   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1203                           CXXBasePath &Path) {
1204     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1205   };
1206
1207   const CXXRecordDecl *ClassWithFields = nullptr;
1208   if (RD->hasDirectFields())
1209     // [dcl.decomp]p4:
1210     //   Otherwise, all of E's non-static data members shall be public direct
1211     //   members of E ...
1212     ClassWithFields = RD;
1213   else {
1214     //   ... or of ...
1215     CXXBasePaths Paths;
1216     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1217     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1218       // If no classes have fields, just decompose RD itself. (This will work
1219       // if and only if zero bindings were provided.)
1220       return RD;
1221     }
1222
1223     CXXBasePath *BestPath = nullptr;
1224     for (auto &P : Paths) {
1225       if (!BestPath)
1226         BestPath = &P;
1227       else if (!S.Context.hasSameType(P.back().Base->getType(),
1228                                       BestPath->back().Base->getType())) {
1229         //   ... the same ...
1230         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1231           << false << RD << BestPath->back().Base->getType()
1232           << P.back().Base->getType();
1233         return nullptr;
1234       } else if (P.Access < BestPath->Access) {
1235         BestPath = &P;
1236       }
1237     }
1238
1239     //   ... unambiguous ...
1240     QualType BaseType = BestPath->back().Base->getType();
1241     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1242       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1243         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1244       return nullptr;
1245     }
1246
1247     //   ... public base class of E.
1248     if (BestPath->Access != AS_public) {
1249       S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1250         << RD << BaseType;
1251       for (auto &BS : *BestPath) {
1252         if (BS.Base->getAccessSpecifier() != AS_public) {
1253           S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1254             << (BS.Base->getAccessSpecifier() == AS_protected)
1255             << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1256           break;
1257         }
1258       }
1259       return nullptr;
1260     }
1261
1262     ClassWithFields = BaseType->getAsCXXRecordDecl();
1263     S.BuildBasePathArray(Paths, BasePath);
1264   }
1265
1266   // The above search did not check whether the selected class itself has base
1267   // classes with fields, so check that now.
1268   CXXBasePaths Paths;
1269   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1270     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1271       << (ClassWithFields == RD) << RD << ClassWithFields
1272       << Paths.front().back().Base->getType();
1273     return nullptr;
1274   }
1275
1276   return ClassWithFields;
1277 }
1278
1279 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1280                                      ValueDecl *Src, QualType DecompType,
1281                                      const CXXRecordDecl *RD) {
1282   CXXCastPath BasePath;
1283   RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1284   if (!RD)
1285     return true;
1286   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1287                                                  DecompType.getQualifiers());
1288
1289   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1290     unsigned NumFields =
1291         std::count_if(RD->field_begin(), RD->field_end(),
1292                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1293     assert(Bindings.size() != NumFields);
1294     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1295         << DecompType << (unsigned)Bindings.size() << NumFields
1296         << (NumFields < Bindings.size());
1297     return true;
1298   };
1299
1300   //   all of E's non-static data members shall be public [...] members,
1301   //   E shall not have an anonymous union member, ...
1302   unsigned I = 0;
1303   for (auto *FD : RD->fields()) {
1304     if (FD->isUnnamedBitfield())
1305       continue;
1306
1307     if (FD->isAnonymousStructOrUnion()) {
1308       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1309         << DecompType << FD->getType()->isUnionType();
1310       S.Diag(FD->getLocation(), diag::note_declared_at);
1311       return true;
1312     }
1313
1314     // We have a real field to bind.
1315     if (I >= Bindings.size())
1316       return DiagnoseBadNumberOfBindings();
1317     auto *B = Bindings[I++];
1318
1319     SourceLocation Loc = B->getLocation();
1320     if (FD->getAccess() != AS_public) {
1321       S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1322
1323       // Determine whether the access specifier was explicit.
1324       bool Implicit = true;
1325       for (const auto *D : RD->decls()) {
1326         if (declaresSameEntity(D, FD))
1327           break;
1328         if (isa<AccessSpecDecl>(D)) {
1329           Implicit = false;
1330           break;
1331         }
1332       }
1333
1334       S.Diag(FD->getLocation(), diag::note_access_natural)
1335         << (FD->getAccess() == AS_protected) << Implicit;
1336       return true;
1337     }
1338
1339     // Initialize the binding to Src.FD.
1340     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1341     if (E.isInvalid())
1342       return true;
1343     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1344                             VK_LValue, &BasePath);
1345     if (E.isInvalid())
1346       return true;
1347     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1348                                   CXXScopeSpec(), FD,
1349                                   DeclAccessPair::make(FD, FD->getAccess()),
1350                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1351     if (E.isInvalid())
1352       return true;
1353
1354     // If the type of the member is T, the referenced type is cv T, where cv is
1355     // the cv-qualification of the decomposition expression.
1356     //
1357     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1358     // 'const' to the type of the field.
1359     Qualifiers Q = DecompType.getQualifiers();
1360     if (FD->isMutable())
1361       Q.removeConst();
1362     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1363   }
1364
1365   if (I != Bindings.size())
1366     return DiagnoseBadNumberOfBindings();
1367
1368   return false;
1369 }
1370
1371 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1372   QualType DecompType = DD->getType();
1373
1374   // If the type of the decomposition is dependent, then so is the type of
1375   // each binding.
1376   if (DecompType->isDependentType()) {
1377     for (auto *B : DD->bindings())
1378       B->setType(Context.DependentTy);
1379     return;
1380   }
1381
1382   DecompType = DecompType.getNonReferenceType();
1383   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1384
1385   // C++1z [dcl.decomp]/2:
1386   //   If E is an array type [...]
1387   // As an extension, we also support decomposition of built-in complex and
1388   // vector types.
1389   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1390     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1391       DD->setInvalidDecl();
1392     return;
1393   }
1394   if (auto *VT = DecompType->getAs<VectorType>()) {
1395     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1396       DD->setInvalidDecl();
1397     return;
1398   }
1399   if (auto *CT = DecompType->getAs<ComplexType>()) {
1400     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1401       DD->setInvalidDecl();
1402     return;
1403   }
1404
1405   // C++1z [dcl.decomp]/3:
1406   //   if the expression std::tuple_size<E>::value is a well-formed integral
1407   //   constant expression, [...]
1408   llvm::APSInt TupleSize(32);
1409   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1410   case IsTupleLike::Error:
1411     DD->setInvalidDecl();
1412     return;
1413
1414   case IsTupleLike::TupleLike:
1415     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1416       DD->setInvalidDecl();
1417     return;
1418
1419   case IsTupleLike::NotTupleLike:
1420     break;
1421   }
1422
1423   // C++1z [dcl.dcl]/8:
1424   //   [E shall be of array or non-union class type]
1425   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1426   if (!RD || RD->isUnion()) {
1427     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1428         << DD << !RD << DecompType;
1429     DD->setInvalidDecl();
1430     return;
1431   }
1432
1433   // C++1z [dcl.decomp]/4:
1434   //   all of E's non-static data members shall be [...] direct members of
1435   //   E or of the same unambiguous public base class of E, ...
1436   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1437     DD->setInvalidDecl();
1438 }
1439
1440 /// \brief Merge the exception specifications of two variable declarations.
1441 ///
1442 /// This is called when there's a redeclaration of a VarDecl. The function
1443 /// checks if the redeclaration might have an exception specification and
1444 /// validates compatibility and merges the specs if necessary.
1445 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1446   // Shortcut if exceptions are disabled.
1447   if (!getLangOpts().CXXExceptions)
1448     return;
1449
1450   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1451          "Should only be called if types are otherwise the same.");
1452
1453   QualType NewType = New->getType();
1454   QualType OldType = Old->getType();
1455
1456   // We're only interested in pointers and references to functions, as well
1457   // as pointers to member functions.
1458   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1459     NewType = R->getPointeeType();
1460     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1461   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1462     NewType = P->getPointeeType();
1463     OldType = OldType->getAs<PointerType>()->getPointeeType();
1464   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1465     NewType = M->getPointeeType();
1466     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1467   }
1468
1469   if (!NewType->isFunctionProtoType())
1470     return;
1471
1472   // There's lots of special cases for functions. For function pointers, system
1473   // libraries are hopefully not as broken so that we don't need these
1474   // workarounds.
1475   if (CheckEquivalentExceptionSpec(
1476         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1477         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1478     New->setInvalidDecl();
1479   }
1480 }
1481
1482 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1483 /// function declaration are well-formed according to C++
1484 /// [dcl.fct.default].
1485 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1486   unsigned NumParams = FD->getNumParams();
1487   unsigned p;
1488
1489   // Find first parameter with a default argument
1490   for (p = 0; p < NumParams; ++p) {
1491     ParmVarDecl *Param = FD->getParamDecl(p);
1492     if (Param->hasDefaultArg())
1493       break;
1494   }
1495
1496   // C++11 [dcl.fct.default]p4:
1497   //   In a given function declaration, each parameter subsequent to a parameter
1498   //   with a default argument shall have a default argument supplied in this or
1499   //   a previous declaration or shall be a function parameter pack. A default
1500   //   argument shall not be redefined by a later declaration (not even to the
1501   //   same value).
1502   unsigned LastMissingDefaultArg = 0;
1503   for (; p < NumParams; ++p) {
1504     ParmVarDecl *Param = FD->getParamDecl(p);
1505     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1506       if (Param->isInvalidDecl())
1507         /* We already complained about this parameter. */;
1508       else if (Param->getIdentifier())
1509         Diag(Param->getLocation(),
1510              diag::err_param_default_argument_missing_name)
1511           << Param->getIdentifier();
1512       else
1513         Diag(Param->getLocation(),
1514              diag::err_param_default_argument_missing);
1515
1516       LastMissingDefaultArg = p;
1517     }
1518   }
1519
1520   if (LastMissingDefaultArg > 0) {
1521     // Some default arguments were missing. Clear out all of the
1522     // default arguments up to (and including) the last missing
1523     // default argument, so that we leave the function parameters
1524     // in a semantically valid state.
1525     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1526       ParmVarDecl *Param = FD->getParamDecl(p);
1527       if (Param->hasDefaultArg()) {
1528         Param->setDefaultArg(nullptr);
1529       }
1530     }
1531   }
1532 }
1533
1534 // CheckConstexprParameterTypes - Check whether a function's parameter types
1535 // are all literal types. If so, return true. If not, produce a suitable
1536 // diagnostic and return false.
1537 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1538                                          const FunctionDecl *FD) {
1539   unsigned ArgIndex = 0;
1540   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1541   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1542                                               e = FT->param_type_end();
1543        i != e; ++i, ++ArgIndex) {
1544     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1545     SourceLocation ParamLoc = PD->getLocation();
1546     if (!(*i)->isDependentType() &&
1547         SemaRef.RequireLiteralType(ParamLoc, *i,
1548                                    diag::err_constexpr_non_literal_param,
1549                                    ArgIndex+1, PD->getSourceRange(),
1550                                    isa<CXXConstructorDecl>(FD)))
1551       return false;
1552   }
1553   return true;
1554 }
1555
1556 /// \brief Get diagnostic %select index for tag kind for
1557 /// record diagnostic message.
1558 /// WARNING: Indexes apply to particular diagnostics only!
1559 ///
1560 /// \returns diagnostic %select index.
1561 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1562   switch (Tag) {
1563   case TTK_Struct: return 0;
1564   case TTK_Interface: return 1;
1565   case TTK_Class:  return 2;
1566   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1567   }
1568 }
1569
1570 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1571 // the requirements of a constexpr function definition or a constexpr
1572 // constructor definition. If so, return true. If not, produce appropriate
1573 // diagnostics and return false.
1574 //
1575 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1576 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1577   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1578   if (MD && MD->isInstance()) {
1579     // C++11 [dcl.constexpr]p4:
1580     //  The definition of a constexpr constructor shall satisfy the following
1581     //  constraints:
1582     //  - the class shall not have any virtual base classes;
1583     const CXXRecordDecl *RD = MD->getParent();
1584     if (RD->getNumVBases()) {
1585       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1586         << isa<CXXConstructorDecl>(NewFD)
1587         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1588       for (const auto &I : RD->vbases())
1589         Diag(I.getLocStart(),
1590              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
1591       return false;
1592     }
1593   }
1594
1595   if (!isa<CXXConstructorDecl>(NewFD)) {
1596     // C++11 [dcl.constexpr]p3:
1597     //  The definition of a constexpr function shall satisfy the following
1598     //  constraints:
1599     // - it shall not be virtual;
1600     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1601     if (Method && Method->isVirtual()) {
1602       Method = Method->getCanonicalDecl();
1603       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1604
1605       // If it's not obvious why this function is virtual, find an overridden
1606       // function which uses the 'virtual' keyword.
1607       const CXXMethodDecl *WrittenVirtual = Method;
1608       while (!WrittenVirtual->isVirtualAsWritten())
1609         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1610       if (WrittenVirtual != Method)
1611         Diag(WrittenVirtual->getLocation(),
1612              diag::note_overridden_virtual_function);
1613       return false;
1614     }
1615
1616     // - its return type shall be a literal type;
1617     QualType RT = NewFD->getReturnType();
1618     if (!RT->isDependentType() &&
1619         RequireLiteralType(NewFD->getLocation(), RT,
1620                            diag::err_constexpr_non_literal_return))
1621       return false;
1622   }
1623
1624   // - each of its parameter types shall be a literal type;
1625   if (!CheckConstexprParameterTypes(*this, NewFD))
1626     return false;
1627
1628   return true;
1629 }
1630
1631 /// Check the given declaration statement is legal within a constexpr function
1632 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1633 ///
1634 /// \return true if the body is OK (maybe only as an extension), false if we
1635 ///         have diagnosed a problem.
1636 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1637                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1638   // C++11 [dcl.constexpr]p3 and p4:
1639   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1640   //  contain only
1641   for (const auto *DclIt : DS->decls()) {
1642     switch (DclIt->getKind()) {
1643     case Decl::StaticAssert:
1644     case Decl::Using:
1645     case Decl::UsingShadow:
1646     case Decl::UsingDirective:
1647     case Decl::UnresolvedUsingTypename:
1648     case Decl::UnresolvedUsingValue:
1649       //   - static_assert-declarations
1650       //   - using-declarations,
1651       //   - using-directives,
1652       continue;
1653
1654     case Decl::Typedef:
1655     case Decl::TypeAlias: {
1656       //   - typedef declarations and alias-declarations that do not define
1657       //     classes or enumerations,
1658       const auto *TN = cast<TypedefNameDecl>(DclIt);
1659       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1660         // Don't allow variably-modified types in constexpr functions.
1661         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1662         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1663           << TL.getSourceRange() << TL.getType()
1664           << isa<CXXConstructorDecl>(Dcl);
1665         return false;
1666       }
1667       continue;
1668     }
1669
1670     case Decl::Enum:
1671     case Decl::CXXRecord:
1672       // C++1y allows types to be defined, not just declared.
1673       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1674         SemaRef.Diag(DS->getLocStart(),
1675                      SemaRef.getLangOpts().CPlusPlus14
1676                        ? diag::warn_cxx11_compat_constexpr_type_definition
1677                        : diag::ext_constexpr_type_definition)
1678           << isa<CXXConstructorDecl>(Dcl);
1679       continue;
1680
1681     case Decl::EnumConstant:
1682     case Decl::IndirectField:
1683     case Decl::ParmVar:
1684       // These can only appear with other declarations which are banned in
1685       // C++11 and permitted in C++1y, so ignore them.
1686       continue;
1687
1688     case Decl::Var:
1689     case Decl::Decomposition: {
1690       // C++1y [dcl.constexpr]p3 allows anything except:
1691       //   a definition of a variable of non-literal type or of static or
1692       //   thread storage duration or for which no initialization is performed.
1693       const auto *VD = cast<VarDecl>(DclIt);
1694       if (VD->isThisDeclarationADefinition()) {
1695         if (VD->isStaticLocal()) {
1696           SemaRef.Diag(VD->getLocation(),
1697                        diag::err_constexpr_local_var_static)
1698             << isa<CXXConstructorDecl>(Dcl)
1699             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1700           return false;
1701         }
1702         if (!VD->getType()->isDependentType() &&
1703             SemaRef.RequireLiteralType(
1704               VD->getLocation(), VD->getType(),
1705               diag::err_constexpr_local_var_non_literal_type,
1706               isa<CXXConstructorDecl>(Dcl)))
1707           return false;
1708         if (!VD->getType()->isDependentType() &&
1709             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1710           SemaRef.Diag(VD->getLocation(),
1711                        diag::err_constexpr_local_var_no_init)
1712             << isa<CXXConstructorDecl>(Dcl);
1713           return false;
1714         }
1715       }
1716       SemaRef.Diag(VD->getLocation(),
1717                    SemaRef.getLangOpts().CPlusPlus14
1718                     ? diag::warn_cxx11_compat_constexpr_local_var
1719                     : diag::ext_constexpr_local_var)
1720         << isa<CXXConstructorDecl>(Dcl);
1721       continue;
1722     }
1723
1724     case Decl::NamespaceAlias:
1725     case Decl::Function:
1726       // These are disallowed in C++11 and permitted in C++1y. Allow them
1727       // everywhere as an extension.
1728       if (!Cxx1yLoc.isValid())
1729         Cxx1yLoc = DS->getLocStart();
1730       continue;
1731
1732     default:
1733       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1734         << isa<CXXConstructorDecl>(Dcl);
1735       return false;
1736     }
1737   }
1738
1739   return true;
1740 }
1741
1742 /// Check that the given field is initialized within a constexpr constructor.
1743 ///
1744 /// \param Dcl The constexpr constructor being checked.
1745 /// \param Field The field being checked. This may be a member of an anonymous
1746 ///        struct or union nested within the class being checked.
1747 /// \param Inits All declarations, including anonymous struct/union members and
1748 ///        indirect members, for which any initialization was provided.
1749 /// \param Diagnosed Set to true if an error is produced.
1750 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1751                                           const FunctionDecl *Dcl,
1752                                           FieldDecl *Field,
1753                                           llvm::SmallSet<Decl*, 16> &Inits,
1754                                           bool &Diagnosed) {
1755   if (Field->isInvalidDecl())
1756     return;
1757
1758   if (Field->isUnnamedBitfield())
1759     return;
1760
1761   // Anonymous unions with no variant members and empty anonymous structs do not
1762   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1763   // indirect fields don't need initializing.
1764   if (Field->isAnonymousStructOrUnion() &&
1765       (Field->getType()->isUnionType()
1766            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1767            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1768     return;
1769
1770   if (!Inits.count(Field)) {
1771     if (!Diagnosed) {
1772       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1773       Diagnosed = true;
1774     }
1775     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1776   } else if (Field->isAnonymousStructOrUnion()) {
1777     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1778     for (auto *I : RD->fields())
1779       // If an anonymous union contains an anonymous struct of which any member
1780       // is initialized, all members must be initialized.
1781       if (!RD->isUnion() || Inits.count(I))
1782         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1783   }
1784 }
1785
1786 /// Check the provided statement is allowed in a constexpr function
1787 /// definition.
1788 static bool
1789 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1790                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1791                            SourceLocation &Cxx1yLoc) {
1792   // - its function-body shall be [...] a compound-statement that contains only
1793   switch (S->getStmtClass()) {
1794   case Stmt::NullStmtClass:
1795     //   - null statements,
1796     return true;
1797
1798   case Stmt::DeclStmtClass:
1799     //   - static_assert-declarations
1800     //   - using-declarations,
1801     //   - using-directives,
1802     //   - typedef declarations and alias-declarations that do not define
1803     //     classes or enumerations,
1804     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1805       return false;
1806     return true;
1807
1808   case Stmt::ReturnStmtClass:
1809     //   - and exactly one return statement;
1810     if (isa<CXXConstructorDecl>(Dcl)) {
1811       // C++1y allows return statements in constexpr constructors.
1812       if (!Cxx1yLoc.isValid())
1813         Cxx1yLoc = S->getLocStart();
1814       return true;
1815     }
1816
1817     ReturnStmts.push_back(S->getLocStart());
1818     return true;
1819
1820   case Stmt::CompoundStmtClass: {
1821     // C++1y allows compound-statements.
1822     if (!Cxx1yLoc.isValid())
1823       Cxx1yLoc = S->getLocStart();
1824
1825     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1826     for (auto *BodyIt : CompStmt->body()) {
1827       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1828                                       Cxx1yLoc))
1829         return false;
1830     }
1831     return true;
1832   }
1833
1834   case Stmt::AttributedStmtClass:
1835     if (!Cxx1yLoc.isValid())
1836       Cxx1yLoc = S->getLocStart();
1837     return true;
1838
1839   case Stmt::IfStmtClass: {
1840     // C++1y allows if-statements.
1841     if (!Cxx1yLoc.isValid())
1842       Cxx1yLoc = S->getLocStart();
1843
1844     IfStmt *If = cast<IfStmt>(S);
1845     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1846                                     Cxx1yLoc))
1847       return false;
1848     if (If->getElse() &&
1849         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1850                                     Cxx1yLoc))
1851       return false;
1852     return true;
1853   }
1854
1855   case Stmt::WhileStmtClass:
1856   case Stmt::DoStmtClass:
1857   case Stmt::ForStmtClass:
1858   case Stmt::CXXForRangeStmtClass:
1859   case Stmt::ContinueStmtClass:
1860     // C++1y allows all of these. We don't allow them as extensions in C++11,
1861     // because they don't make sense without variable mutation.
1862     if (!SemaRef.getLangOpts().CPlusPlus14)
1863       break;
1864     if (!Cxx1yLoc.isValid())
1865       Cxx1yLoc = S->getLocStart();
1866     for (Stmt *SubStmt : S->children())
1867       if (SubStmt &&
1868           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1869                                       Cxx1yLoc))
1870         return false;
1871     return true;
1872
1873   case Stmt::SwitchStmtClass:
1874   case Stmt::CaseStmtClass:
1875   case Stmt::DefaultStmtClass:
1876   case Stmt::BreakStmtClass:
1877     // C++1y allows switch-statements, and since they don't need variable
1878     // mutation, we can reasonably allow them in C++11 as an extension.
1879     if (!Cxx1yLoc.isValid())
1880       Cxx1yLoc = S->getLocStart();
1881     for (Stmt *SubStmt : S->children())
1882       if (SubStmt &&
1883           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1884                                       Cxx1yLoc))
1885         return false;
1886     return true;
1887
1888   default:
1889     if (!isa<Expr>(S))
1890       break;
1891
1892     // C++1y allows expression-statements.
1893     if (!Cxx1yLoc.isValid())
1894       Cxx1yLoc = S->getLocStart();
1895     return true;
1896   }
1897
1898   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1899     << isa<CXXConstructorDecl>(Dcl);
1900   return false;
1901 }
1902
1903 /// Check the body for the given constexpr function declaration only contains
1904 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1905 ///
1906 /// \return true if the body is OK, false if we have diagnosed a problem.
1907 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1908   if (isa<CXXTryStmt>(Body)) {
1909     // C++11 [dcl.constexpr]p3:
1910     //  The definition of a constexpr function shall satisfy the following
1911     //  constraints: [...]
1912     // - its function-body shall be = delete, = default, or a
1913     //   compound-statement
1914     //
1915     // C++11 [dcl.constexpr]p4:
1916     //  In the definition of a constexpr constructor, [...]
1917     // - its function-body shall not be a function-try-block;
1918     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1919       << isa<CXXConstructorDecl>(Dcl);
1920     return false;
1921   }
1922
1923   SmallVector<SourceLocation, 4> ReturnStmts;
1924
1925   // - its function-body shall be [...] a compound-statement that contains only
1926   //   [... list of cases ...]
1927   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1928   SourceLocation Cxx1yLoc;
1929   for (auto *BodyIt : CompBody->body()) {
1930     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1931       return false;
1932   }
1933
1934   if (Cxx1yLoc.isValid())
1935     Diag(Cxx1yLoc,
1936          getLangOpts().CPlusPlus14
1937            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1938            : diag::ext_constexpr_body_invalid_stmt)
1939       << isa<CXXConstructorDecl>(Dcl);
1940
1941   if (const CXXConstructorDecl *Constructor
1942         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1943     const CXXRecordDecl *RD = Constructor->getParent();
1944     // DR1359:
1945     // - every non-variant non-static data member and base class sub-object
1946     //   shall be initialized;
1947     // DR1460:
1948     // - if the class is a union having variant members, exactly one of them
1949     //   shall be initialized;
1950     if (RD->isUnion()) {
1951       if (Constructor->getNumCtorInitializers() == 0 &&
1952           RD->hasVariantMembers()) {
1953         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1954         return false;
1955       }
1956     } else if (!Constructor->isDependentContext() &&
1957                !Constructor->isDelegatingConstructor()) {
1958       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1959
1960       // Skip detailed checking if we have enough initializers, and we would
1961       // allow at most one initializer per member.
1962       bool AnyAnonStructUnionMembers = false;
1963       unsigned Fields = 0;
1964       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1965            E = RD->field_end(); I != E; ++I, ++Fields) {
1966         if (I->isAnonymousStructOrUnion()) {
1967           AnyAnonStructUnionMembers = true;
1968           break;
1969         }
1970       }
1971       // DR1460:
1972       // - if the class is a union-like class, but is not a union, for each of
1973       //   its anonymous union members having variant members, exactly one of
1974       //   them shall be initialized;
1975       if (AnyAnonStructUnionMembers ||
1976           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1977         // Check initialization of non-static data members. Base classes are
1978         // always initialized so do not need to be checked. Dependent bases
1979         // might not have initializers in the member initializer list.
1980         llvm::SmallSet<Decl*, 16> Inits;
1981         for (const auto *I: Constructor->inits()) {
1982           if (FieldDecl *FD = I->getMember())
1983             Inits.insert(FD);
1984           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1985             Inits.insert(ID->chain_begin(), ID->chain_end());
1986         }
1987
1988         bool Diagnosed = false;
1989         for (auto *I : RD->fields())
1990           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1991         if (Diagnosed)
1992           return false;
1993       }
1994     }
1995   } else {
1996     if (ReturnStmts.empty()) {
1997       // C++1y doesn't require constexpr functions to contain a 'return'
1998       // statement. We still do, unless the return type might be void, because
1999       // otherwise if there's no return statement, the function cannot
2000       // be used in a core constant expression.
2001       bool OK = getLangOpts().CPlusPlus14 &&
2002                 (Dcl->getReturnType()->isVoidType() ||
2003                  Dcl->getReturnType()->isDependentType());
2004       Diag(Dcl->getLocation(),
2005            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2006               : diag::err_constexpr_body_no_return);
2007       if (!OK)
2008         return false;
2009     } else if (ReturnStmts.size() > 1) {
2010       Diag(ReturnStmts.back(),
2011            getLangOpts().CPlusPlus14
2012              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2013              : diag::ext_constexpr_body_multiple_return);
2014       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2015         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2016     }
2017   }
2018
2019   // C++11 [dcl.constexpr]p5:
2020   //   if no function argument values exist such that the function invocation
2021   //   substitution would produce a constant expression, the program is
2022   //   ill-formed; no diagnostic required.
2023   // C++11 [dcl.constexpr]p3:
2024   //   - every constructor call and implicit conversion used in initializing the
2025   //     return value shall be one of those allowed in a constant expression.
2026   // C++11 [dcl.constexpr]p4:
2027   //   - every constructor involved in initializing non-static data members and
2028   //     base class sub-objects shall be a constexpr constructor.
2029   SmallVector<PartialDiagnosticAt, 8> Diags;
2030   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2031     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2032       << isa<CXXConstructorDecl>(Dcl);
2033     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2034       Diag(Diags[I].first, Diags[I].second);
2035     // Don't return false here: we allow this for compatibility in
2036     // system headers.
2037   }
2038
2039   return true;
2040 }
2041
2042 /// isCurrentClassName - Determine whether the identifier II is the
2043 /// name of the class type currently being defined. In the case of
2044 /// nested classes, this will only return true if II is the name of
2045 /// the innermost class.
2046 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2047                               const CXXScopeSpec *SS) {
2048   assert(getLangOpts().CPlusPlus && "No class names in C!");
2049
2050   CXXRecordDecl *CurDecl;
2051   if (SS && SS->isSet() && !SS->isInvalid()) {
2052     DeclContext *DC = computeDeclContext(*SS, true);
2053     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2054   } else
2055     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2056
2057   if (CurDecl && CurDecl->getIdentifier())
2058     return &II == CurDecl->getIdentifier();
2059   return false;
2060 }
2061
2062 /// \brief Determine whether the identifier II is a typo for the name of
2063 /// the class type currently being defined. If so, update it to the identifier
2064 /// that should have been used.
2065 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2066   assert(getLangOpts().CPlusPlus && "No class names in C!");
2067
2068   if (!getLangOpts().SpellChecking)
2069     return false;
2070
2071   CXXRecordDecl *CurDecl;
2072   if (SS && SS->isSet() && !SS->isInvalid()) {
2073     DeclContext *DC = computeDeclContext(*SS, true);
2074     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2075   } else
2076     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2077
2078   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2079       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2080           < II->getLength()) {
2081     II = CurDecl->getIdentifier();
2082     return true;
2083   }
2084
2085   return false;
2086 }
2087
2088 /// \brief Determine whether the given class is a base class of the given
2089 /// class, including looking at dependent bases.
2090 static bool findCircularInheritance(const CXXRecordDecl *Class,
2091                                     const CXXRecordDecl *Current) {
2092   SmallVector<const CXXRecordDecl*, 8> Queue;
2093
2094   Class = Class->getCanonicalDecl();
2095   while (true) {
2096     for (const auto &I : Current->bases()) {
2097       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2098       if (!Base)
2099         continue;
2100
2101       Base = Base->getDefinition();
2102       if (!Base)
2103         continue;
2104
2105       if (Base->getCanonicalDecl() == Class)
2106         return true;
2107
2108       Queue.push_back(Base);
2109     }
2110
2111     if (Queue.empty())
2112       return false;
2113
2114     Current = Queue.pop_back_val();
2115   }
2116
2117   return false;
2118 }
2119
2120 /// \brief Check the validity of a C++ base class specifier.
2121 ///
2122 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2123 /// and returns NULL otherwise.
2124 CXXBaseSpecifier *
2125 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2126                          SourceRange SpecifierRange,
2127                          bool Virtual, AccessSpecifier Access,
2128                          TypeSourceInfo *TInfo,
2129                          SourceLocation EllipsisLoc) {
2130   QualType BaseType = TInfo->getType();
2131
2132   // C++ [class.union]p1:
2133   //   A union shall not have base classes.
2134   if (Class->isUnion()) {
2135     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2136       << SpecifierRange;
2137     return nullptr;
2138   }
2139
2140   if (EllipsisLoc.isValid() && 
2141       !TInfo->getType()->containsUnexpandedParameterPack()) {
2142     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2143       << TInfo->getTypeLoc().getSourceRange();
2144     EllipsisLoc = SourceLocation();
2145   }
2146
2147   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2148
2149   if (BaseType->isDependentType()) {
2150     // Make sure that we don't have circular inheritance among our dependent
2151     // bases. For non-dependent bases, the check for completeness below handles
2152     // this.
2153     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2154       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2155           ((BaseDecl = BaseDecl->getDefinition()) &&
2156            findCircularInheritance(Class, BaseDecl))) {
2157         Diag(BaseLoc, diag::err_circular_inheritance)
2158           << BaseType << Context.getTypeDeclType(Class);
2159
2160         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2161           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2162             << BaseType;
2163
2164         return nullptr;
2165       }
2166     }
2167
2168     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2169                                           Class->getTagKind() == TTK_Class,
2170                                           Access, TInfo, EllipsisLoc);
2171   }
2172
2173   // Base specifiers must be record types.
2174   if (!BaseType->isRecordType()) {
2175     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2176     return nullptr;
2177   }
2178
2179   // C++ [class.union]p1:
2180   //   A union shall not be used as a base class.
2181   if (BaseType->isUnionType()) {
2182     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2183     return nullptr;
2184   }
2185
2186   // For the MS ABI, propagate DLL attributes to base class templates.
2187   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2188     if (Attr *ClassAttr = getDLLAttr(Class)) {
2189       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2190               BaseType->getAsCXXRecordDecl())) {
2191         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2192                                             BaseLoc);
2193       }
2194     }
2195   }
2196
2197   // C++ [class.derived]p2:
2198   //   The class-name in a base-specifier shall not be an incompletely
2199   //   defined class.
2200   if (RequireCompleteType(BaseLoc, BaseType,
2201                           diag::err_incomplete_base_class, SpecifierRange)) {
2202     Class->setInvalidDecl();
2203     return nullptr;
2204   }
2205
2206   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2207   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2208   assert(BaseDecl && "Record type has no declaration");
2209   BaseDecl = BaseDecl->getDefinition();
2210   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2211   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2212   assert(CXXBaseDecl && "Base type is not a C++ type");
2213
2214   // A class which contains a flexible array member is not suitable for use as a
2215   // base class:
2216   //   - If the layout determines that a base comes before another base,
2217   //     the flexible array member would index into the subsequent base.
2218   //   - If the layout determines that base comes before the derived class,
2219   //     the flexible array member would index into the derived class.
2220   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2221     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2222       << CXXBaseDecl->getDeclName();
2223     return nullptr;
2224   }
2225
2226   // C++ [class]p3:
2227   //   If a class is marked final and it appears as a base-type-specifier in
2228   //   base-clause, the program is ill-formed.
2229   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2230     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2231       << CXXBaseDecl->getDeclName()
2232       << FA->isSpelledAsSealed();
2233     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2234         << CXXBaseDecl->getDeclName() << FA->getRange();
2235     return nullptr;
2236   }
2237
2238   if (BaseDecl->isInvalidDecl())
2239     Class->setInvalidDecl();
2240
2241   // Create the base specifier.
2242   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2243                                         Class->getTagKind() == TTK_Class,
2244                                         Access, TInfo, EllipsisLoc);
2245 }
2246
2247 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2248 /// one entry in the base class list of a class specifier, for
2249 /// example:
2250 ///    class foo : public bar, virtual private baz {
2251 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2252 BaseResult
2253 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2254                          ParsedAttributes &Attributes,
2255                          bool Virtual, AccessSpecifier Access,
2256                          ParsedType basetype, SourceLocation BaseLoc,
2257                          SourceLocation EllipsisLoc) {
2258   if (!classdecl)
2259     return true;
2260
2261   AdjustDeclIfTemplate(classdecl);
2262   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2263   if (!Class)
2264     return true;
2265
2266   // We haven't yet attached the base specifiers.
2267   Class->setIsParsingBaseSpecifiers();
2268
2269   // We do not support any C++11 attributes on base-specifiers yet.
2270   // Diagnose any attributes we see.
2271   if (!Attributes.empty()) {
2272     for (AttributeList *Attr = Attributes.getList(); Attr;
2273          Attr = Attr->getNext()) {
2274       if (Attr->isInvalid() ||
2275           Attr->getKind() == AttributeList::IgnoredAttribute)
2276         continue;
2277       Diag(Attr->getLoc(),
2278            Attr->getKind() == AttributeList::UnknownAttribute
2279              ? diag::warn_unknown_attribute_ignored
2280              : diag::err_base_specifier_attribute)
2281         << Attr->getName();
2282     }
2283   }
2284
2285   TypeSourceInfo *TInfo = nullptr;
2286   GetTypeFromParser(basetype, &TInfo);
2287
2288   if (EllipsisLoc.isInvalid() &&
2289       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 
2290                                       UPPC_BaseType))
2291     return true;
2292   
2293   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2294                                                       Virtual, Access, TInfo,
2295                                                       EllipsisLoc))
2296     return BaseSpec;
2297   else
2298     Class->setInvalidDecl();
2299
2300   return true;
2301 }
2302
2303 /// Use small set to collect indirect bases.  As this is only used
2304 /// locally, there's no need to abstract the small size parameter.
2305 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2306
2307 /// \brief Recursively add the bases of Type.  Don't add Type itself.
2308 static void
2309 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2310                   const QualType &Type)
2311 {
2312   // Even though the incoming type is a base, it might not be
2313   // a class -- it could be a template parm, for instance.
2314   if (auto Rec = Type->getAs<RecordType>()) {
2315     auto Decl = Rec->getAsCXXRecordDecl();
2316
2317     // Iterate over its bases.
2318     for (const auto &BaseSpec : Decl->bases()) {
2319       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2320         .getUnqualifiedType();
2321       if (Set.insert(Base).second)
2322         // If we've not already seen it, recurse.
2323         NoteIndirectBases(Context, Set, Base);
2324     }
2325   }
2326 }
2327
2328 /// \brief Performs the actual work of attaching the given base class
2329 /// specifiers to a C++ class.
2330 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2331                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2332  if (Bases.empty())
2333     return false;
2334
2335   // Used to keep track of which base types we have already seen, so
2336   // that we can properly diagnose redundant direct base types. Note
2337   // that the key is always the unqualified canonical type of the base
2338   // class.
2339   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2340
2341   // Used to track indirect bases so we can see if a direct base is
2342   // ambiguous.
2343   IndirectBaseSet IndirectBaseTypes;
2344
2345   // Copy non-redundant base specifiers into permanent storage.
2346   unsigned NumGoodBases = 0;
2347   bool Invalid = false;
2348   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2349     QualType NewBaseType
2350       = Context.getCanonicalType(Bases[idx]->getType());
2351     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2352
2353     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2354     if (KnownBase) {
2355       // C++ [class.mi]p3:
2356       //   A class shall not be specified as a direct base class of a
2357       //   derived class more than once.
2358       Diag(Bases[idx]->getLocStart(),
2359            diag::err_duplicate_base_class)
2360         << KnownBase->getType()
2361         << Bases[idx]->getSourceRange();
2362
2363       // Delete the duplicate base class specifier; we're going to
2364       // overwrite its pointer later.
2365       Context.Deallocate(Bases[idx]);
2366
2367       Invalid = true;
2368     } else {
2369       // Okay, add this new base class.
2370       KnownBase = Bases[idx];
2371       Bases[NumGoodBases++] = Bases[idx];
2372
2373       // Note this base's direct & indirect bases, if there could be ambiguity.
2374       if (Bases.size() > 1)
2375         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2376       
2377       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2378         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2379         if (Class->isInterface() &&
2380               (!RD->isInterface() ||
2381                KnownBase->getAccessSpecifier() != AS_public)) {
2382           // The Microsoft extension __interface does not permit bases that
2383           // are not themselves public interfaces.
2384           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2385             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2386             << RD->getSourceRange();
2387           Invalid = true;
2388         }
2389         if (RD->hasAttr<WeakAttr>())
2390           Class->addAttr(WeakAttr::CreateImplicit(Context));
2391       }
2392     }
2393   }
2394
2395   // Attach the remaining base class specifiers to the derived class.
2396   Class->setBases(Bases.data(), NumGoodBases);
2397   
2398   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2399     // Check whether this direct base is inaccessible due to ambiguity.
2400     QualType BaseType = Bases[idx]->getType();
2401     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2402       .getUnqualifiedType();
2403
2404     if (IndirectBaseTypes.count(CanonicalBase)) {
2405       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2406                          /*DetectVirtual=*/true);
2407       bool found
2408         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2409       assert(found);
2410       (void)found;
2411
2412       if (Paths.isAmbiguous(CanonicalBase))
2413         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2414           << BaseType << getAmbiguousPathsDisplayString(Paths)
2415           << Bases[idx]->getSourceRange();
2416       else
2417         assert(Bases[idx]->isVirtual());
2418     }
2419
2420     // Delete the base class specifier, since its data has been copied
2421     // into the CXXRecordDecl.
2422     Context.Deallocate(Bases[idx]);
2423   }
2424
2425   return Invalid;
2426 }
2427
2428 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2429 /// class, after checking whether there are any duplicate base
2430 /// classes.
2431 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2432                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2433   if (!ClassDecl || Bases.empty())
2434     return;
2435
2436   AdjustDeclIfTemplate(ClassDecl);
2437   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2438 }
2439
2440 /// \brief Determine whether the type \p Derived is a C++ class that is
2441 /// derived from the type \p Base.
2442 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2443   if (!getLangOpts().CPlusPlus)
2444     return false;
2445
2446   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2447   if (!DerivedRD)
2448     return false;
2449   
2450   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2451   if (!BaseRD)
2452     return false;
2453
2454   // If either the base or the derived type is invalid, don't try to
2455   // check whether one is derived from the other.
2456   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2457     return false;
2458
2459   // FIXME: In a modules build, do we need the entire path to be visible for us
2460   // to be able to use the inheritance relationship?
2461   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2462     return false;
2463   
2464   return DerivedRD->isDerivedFrom(BaseRD);
2465 }
2466
2467 /// \brief Determine whether the type \p Derived is a C++ class that is
2468 /// derived from the type \p Base.
2469 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2470                          CXXBasePaths &Paths) {
2471   if (!getLangOpts().CPlusPlus)
2472     return false;
2473   
2474   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2475   if (!DerivedRD)
2476     return false;
2477   
2478   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2479   if (!BaseRD)
2480     return false;
2481   
2482   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2483     return false;
2484   
2485   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2486 }
2487
2488 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 
2489                               CXXCastPath &BasePathArray) {
2490   assert(BasePathArray.empty() && "Base path array must be empty!");
2491   assert(Paths.isRecordingPaths() && "Must record paths!");
2492   
2493   const CXXBasePath &Path = Paths.front();
2494        
2495   // We first go backward and check if we have a virtual base.
2496   // FIXME: It would be better if CXXBasePath had the base specifier for
2497   // the nearest virtual base.
2498   unsigned Start = 0;
2499   for (unsigned I = Path.size(); I != 0; --I) {
2500     if (Path[I - 1].Base->isVirtual()) {
2501       Start = I - 1;
2502       break;
2503     }
2504   }
2505
2506   // Now add all bases.
2507   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2508     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2509 }
2510
2511 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2512 /// conversion (where Derived and Base are class types) is
2513 /// well-formed, meaning that the conversion is unambiguous (and
2514 /// that all of the base classes are accessible). Returns true
2515 /// and emits a diagnostic if the code is ill-formed, returns false
2516 /// otherwise. Loc is the location where this routine should point to
2517 /// if there is an error, and Range is the source range to highlight
2518 /// if there is an error.
2519 ///
2520 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2521 /// diagnostic for the respective type of error will be suppressed, but the
2522 /// check for ill-formed code will still be performed.
2523 bool
2524 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2525                                    unsigned InaccessibleBaseID,
2526                                    unsigned AmbigiousBaseConvID,
2527                                    SourceLocation Loc, SourceRange Range,
2528                                    DeclarationName Name,
2529                                    CXXCastPath *BasePath,
2530                                    bool IgnoreAccess) {
2531   // First, determine whether the path from Derived to Base is
2532   // ambiguous. This is slightly more expensive than checking whether
2533   // the Derived to Base conversion exists, because here we need to
2534   // explore multiple paths to determine if there is an ambiguity.
2535   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2536                      /*DetectVirtual=*/false);
2537   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2538   assert(DerivationOkay &&
2539          "Can only be used with a derived-to-base conversion");
2540   (void)DerivationOkay;
2541   
2542   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
2543     if (!IgnoreAccess) {
2544       // Check that the base class can be accessed.
2545       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2546                                    InaccessibleBaseID)) {
2547         case AR_inaccessible: 
2548           return true;
2549         case AR_accessible: 
2550         case AR_dependent:
2551         case AR_delayed:
2552           break;
2553       }
2554     }
2555     
2556     // Build a base path if necessary.
2557     if (BasePath)
2558       BuildBasePathArray(Paths, *BasePath);
2559     return false;
2560   }
2561   
2562   if (AmbigiousBaseConvID) {
2563     // We know that the derived-to-base conversion is ambiguous, and
2564     // we're going to produce a diagnostic. Perform the derived-to-base
2565     // search just one more time to compute all of the possible paths so
2566     // that we can print them out. This is more expensive than any of
2567     // the previous derived-to-base checks we've done, but at this point
2568     // performance isn't as much of an issue.
2569     Paths.clear();
2570     Paths.setRecordingPaths(true);
2571     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2572     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2573     (void)StillOkay;
2574
2575     // Build up a textual representation of the ambiguous paths, e.g.,
2576     // D -> B -> A, that will be used to illustrate the ambiguous
2577     // conversions in the diagnostic. We only print one of the paths
2578     // to each base class subobject.
2579     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2580
2581     Diag(Loc, AmbigiousBaseConvID)
2582     << Derived << Base << PathDisplayStr << Range << Name;
2583   }
2584   return true;
2585 }
2586
2587 bool
2588 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2589                                    SourceLocation Loc, SourceRange Range,
2590                                    CXXCastPath *BasePath,
2591                                    bool IgnoreAccess) {
2592   return CheckDerivedToBaseConversion(
2593       Derived, Base, diag::err_upcast_to_inaccessible_base,
2594       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2595       BasePath, IgnoreAccess);
2596 }
2597
2598
2599 /// @brief Builds a string representing ambiguous paths from a
2600 /// specific derived class to different subobjects of the same base
2601 /// class.
2602 ///
2603 /// This function builds a string that can be used in error messages
2604 /// to show the different paths that one can take through the
2605 /// inheritance hierarchy to go from the derived class to different
2606 /// subobjects of a base class. The result looks something like this:
2607 /// @code
2608 /// struct D -> struct B -> struct A
2609 /// struct D -> struct C -> struct A
2610 /// @endcode
2611 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2612   std::string PathDisplayStr;
2613   std::set<unsigned> DisplayedPaths;
2614   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2615        Path != Paths.end(); ++Path) {
2616     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2617       // We haven't displayed a path to this particular base
2618       // class subobject yet.
2619       PathDisplayStr += "\n    ";
2620       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2621       for (CXXBasePath::const_iterator Element = Path->begin();
2622            Element != Path->end(); ++Element)
2623         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2624     }
2625   }
2626   
2627   return PathDisplayStr;
2628 }
2629
2630 //===----------------------------------------------------------------------===//
2631 // C++ class member Handling
2632 //===----------------------------------------------------------------------===//
2633
2634 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2635 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2636                                 SourceLocation ASLoc,
2637                                 SourceLocation ColonLoc,
2638                                 AttributeList *Attrs) {
2639   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2640   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2641                                                   ASLoc, ColonLoc);
2642   CurContext->addHiddenDecl(ASDecl);
2643   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2644 }
2645
2646 /// CheckOverrideControl - Check C++11 override control semantics.
2647 void Sema::CheckOverrideControl(NamedDecl *D) {
2648   if (D->isInvalidDecl())
2649     return;
2650
2651   // We only care about "override" and "final" declarations.
2652   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2653     return;
2654
2655   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2656
2657   // We can't check dependent instance methods.
2658   if (MD && MD->isInstance() &&
2659       (MD->getParent()->hasAnyDependentBases() ||
2660        MD->getType()->isDependentType()))
2661     return;
2662
2663   if (MD && !MD->isVirtual()) {
2664     // If we have a non-virtual method, check if if hides a virtual method.
2665     // (In that case, it's most likely the method has the wrong type.)
2666     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2667     FindHiddenVirtualMethods(MD, OverloadedMethods);
2668
2669     if (!OverloadedMethods.empty()) {
2670       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2671         Diag(OA->getLocation(),
2672              diag::override_keyword_hides_virtual_member_function)
2673           << "override" << (OverloadedMethods.size() > 1);
2674       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2675         Diag(FA->getLocation(),
2676              diag::override_keyword_hides_virtual_member_function)
2677           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2678           << (OverloadedMethods.size() > 1);
2679       }
2680       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2681       MD->setInvalidDecl();
2682       return;
2683     }
2684     // Fall through into the general case diagnostic.
2685     // FIXME: We might want to attempt typo correction here.
2686   }
2687
2688   if (!MD || !MD->isVirtual()) {
2689     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2690       Diag(OA->getLocation(),
2691            diag::override_keyword_only_allowed_on_virtual_member_functions)
2692         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2693       D->dropAttr<OverrideAttr>();
2694     }
2695     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2696       Diag(FA->getLocation(),
2697            diag::override_keyword_only_allowed_on_virtual_member_functions)
2698         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2699         << FixItHint::CreateRemoval(FA->getLocation());
2700       D->dropAttr<FinalAttr>();
2701     }
2702     return;
2703   }
2704
2705   // C++11 [class.virtual]p5:
2706   //   If a function is marked with the virt-specifier override and
2707   //   does not override a member function of a base class, the program is
2708   //   ill-formed.
2709   bool HasOverriddenMethods =
2710     MD->begin_overridden_methods() != MD->end_overridden_methods();
2711   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2712     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2713       << MD->getDeclName();
2714 }
2715
2716 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2717   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2718     return;
2719   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2720   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
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     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2733                           ? diag::warn_destructor_marked_not_override_overriding
2734                           : diag::warn_function_marked_not_override_overriding;
2735     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2736     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2737     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2738   }
2739 }
2740
2741 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2742 /// function overrides a virtual member function marked 'final', according to
2743 /// C++11 [class.virtual]p4.
2744 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2745                                                   const CXXMethodDecl *Old) {
2746   FinalAttr *FA = Old->getAttr<FinalAttr>();
2747   if (!FA)
2748     return false;
2749
2750   Diag(New->getLocation(), diag::err_final_function_overridden)
2751     << New->getDeclName()
2752     << FA->isSpelledAsSealed();
2753   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2754   return true;
2755 }
2756
2757 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2758   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2759   // FIXME: Destruction of ObjC lifetime types has side-effects.
2760   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2761     return !RD->isCompleteDefinition() ||
2762            !RD->hasTrivialDefaultConstructor() ||
2763            !RD->hasTrivialDestructor();
2764   return false;
2765 }
2766
2767 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2768   for (AttributeList *it = list; it != nullptr; it = it->getNext())
2769     if (it->isDeclspecPropertyAttribute())
2770       return it;
2771   return nullptr;
2772 }
2773
2774 // Check if there is a field shadowing.
2775 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2776                                       DeclarationName FieldName,
2777                                       const CXXRecordDecl *RD) {
2778   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2779     return;
2780
2781   // To record a shadowed field in a base
2782   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2783   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2784                            CXXBasePath &Path) {
2785     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2786     // Record an ambiguous path directly
2787     if (Bases.find(Base) != Bases.end())
2788       return true;
2789     for (const auto Field : Base->lookup(FieldName)) {
2790       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2791           Field->getAccess() != AS_private) {
2792         assert(Field->getAccess() != AS_none);
2793         assert(Bases.find(Base) == Bases.end());
2794         Bases[Base] = Field;
2795         return true;
2796       }
2797     }
2798     return false;
2799   };
2800
2801   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2802                      /*DetectVirtual=*/true);
2803   if (!RD->lookupInBases(FieldShadowed, Paths))
2804     return;
2805
2806   for (const auto &P : Paths) {
2807     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2808     auto It = Bases.find(Base);
2809     // Skip duplicated bases
2810     if (It == Bases.end())
2811       continue;
2812     auto BaseField = It->second;
2813     assert(BaseField->getAccess() != AS_private);
2814     if (AS_none !=
2815         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2816       Diag(Loc, diag::warn_shadow_field)
2817         << FieldName.getAsString() << RD->getName() << Base->getName();
2818       Diag(BaseField->getLocation(), diag::note_shadow_field);
2819       Bases.erase(It);
2820     }
2821   }
2822 }
2823
2824 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2825 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2826 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2827 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2828 /// present (but parsing it has been deferred).
2829 NamedDecl *
2830 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2831                                MultiTemplateParamsArg TemplateParameterLists,
2832                                Expr *BW, const VirtSpecifiers &VS,
2833                                InClassInitStyle InitStyle) {
2834   const DeclSpec &DS = D.getDeclSpec();
2835   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2836   DeclarationName Name = NameInfo.getName();
2837   SourceLocation Loc = NameInfo.getLoc();
2838
2839   // For anonymous bitfields, the location should point to the type.
2840   if (Loc.isInvalid())
2841     Loc = D.getLocStart();
2842
2843   Expr *BitWidth = static_cast<Expr*>(BW);
2844
2845   assert(isa<CXXRecordDecl>(CurContext));
2846   assert(!DS.isFriendSpecified());
2847
2848   bool isFunc = D.isDeclarationOfFunction();
2849
2850   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2851     // The Microsoft extension __interface only permits public member functions
2852     // and prohibits constructors, destructors, operators, non-public member
2853     // functions, static methods and data members.
2854     unsigned InvalidDecl;
2855     bool ShowDeclName = true;
2856     if (!isFunc)
2857       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2858     else if (AS != AS_public)
2859       InvalidDecl = 2;
2860     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2861       InvalidDecl = 3;
2862     else switch (Name.getNameKind()) {
2863       case DeclarationName::CXXConstructorName:
2864         InvalidDecl = 4;
2865         ShowDeclName = false;
2866         break;
2867
2868       case DeclarationName::CXXDestructorName:
2869         InvalidDecl = 5;
2870         ShowDeclName = false;
2871         break;
2872
2873       case DeclarationName::CXXOperatorName:
2874       case DeclarationName::CXXConversionFunctionName:
2875         InvalidDecl = 6;
2876         break;
2877
2878       default:
2879         InvalidDecl = 0;
2880         break;
2881     }
2882
2883     if (InvalidDecl) {
2884       if (ShowDeclName)
2885         Diag(Loc, diag::err_invalid_member_in_interface)
2886           << (InvalidDecl-1) << Name;
2887       else
2888         Diag(Loc, diag::err_invalid_member_in_interface)
2889           << (InvalidDecl-1) << "";
2890       return nullptr;
2891     }
2892   }
2893
2894   // C++ 9.2p6: A member shall not be declared to have automatic storage
2895   // duration (auto, register) or with the extern storage-class-specifier.
2896   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2897   // data members and cannot be applied to names declared const or static,
2898   // and cannot be applied to reference members.
2899   switch (DS.getStorageClassSpec()) {
2900   case DeclSpec::SCS_unspecified:
2901   case DeclSpec::SCS_typedef:
2902   case DeclSpec::SCS_static:
2903     break;
2904   case DeclSpec::SCS_mutable:
2905     if (isFunc) {
2906       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2907
2908       // FIXME: It would be nicer if the keyword was ignored only for this
2909       // declarator. Otherwise we could get follow-up errors.
2910       D.getMutableDeclSpec().ClearStorageClassSpecs();
2911     }
2912     break;
2913   default:
2914     Diag(DS.getStorageClassSpecLoc(),
2915          diag::err_storageclass_invalid_for_member);
2916     D.getMutableDeclSpec().ClearStorageClassSpecs();
2917     break;
2918   }
2919
2920   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2921                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2922                       !isFunc);
2923
2924   if (DS.isConstexprSpecified() && isInstField) {
2925     SemaDiagnosticBuilder B =
2926         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2927     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2928     if (InitStyle == ICIS_NoInit) {
2929       B << 0 << 0;
2930       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2931         B << FixItHint::CreateRemoval(ConstexprLoc);
2932       else {
2933         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2934         D.getMutableDeclSpec().ClearConstexprSpec();
2935         const char *PrevSpec;
2936         unsigned DiagID;
2937         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2938             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2939         (void)Failed;
2940         assert(!Failed && "Making a constexpr member const shouldn't fail");
2941       }
2942     } else {
2943       B << 1;
2944       const char *PrevSpec;
2945       unsigned DiagID;
2946       if (D.getMutableDeclSpec().SetStorageClassSpec(
2947           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2948           Context.getPrintingPolicy())) {
2949         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2950                "This is the only DeclSpec that should fail to be applied");
2951         B << 1;
2952       } else {
2953         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2954         isInstField = false;
2955       }
2956     }
2957   }
2958
2959   NamedDecl *Member;
2960   if (isInstField) {
2961     CXXScopeSpec &SS = D.getCXXScopeSpec();
2962
2963     // Data members must have identifiers for names.
2964     if (!Name.isIdentifier()) {
2965       Diag(Loc, diag::err_bad_variable_name)
2966         << Name;
2967       return nullptr;
2968     }
2969
2970     IdentifierInfo *II = Name.getAsIdentifierInfo();
2971
2972     // Member field could not be with "template" keyword.
2973     // So TemplateParameterLists should be empty in this case.
2974     if (TemplateParameterLists.size()) {
2975       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2976       if (TemplateParams->size()) {
2977         // There is no such thing as a member field template.
2978         Diag(D.getIdentifierLoc(), diag::err_template_member)
2979             << II
2980             << SourceRange(TemplateParams->getTemplateLoc(),
2981                 TemplateParams->getRAngleLoc());
2982       } else {
2983         // There is an extraneous 'template<>' for this member.
2984         Diag(TemplateParams->getTemplateLoc(),
2985             diag::err_template_member_noparams)
2986             << II
2987             << SourceRange(TemplateParams->getTemplateLoc(),
2988                 TemplateParams->getRAngleLoc());
2989       }
2990       return nullptr;
2991     }
2992
2993     if (SS.isSet() && !SS.isInvalid()) {
2994       // The user provided a superfluous scope specifier inside a class
2995       // definition:
2996       //
2997       // class X {
2998       //   int X::member;
2999       // };
3000       if (DeclContext *DC = computeDeclContext(SS, false))
3001         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
3002       else
3003         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3004           << Name << SS.getRange();
3005       
3006       SS.clear();
3007     }
3008
3009     AttributeList *MSPropertyAttr =
3010       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
3011     if (MSPropertyAttr) {
3012       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3013                                 BitWidth, InitStyle, AS, MSPropertyAttr);
3014       if (!Member)
3015         return nullptr;
3016       isInstField = false;
3017     } else {
3018       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3019                                 BitWidth, InitStyle, AS);
3020       if (!Member)
3021         return nullptr;
3022     }
3023
3024     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3025   } else {
3026     Member = HandleDeclarator(S, D, TemplateParameterLists);
3027     if (!Member)
3028       return nullptr;
3029
3030     // Non-instance-fields can't have a bitfield.
3031     if (BitWidth) {
3032       if (Member->isInvalidDecl()) {
3033         // don't emit another diagnostic.
3034       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3035         // C++ 9.6p3: A bit-field shall not be a static member.
3036         // "static member 'A' cannot be a bit-field"
3037         Diag(Loc, diag::err_static_not_bitfield)
3038           << Name << BitWidth->getSourceRange();
3039       } else if (isa<TypedefDecl>(Member)) {
3040         // "typedef member 'x' cannot be a bit-field"
3041         Diag(Loc, diag::err_typedef_not_bitfield)
3042           << Name << BitWidth->getSourceRange();
3043       } else {
3044         // A function typedef ("typedef int f(); f a;").
3045         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3046         Diag(Loc, diag::err_not_integral_type_bitfield)
3047           << Name << cast<ValueDecl>(Member)->getType()
3048           << BitWidth->getSourceRange();
3049       }
3050
3051       BitWidth = nullptr;
3052       Member->setInvalidDecl();
3053     }
3054
3055     Member->setAccess(AS);
3056
3057     // If we have declared a member function template or static data member
3058     // template, set the access of the templated declaration as well.
3059     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3060       FunTmpl->getTemplatedDecl()->setAccess(AS);
3061     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3062       VarTmpl->getTemplatedDecl()->setAccess(AS);
3063   }
3064
3065   if (VS.isOverrideSpecified())
3066     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3067   if (VS.isFinalSpecified())
3068     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3069                                             VS.isFinalSpelledSealed()));
3070
3071   if (VS.getLastLocation().isValid()) {
3072     // Update the end location of a method that has a virt-specifiers.
3073     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3074       MD->setRangeEnd(VS.getLastLocation());
3075   }
3076
3077   CheckOverrideControl(Member);
3078
3079   assert((Name || isInstField) && "No identifier for non-field ?");
3080
3081   if (isInstField) {
3082     FieldDecl *FD = cast<FieldDecl>(Member);
3083     FieldCollector->Add(FD);
3084
3085     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3086       // Remember all explicit private FieldDecls that have a name, no side
3087       // effects and are not part of a dependent type declaration.
3088       if (!FD->isImplicit() && FD->getDeclName() &&
3089           FD->getAccess() == AS_private &&
3090           !FD->hasAttr<UnusedAttr>() &&
3091           !FD->getParent()->isDependentContext() &&
3092           !InitializationHasSideEffects(*FD))
3093         UnusedPrivateFields.insert(FD);
3094     }
3095   }
3096
3097   return Member;
3098 }
3099
3100 namespace {
3101   class UninitializedFieldVisitor
3102       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3103     Sema &S;
3104     // List of Decls to generate a warning on.  Also remove Decls that become
3105     // initialized.
3106     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3107     // List of base classes of the record.  Classes are removed after their
3108     // initializers.
3109     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3110     // Vector of decls to be removed from the Decl set prior to visiting the
3111     // nodes.  These Decls may have been initialized in the prior initializer.
3112     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3113     // If non-null, add a note to the warning pointing back to the constructor.
3114     const CXXConstructorDecl *Constructor;
3115     // Variables to hold state when processing an initializer list.  When
3116     // InitList is true, special case initialization of FieldDecls matching
3117     // InitListFieldDecl.
3118     bool InitList;
3119     FieldDecl *InitListFieldDecl;
3120     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3121
3122   public:
3123     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3124     UninitializedFieldVisitor(Sema &S,
3125                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3126                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3127       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3128         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3129
3130     // Returns true if the use of ME is not an uninitialized use.
3131     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3132                                          bool CheckReferenceOnly) {
3133       llvm::SmallVector<FieldDecl*, 4> Fields;
3134       bool ReferenceField = false;
3135       while (ME) {
3136         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3137         if (!FD)
3138           return false;
3139         Fields.push_back(FD);
3140         if (FD->getType()->isReferenceType())
3141           ReferenceField = true;
3142         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3143       }
3144
3145       // Binding a reference to an unintialized field is not an
3146       // uninitialized use.
3147       if (CheckReferenceOnly && !ReferenceField)
3148         return true;
3149
3150       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3151       // Discard the first field since it is the field decl that is being
3152       // initialized.
3153       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3154         UsedFieldIndex.push_back((*I)->getFieldIndex());
3155       }
3156
3157       for (auto UsedIter = UsedFieldIndex.begin(),
3158                 UsedEnd = UsedFieldIndex.end(),
3159                 OrigIter = InitFieldIndex.begin(),
3160                 OrigEnd = InitFieldIndex.end();
3161            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3162         if (*UsedIter < *OrigIter)
3163           return true;
3164         if (*UsedIter > *OrigIter)
3165           break;
3166       }
3167
3168       return false;
3169     }
3170
3171     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3172                           bool AddressOf) {
3173       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3174         return;
3175
3176       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3177       // or union.
3178       MemberExpr *FieldME = ME;
3179
3180       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3181
3182       Expr *Base = ME;
3183       while (MemberExpr *SubME =
3184                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3185
3186         if (isa<VarDecl>(SubME->getMemberDecl()))
3187           return;
3188
3189         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3190           if (!FD->isAnonymousStructOrUnion())
3191             FieldME = SubME;
3192
3193         if (!FieldME->getType().isPODType(S.Context))
3194           AllPODFields = false;
3195
3196         Base = SubME->getBase();
3197       }
3198
3199       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3200         return;
3201
3202       if (AddressOf && AllPODFields)
3203         return;
3204
3205       ValueDecl* FoundVD = FieldME->getMemberDecl();
3206
3207       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3208         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3209           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3210         }
3211
3212         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3213           QualType T = BaseCast->getType();
3214           if (T->isPointerType() &&
3215               BaseClasses.count(T->getPointeeType())) {
3216             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3217                 << T->getPointeeType() << FoundVD;
3218           }
3219         }
3220       }
3221
3222       if (!Decls.count(FoundVD))
3223         return;
3224
3225       const bool IsReference = FoundVD->getType()->isReferenceType();
3226
3227       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3228         // Special checking for initializer lists.
3229         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3230           return;
3231         }
3232       } else {
3233         // Prevent double warnings on use of unbounded references.
3234         if (CheckReferenceOnly && !IsReference)
3235           return;
3236       }
3237
3238       unsigned diag = IsReference
3239           ? diag::warn_reference_field_is_uninit
3240           : diag::warn_field_is_uninit;
3241       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3242       if (Constructor)
3243         S.Diag(Constructor->getLocation(),
3244                diag::note_uninit_in_this_constructor)
3245           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3246
3247     }
3248
3249     void HandleValue(Expr *E, bool AddressOf) {
3250       E = E->IgnoreParens();
3251
3252       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3253         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3254                          AddressOf /*AddressOf*/);
3255         return;
3256       }
3257
3258       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3259         Visit(CO->getCond());
3260         HandleValue(CO->getTrueExpr(), AddressOf);
3261         HandleValue(CO->getFalseExpr(), AddressOf);
3262         return;
3263       }
3264
3265       if (BinaryConditionalOperator *BCO =
3266               dyn_cast<BinaryConditionalOperator>(E)) {
3267         Visit(BCO->getCond());
3268         HandleValue(BCO->getFalseExpr(), AddressOf);
3269         return;
3270       }
3271
3272       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3273         HandleValue(OVE->getSourceExpr(), AddressOf);
3274         return;
3275       }
3276
3277       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3278         switch (BO->getOpcode()) {
3279         default:
3280           break;
3281         case(BO_PtrMemD):
3282         case(BO_PtrMemI):
3283           HandleValue(BO->getLHS(), AddressOf);
3284           Visit(BO->getRHS());
3285           return;
3286         case(BO_Comma):
3287           Visit(BO->getLHS());
3288           HandleValue(BO->getRHS(), AddressOf);
3289           return;
3290         }
3291       }
3292
3293       Visit(E);
3294     }
3295
3296     void CheckInitListExpr(InitListExpr *ILE) {
3297       InitFieldIndex.push_back(0);
3298       for (auto Child : ILE->children()) {
3299         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3300           CheckInitListExpr(SubList);
3301         } else {
3302           Visit(Child);
3303         }
3304         ++InitFieldIndex.back();
3305       }
3306       InitFieldIndex.pop_back();
3307     }
3308
3309     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3310                           FieldDecl *Field, const Type *BaseClass) {
3311       // Remove Decls that may have been initialized in the previous
3312       // initializer.
3313       for (ValueDecl* VD : DeclsToRemove)
3314         Decls.erase(VD);
3315       DeclsToRemove.clear();
3316
3317       Constructor = FieldConstructor;
3318       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3319
3320       if (ILE && Field) {
3321         InitList = true;
3322         InitListFieldDecl = Field;
3323         InitFieldIndex.clear();
3324         CheckInitListExpr(ILE);
3325       } else {
3326         InitList = false;
3327         Visit(E);
3328       }
3329
3330       if (Field)
3331         Decls.erase(Field);
3332       if (BaseClass)
3333         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3334     }
3335
3336     void VisitMemberExpr(MemberExpr *ME) {
3337       // All uses of unbounded reference fields will warn.
3338       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3339     }
3340
3341     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3342       if (E->getCastKind() == CK_LValueToRValue) {
3343         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3344         return;
3345       }
3346
3347       Inherited::VisitImplicitCastExpr(E);
3348     }
3349
3350     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3351       if (E->getConstructor()->isCopyConstructor()) {
3352         Expr *ArgExpr = E->getArg(0);
3353         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3354           if (ILE->getNumInits() == 1)
3355             ArgExpr = ILE->getInit(0);
3356         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3357           if (ICE->getCastKind() == CK_NoOp)
3358             ArgExpr = ICE->getSubExpr();
3359         HandleValue(ArgExpr, false /*AddressOf*/);
3360         return;
3361       }
3362       Inherited::VisitCXXConstructExpr(E);
3363     }
3364
3365     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3366       Expr *Callee = E->getCallee();
3367       if (isa<MemberExpr>(Callee)) {
3368         HandleValue(Callee, false /*AddressOf*/);
3369         for (auto Arg : E->arguments())
3370           Visit(Arg);
3371         return;
3372       }
3373
3374       Inherited::VisitCXXMemberCallExpr(E);
3375     }
3376
3377     void VisitCallExpr(CallExpr *E) {
3378       // Treat std::move as a use.
3379       if (E->getNumArgs() == 1) {
3380         if (FunctionDecl *FD = E->getDirectCallee()) {
3381           if (FD->isInStdNamespace() && FD->getIdentifier() &&
3382               FD->getIdentifier()->isStr("move")) {
3383             HandleValue(E->getArg(0), false /*AddressOf*/);
3384             return;
3385           }
3386         }
3387       }
3388
3389       Inherited::VisitCallExpr(E);
3390     }
3391
3392     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3393       Expr *Callee = E->getCallee();
3394
3395       if (isa<UnresolvedLookupExpr>(Callee))
3396         return Inherited::VisitCXXOperatorCallExpr(E);
3397
3398       Visit(Callee);
3399       for (auto Arg : E->arguments())
3400         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3401     }
3402
3403     void VisitBinaryOperator(BinaryOperator *E) {
3404       // If a field assignment is detected, remove the field from the
3405       // uninitiailized field set.
3406       if (E->getOpcode() == BO_Assign)
3407         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3408           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3409             if (!FD->getType()->isReferenceType())
3410               DeclsToRemove.push_back(FD);
3411
3412       if (E->isCompoundAssignmentOp()) {
3413         HandleValue(E->getLHS(), false /*AddressOf*/);
3414         Visit(E->getRHS());
3415         return;
3416       }
3417
3418       Inherited::VisitBinaryOperator(E);
3419     }
3420
3421     void VisitUnaryOperator(UnaryOperator *E) {
3422       if (E->isIncrementDecrementOp()) {
3423         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3424         return;
3425       }
3426       if (E->getOpcode() == UO_AddrOf) {
3427         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3428           HandleValue(ME->getBase(), true /*AddressOf*/);
3429           return;
3430         }
3431       }
3432
3433       Inherited::VisitUnaryOperator(E);
3434     }
3435   };
3436
3437   // Diagnose value-uses of fields to initialize themselves, e.g.
3438   //   foo(foo)
3439   // where foo is not also a parameter to the constructor.
3440   // Also diagnose across field uninitialized use such as
3441   //   x(y), y(x)
3442   // TODO: implement -Wuninitialized and fold this into that framework.
3443   static void DiagnoseUninitializedFields(
3444       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3445
3446     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3447                                            Constructor->getLocation())) {
3448       return;
3449     }
3450
3451     if (Constructor->isInvalidDecl())
3452       return;
3453
3454     const CXXRecordDecl *RD = Constructor->getParent();
3455
3456     if (RD->getDescribedClassTemplate())
3457       return;
3458
3459     // Holds fields that are uninitialized.
3460     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3461
3462     // At the beginning, all fields are uninitialized.
3463     for (auto *I : RD->decls()) {
3464       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3465         UninitializedFields.insert(FD);
3466       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3467         UninitializedFields.insert(IFD->getAnonField());
3468       }
3469     }
3470
3471     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3472     for (auto I : RD->bases())
3473       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3474
3475     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3476       return;
3477
3478     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3479                                                    UninitializedFields,
3480                                                    UninitializedBaseClasses);
3481
3482     for (const auto *FieldInit : Constructor->inits()) {
3483       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3484         break;
3485
3486       Expr *InitExpr = FieldInit->getInit();
3487       if (!InitExpr)
3488         continue;
3489
3490       if (CXXDefaultInitExpr *Default =
3491               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3492         InitExpr = Default->getExpr();
3493         if (!InitExpr)
3494           continue;
3495         // In class initializers will point to the constructor.
3496         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3497                                               FieldInit->getAnyMember(),
3498                                               FieldInit->getBaseClass());
3499       } else {
3500         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3501                                               FieldInit->getAnyMember(),
3502                                               FieldInit->getBaseClass());
3503       }
3504     }
3505   }
3506 } // namespace
3507
3508 /// \brief Enter a new C++ default initializer scope. After calling this, the
3509 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3510 /// parsing or instantiating the initializer failed.
3511 void Sema::ActOnStartCXXInClassMemberInitializer() {
3512   // Create a synthetic function scope to represent the call to the constructor
3513   // that notionally surrounds a use of this initializer.
3514   PushFunctionScope();
3515 }
3516
3517 /// \brief This is invoked after parsing an in-class initializer for a
3518 /// non-static C++ class member, and after instantiating an in-class initializer
3519 /// in a class template. Such actions are deferred until the class is complete.
3520 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3521                                                   SourceLocation InitLoc,
3522                                                   Expr *InitExpr) {
3523   // Pop the notional constructor scope we created earlier.
3524   PopFunctionScopeInfo(nullptr, D);
3525
3526   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3527   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3528          "must set init style when field is created");
3529
3530   if (!InitExpr) {
3531     D->setInvalidDecl();
3532     if (FD)
3533       FD->removeInClassInitializer();
3534     return;
3535   }
3536
3537   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3538     FD->setInvalidDecl();
3539     FD->removeInClassInitializer();
3540     return;
3541   }
3542
3543   ExprResult Init = InitExpr;
3544   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3545     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3546     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
3547         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
3548         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3549     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3550     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3551     if (Init.isInvalid()) {
3552       FD->setInvalidDecl();
3553       return;
3554     }
3555   }
3556
3557   // C++11 [class.base.init]p7:
3558   //   The initialization of each base and member constitutes a
3559   //   full-expression.
3560   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3561   if (Init.isInvalid()) {
3562     FD->setInvalidDecl();
3563     return;
3564   }
3565
3566   InitExpr = Init.get();
3567
3568   FD->setInClassInitializer(InitExpr);
3569 }
3570
3571 /// \brief Find the direct and/or virtual base specifiers that
3572 /// correspond to the given base type, for use in base initialization
3573 /// within a constructor.
3574 static bool FindBaseInitializer(Sema &SemaRef, 
3575                                 CXXRecordDecl *ClassDecl,
3576                                 QualType BaseType,
3577                                 const CXXBaseSpecifier *&DirectBaseSpec,
3578                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3579   // First, check for a direct base class.
3580   DirectBaseSpec = nullptr;
3581   for (const auto &Base : ClassDecl->bases()) {
3582     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3583       // We found a direct base of this type. That's what we're
3584       // initializing.
3585       DirectBaseSpec = &Base;
3586       break;
3587     }
3588   }
3589
3590   // Check for a virtual base class.
3591   // FIXME: We might be able to short-circuit this if we know in advance that
3592   // there are no virtual bases.
3593   VirtualBaseSpec = nullptr;
3594   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3595     // We haven't found a base yet; search the class hierarchy for a
3596     // virtual base class.
3597     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3598                        /*DetectVirtual=*/false);
3599     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3600                               SemaRef.Context.getTypeDeclType(ClassDecl),
3601                               BaseType, Paths)) {
3602       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3603            Path != Paths.end(); ++Path) {
3604         if (Path->back().Base->isVirtual()) {
3605           VirtualBaseSpec = Path->back().Base;
3606           break;
3607         }
3608       }
3609     }
3610   }
3611
3612   return DirectBaseSpec || VirtualBaseSpec;
3613 }
3614
3615 /// \brief Handle a C++ member initializer using braced-init-list syntax.
3616 MemInitResult
3617 Sema::ActOnMemInitializer(Decl *ConstructorD,
3618                           Scope *S,
3619                           CXXScopeSpec &SS,
3620                           IdentifierInfo *MemberOrBase,
3621                           ParsedType TemplateTypeTy,
3622                           const DeclSpec &DS,
3623                           SourceLocation IdLoc,
3624                           Expr *InitList,
3625                           SourceLocation EllipsisLoc) {
3626   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3627                              DS, IdLoc, InitList,
3628                              EllipsisLoc);
3629 }
3630
3631 /// \brief Handle a C++ member initializer using parentheses syntax.
3632 MemInitResult
3633 Sema::ActOnMemInitializer(Decl *ConstructorD,
3634                           Scope *S,
3635                           CXXScopeSpec &SS,
3636                           IdentifierInfo *MemberOrBase,
3637                           ParsedType TemplateTypeTy,
3638                           const DeclSpec &DS,
3639                           SourceLocation IdLoc,
3640                           SourceLocation LParenLoc,
3641                           ArrayRef<Expr *> Args,
3642                           SourceLocation RParenLoc,
3643                           SourceLocation EllipsisLoc) {
3644   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3645                                            Args, RParenLoc);
3646   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3647                              DS, IdLoc, List, EllipsisLoc);
3648 }
3649
3650 namespace {
3651
3652 // Callback to only accept typo corrections that can be a valid C++ member
3653 // intializer: either a non-static field member or a base class.
3654 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3655 public:
3656   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3657       : ClassDecl(ClassDecl) {}
3658
3659   bool ValidateCandidate(const TypoCorrection &candidate) override {
3660     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3661       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3662         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3663       return isa<TypeDecl>(ND);
3664     }
3665     return false;
3666   }
3667
3668 private:
3669   CXXRecordDecl *ClassDecl;
3670 };
3671
3672 }
3673
3674 /// \brief Handle a C++ member initializer.
3675 MemInitResult
3676 Sema::BuildMemInitializer(Decl *ConstructorD,
3677                           Scope *S,
3678                           CXXScopeSpec &SS,
3679                           IdentifierInfo *MemberOrBase,
3680                           ParsedType TemplateTypeTy,
3681                           const DeclSpec &DS,
3682                           SourceLocation IdLoc,
3683                           Expr *Init,
3684                           SourceLocation EllipsisLoc) {
3685   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3686   if (!Res.isUsable())
3687     return true;
3688   Init = Res.get();
3689
3690   if (!ConstructorD)
3691     return true;
3692
3693   AdjustDeclIfTemplate(ConstructorD);
3694
3695   CXXConstructorDecl *Constructor
3696     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3697   if (!Constructor) {
3698     // The user wrote a constructor initializer on a function that is
3699     // not a C++ constructor. Ignore the error for now, because we may
3700     // have more member initializers coming; we'll diagnose it just
3701     // once in ActOnMemInitializers.
3702     return true;
3703   }
3704
3705   CXXRecordDecl *ClassDecl = Constructor->getParent();
3706
3707   // C++ [class.base.init]p2:
3708   //   Names in a mem-initializer-id are looked up in the scope of the
3709   //   constructor's class and, if not found in that scope, are looked
3710   //   up in the scope containing the constructor's definition.
3711   //   [Note: if the constructor's class contains a member with the
3712   //   same name as a direct or virtual base class of the class, a
3713   //   mem-initializer-id naming the member or base class and composed
3714   //   of a single identifier refers to the class member. A
3715   //   mem-initializer-id for the hidden base class may be specified
3716   //   using a qualified name. ]
3717   if (!SS.getScopeRep() && !TemplateTypeTy) {
3718     // Look for a member, first.
3719     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3720     if (!Result.empty()) {
3721       ValueDecl *Member;
3722       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3723           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3724         if (EllipsisLoc.isValid())
3725           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3726             << MemberOrBase
3727             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3728
3729         return BuildMemberInitializer(Member, Init, IdLoc);
3730       }
3731     }
3732   }
3733   // It didn't name a member, so see if it names a class.
3734   QualType BaseType;
3735   TypeSourceInfo *TInfo = nullptr;
3736
3737   if (TemplateTypeTy) {
3738     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3739   } else if (DS.getTypeSpecType() == TST_decltype) {
3740     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3741   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3742     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3743     return true;
3744   } else {
3745     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3746     LookupParsedName(R, S, &SS);
3747
3748     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3749     if (!TyD) {
3750       if (R.isAmbiguous()) return true;
3751
3752       // We don't want access-control diagnostics here.
3753       R.suppressDiagnostics();
3754
3755       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3756         bool NotUnknownSpecialization = false;
3757         DeclContext *DC = computeDeclContext(SS, false);
3758         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 
3759           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3760
3761         if (!NotUnknownSpecialization) {
3762           // When the scope specifier can refer to a member of an unknown
3763           // specialization, we take it as a type name.
3764           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3765                                        SS.getWithLocInContext(Context),
3766                                        *MemberOrBase, IdLoc);
3767           if (BaseType.isNull())
3768             return true;
3769
3770           R.clear();
3771           R.setLookupName(MemberOrBase);
3772         }
3773       }
3774
3775       // If no results were found, try to correct typos.
3776       TypoCorrection Corr;
3777       if (R.empty() && BaseType.isNull() &&
3778           (Corr = CorrectTypo(
3779                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3780                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3781                CTK_ErrorRecovery, ClassDecl))) {
3782         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3783           // We have found a non-static data member with a similar
3784           // name to what was typed; complain and initialize that
3785           // member.
3786           diagnoseTypo(Corr,
3787                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3788                          << MemberOrBase << true);
3789           return BuildMemberInitializer(Member, Init, IdLoc);
3790         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3791           const CXXBaseSpecifier *DirectBaseSpec;
3792           const CXXBaseSpecifier *VirtualBaseSpec;
3793           if (FindBaseInitializer(*this, ClassDecl, 
3794                                   Context.getTypeDeclType(Type),
3795                                   DirectBaseSpec, VirtualBaseSpec)) {
3796             // We have found a direct or virtual base class with a
3797             // similar name to what was typed; complain and initialize
3798             // that base class.
3799             diagnoseTypo(Corr,
3800                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3801                            << MemberOrBase << false,
3802                          PDiag() /*Suppress note, we provide our own.*/);
3803
3804             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3805                                                               : VirtualBaseSpec;
3806             Diag(BaseSpec->getLocStart(),
3807                  diag::note_base_class_specified_here)
3808               << BaseSpec->getType()
3809               << BaseSpec->getSourceRange();
3810
3811             TyD = Type;
3812           }
3813         }
3814       }
3815
3816       if (!TyD && BaseType.isNull()) {
3817         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3818           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3819         return true;
3820       }
3821     }
3822
3823     if (BaseType.isNull()) {
3824       BaseType = Context.getTypeDeclType(TyD);
3825       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3826       if (SS.isSet()) {
3827         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3828                                              BaseType);
3829         TInfo = Context.CreateTypeSourceInfo(BaseType);
3830         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3831         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3832         TL.setElaboratedKeywordLoc(SourceLocation());
3833         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3834       }
3835     }
3836   }
3837
3838   if (!TInfo)
3839     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3840
3841   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3842 }
3843
3844 /// Checks a member initializer expression for cases where reference (or
3845 /// pointer) members are bound to by-value parameters (or their addresses).
3846 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3847                                                Expr *Init,
3848                                                SourceLocation IdLoc) {
3849   QualType MemberTy = Member->getType();
3850
3851   // We only handle pointers and references currently.
3852   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3853   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3854     return;
3855
3856   const bool IsPointer = MemberTy->isPointerType();
3857   if (IsPointer) {
3858     if (const UnaryOperator *Op
3859           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3860       // The only case we're worried about with pointers requires taking the
3861       // address.
3862       if (Op->getOpcode() != UO_AddrOf)
3863         return;
3864
3865       Init = Op->getSubExpr();
3866     } else {
3867       // We only handle address-of expression initializers for pointers.
3868       return;
3869     }
3870   }
3871
3872   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3873     // We only warn when referring to a non-reference parameter declaration.
3874     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3875     if (!Parameter || Parameter->getType()->isReferenceType())
3876       return;
3877
3878     S.Diag(Init->getExprLoc(),
3879            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3880                      : diag::warn_bind_ref_member_to_parameter)
3881       << Member << Parameter << Init->getSourceRange();
3882   } else {
3883     // Other initializers are fine.
3884     return;
3885   }
3886
3887   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3888     << (unsigned)IsPointer;
3889 }
3890
3891 MemInitResult
3892 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3893                              SourceLocation IdLoc) {
3894   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3895   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3896   assert((DirectMember || IndirectMember) &&
3897          "Member must be a FieldDecl or IndirectFieldDecl");
3898
3899   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3900     return true;
3901
3902   if (Member->isInvalidDecl())
3903     return true;
3904
3905   MultiExprArg Args;
3906   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3907     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3908   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3909     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3910   } else {
3911     // Template instantiation doesn't reconstruct ParenListExprs for us.
3912     Args = Init;
3913   }
3914
3915   SourceRange InitRange = Init->getSourceRange();
3916
3917   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3918     // Can't check initialization for a member of dependent type or when
3919     // any of the arguments are type-dependent expressions.
3920     DiscardCleanupsInEvaluationContext();
3921   } else {
3922     bool InitList = false;
3923     if (isa<InitListExpr>(Init)) {
3924       InitList = true;
3925       Args = Init;
3926     }
3927
3928     // Initialize the member.
3929     InitializedEntity MemberEntity =
3930       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3931                    : InitializedEntity::InitializeMember(IndirectMember,
3932                                                          nullptr);
3933     InitializationKind Kind =
3934       InitList ? InitializationKind::CreateDirectList(IdLoc)
3935                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3936                                                   InitRange.getEnd());
3937
3938     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3939     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3940                                             nullptr);
3941     if (MemberInit.isInvalid())
3942       return true;
3943
3944     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3945
3946     // C++11 [class.base.init]p7:
3947     //   The initialization of each base and member constitutes a
3948     //   full-expression.
3949     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3950     if (MemberInit.isInvalid())
3951       return true;
3952
3953     Init = MemberInit.get();
3954   }
3955
3956   if (DirectMember) {
3957     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3958                                             InitRange.getBegin(), Init,
3959                                             InitRange.getEnd());
3960   } else {
3961     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3962                                             InitRange.getBegin(), Init,
3963                                             InitRange.getEnd());
3964   }
3965 }
3966
3967 MemInitResult
3968 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3969                                  CXXRecordDecl *ClassDecl) {
3970   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3971   if (!LangOpts.CPlusPlus11)
3972     return Diag(NameLoc, diag::err_delegating_ctor)
3973       << TInfo->getTypeLoc().getLocalSourceRange();
3974   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3975
3976   bool InitList = true;
3977   MultiExprArg Args = Init;
3978   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3979     InitList = false;
3980     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3981   }
3982
3983   SourceRange InitRange = Init->getSourceRange();
3984   // Initialize the object.
3985   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3986                                      QualType(ClassDecl->getTypeForDecl(), 0));
3987   InitializationKind Kind =
3988     InitList ? InitializationKind::CreateDirectList(NameLoc)
3989              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3990                                                 InitRange.getEnd());
3991   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3992   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3993                                               Args, nullptr);
3994   if (DelegationInit.isInvalid())
3995     return true;
3996
3997   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3998          "Delegating constructor with no target?");
3999
4000   // C++11 [class.base.init]p7:
4001   //   The initialization of each base and member constitutes a
4002   //   full-expression.
4003   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4004                                        InitRange.getBegin());
4005   if (DelegationInit.isInvalid())
4006     return true;
4007
4008   // If we are in a dependent context, template instantiation will
4009   // perform this type-checking again. Just save the arguments that we
4010   // received in a ParenListExpr.
4011   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4012   // of the information that we have about the base
4013   // initializer. However, deconstructing the ASTs is a dicey process,
4014   // and this approach is far more likely to get the corner cases right.
4015   if (CurContext->isDependentContext())
4016     DelegationInit = Init;
4017
4018   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 
4019                                           DelegationInit.getAs<Expr>(),
4020                                           InitRange.getEnd());
4021 }
4022
4023 MemInitResult
4024 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4025                            Expr *Init, CXXRecordDecl *ClassDecl,
4026                            SourceLocation EllipsisLoc) {
4027   SourceLocation BaseLoc
4028     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4029
4030   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4031     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4032              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4033
4034   // C++ [class.base.init]p2:
4035   //   [...] Unless the mem-initializer-id names a nonstatic data
4036   //   member of the constructor's class or a direct or virtual base
4037   //   of that class, the mem-initializer is ill-formed. A
4038   //   mem-initializer-list can initialize a base class using any
4039   //   name that denotes that base class type.
4040   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4041
4042   SourceRange InitRange = Init->getSourceRange();
4043   if (EllipsisLoc.isValid()) {
4044     // This is a pack expansion.
4045     if (!BaseType->containsUnexpandedParameterPack())  {
4046       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4047         << SourceRange(BaseLoc, InitRange.getEnd());
4048
4049       EllipsisLoc = SourceLocation();
4050     }
4051   } else {
4052     // Check for any unexpanded parameter packs.
4053     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4054       return true;
4055
4056     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4057       return true;
4058   }
4059
4060   // Check for direct and virtual base classes.
4061   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4062   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4063   if (!Dependent) { 
4064     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4065                                        BaseType))
4066       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4067
4068     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 
4069                         VirtualBaseSpec);
4070
4071     // C++ [base.class.init]p2:
4072     // Unless the mem-initializer-id names a nonstatic data member of the
4073     // constructor's class or a direct or virtual base of that class, the
4074     // mem-initializer is ill-formed.
4075     if (!DirectBaseSpec && !VirtualBaseSpec) {
4076       // If the class has any dependent bases, then it's possible that
4077       // one of those types will resolve to the same type as
4078       // BaseType. Therefore, just treat this as a dependent base
4079       // class initialization.  FIXME: Should we try to check the
4080       // initialization anyway? It seems odd.
4081       if (ClassDecl->hasAnyDependentBases())
4082         Dependent = true;
4083       else
4084         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4085           << BaseType << Context.getTypeDeclType(ClassDecl)
4086           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4087     }
4088   }
4089
4090   if (Dependent) {
4091     DiscardCleanupsInEvaluationContext();
4092
4093     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4094                                             /*IsVirtual=*/false,
4095                                             InitRange.getBegin(), Init,
4096                                             InitRange.getEnd(), EllipsisLoc);
4097   }
4098
4099   // C++ [base.class.init]p2:
4100   //   If a mem-initializer-id is ambiguous because it designates both
4101   //   a direct non-virtual base class and an inherited virtual base
4102   //   class, the mem-initializer is ill-formed.
4103   if (DirectBaseSpec && VirtualBaseSpec)
4104     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4105       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4106
4107   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4108   if (!BaseSpec)
4109     BaseSpec = VirtualBaseSpec;
4110
4111   // Initialize the base.
4112   bool InitList = true;
4113   MultiExprArg Args = Init;
4114   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4115     InitList = false;
4116     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4117   }
4118
4119   InitializedEntity BaseEntity =
4120     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4121   InitializationKind Kind =
4122     InitList ? InitializationKind::CreateDirectList(BaseLoc)
4123              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4124                                                 InitRange.getEnd());
4125   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4126   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4127   if (BaseInit.isInvalid())
4128     return true;
4129
4130   // C++11 [class.base.init]p7:
4131   //   The initialization of each base and member constitutes a
4132   //   full-expression.
4133   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4134   if (BaseInit.isInvalid())
4135     return true;
4136
4137   // If we are in a dependent context, template instantiation will
4138   // perform this type-checking again. Just save the arguments that we
4139   // received in a ParenListExpr.
4140   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4141   // of the information that we have about the base
4142   // initializer. However, deconstructing the ASTs is a dicey process,
4143   // and this approach is far more likely to get the corner cases right.
4144   if (CurContext->isDependentContext())
4145     BaseInit = Init;
4146
4147   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4148                                           BaseSpec->isVirtual(),
4149                                           InitRange.getBegin(),
4150                                           BaseInit.getAs<Expr>(),
4151                                           InitRange.getEnd(), EllipsisLoc);
4152 }
4153
4154 // Create a static_cast\<T&&>(expr).
4155 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4156   if (T.isNull()) T = E->getType();
4157   QualType TargetType = SemaRef.BuildReferenceType(
4158       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4159   SourceLocation ExprLoc = E->getLocStart();
4160   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4161       TargetType, ExprLoc);
4162
4163   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4164                                    SourceRange(ExprLoc, ExprLoc),
4165                                    E->getSourceRange()).get();
4166 }
4167
4168 /// ImplicitInitializerKind - How an implicit base or member initializer should
4169 /// initialize its base or member.
4170 enum ImplicitInitializerKind {
4171   IIK_Default,
4172   IIK_Copy,
4173   IIK_Move,
4174   IIK_Inherit
4175 };
4176
4177 static bool
4178 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4179                              ImplicitInitializerKind ImplicitInitKind,
4180                              CXXBaseSpecifier *BaseSpec,
4181                              bool IsInheritedVirtualBase,
4182                              CXXCtorInitializer *&CXXBaseInit) {
4183   InitializedEntity InitEntity
4184     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4185                                         IsInheritedVirtualBase);
4186
4187   ExprResult BaseInit;
4188   
4189   switch (ImplicitInitKind) {
4190   case IIK_Inherit:
4191   case IIK_Default: {
4192     InitializationKind InitKind
4193       = InitializationKind::CreateDefault(Constructor->getLocation());
4194     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4195     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4196     break;
4197   }
4198
4199   case IIK_Move:
4200   case IIK_Copy: {
4201     bool Moving = ImplicitInitKind == IIK_Move;
4202     ParmVarDecl *Param = Constructor->getParamDecl(0);
4203     QualType ParamType = Param->getType().getNonReferenceType();
4204
4205     Expr *CopyCtorArg = 
4206       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4207                           SourceLocation(), Param, false,
4208                           Constructor->getLocation(), ParamType,
4209                           VK_LValue, nullptr);
4210
4211     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4212
4213     // Cast to the base class to avoid ambiguities.
4214     QualType ArgTy = 
4215       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 
4216                                        ParamType.getQualifiers());
4217
4218     if (Moving) {
4219       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4220     }
4221
4222     CXXCastPath BasePath;
4223     BasePath.push_back(BaseSpec);
4224     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4225                                             CK_UncheckedDerivedToBase,
4226                                             Moving ? VK_XValue : VK_LValue,
4227                                             &BasePath).get();
4228
4229     InitializationKind InitKind
4230       = InitializationKind::CreateDirect(Constructor->getLocation(),
4231                                          SourceLocation(), SourceLocation());
4232     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4233     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4234     break;
4235   }
4236   }
4237
4238   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4239   if (BaseInit.isInvalid())
4240     return true;
4241         
4242   CXXBaseInit =
4243     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4244                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 
4245                                                         SourceLocation()),
4246                                              BaseSpec->isVirtual(),
4247                                              SourceLocation(),
4248                                              BaseInit.getAs<Expr>(),
4249                                              SourceLocation(),
4250                                              SourceLocation());
4251
4252   return false;
4253 }
4254
4255 static bool RefersToRValueRef(Expr *MemRef) {
4256   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4257   return Referenced->getType()->isRValueReferenceType();
4258 }
4259
4260 static bool
4261 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4262                                ImplicitInitializerKind ImplicitInitKind,
4263                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4264                                CXXCtorInitializer *&CXXMemberInit) {
4265   if (Field->isInvalidDecl())
4266     return true;
4267
4268   SourceLocation Loc = Constructor->getLocation();
4269
4270   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4271     bool Moving = ImplicitInitKind == IIK_Move;
4272     ParmVarDecl *Param = Constructor->getParamDecl(0);
4273     QualType ParamType = Param->getType().getNonReferenceType();
4274
4275     // Suppress copying zero-width bitfields.
4276     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4277       return false;
4278         
4279     Expr *MemberExprBase = 
4280       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4281                           SourceLocation(), Param, false,
4282                           Loc, ParamType, VK_LValue, nullptr);
4283
4284     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4285
4286     if (Moving) {
4287       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4288     }
4289
4290     // Build a reference to this field within the parameter.
4291     CXXScopeSpec SS;
4292     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4293                               Sema::LookupMemberName);
4294     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4295                                   : cast<ValueDecl>(Field), AS_public);
4296     MemberLookup.resolveKind();
4297     ExprResult CtorArg 
4298       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4299                                          ParamType, Loc,
4300                                          /*IsArrow=*/false,
4301                                          SS,
4302                                          /*TemplateKWLoc=*/SourceLocation(),
4303                                          /*FirstQualifierInScope=*/nullptr,
4304                                          MemberLookup,
4305                                          /*TemplateArgs=*/nullptr,
4306                                          /*S*/nullptr);
4307     if (CtorArg.isInvalid())
4308       return true;
4309
4310     // C++11 [class.copy]p15:
4311     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4312     //     with static_cast<T&&>(x.m);
4313     if (RefersToRValueRef(CtorArg.get())) {
4314       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4315     }
4316
4317     InitializedEntity Entity =
4318         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4319                                                        /*Implicit*/ true)
4320                  : InitializedEntity::InitializeMember(Field, nullptr,
4321                                                        /*Implicit*/ true);
4322
4323     // Direct-initialize to use the copy constructor.
4324     InitializationKind InitKind =
4325       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4326     
4327     Expr *CtorArgE = CtorArg.getAs<Expr>();
4328     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4329     ExprResult MemberInit =
4330         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4331     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4332     if (MemberInit.isInvalid())
4333       return true;
4334
4335     if (Indirect)
4336       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4337           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4338     else
4339       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4340           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4341     return false;
4342   }
4343
4344   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4345          "Unhandled implicit init kind!");
4346
4347   QualType FieldBaseElementType = 
4348     SemaRef.Context.getBaseElementType(Field->getType());
4349   
4350   if (FieldBaseElementType->isRecordType()) {
4351     InitializedEntity InitEntity =
4352         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4353                                                        /*Implicit*/ true)
4354                  : InitializedEntity::InitializeMember(Field, nullptr,
4355                                                        /*Implicit*/ true);
4356     InitializationKind InitKind = 
4357       InitializationKind::CreateDefault(Loc);
4358
4359     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4360     ExprResult MemberInit =
4361       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4362
4363     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4364     if (MemberInit.isInvalid())
4365       return true;
4366     
4367     if (Indirect)
4368       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4369                                                                Indirect, Loc, 
4370                                                                Loc,
4371                                                                MemberInit.get(),
4372                                                                Loc);
4373     else
4374       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4375                                                                Field, Loc, Loc,
4376                                                                MemberInit.get(),
4377                                                                Loc);
4378     return false;
4379   }
4380
4381   if (!Field->getParent()->isUnion()) {
4382     if (FieldBaseElementType->isReferenceType()) {
4383       SemaRef.Diag(Constructor->getLocation(), 
4384                    diag::err_uninitialized_member_in_ctor)
4385       << (int)Constructor->isImplicit() 
4386       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4387       << 0 << Field->getDeclName();
4388       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4389       return true;
4390     }
4391
4392     if (FieldBaseElementType.isConstQualified()) {
4393       SemaRef.Diag(Constructor->getLocation(), 
4394                    diag::err_uninitialized_member_in_ctor)
4395       << (int)Constructor->isImplicit() 
4396       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4397       << 1 << Field->getDeclName();
4398       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4399       return true;
4400     }
4401   }
4402   
4403   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4404     // ARC and Weak:
4405     //   Default-initialize Objective-C pointers to NULL.
4406     CXXMemberInit
4407       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 
4408                                                  Loc, Loc, 
4409                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 
4410                                                  Loc);
4411     return false;
4412   }
4413       
4414   // Nothing to initialize.
4415   CXXMemberInit = nullptr;
4416   return false;
4417 }
4418
4419 namespace {
4420 struct BaseAndFieldInfo {
4421   Sema &S;
4422   CXXConstructorDecl *Ctor;
4423   bool AnyErrorsInInits;
4424   ImplicitInitializerKind IIK;
4425   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4426   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4427   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4428
4429   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4430     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4431     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4432     if (Ctor->getInheritedConstructor())
4433       IIK = IIK_Inherit;
4434     else if (Generated && Ctor->isCopyConstructor())
4435       IIK = IIK_Copy;
4436     else if (Generated && Ctor->isMoveConstructor())
4437       IIK = IIK_Move;
4438     else
4439       IIK = IIK_Default;
4440   }
4441   
4442   bool isImplicitCopyOrMove() const {
4443     switch (IIK) {
4444     case IIK_Copy:
4445     case IIK_Move:
4446       return true;
4447       
4448     case IIK_Default:
4449     case IIK_Inherit:
4450       return false;
4451     }
4452
4453     llvm_unreachable("Invalid ImplicitInitializerKind!");
4454   }
4455
4456   bool addFieldInitializer(CXXCtorInitializer *Init) {
4457     AllToInit.push_back(Init);
4458
4459     // Check whether this initializer makes the field "used".
4460     if (Init->getInit()->HasSideEffects(S.Context))
4461       S.UnusedPrivateFields.remove(Init->getAnyMember());
4462
4463     return false;
4464   }
4465
4466   bool isInactiveUnionMember(FieldDecl *Field) {
4467     RecordDecl *Record = Field->getParent();
4468     if (!Record->isUnion())
4469       return false;
4470
4471     if (FieldDecl *Active =
4472             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4473       return Active != Field->getCanonicalDecl();
4474
4475     // In an implicit copy or move constructor, ignore any in-class initializer.
4476     if (isImplicitCopyOrMove())
4477       return true;
4478
4479     // If there's no explicit initialization, the field is active only if it
4480     // has an in-class initializer...
4481     if (Field->hasInClassInitializer())
4482       return false;
4483     // ... or it's an anonymous struct or union whose class has an in-class
4484     // initializer.
4485     if (!Field->isAnonymousStructOrUnion())
4486       return true;
4487     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4488     return !FieldRD->hasInClassInitializer();
4489   }
4490
4491   /// \brief Determine whether the given field is, or is within, a union member
4492   /// that is inactive (because there was an initializer given for a different
4493   /// member of the union, or because the union was not initialized at all).
4494   bool isWithinInactiveUnionMember(FieldDecl *Field,
4495                                    IndirectFieldDecl *Indirect) {
4496     if (!Indirect)
4497       return isInactiveUnionMember(Field);
4498
4499     for (auto *C : Indirect->chain()) {
4500       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4501       if (Field && isInactiveUnionMember(Field))
4502         return true;
4503     }
4504     return false;
4505   }
4506 };
4507 }
4508
4509 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
4510 /// array type.
4511 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4512   if (T->isIncompleteArrayType())
4513     return true;
4514   
4515   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4516     if (!ArrayT->getSize())
4517       return true;
4518     
4519     T = ArrayT->getElementType();
4520   }
4521   
4522   return false;
4523 }
4524
4525 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4526                                     FieldDecl *Field, 
4527                                     IndirectFieldDecl *Indirect = nullptr) {
4528   if (Field->isInvalidDecl())
4529     return false;
4530
4531   // Overwhelmingly common case: we have a direct initializer for this field.
4532   if (CXXCtorInitializer *Init =
4533           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4534     return Info.addFieldInitializer(Init);
4535
4536   // C++11 [class.base.init]p8:
4537   //   if the entity is a non-static data member that has a
4538   //   brace-or-equal-initializer and either
4539   //   -- the constructor's class is a union and no other variant member of that
4540   //      union is designated by a mem-initializer-id or
4541   //   -- the constructor's class is not a union, and, if the entity is a member
4542   //      of an anonymous union, no other member of that union is designated by
4543   //      a mem-initializer-id,
4544   //   the entity is initialized as specified in [dcl.init].
4545   //
4546   // We also apply the same rules to handle anonymous structs within anonymous
4547   // unions.
4548   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4549     return false;
4550
4551   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4552     ExprResult DIE =
4553         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4554     if (DIE.isInvalid())
4555       return true;
4556     CXXCtorInitializer *Init;
4557     if (Indirect)
4558       Init = new (SemaRef.Context)
4559           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4560                              SourceLocation(), DIE.get(), SourceLocation());
4561     else
4562       Init = new (SemaRef.Context)
4563           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4564                              SourceLocation(), DIE.get(), SourceLocation());
4565     return Info.addFieldInitializer(Init);
4566   }
4567
4568   // Don't initialize incomplete or zero-length arrays.
4569   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4570     return false;
4571
4572   // Don't try to build an implicit initializer if there were semantic
4573   // errors in any of the initializers (and therefore we might be
4574   // missing some that the user actually wrote).
4575   if (Info.AnyErrorsInInits)
4576     return false;
4577
4578   CXXCtorInitializer *Init = nullptr;
4579   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4580                                      Indirect, Init))
4581     return true;
4582
4583   if (!Init)
4584     return false;
4585
4586   return Info.addFieldInitializer(Init);
4587 }
4588
4589 bool
4590 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4591                                CXXCtorInitializer *Initializer) {
4592   assert(Initializer->isDelegatingInitializer());
4593   Constructor->setNumCtorInitializers(1);
4594   CXXCtorInitializer **initializer =
4595     new (Context) CXXCtorInitializer*[1];
4596   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4597   Constructor->setCtorInitializers(initializer);
4598
4599   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4600     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4601     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4602   }
4603
4604   DelegatingCtorDecls.push_back(Constructor);
4605
4606   DiagnoseUninitializedFields(*this, Constructor);
4607
4608   return false;
4609 }
4610
4611 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4612                                ArrayRef<CXXCtorInitializer *> Initializers) {
4613   if (Constructor->isDependentContext()) {
4614     // Just store the initializers as written, they will be checked during
4615     // instantiation.
4616     if (!Initializers.empty()) {
4617       Constructor->setNumCtorInitializers(Initializers.size());
4618       CXXCtorInitializer **baseOrMemberInitializers =
4619         new (Context) CXXCtorInitializer*[Initializers.size()];
4620       memcpy(baseOrMemberInitializers, Initializers.data(),
4621              Initializers.size() * sizeof(CXXCtorInitializer*));
4622       Constructor->setCtorInitializers(baseOrMemberInitializers);
4623     }
4624
4625     // Let template instantiation know whether we had errors.
4626     if (AnyErrors)
4627       Constructor->setInvalidDecl();
4628
4629     return false;
4630   }
4631
4632   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4633
4634   // We need to build the initializer AST according to order of construction
4635   // and not what user specified in the Initializers list.
4636   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4637   if (!ClassDecl)
4638     return true;
4639   
4640   bool HadError = false;
4641
4642   for (unsigned i = 0; i < Initializers.size(); i++) {
4643     CXXCtorInitializer *Member = Initializers[i];
4644
4645     if (Member->isBaseInitializer())
4646       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4647     else {
4648       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4649
4650       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4651         for (auto *C : F->chain()) {
4652           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4653           if (FD && FD->getParent()->isUnion())
4654             Info.ActiveUnionMember.insert(std::make_pair(
4655                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4656         }
4657       } else if (FieldDecl *FD = Member->getMember()) {
4658         if (FD->getParent()->isUnion())
4659           Info.ActiveUnionMember.insert(std::make_pair(
4660               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4661       }
4662     }
4663   }
4664
4665   // Keep track of the direct virtual bases.
4666   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4667   for (auto &I : ClassDecl->bases()) {
4668     if (I.isVirtual())
4669       DirectVBases.insert(&I);
4670   }
4671
4672   // Push virtual bases before others.
4673   for (auto &VBase : ClassDecl->vbases()) {
4674     if (CXXCtorInitializer *Value
4675         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4676       // [class.base.init]p7, per DR257:
4677       //   A mem-initializer where the mem-initializer-id names a virtual base
4678       //   class is ignored during execution of a constructor of any class that
4679       //   is not the most derived class.
4680       if (ClassDecl->isAbstract()) {
4681         // FIXME: Provide a fixit to remove the base specifier. This requires
4682         // tracking the location of the associated comma for a base specifier.
4683         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4684           << VBase.getType() << ClassDecl;
4685         DiagnoseAbstractType(ClassDecl);
4686       }
4687
4688       Info.AllToInit.push_back(Value);
4689     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4690       // [class.base.init]p8, per DR257:
4691       //   If a given [...] base class is not named by a mem-initializer-id
4692       //   [...] and the entity is not a virtual base class of an abstract
4693       //   class, then [...] the entity is default-initialized.
4694       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4695       CXXCtorInitializer *CXXBaseInit;
4696       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4697                                        &VBase, IsInheritedVirtualBase,
4698                                        CXXBaseInit)) {
4699         HadError = true;
4700         continue;
4701       }
4702
4703       Info.AllToInit.push_back(CXXBaseInit);
4704     }
4705   }
4706
4707   // Non-virtual bases.
4708   for (auto &Base : ClassDecl->bases()) {
4709     // Virtuals are in the virtual base list and already constructed.
4710     if (Base.isVirtual())
4711       continue;
4712
4713     if (CXXCtorInitializer *Value
4714           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4715       Info.AllToInit.push_back(Value);
4716     } else if (!AnyErrors) {
4717       CXXCtorInitializer *CXXBaseInit;
4718       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4719                                        &Base, /*IsInheritedVirtualBase=*/false,
4720                                        CXXBaseInit)) {
4721         HadError = true;
4722         continue;
4723       }
4724
4725       Info.AllToInit.push_back(CXXBaseInit);
4726     }
4727   }
4728
4729   // Fields.
4730   for (auto *Mem : ClassDecl->decls()) {
4731     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4732       // C++ [class.bit]p2:
4733       //   A declaration for a bit-field that omits the identifier declares an
4734       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4735       //   initialized.
4736       if (F->isUnnamedBitfield())
4737         continue;
4738             
4739       // If we're not generating the implicit copy/move constructor, then we'll
4740       // handle anonymous struct/union fields based on their individual
4741       // indirect fields.
4742       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4743         continue;
4744           
4745       if (CollectFieldInitializer(*this, Info, F))
4746         HadError = true;
4747       continue;
4748     }
4749     
4750     // Beyond this point, we only consider default initialization.
4751     if (Info.isImplicitCopyOrMove())
4752       continue;
4753     
4754     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4755       if (F->getType()->isIncompleteArrayType()) {
4756         assert(ClassDecl->hasFlexibleArrayMember() &&
4757                "Incomplete array type is not valid");
4758         continue;
4759       }
4760       
4761       // Initialize each field of an anonymous struct individually.
4762       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4763         HadError = true;
4764       
4765       continue;        
4766     }
4767   }
4768
4769   unsigned NumInitializers = Info.AllToInit.size();
4770   if (NumInitializers > 0) {
4771     Constructor->setNumCtorInitializers(NumInitializers);
4772     CXXCtorInitializer **baseOrMemberInitializers =
4773       new (Context) CXXCtorInitializer*[NumInitializers];
4774     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4775            NumInitializers * sizeof(CXXCtorInitializer*));
4776     Constructor->setCtorInitializers(baseOrMemberInitializers);
4777
4778     // Constructors implicitly reference the base and member
4779     // destructors.
4780     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4781                                            Constructor->getParent());
4782   }
4783
4784   return HadError;
4785 }
4786
4787 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4788   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4789     const RecordDecl *RD = RT->getDecl();
4790     if (RD->isAnonymousStructOrUnion()) {
4791       for (auto *Field : RD->fields())
4792         PopulateKeysForFields(Field, IdealInits);
4793       return;
4794     }
4795   }
4796   IdealInits.push_back(Field->getCanonicalDecl());
4797 }
4798
4799 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4800   return Context.getCanonicalType(BaseType).getTypePtr();
4801 }
4802
4803 static const void *GetKeyForMember(ASTContext &Context,
4804                                    CXXCtorInitializer *Member) {
4805   if (!Member->isAnyMemberInitializer())
4806     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4807     
4808   return Member->getAnyMember()->getCanonicalDecl();
4809 }
4810
4811 static void DiagnoseBaseOrMemInitializerOrder(
4812     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4813     ArrayRef<CXXCtorInitializer *> Inits) {
4814   if (Constructor->getDeclContext()->isDependentContext())
4815     return;
4816
4817   // Don't check initializers order unless the warning is enabled at the
4818   // location of at least one initializer. 
4819   bool ShouldCheckOrder = false;
4820   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4821     CXXCtorInitializer *Init = Inits[InitIndex];
4822     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4823                                  Init->getSourceLocation())) {
4824       ShouldCheckOrder = true;
4825       break;
4826     }
4827   }
4828   if (!ShouldCheckOrder)
4829     return;
4830   
4831   // Build the list of bases and members in the order that they'll
4832   // actually be initialized.  The explicit initializers should be in
4833   // this same order but may be missing things.
4834   SmallVector<const void*, 32> IdealInitKeys;
4835
4836   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4837
4838   // 1. Virtual bases.
4839   for (const auto &VBase : ClassDecl->vbases())
4840     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4841
4842   // 2. Non-virtual bases.
4843   for (const auto &Base : ClassDecl->bases()) {
4844     if (Base.isVirtual())
4845       continue;
4846     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4847   }
4848
4849   // 3. Direct fields.
4850   for (auto *Field : ClassDecl->fields()) {
4851     if (Field->isUnnamedBitfield())
4852       continue;
4853     
4854     PopulateKeysForFields(Field, IdealInitKeys);
4855   }
4856   
4857   unsigned NumIdealInits = IdealInitKeys.size();
4858   unsigned IdealIndex = 0;
4859
4860   CXXCtorInitializer *PrevInit = nullptr;
4861   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4862     CXXCtorInitializer *Init = Inits[InitIndex];
4863     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4864
4865     // Scan forward to try to find this initializer in the idealized
4866     // initializers list.
4867     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4868       if (InitKey == IdealInitKeys[IdealIndex])
4869         break;
4870
4871     // If we didn't find this initializer, it must be because we
4872     // scanned past it on a previous iteration.  That can only
4873     // happen if we're out of order;  emit a warning.
4874     if (IdealIndex == NumIdealInits && PrevInit) {
4875       Sema::SemaDiagnosticBuilder D =
4876         SemaRef.Diag(PrevInit->getSourceLocation(),
4877                      diag::warn_initializer_out_of_order);
4878
4879       if (PrevInit->isAnyMemberInitializer())
4880         D << 0 << PrevInit->getAnyMember()->getDeclName();
4881       else
4882         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4883       
4884       if (Init->isAnyMemberInitializer())
4885         D << 0 << Init->getAnyMember()->getDeclName();
4886       else
4887         D << 1 << Init->getTypeSourceInfo()->getType();
4888
4889       // Move back to the initializer's location in the ideal list.
4890       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4891         if (InitKey == IdealInitKeys[IdealIndex])
4892           break;
4893
4894       assert(IdealIndex < NumIdealInits &&
4895              "initializer not found in initializer list");
4896     }
4897
4898     PrevInit = Init;
4899   }
4900 }
4901
4902 namespace {
4903 bool CheckRedundantInit(Sema &S,
4904                         CXXCtorInitializer *Init,
4905                         CXXCtorInitializer *&PrevInit) {
4906   if (!PrevInit) {
4907     PrevInit = Init;
4908     return false;
4909   }
4910
4911   if (FieldDecl *Field = Init->getAnyMember())
4912     S.Diag(Init->getSourceLocation(),
4913            diag::err_multiple_mem_initialization)
4914       << Field->getDeclName()
4915       << Init->getSourceRange();
4916   else {
4917     const Type *BaseClass = Init->getBaseClass();
4918     assert(BaseClass && "neither field nor base");
4919     S.Diag(Init->getSourceLocation(),
4920            diag::err_multiple_base_initialization)
4921       << QualType(BaseClass, 0)
4922       << Init->getSourceRange();
4923   }
4924   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4925     << 0 << PrevInit->getSourceRange();
4926
4927   return true;
4928 }
4929
4930 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4931 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4932
4933 bool CheckRedundantUnionInit(Sema &S,
4934                              CXXCtorInitializer *Init,
4935                              RedundantUnionMap &Unions) {
4936   FieldDecl *Field = Init->getAnyMember();
4937   RecordDecl *Parent = Field->getParent();
4938   NamedDecl *Child = Field;
4939
4940   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4941     if (Parent->isUnion()) {
4942       UnionEntry &En = Unions[Parent];
4943       if (En.first && En.first != Child) {
4944         S.Diag(Init->getSourceLocation(),
4945                diag::err_multiple_mem_union_initialization)
4946           << Field->getDeclName()
4947           << Init->getSourceRange();
4948         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4949           << 0 << En.second->getSourceRange();
4950         return true;
4951       } 
4952       if (!En.first) {
4953         En.first = Child;
4954         En.second = Init;
4955       }
4956       if (!Parent->isAnonymousStructOrUnion())
4957         return false;
4958     }
4959
4960     Child = Parent;
4961     Parent = cast<RecordDecl>(Parent->getDeclContext());
4962   }
4963
4964   return false;
4965 }
4966 }
4967
4968 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4969 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4970                                 SourceLocation ColonLoc,
4971                                 ArrayRef<CXXCtorInitializer*> MemInits,
4972                                 bool AnyErrors) {
4973   if (!ConstructorDecl)
4974     return;
4975
4976   AdjustDeclIfTemplate(ConstructorDecl);
4977
4978   CXXConstructorDecl *Constructor
4979     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4980
4981   if (!Constructor) {
4982     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4983     return;
4984   }
4985   
4986   // Mapping for the duplicate initializers check.
4987   // For member initializers, this is keyed with a FieldDecl*.
4988   // For base initializers, this is keyed with a Type*.
4989   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4990
4991   // Mapping for the inconsistent anonymous-union initializers check.
4992   RedundantUnionMap MemberUnions;
4993
4994   bool HadError = false;
4995   for (unsigned i = 0; i < MemInits.size(); i++) {
4996     CXXCtorInitializer *Init = MemInits[i];
4997
4998     // Set the source order index.
4999     Init->setSourceOrder(i);
5000
5001     if (Init->isAnyMemberInitializer()) {
5002       const void *Key = GetKeyForMember(Context, Init);
5003       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5004           CheckRedundantUnionInit(*this, Init, MemberUnions))
5005         HadError = true;
5006     } else if (Init->isBaseInitializer()) {
5007       const void *Key = GetKeyForMember(Context, Init);
5008       if (CheckRedundantInit(*this, Init, Members[Key]))
5009         HadError = true;
5010     } else {
5011       assert(Init->isDelegatingInitializer());
5012       // This must be the only initializer
5013       if (MemInits.size() != 1) {
5014         Diag(Init->getSourceLocation(),
5015              diag::err_delegating_initializer_alone)
5016           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5017         // We will treat this as being the only initializer.
5018       }
5019       SetDelegatingInitializer(Constructor, MemInits[i]);
5020       // Return immediately as the initializer is set.
5021       return;
5022     }
5023   }
5024
5025   if (HadError)
5026     return;
5027
5028   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5029
5030   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5031
5032   DiagnoseUninitializedFields(*this, Constructor);
5033 }
5034
5035 void
5036 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5037                                              CXXRecordDecl *ClassDecl) {
5038   // Ignore dependent contexts. Also ignore unions, since their members never
5039   // have destructors implicitly called.
5040   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5041     return;
5042
5043   // FIXME: all the access-control diagnostics are positioned on the
5044   // field/base declaration.  That's probably good; that said, the
5045   // user might reasonably want to know why the destructor is being
5046   // emitted, and we currently don't say.
5047   
5048   // Non-static data members.
5049   for (auto *Field : ClassDecl->fields()) {
5050     if (Field->isInvalidDecl())
5051       continue;
5052     
5053     // Don't destroy incomplete or zero-length arrays.
5054     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5055       continue;
5056
5057     QualType FieldType = Context.getBaseElementType(Field->getType());
5058     
5059     const RecordType* RT = FieldType->getAs<RecordType>();
5060     if (!RT)
5061       continue;
5062     
5063     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5064     if (FieldClassDecl->isInvalidDecl())
5065       continue;
5066     if (FieldClassDecl->hasIrrelevantDestructor())
5067       continue;
5068     // The destructor for an implicit anonymous union member is never invoked.
5069     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5070       continue;
5071
5072     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5073     assert(Dtor && "No dtor found for FieldClassDecl!");
5074     CheckDestructorAccess(Field->getLocation(), Dtor,
5075                           PDiag(diag::err_access_dtor_field)
5076                             << Field->getDeclName()
5077                             << FieldType);
5078
5079     MarkFunctionReferenced(Location, Dtor);
5080     DiagnoseUseOfDecl(Dtor, Location);
5081   }
5082
5083   // We only potentially invoke the destructors of potentially constructed
5084   // subobjects.
5085   bool VisitVirtualBases = !ClassDecl->isAbstract();
5086
5087   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5088
5089   // Bases.
5090   for (const auto &Base : ClassDecl->bases()) {
5091     // Bases are always records in a well-formed non-dependent class.
5092     const RecordType *RT = Base.getType()->getAs<RecordType>();
5093
5094     // Remember direct virtual bases.
5095     if (Base.isVirtual()) {
5096       if (!VisitVirtualBases)
5097         continue;
5098       DirectVirtualBases.insert(RT);
5099     }
5100
5101     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5102     // If our base class is invalid, we probably can't get its dtor anyway.
5103     if (BaseClassDecl->isInvalidDecl())
5104       continue;
5105     if (BaseClassDecl->hasIrrelevantDestructor())
5106       continue;
5107
5108     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5109     assert(Dtor && "No dtor found for BaseClassDecl!");
5110
5111     // FIXME: caret should be on the start of the class name
5112     CheckDestructorAccess(Base.getLocStart(), Dtor,
5113                           PDiag(diag::err_access_dtor_base)
5114                             << Base.getType()
5115                             << Base.getSourceRange(),
5116                           Context.getTypeDeclType(ClassDecl));
5117     
5118     MarkFunctionReferenced(Location, Dtor);
5119     DiagnoseUseOfDecl(Dtor, Location);
5120   }
5121
5122   if (!VisitVirtualBases)
5123     return;
5124   
5125   // Virtual bases.
5126   for (const auto &VBase : ClassDecl->vbases()) {
5127     // Bases are always records in a well-formed non-dependent class.
5128     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5129
5130     // Ignore direct virtual bases.
5131     if (DirectVirtualBases.count(RT))
5132       continue;
5133
5134     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5135     // If our base class is invalid, we probably can't get its dtor anyway.
5136     if (BaseClassDecl->isInvalidDecl())
5137       continue;
5138     if (BaseClassDecl->hasIrrelevantDestructor())
5139       continue;
5140
5141     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5142     assert(Dtor && "No dtor found for BaseClassDecl!");
5143     if (CheckDestructorAccess(
5144             ClassDecl->getLocation(), Dtor,
5145             PDiag(diag::err_access_dtor_vbase)
5146                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5147             Context.getTypeDeclType(ClassDecl)) ==
5148         AR_accessible) {
5149       CheckDerivedToBaseConversion(
5150           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5151           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5152           SourceRange(), DeclarationName(), nullptr);
5153     }
5154
5155     MarkFunctionReferenced(Location, Dtor);
5156     DiagnoseUseOfDecl(Dtor, Location);
5157   }
5158 }
5159
5160 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5161   if (!CDtorDecl)
5162     return;
5163
5164   if (CXXConstructorDecl *Constructor
5165       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5166     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5167     DiagnoseUninitializedFields(*this, Constructor);
5168   }
5169 }
5170
5171 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5172   if (!getLangOpts().CPlusPlus)
5173     return false;
5174
5175   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5176   if (!RD)
5177     return false;
5178
5179   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5180   // class template specialization here, but doing so breaks a lot of code.
5181
5182   // We can't answer whether something is abstract until it has a
5183   // definition. If it's currently being defined, we'll walk back
5184   // over all the declarations when we have a full definition.
5185   const CXXRecordDecl *Def = RD->getDefinition();
5186   if (!Def || Def->isBeingDefined())
5187     return false;
5188
5189   return RD->isAbstract();
5190 }
5191
5192 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5193                                   TypeDiagnoser &Diagnoser) {
5194   if (!isAbstractType(Loc, T))
5195     return false;
5196
5197   T = Context.getBaseElementType(T);
5198   Diagnoser.diagnose(*this, Loc, T);
5199   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5200   return true;
5201 }
5202
5203 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5204   // Check if we've already emitted the list of pure virtual functions
5205   // for this class.
5206   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5207     return;
5208
5209   // If the diagnostic is suppressed, don't emit the notes. We're only
5210   // going to emit them once, so try to attach them to a diagnostic we're
5211   // actually going to show.
5212   if (Diags.isLastDiagnosticIgnored())
5213     return;
5214
5215   CXXFinalOverriderMap FinalOverriders;
5216   RD->getFinalOverriders(FinalOverriders);
5217
5218   // Keep a set of seen pure methods so we won't diagnose the same method
5219   // more than once.
5220   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5221   
5222   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 
5223                                    MEnd = FinalOverriders.end();
5224        M != MEnd; 
5225        ++M) {
5226     for (OverridingMethods::iterator SO = M->second.begin(), 
5227                                   SOEnd = M->second.end();
5228          SO != SOEnd; ++SO) {
5229       // C++ [class.abstract]p4:
5230       //   A class is abstract if it contains or inherits at least one
5231       //   pure virtual function for which the final overrider is pure
5232       //   virtual.
5233
5234       // 
5235       if (SO->second.size() != 1)
5236         continue;
5237
5238       if (!SO->second.front().Method->isPure())
5239         continue;
5240
5241       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5242         continue;
5243
5244       Diag(SO->second.front().Method->getLocation(), 
5245            diag::note_pure_virtual_function) 
5246         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5247     }
5248   }
5249
5250   if (!PureVirtualClassDiagSet)
5251     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5252   PureVirtualClassDiagSet->insert(RD);
5253 }
5254
5255 namespace {
5256 struct AbstractUsageInfo {
5257   Sema &S;
5258   CXXRecordDecl *Record;
5259   CanQualType AbstractType;
5260   bool Invalid;
5261
5262   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5263     : S(S), Record(Record),
5264       AbstractType(S.Context.getCanonicalType(
5265                    S.Context.getTypeDeclType(Record))),
5266       Invalid(false) {}
5267
5268   void DiagnoseAbstractType() {
5269     if (Invalid) return;
5270     S.DiagnoseAbstractType(Record);
5271     Invalid = true;
5272   }
5273
5274   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5275 };
5276
5277 struct CheckAbstractUsage {
5278   AbstractUsageInfo &Info;
5279   const NamedDecl *Ctx;
5280
5281   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5282     : Info(Info), Ctx(Ctx) {}
5283
5284   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5285     switch (TL.getTypeLocClass()) {
5286 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5287 #define TYPELOC(CLASS, PARENT) \
5288     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5289 #include "clang/AST/TypeLocNodes.def"
5290     }
5291   }
5292
5293   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5294     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5295     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5296       if (!TL.getParam(I))
5297         continue;
5298
5299       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5300       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5301     }
5302   }
5303
5304   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5305     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5306   }
5307
5308   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5309     // Visit the type parameters from a permissive context.
5310     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5311       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5312       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5313         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5314           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5315       // TODO: other template argument types?
5316     }
5317   }
5318
5319   // Visit pointee types from a permissive context.
5320 #define CheckPolymorphic(Type) \
5321   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5322     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5323   }
5324   CheckPolymorphic(PointerTypeLoc)
5325   CheckPolymorphic(ReferenceTypeLoc)
5326   CheckPolymorphic(MemberPointerTypeLoc)
5327   CheckPolymorphic(BlockPointerTypeLoc)
5328   CheckPolymorphic(AtomicTypeLoc)
5329
5330   /// Handle all the types we haven't given a more specific
5331   /// implementation for above.
5332   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5333     // Every other kind of type that we haven't called out already
5334     // that has an inner type is either (1) sugar or (2) contains that
5335     // inner type in some way as a subobject.
5336     if (TypeLoc Next = TL.getNextTypeLoc())
5337       return Visit(Next, Sel);
5338
5339     // If there's no inner type and we're in a permissive context,
5340     // don't diagnose.
5341     if (Sel == Sema::AbstractNone) return;
5342
5343     // Check whether the type matches the abstract type.
5344     QualType T = TL.getType();
5345     if (T->isArrayType()) {
5346       Sel = Sema::AbstractArrayType;
5347       T = Info.S.Context.getBaseElementType(T);
5348     }
5349     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5350     if (CT != Info.AbstractType) return;
5351
5352     // It matched; do some magic.
5353     if (Sel == Sema::AbstractArrayType) {
5354       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5355         << T << TL.getSourceRange();
5356     } else {
5357       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5358         << Sel << T << TL.getSourceRange();
5359     }
5360     Info.DiagnoseAbstractType();
5361   }
5362 };
5363
5364 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5365                                   Sema::AbstractDiagSelID Sel) {
5366   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5367 }
5368
5369 }
5370
5371 /// Check for invalid uses of an abstract type in a method declaration.
5372 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5373                                     CXXMethodDecl *MD) {
5374   // No need to do the check on definitions, which require that
5375   // the return/param types be complete.
5376   if (MD->doesThisDeclarationHaveABody())
5377     return;
5378
5379   // For safety's sake, just ignore it if we don't have type source
5380   // information.  This should never happen for non-implicit methods,
5381   // but...
5382   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5383     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5384 }
5385
5386 /// Check for invalid uses of an abstract type within a class definition.
5387 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5388                                     CXXRecordDecl *RD) {
5389   for (auto *D : RD->decls()) {
5390     if (D->isImplicit()) continue;
5391
5392     // Methods and method templates.
5393     if (isa<CXXMethodDecl>(D)) {
5394       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5395     } else if (isa<FunctionTemplateDecl>(D)) {
5396       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5397       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5398
5399     // Fields and static variables.
5400     } else if (isa<FieldDecl>(D)) {
5401       FieldDecl *FD = cast<FieldDecl>(D);
5402       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5403         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5404     } else if (isa<VarDecl>(D)) {
5405       VarDecl *VD = cast<VarDecl>(D);
5406       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5407         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5408
5409     // Nested classes and class templates.
5410     } else if (isa<CXXRecordDecl>(D)) {
5411       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5412     } else if (isa<ClassTemplateDecl>(D)) {
5413       CheckAbstractClassUsage(Info,
5414                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5415     }
5416   }
5417 }
5418
5419 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5420   Attr *ClassAttr = getDLLAttr(Class);
5421   if (!ClassAttr)
5422     return;
5423
5424   assert(ClassAttr->getKind() == attr::DLLExport);
5425
5426   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5427
5428   if (TSK == TSK_ExplicitInstantiationDeclaration)
5429     // Don't go any further if this is just an explicit instantiation
5430     // declaration.
5431     return;
5432
5433   for (Decl *Member : Class->decls()) {
5434     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5435     if (!MD)
5436       continue;
5437
5438     if (Member->getAttr<DLLExportAttr>()) {
5439       if (MD->isUserProvided()) {
5440         // Instantiate non-default class member functions ...
5441
5442         // .. except for certain kinds of template specializations.
5443         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5444           continue;
5445
5446         S.MarkFunctionReferenced(Class->getLocation(), MD);
5447
5448         // The function will be passed to the consumer when its definition is
5449         // encountered.
5450       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5451                  MD->isCopyAssignmentOperator() ||
5452                  MD->isMoveAssignmentOperator()) {
5453         // Synthesize and instantiate non-trivial implicit methods, explicitly
5454         // defaulted methods, and the copy and move assignment operators. The
5455         // latter are exported even if they are trivial, because the address of
5456         // an operator can be taken and should compare equal across libraries.
5457         DiagnosticErrorTrap Trap(S.Diags);
5458         S.MarkFunctionReferenced(Class->getLocation(), MD);
5459         if (Trap.hasErrorOccurred()) {
5460           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5461               << Class->getName() << !S.getLangOpts().CPlusPlus11;
5462           break;
5463         }
5464
5465         // There is no later point when we will see the definition of this
5466         // function, so pass it to the consumer now.
5467         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5468       }
5469     }
5470   }
5471 }
5472
5473 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5474                                                         CXXRecordDecl *Class) {
5475   // Only the MS ABI has default constructor closures, so we don't need to do
5476   // this semantic checking anywhere else.
5477   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5478     return;
5479
5480   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5481   for (Decl *Member : Class->decls()) {
5482     // Look for exported default constructors.
5483     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5484     if (!CD || !CD->isDefaultConstructor())
5485       continue;
5486     auto *Attr = CD->getAttr<DLLExportAttr>();
5487     if (!Attr)
5488       continue;
5489
5490     // If the class is non-dependent, mark the default arguments as ODR-used so
5491     // that we can properly codegen the constructor closure.
5492     if (!Class->isDependentContext()) {
5493       for (ParmVarDecl *PD : CD->parameters()) {
5494         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5495         S.DiscardCleanupsInEvaluationContext();
5496       }
5497     }
5498
5499     if (LastExportedDefaultCtor) {
5500       S.Diag(LastExportedDefaultCtor->getLocation(),
5501              diag::err_attribute_dll_ambiguous_default_ctor)
5502           << Class;
5503       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5504           << CD->getDeclName();
5505       return;
5506     }
5507     LastExportedDefaultCtor = CD;
5508   }
5509 }
5510
5511 /// \brief Check class-level dllimport/dllexport attribute.
5512 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5513   Attr *ClassAttr = getDLLAttr(Class);
5514
5515   // MSVC inherits DLL attributes to partial class template specializations.
5516   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5517     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5518       if (Attr *TemplateAttr =
5519               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5520         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5521         A->setInherited(true);
5522         ClassAttr = A;
5523       }
5524     }
5525   }
5526
5527   if (!ClassAttr)
5528     return;
5529
5530   if (!Class->isExternallyVisible()) {
5531     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5532         << Class << ClassAttr;
5533     return;
5534   }
5535
5536   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5537       !ClassAttr->isInherited()) {
5538     // Diagnose dll attributes on members of class with dll attribute.
5539     for (Decl *Member : Class->decls()) {
5540       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5541         continue;
5542       InheritableAttr *MemberAttr = getDLLAttr(Member);
5543       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5544         continue;
5545
5546       Diag(MemberAttr->getLocation(),
5547              diag::err_attribute_dll_member_of_dll_class)
5548           << MemberAttr << ClassAttr;
5549       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5550       Member->setInvalidDecl();
5551     }
5552   }
5553
5554   if (Class->getDescribedClassTemplate())
5555     // Don't inherit dll attribute until the template is instantiated.
5556     return;
5557
5558   // The class is either imported or exported.
5559   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5560
5561   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5562
5563   // Ignore explicit dllexport on explicit class template instantiation declarations.
5564   if (ClassExported && !ClassAttr->isInherited() &&
5565       TSK == TSK_ExplicitInstantiationDeclaration) {
5566     Class->dropAttr<DLLExportAttr>();
5567     return;
5568   }
5569
5570   // Force declaration of implicit members so they can inherit the attribute.
5571   ForceDeclarationOfImplicitMembers(Class);
5572
5573   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5574   // seem to be true in practice?
5575
5576   for (Decl *Member : Class->decls()) {
5577     VarDecl *VD = dyn_cast<VarDecl>(Member);
5578     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5579
5580     // Only methods and static fields inherit the attributes.
5581     if (!VD && !MD)
5582       continue;
5583
5584     if (MD) {
5585       // Don't process deleted methods.
5586       if (MD->isDeleted())
5587         continue;
5588
5589       if (MD->isInlined()) {
5590         // MinGW does not import or export inline methods.
5591         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5592             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5593           continue;
5594
5595         // MSVC versions before 2015 don't export the move assignment operators
5596         // and move constructor, so don't attempt to import/export them if
5597         // we have a definition.
5598         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5599         if ((MD->isMoveAssignmentOperator() ||
5600              (Ctor && Ctor->isMoveConstructor())) &&
5601             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5602           continue;
5603
5604         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5605         // operator is exported anyway.
5606         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5607             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5608           continue;
5609       }
5610     }
5611
5612     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5613       continue;
5614
5615     if (!getDLLAttr(Member)) {
5616       auto *NewAttr =
5617           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5618       NewAttr->setInherited(true);
5619       Member->addAttr(NewAttr);
5620     }
5621   }
5622
5623   if (ClassExported)
5624     DelayedDllExportClasses.push_back(Class);
5625 }
5626
5627 /// \brief Perform propagation of DLL attributes from a derived class to a
5628 /// templated base class for MS compatibility.
5629 void Sema::propagateDLLAttrToBaseClassTemplate(
5630     CXXRecordDecl *Class, Attr *ClassAttr,
5631     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5632   if (getDLLAttr(
5633           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5634     // If the base class template has a DLL attribute, don't try to change it.
5635     return;
5636   }
5637
5638   auto TSK = BaseTemplateSpec->getSpecializationKind();
5639   if (!getDLLAttr(BaseTemplateSpec) &&
5640       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5641        TSK == TSK_ImplicitInstantiation)) {
5642     // The template hasn't been instantiated yet (or it has, but only as an
5643     // explicit instantiation declaration or implicit instantiation, which means
5644     // we haven't codegenned any members yet), so propagate the attribute.
5645     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5646     NewAttr->setInherited(true);
5647     BaseTemplateSpec->addAttr(NewAttr);
5648
5649     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5650     // needs to be run again to work see the new attribute. Otherwise this will
5651     // get run whenever the template is instantiated.
5652     if (TSK != TSK_Undeclared)
5653       checkClassLevelDLLAttribute(BaseTemplateSpec);
5654
5655     return;
5656   }
5657
5658   if (getDLLAttr(BaseTemplateSpec)) {
5659     // The template has already been specialized or instantiated with an
5660     // attribute, explicitly or through propagation. We should not try to change
5661     // it.
5662     return;
5663   }
5664
5665   // The template was previously instantiated or explicitly specialized without
5666   // a dll attribute, It's too late for us to add an attribute, so warn that
5667   // this is unsupported.
5668   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5669       << BaseTemplateSpec->isExplicitSpecialization();
5670   Diag(ClassAttr->getLocation(), diag::note_attribute);
5671   if (BaseTemplateSpec->isExplicitSpecialization()) {
5672     Diag(BaseTemplateSpec->getLocation(),
5673            diag::note_template_class_explicit_specialization_was_here)
5674         << BaseTemplateSpec;
5675   } else {
5676     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5677            diag::note_template_class_instantiation_was_here)
5678         << BaseTemplateSpec;
5679   }
5680 }
5681
5682 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5683                                         SourceLocation DefaultLoc) {
5684   switch (S.getSpecialMember(MD)) {
5685   case Sema::CXXDefaultConstructor:
5686     S.DefineImplicitDefaultConstructor(DefaultLoc,
5687                                        cast<CXXConstructorDecl>(MD));
5688     break;
5689   case Sema::CXXCopyConstructor:
5690     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5691     break;
5692   case Sema::CXXCopyAssignment:
5693     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5694     break;
5695   case Sema::CXXDestructor:
5696     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5697     break;
5698   case Sema::CXXMoveConstructor:
5699     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5700     break;
5701   case Sema::CXXMoveAssignment:
5702     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5703     break;
5704   case Sema::CXXInvalid:
5705     llvm_unreachable("Invalid special member.");
5706   }
5707 }
5708
5709 /// \brief Perform semantic checks on a class definition that has been
5710 /// completing, introducing implicitly-declared members, checking for
5711 /// abstract types, etc.
5712 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5713   if (!Record)
5714     return;
5715
5716   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5717     AbstractUsageInfo Info(*this, Record);
5718     CheckAbstractClassUsage(Info, Record);
5719   }
5720   
5721   // If this is not an aggregate type and has no user-declared constructor,
5722   // complain about any non-static data members of reference or const scalar
5723   // type, since they will never get initializers.
5724   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5725       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5726       !Record->isLambda()) {
5727     bool Complained = false;
5728     for (const auto *F : Record->fields()) {
5729       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5730         continue;
5731
5732       if (F->getType()->isReferenceType() ||
5733           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5734         if (!Complained) {
5735           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5736             << Record->getTagKind() << Record;
5737           Complained = true;
5738         }
5739         
5740         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5741           << F->getType()->isReferenceType()
5742           << F->getDeclName();
5743       }
5744     }
5745   }
5746
5747   if (Record->getIdentifier()) {
5748     // C++ [class.mem]p13:
5749     //   If T is the name of a class, then each of the following shall have a 
5750     //   name different from T:
5751     //     - every member of every anonymous union that is a member of class T.
5752     //
5753     // C++ [class.mem]p14:
5754     //   In addition, if class T has a user-declared constructor (12.1), every 
5755     //   non-static data member of class T shall have a name different from T.
5756     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5757     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5758          ++I) {
5759       NamedDecl *D = *I;
5760       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5761           isa<IndirectFieldDecl>(D)) {
5762         Diag(D->getLocation(), diag::err_member_name_of_class)
5763           << D->getDeclName();
5764         break;
5765       }
5766     }
5767   }
5768
5769   // Warn if the class has virtual methods but non-virtual public destructor.
5770   if (Record->isPolymorphic() && !Record->isDependentType()) {
5771     CXXDestructorDecl *dtor = Record->getDestructor();
5772     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5773         !Record->hasAttr<FinalAttr>())
5774       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5775            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5776   }
5777
5778   if (Record->isAbstract()) {
5779     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5780       Diag(Record->getLocation(), diag::warn_abstract_final_class)
5781         << FA->isSpelledAsSealed();
5782       DiagnoseAbstractType(Record);
5783     }
5784   }
5785
5786   bool HasMethodWithOverrideControl = false,
5787        HasOverridingMethodWithoutOverrideControl = false;
5788   if (!Record->isDependentType()) {
5789     for (auto *M : Record->methods()) {
5790       // See if a method overloads virtual methods in a base
5791       // class without overriding any.
5792       if (!M->isStatic())
5793         DiagnoseHiddenVirtualMethods(M);
5794       if (M->hasAttr<OverrideAttr>())
5795         HasMethodWithOverrideControl = true;
5796       else if (M->size_overridden_methods() > 0)
5797         HasOverridingMethodWithoutOverrideControl = true;
5798       // Check whether the explicitly-defaulted special members are valid.
5799       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
5800         CheckExplicitlyDefaultedSpecialMember(M);
5801
5802       // For an explicitly defaulted or deleted special member, we defer
5803       // determining triviality until the class is complete. That time is now!
5804       CXXSpecialMember CSM = getSpecialMember(M);
5805       if (!M->isImplicit() && !M->isUserProvided()) {
5806         if (CSM != CXXInvalid) {
5807           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
5808
5809           // Inform the class that we've finished declaring this member.
5810           Record->finishedDefaultedOrDeletedMember(M);
5811         }
5812       }
5813
5814       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5815           M->hasAttr<DLLExportAttr>()) {
5816         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5817             M->isTrivial() &&
5818             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5819              CSM == CXXDestructor))
5820           M->dropAttr<DLLExportAttr>();
5821
5822         if (M->hasAttr<DLLExportAttr>()) {
5823           DefineImplicitSpecialMember(*this, M, M->getLocation());
5824           ActOnFinishInlineFunctionDef(M);
5825         }
5826       }
5827     }
5828   }
5829
5830   if (HasMethodWithOverrideControl &&
5831       HasOverridingMethodWithoutOverrideControl) {
5832     // At least one method has the 'override' control declared.
5833     // Diagnose all other overridden methods which do not have 'override' specified on them.
5834     for (auto *M : Record->methods())
5835       DiagnoseAbsenceOfOverrideControl(M);
5836   }
5837
5838   // ms_struct is a request to use the same ABI rules as MSVC.  Check
5839   // whether this class uses any C++ features that are implemented
5840   // completely differently in MSVC, and if so, emit a diagnostic.
5841   // That diagnostic defaults to an error, but we allow projects to
5842   // map it down to a warning (or ignore it).  It's a fairly common
5843   // practice among users of the ms_struct pragma to mass-annotate
5844   // headers, sweeping up a bunch of types that the project doesn't
5845   // really rely on MSVC-compatible layout for.  We must therefore
5846   // support "ms_struct except for C++ stuff" as a secondary ABI.
5847   if (Record->isMsStruct(Context) &&
5848       (Record->isPolymorphic() || Record->getNumBases())) {
5849     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5850   }
5851
5852   checkClassLevelDLLAttribute(Record);
5853 }
5854
5855 /// Look up the special member function that would be called by a special
5856 /// member function for a subobject of class type.
5857 ///
5858 /// \param Class The class type of the subobject.
5859 /// \param CSM The kind of special member function.
5860 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5861 /// \param ConstRHS True if this is a copy operation with a const object
5862 ///        on its RHS, that is, if the argument to the outer special member
5863 ///        function is 'const' and this is not a field marked 'mutable'.
5864 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
5865     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5866     unsigned FieldQuals, bool ConstRHS) {
5867   unsigned LHSQuals = 0;
5868   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5869     LHSQuals = FieldQuals;
5870
5871   unsigned RHSQuals = FieldQuals;
5872   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5873     RHSQuals = 0;
5874   else if (ConstRHS)
5875     RHSQuals |= Qualifiers::Const;
5876
5877   return S.LookupSpecialMember(Class, CSM,
5878                                RHSQuals & Qualifiers::Const,
5879                                RHSQuals & Qualifiers::Volatile,
5880                                false,
5881                                LHSQuals & Qualifiers::Const,
5882                                LHSQuals & Qualifiers::Volatile);
5883 }
5884
5885 class Sema::InheritedConstructorInfo {
5886   Sema &S;
5887   SourceLocation UseLoc;
5888
5889   /// A mapping from the base classes through which the constructor was
5890   /// inherited to the using shadow declaration in that base class (or a null
5891   /// pointer if the constructor was declared in that base class).
5892   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5893       InheritedFromBases;
5894
5895 public:
5896   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5897                            ConstructorUsingShadowDecl *Shadow)
5898       : S(S), UseLoc(UseLoc) {
5899     bool DiagnosedMultipleConstructedBases = false;
5900     CXXRecordDecl *ConstructedBase = nullptr;
5901     UsingDecl *ConstructedBaseUsing = nullptr;
5902
5903     // Find the set of such base class subobjects and check that there's a
5904     // unique constructed subobject.
5905     for (auto *D : Shadow->redecls()) {
5906       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5907       auto *DNominatedBase = DShadow->getNominatedBaseClass();
5908       auto *DConstructedBase = DShadow->getConstructedBaseClass();
5909
5910       InheritedFromBases.insert(
5911           std::make_pair(DNominatedBase->getCanonicalDecl(),
5912                          DShadow->getNominatedBaseClassShadowDecl()));
5913       if (DShadow->constructsVirtualBase())
5914         InheritedFromBases.insert(
5915             std::make_pair(DConstructedBase->getCanonicalDecl(),
5916                            DShadow->getConstructedBaseClassShadowDecl()));
5917       else
5918         assert(DNominatedBase == DConstructedBase);
5919
5920       // [class.inhctor.init]p2:
5921       //   If the constructor was inherited from multiple base class subobjects
5922       //   of type B, the program is ill-formed.
5923       if (!ConstructedBase) {
5924         ConstructedBase = DConstructedBase;
5925         ConstructedBaseUsing = D->getUsingDecl();
5926       } else if (ConstructedBase != DConstructedBase &&
5927                  !Shadow->isInvalidDecl()) {
5928         if (!DiagnosedMultipleConstructedBases) {
5929           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5930               << Shadow->getTargetDecl();
5931           S.Diag(ConstructedBaseUsing->getLocation(),
5932                diag::note_ambiguous_inherited_constructor_using)
5933               << ConstructedBase;
5934           DiagnosedMultipleConstructedBases = true;
5935         }
5936         S.Diag(D->getUsingDecl()->getLocation(),
5937                diag::note_ambiguous_inherited_constructor_using)
5938             << DConstructedBase;
5939       }
5940     }
5941
5942     if (DiagnosedMultipleConstructedBases)
5943       Shadow->setInvalidDecl();
5944   }
5945
5946   /// Find the constructor to use for inherited construction of a base class,
5947   /// and whether that base class constructor inherits the constructor from a
5948   /// virtual base class (in which case it won't actually invoke it).
5949   std::pair<CXXConstructorDecl *, bool>
5950   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5951     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5952     if (It == InheritedFromBases.end())
5953       return std::make_pair(nullptr, false);
5954
5955     // This is an intermediary class.
5956     if (It->second)
5957       return std::make_pair(
5958           S.findInheritingConstructor(UseLoc, Ctor, It->second),
5959           It->second->constructsVirtualBase());
5960
5961     // This is the base class from which the constructor was inherited.
5962     return std::make_pair(Ctor, false);
5963   }
5964 };
5965
5966 /// Is the special member function which would be selected to perform the
5967 /// specified operation on the specified class type a constexpr constructor?
5968 static bool
5969 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5970                          Sema::CXXSpecialMember CSM, unsigned Quals,
5971                          bool ConstRHS,
5972                          CXXConstructorDecl *InheritedCtor = nullptr,
5973                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
5974   // If we're inheriting a constructor, see if we need to call it for this base
5975   // class.
5976   if (InheritedCtor) {
5977     assert(CSM == Sema::CXXDefaultConstructor);
5978     auto BaseCtor =
5979         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5980     if (BaseCtor)
5981       return BaseCtor->isConstexpr();
5982   }
5983
5984   if (CSM == Sema::CXXDefaultConstructor)
5985     return ClassDecl->hasConstexprDefaultConstructor();
5986
5987   Sema::SpecialMemberOverloadResult SMOR =
5988       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5989   if (!SMOR.getMethod())
5990     // A constructor we wouldn't select can't be "involved in initializing"
5991     // anything.
5992     return true;
5993   return SMOR.getMethod()->isConstexpr();
5994 }
5995
5996 /// Determine whether the specified special member function would be constexpr
5997 /// if it were implicitly defined.
5998 static bool defaultedSpecialMemberIsConstexpr(
5999     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6000     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6001     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6002   if (!S.getLangOpts().CPlusPlus11)
6003     return false;
6004
6005   // C++11 [dcl.constexpr]p4:
6006   // In the definition of a constexpr constructor [...]
6007   bool Ctor = true;
6008   switch (CSM) {
6009   case Sema::CXXDefaultConstructor:
6010     if (Inherited)
6011       break;
6012     // Since default constructor lookup is essentially trivial (and cannot
6013     // involve, for instance, template instantiation), we compute whether a
6014     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6015     //
6016     // This is important for performance; we need to know whether the default
6017     // constructor is constexpr to determine whether the type is a literal type.
6018     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6019
6020   case Sema::CXXCopyConstructor:
6021   case Sema::CXXMoveConstructor:
6022     // For copy or move constructors, we need to perform overload resolution.
6023     break;
6024
6025   case Sema::CXXCopyAssignment:
6026   case Sema::CXXMoveAssignment:
6027     if (!S.getLangOpts().CPlusPlus14)
6028       return false;
6029     // In C++1y, we need to perform overload resolution.
6030     Ctor = false;
6031     break;
6032
6033   case Sema::CXXDestructor:
6034   case Sema::CXXInvalid:
6035     return false;
6036   }
6037
6038   //   -- if the class is a non-empty union, or for each non-empty anonymous
6039   //      union member of a non-union class, exactly one non-static data member
6040   //      shall be initialized; [DR1359]
6041   //
6042   // If we squint, this is guaranteed, since exactly one non-static data member
6043   // will be initialized (if the constructor isn't deleted), we just don't know
6044   // which one.
6045   if (Ctor && ClassDecl->isUnion())
6046     return CSM == Sema::CXXDefaultConstructor
6047                ? ClassDecl->hasInClassInitializer() ||
6048                      !ClassDecl->hasVariantMembers()
6049                : true;
6050
6051   //   -- the class shall not have any virtual base classes;
6052   if (Ctor && ClassDecl->getNumVBases())
6053     return false;
6054
6055   // C++1y [class.copy]p26:
6056   //   -- [the class] is a literal type, and
6057   if (!Ctor && !ClassDecl->isLiteral())
6058     return false;
6059
6060   //   -- every constructor involved in initializing [...] base class
6061   //      sub-objects shall be a constexpr constructor;
6062   //   -- the assignment operator selected to copy/move each direct base
6063   //      class is a constexpr function, and
6064   for (const auto &B : ClassDecl->bases()) {
6065     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6066     if (!BaseType) continue;
6067
6068     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6069     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6070                                   InheritedCtor, Inherited))
6071       return false;
6072   }
6073
6074   //   -- every constructor involved in initializing non-static data members
6075   //      [...] shall be a constexpr constructor;
6076   //   -- every non-static data member and base class sub-object shall be
6077   //      initialized
6078   //   -- for each non-static data member of X that is of class type (or array
6079   //      thereof), the assignment operator selected to copy/move that member is
6080   //      a constexpr function
6081   for (const auto *F : ClassDecl->fields()) {
6082     if (F->isInvalidDecl())
6083       continue;
6084     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6085       continue;
6086     QualType BaseType = S.Context.getBaseElementType(F->getType());
6087     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6088       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6089       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6090                                     BaseType.getCVRQualifiers(),
6091                                     ConstArg && !F->isMutable()))
6092         return false;
6093     } else if (CSM == Sema::CXXDefaultConstructor) {
6094       return false;
6095     }
6096   }
6097
6098   // All OK, it's constexpr!
6099   return true;
6100 }
6101
6102 static Sema::ImplicitExceptionSpecification
6103 ComputeDefaultedSpecialMemberExceptionSpec(
6104     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6105     Sema::InheritedConstructorInfo *ICI);
6106
6107 static Sema::ImplicitExceptionSpecification
6108 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6109   auto CSM = S.getSpecialMember(MD);
6110   if (CSM != Sema::CXXInvalid)
6111     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6112
6113   auto *CD = cast<CXXConstructorDecl>(MD);
6114   assert(CD->getInheritedConstructor() &&
6115          "only special members have implicit exception specs");
6116   Sema::InheritedConstructorInfo ICI(
6117       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6118   return ComputeDefaultedSpecialMemberExceptionSpec(
6119       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6120 }
6121
6122 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6123                                                             CXXMethodDecl *MD) {
6124   FunctionProtoType::ExtProtoInfo EPI;
6125
6126   // Build an exception specification pointing back at this member.
6127   EPI.ExceptionSpec.Type = EST_Unevaluated;
6128   EPI.ExceptionSpec.SourceDecl = MD;
6129
6130   // Set the calling convention to the default for C++ instance methods.
6131   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6132       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6133                                             /*IsCXXMethod=*/true));
6134   return EPI;
6135 }
6136
6137 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6138   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6139   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6140     return;
6141
6142   // Evaluate the exception specification.
6143   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6144   auto ESI = IES.getExceptionSpec();
6145
6146   // Update the type of the special member to use it.
6147   UpdateExceptionSpec(MD, ESI);
6148
6149   // A user-provided destructor can be defined outside the class. When that
6150   // happens, be sure to update the exception specification on both
6151   // declarations.
6152   const FunctionProtoType *CanonicalFPT =
6153     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6154   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6155     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6156 }
6157
6158 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6159   CXXRecordDecl *RD = MD->getParent();
6160   CXXSpecialMember CSM = getSpecialMember(MD);
6161
6162   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6163          "not an explicitly-defaulted special member");
6164
6165   // Whether this was the first-declared instance of the constructor.
6166   // This affects whether we implicitly add an exception spec and constexpr.
6167   bool First = MD == MD->getCanonicalDecl();
6168
6169   bool HadError = false;
6170
6171   // C++11 [dcl.fct.def.default]p1:
6172   //   A function that is explicitly defaulted shall
6173   //     -- be a special member function (checked elsewhere),
6174   //     -- have the same type (except for ref-qualifiers, and except that a
6175   //        copy operation can take a non-const reference) as an implicit
6176   //        declaration, and
6177   //     -- not have default arguments.
6178   unsigned ExpectedParams = 1;
6179   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6180     ExpectedParams = 0;
6181   if (MD->getNumParams() != ExpectedParams) {
6182     // This also checks for default arguments: a copy or move constructor with a
6183     // default argument is classified as a default constructor, and assignment
6184     // operations and destructors can't have default arguments.
6185     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6186       << CSM << MD->getSourceRange();
6187     HadError = true;
6188   } else if (MD->isVariadic()) {
6189     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6190       << CSM << MD->getSourceRange();
6191     HadError = true;
6192   }
6193
6194   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6195
6196   bool CanHaveConstParam = false;
6197   if (CSM == CXXCopyConstructor)
6198     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6199   else if (CSM == CXXCopyAssignment)
6200     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6201
6202   QualType ReturnType = Context.VoidTy;
6203   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6204     // Check for return type matching.
6205     ReturnType = Type->getReturnType();
6206     QualType ExpectedReturnType =
6207         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6208     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6209       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6210         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6211       HadError = true;
6212     }
6213
6214     // A defaulted special member cannot have cv-qualifiers.
6215     if (Type->getTypeQuals()) {
6216       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6217         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6218       HadError = true;
6219     }
6220   }
6221
6222   // Check for parameter type matching.
6223   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6224   bool HasConstParam = false;
6225   if (ExpectedParams && ArgType->isReferenceType()) {
6226     // Argument must be reference to possibly-const T.
6227     QualType ReferentType = ArgType->getPointeeType();
6228     HasConstParam = ReferentType.isConstQualified();
6229
6230     if (ReferentType.isVolatileQualified()) {
6231       Diag(MD->getLocation(),
6232            diag::err_defaulted_special_member_volatile_param) << CSM;
6233       HadError = true;
6234     }
6235
6236     if (HasConstParam && !CanHaveConstParam) {
6237       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6238         Diag(MD->getLocation(),
6239              diag::err_defaulted_special_member_copy_const_param)
6240           << (CSM == CXXCopyAssignment);
6241         // FIXME: Explain why this special member can't be const.
6242       } else {
6243         Diag(MD->getLocation(),
6244              diag::err_defaulted_special_member_move_const_param)
6245           << (CSM == CXXMoveAssignment);
6246       }
6247       HadError = true;
6248     }
6249   } else if (ExpectedParams) {
6250     // A copy assignment operator can take its argument by value, but a
6251     // defaulted one cannot.
6252     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6253     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6254     HadError = true;
6255   }
6256
6257   // C++11 [dcl.fct.def.default]p2:
6258   //   An explicitly-defaulted function may be declared constexpr only if it
6259   //   would have been implicitly declared as constexpr,
6260   // Do not apply this rule to members of class templates, since core issue 1358
6261   // makes such functions always instantiate to constexpr functions. For
6262   // functions which cannot be constexpr (for non-constructors in C++11 and for
6263   // destructors in C++1y), this is checked elsewhere.
6264   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6265                                                      HasConstParam);
6266   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6267                                  : isa<CXXConstructorDecl>(MD)) &&
6268       MD->isConstexpr() && !Constexpr &&
6269       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6270     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6271     // FIXME: Explain why the special member can't be constexpr.
6272     HadError = true;
6273   }
6274
6275   //   and may have an explicit exception-specification only if it is compatible
6276   //   with the exception-specification on the implicit declaration.
6277   if (Type->hasExceptionSpec()) {
6278     // Delay the check if this is the first declaration of the special member,
6279     // since we may not have parsed some necessary in-class initializers yet.
6280     if (First) {
6281       // If the exception specification needs to be instantiated, do so now,
6282       // before we clobber it with an EST_Unevaluated specification below.
6283       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6284         InstantiateExceptionSpec(MD->getLocStart(), MD);
6285         Type = MD->getType()->getAs<FunctionProtoType>();
6286       }
6287       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6288     } else
6289       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6290   }
6291
6292   //   If a function is explicitly defaulted on its first declaration,
6293   if (First) {
6294     //  -- it is implicitly considered to be constexpr if the implicit
6295     //     definition would be,
6296     MD->setConstexpr(Constexpr);
6297
6298     //  -- it is implicitly considered to have the same exception-specification
6299     //     as if it had been implicitly declared,
6300     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6301     EPI.ExceptionSpec.Type = EST_Unevaluated;
6302     EPI.ExceptionSpec.SourceDecl = MD;
6303     MD->setType(Context.getFunctionType(ReturnType,
6304                                         llvm::makeArrayRef(&ArgType,
6305                                                            ExpectedParams),
6306                                         EPI));
6307   }
6308
6309   if (ShouldDeleteSpecialMember(MD, CSM)) {
6310     if (First) {
6311       SetDeclDeleted(MD, MD->getLocation());
6312     } else {
6313       // C++11 [dcl.fct.def.default]p4:
6314       //   [For a] user-provided explicitly-defaulted function [...] if such a
6315       //   function is implicitly defined as deleted, the program is ill-formed.
6316       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6317       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6318       HadError = true;
6319     }
6320   }
6321
6322   if (HadError)
6323     MD->setInvalidDecl();
6324 }
6325
6326 /// Check whether the exception specification provided for an
6327 /// explicitly-defaulted special member matches the exception specification
6328 /// that would have been generated for an implicit special member, per
6329 /// C++11 [dcl.fct.def.default]p2.
6330 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6331     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6332   // If the exception specification was explicitly specified but hadn't been
6333   // parsed when the method was defaulted, grab it now.
6334   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6335     SpecifiedType =
6336         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6337
6338   // Compute the implicit exception specification.
6339   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6340                                                        /*IsCXXMethod=*/true);
6341   FunctionProtoType::ExtProtoInfo EPI(CC);
6342   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6343   EPI.ExceptionSpec = IES.getExceptionSpec();
6344   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6345     Context.getFunctionType(Context.VoidTy, None, EPI));
6346
6347   // Ensure that it matches.
6348   CheckEquivalentExceptionSpec(
6349     PDiag(diag::err_incorrect_defaulted_exception_spec)
6350       << getSpecialMember(MD), PDiag(),
6351     ImplicitType, SourceLocation(),
6352     SpecifiedType, MD->getLocation());
6353 }
6354
6355 void Sema::CheckDelayedMemberExceptionSpecs() {
6356   decltype(DelayedExceptionSpecChecks) Checks;
6357   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6358
6359   std::swap(Checks, DelayedExceptionSpecChecks);
6360   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6361
6362   // Perform any deferred checking of exception specifications for virtual
6363   // destructors.
6364   for (auto &Check : Checks)
6365     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6366
6367   // Check that any explicitly-defaulted methods have exception specifications
6368   // compatible with their implicit exception specifications.
6369   for (auto &Spec : Specs)
6370     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6371 }
6372
6373 namespace {
6374 /// CRTP base class for visiting operations performed by a special member
6375 /// function (or inherited constructor).
6376 template<typename Derived>
6377 struct SpecialMemberVisitor {
6378   Sema &S;
6379   CXXMethodDecl *MD;
6380   Sema::CXXSpecialMember CSM;
6381   Sema::InheritedConstructorInfo *ICI;
6382
6383   // Properties of the special member, computed for convenience.
6384   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6385
6386   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6387                        Sema::InheritedConstructorInfo *ICI)
6388       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6389     switch (CSM) {
6390     case Sema::CXXDefaultConstructor:
6391     case Sema::CXXCopyConstructor:
6392     case Sema::CXXMoveConstructor:
6393       IsConstructor = true;
6394       break;
6395     case Sema::CXXCopyAssignment:
6396     case Sema::CXXMoveAssignment:
6397       IsAssignment = true;
6398       break;
6399     case Sema::CXXDestructor:
6400       break;
6401     case Sema::CXXInvalid:
6402       llvm_unreachable("invalid special member kind");
6403     }
6404
6405     if (MD->getNumParams()) {
6406       if (const ReferenceType *RT =
6407               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6408         ConstArg = RT->getPointeeType().isConstQualified();
6409     }
6410   }
6411
6412   Derived &getDerived() { return static_cast<Derived&>(*this); }
6413
6414   /// Is this a "move" special member?
6415   bool isMove() const {
6416     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6417   }
6418
6419   /// Look up the corresponding special member in the given class.
6420   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6421                                              unsigned Quals, bool IsMutable) {
6422     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6423                                        ConstArg && !IsMutable);
6424   }
6425
6426   /// Look up the constructor for the specified base class to see if it's
6427   /// overridden due to this being an inherited constructor.
6428   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6429     if (!ICI)
6430       return {};
6431     assert(CSM == Sema::CXXDefaultConstructor);
6432     auto *BaseCtor =
6433       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6434     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6435       return MD;
6436     return {};
6437   }
6438
6439   /// A base or member subobject.
6440   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6441
6442   /// Get the location to use for a subobject in diagnostics.
6443   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6444     // FIXME: For an indirect virtual base, the direct base leading to
6445     // the indirect virtual base would be a more useful choice.
6446     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6447       return B->getBaseTypeLoc();
6448     else
6449       return Subobj.get<FieldDecl*>()->getLocation();
6450   }
6451
6452   enum BasesToVisit {
6453     /// Visit all non-virtual (direct) bases.
6454     VisitNonVirtualBases,
6455     /// Visit all direct bases, virtual or not.
6456     VisitDirectBases,
6457     /// Visit all non-virtual bases, and all virtual bases if the class
6458     /// is not abstract.
6459     VisitPotentiallyConstructedBases,
6460     /// Visit all direct or virtual bases.
6461     VisitAllBases
6462   };
6463
6464   // Visit the bases and members of the class.
6465   bool visit(BasesToVisit Bases) {
6466     CXXRecordDecl *RD = MD->getParent();
6467
6468     if (Bases == VisitPotentiallyConstructedBases)
6469       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6470
6471     for (auto &B : RD->bases())
6472       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6473           getDerived().visitBase(&B))
6474         return true;
6475
6476     if (Bases == VisitAllBases)
6477       for (auto &B : RD->vbases())
6478         if (getDerived().visitBase(&B))
6479           return true;
6480
6481     for (auto *F : RD->fields())
6482       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6483           getDerived().visitField(F))
6484         return true;
6485
6486     return false;
6487   }
6488 };
6489 }
6490
6491 namespace {
6492 struct SpecialMemberDeletionInfo
6493     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6494   bool Diagnose;
6495
6496   SourceLocation Loc;
6497
6498   bool AllFieldsAreConst;
6499
6500   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6501                             Sema::CXXSpecialMember CSM,
6502                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6503       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6504         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6505
6506   bool inUnion() const { return MD->getParent()->isUnion(); }
6507
6508   Sema::CXXSpecialMember getEffectiveCSM() {
6509     return ICI ? Sema::CXXInvalid : CSM;
6510   }
6511
6512   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6513   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6514
6515   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6516   bool shouldDeleteForField(FieldDecl *FD);
6517   bool shouldDeleteForAllConstMembers();
6518
6519   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6520                                      unsigned Quals);
6521   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6522                                     Sema::SpecialMemberOverloadResult SMOR,
6523                                     bool IsDtorCallInCtor);
6524
6525   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6526 };
6527 }
6528
6529 /// Is the given special member inaccessible when used on the given
6530 /// sub-object.
6531 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6532                                              CXXMethodDecl *target) {
6533   /// If we're operating on a base class, the object type is the
6534   /// type of this special member.
6535   QualType objectTy;
6536   AccessSpecifier access = target->getAccess();
6537   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6538     objectTy = S.Context.getTypeDeclType(MD->getParent());
6539     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6540
6541   // If we're operating on a field, the object type is the type of the field.
6542   } else {
6543     objectTy = S.Context.getTypeDeclType(target->getParent());
6544   }
6545
6546   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6547 }
6548
6549 /// Check whether we should delete a special member due to the implicit
6550 /// definition containing a call to a special member of a subobject.
6551 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6552     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6553     bool IsDtorCallInCtor) {
6554   CXXMethodDecl *Decl = SMOR.getMethod();
6555   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6556
6557   int DiagKind = -1;
6558
6559   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6560     DiagKind = !Decl ? 0 : 1;
6561   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6562     DiagKind = 2;
6563   else if (!isAccessible(Subobj, Decl))
6564     DiagKind = 3;
6565   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6566            !Decl->isTrivial()) {
6567     // A member of a union must have a trivial corresponding special member.
6568     // As a weird special case, a destructor call from a union's constructor
6569     // must be accessible and non-deleted, but need not be trivial. Such a
6570     // destructor is never actually called, but is semantically checked as
6571     // if it were.
6572     DiagKind = 4;
6573   }
6574
6575   if (DiagKind == -1)
6576     return false;
6577
6578   if (Diagnose) {
6579     if (Field) {
6580       S.Diag(Field->getLocation(),
6581              diag::note_deleted_special_member_class_subobject)
6582         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6583         << Field << DiagKind << IsDtorCallInCtor;
6584     } else {
6585       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6586       S.Diag(Base->getLocStart(),
6587              diag::note_deleted_special_member_class_subobject)
6588         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6589         << Base->getType() << DiagKind << IsDtorCallInCtor;
6590     }
6591
6592     if (DiagKind == 1)
6593       S.NoteDeletedFunction(Decl);
6594     // FIXME: Explain inaccessibility if DiagKind == 3.
6595   }
6596
6597   return true;
6598 }
6599
6600 /// Check whether we should delete a special member function due to having a
6601 /// direct or virtual base class or non-static data member of class type M.
6602 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6603     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6604   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6605   bool IsMutable = Field && Field->isMutable();
6606
6607   // C++11 [class.ctor]p5:
6608   // -- any direct or virtual base class, or non-static data member with no
6609   //    brace-or-equal-initializer, has class type M (or array thereof) and
6610   //    either M has no default constructor or overload resolution as applied
6611   //    to M's default constructor results in an ambiguity or in a function
6612   //    that is deleted or inaccessible
6613   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6614   // -- a direct or virtual base class B that cannot be copied/moved because
6615   //    overload resolution, as applied to B's corresponding special member,
6616   //    results in an ambiguity or a function that is deleted or inaccessible
6617   //    from the defaulted special member
6618   // C++11 [class.dtor]p5:
6619   // -- any direct or virtual base class [...] has a type with a destructor
6620   //    that is deleted or inaccessible
6621   if (!(CSM == Sema::CXXDefaultConstructor &&
6622         Field && Field->hasInClassInitializer()) &&
6623       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6624                                    false))
6625     return true;
6626
6627   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6628   // -- any direct or virtual base class or non-static data member has a
6629   //    type with a destructor that is deleted or inaccessible
6630   if (IsConstructor) {
6631     Sema::SpecialMemberOverloadResult SMOR =
6632         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6633                               false, false, false, false, false);
6634     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6635       return true;
6636   }
6637
6638   return false;
6639 }
6640
6641 /// Check whether we should delete a special member function due to the class
6642 /// having a particular direct or virtual base class.
6643 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6644   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6645   // If program is correct, BaseClass cannot be null, but if it is, the error
6646   // must be reported elsewhere.
6647   if (!BaseClass)
6648     return false;
6649   // If we have an inheriting constructor, check whether we're calling an
6650   // inherited constructor instead of a default constructor.
6651   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6652   if (auto *BaseCtor = SMOR.getMethod()) {
6653     // Note that we do not check access along this path; other than that,
6654     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6655     // FIXME: Check that the base has a usable destructor! Sink this into
6656     // shouldDeleteForClassSubobject.
6657     if (BaseCtor->isDeleted() && Diagnose) {
6658       S.Diag(Base->getLocStart(),
6659              diag::note_deleted_special_member_class_subobject)
6660         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6661         << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6662       S.NoteDeletedFunction(BaseCtor);
6663     }
6664     return BaseCtor->isDeleted();
6665   }
6666   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6667 }
6668
6669 /// Check whether we should delete a special member function due to the class
6670 /// having a particular non-static data member.
6671 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6672   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6673   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6674
6675   if (CSM == Sema::CXXDefaultConstructor) {
6676     // For a default constructor, all references must be initialized in-class
6677     // and, if a union, it must have a non-const member.
6678     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6679       if (Diagnose)
6680         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6681           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6682       return true;
6683     }
6684     // C++11 [class.ctor]p5: any non-variant non-static data member of
6685     // const-qualified type (or array thereof) with no
6686     // brace-or-equal-initializer does not have a user-provided default
6687     // constructor.
6688     if (!inUnion() && FieldType.isConstQualified() &&
6689         !FD->hasInClassInitializer() &&
6690         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6691       if (Diagnose)
6692         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6693           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6694       return true;
6695     }
6696
6697     if (inUnion() && !FieldType.isConstQualified())
6698       AllFieldsAreConst = false;
6699   } else if (CSM == Sema::CXXCopyConstructor) {
6700     // For a copy constructor, data members must not be of rvalue reference
6701     // type.
6702     if (FieldType->isRValueReferenceType()) {
6703       if (Diagnose)
6704         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6705           << MD->getParent() << FD << FieldType;
6706       return true;
6707     }
6708   } else if (IsAssignment) {
6709     // For an assignment operator, data members must not be of reference type.
6710     if (FieldType->isReferenceType()) {
6711       if (Diagnose)
6712         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6713           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
6714       return true;
6715     }
6716     if (!FieldRecord && FieldType.isConstQualified()) {
6717       // C++11 [class.copy]p23:
6718       // -- a non-static data member of const non-class type (or array thereof)
6719       if (Diagnose)
6720         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6721           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
6722       return true;
6723     }
6724   }
6725
6726   if (FieldRecord) {
6727     // Some additional restrictions exist on the variant members.
6728     if (!inUnion() && FieldRecord->isUnion() &&
6729         FieldRecord->isAnonymousStructOrUnion()) {
6730       bool AllVariantFieldsAreConst = true;
6731
6732       // FIXME: Handle anonymous unions declared within anonymous unions.
6733       for (auto *UI : FieldRecord->fields()) {
6734         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
6735
6736         if (!UnionFieldType.isConstQualified())
6737           AllVariantFieldsAreConst = false;
6738
6739         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6740         if (UnionFieldRecord &&
6741             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
6742                                           UnionFieldType.getCVRQualifiers()))
6743           return true;
6744       }
6745
6746       // At least one member in each anonymous union must be non-const
6747       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
6748           !FieldRecord->field_empty()) {
6749         if (Diagnose)
6750           S.Diag(FieldRecord->getLocation(),
6751                  diag::note_deleted_default_ctor_all_const)
6752             << !!ICI << MD->getParent() << /*anonymous union*/1;
6753         return true;
6754       }
6755
6756       // Don't check the implicit member of the anonymous union type.
6757       // This is technically non-conformant, but sanity demands it.
6758       return false;
6759     }
6760
6761     if (shouldDeleteForClassSubobject(FieldRecord, FD,
6762                                       FieldType.getCVRQualifiers()))
6763       return true;
6764   }
6765
6766   return false;
6767 }
6768
6769 /// C++11 [class.ctor] p5:
6770 ///   A defaulted default constructor for a class X is defined as deleted if
6771 /// X is a union and all of its variant members are of const-qualified type.
6772 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
6773   // This is a silly definition, because it gives an empty union a deleted
6774   // default constructor. Don't do that.
6775   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
6776     bool AnyFields = false;
6777     for (auto *F : MD->getParent()->fields())
6778       if ((AnyFields = !F->isUnnamedBitfield()))
6779         break;
6780     if (!AnyFields)
6781       return false;
6782     if (Diagnose)
6783       S.Diag(MD->getParent()->getLocation(),
6784              diag::note_deleted_default_ctor_all_const)
6785         << !!ICI << MD->getParent() << /*not anonymous union*/0;
6786     return true;
6787   }
6788   return false;
6789 }
6790
6791 /// Determine whether a defaulted special member function should be defined as
6792 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6793 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
6794 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6795                                      InheritedConstructorInfo *ICI,
6796                                      bool Diagnose) {
6797   if (MD->isInvalidDecl())
6798     return false;
6799   CXXRecordDecl *RD = MD->getParent();
6800   assert(!RD->isDependentType() && "do deletion after instantiation");
6801   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
6802     return false;
6803
6804   // C++11 [expr.lambda.prim]p19:
6805   //   The closure type associated with a lambda-expression has a
6806   //   deleted (8.4.3) default constructor and a deleted copy
6807   //   assignment operator.
6808   if (RD->isLambda() &&
6809       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6810     if (Diagnose)
6811       Diag(RD->getLocation(), diag::note_lambda_decl);
6812     return true;
6813   }
6814
6815   // For an anonymous struct or union, the copy and assignment special members
6816   // will never be used, so skip the check. For an anonymous union declared at
6817   // namespace scope, the constructor and destructor are used.
6818   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6819       RD->isAnonymousStructOrUnion())
6820     return false;
6821
6822   // C++11 [class.copy]p7, p18:
6823   //   If the class definition declares a move constructor or move assignment
6824   //   operator, an implicitly declared copy constructor or copy assignment
6825   //   operator is defined as deleted.
6826   if (MD->isImplicit() &&
6827       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
6828     CXXMethodDecl *UserDeclaredMove = nullptr;
6829
6830     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
6831     // deletion of the corresponding copy operation, not both copy operations.
6832     // MSVC 2015 has adopted the standards conforming behavior.
6833     bool DeletesOnlyMatchingCopy =
6834         getLangOpts().MSVCCompat &&
6835         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
6836
6837     if (RD->hasUserDeclaredMoveConstructor() &&
6838         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
6839       if (!Diagnose) return true;
6840
6841       // Find any user-declared move constructor.
6842       for (auto *I : RD->ctors()) {
6843         if (I->isMoveConstructor()) {
6844           UserDeclaredMove = I;
6845           break;
6846         }
6847       }
6848       assert(UserDeclaredMove);
6849     } else if (RD->hasUserDeclaredMoveAssignment() &&
6850                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
6851       if (!Diagnose) return true;
6852
6853       // Find any user-declared move assignment operator.
6854       for (auto *I : RD->methods()) {
6855         if (I->isMoveAssignmentOperator()) {
6856           UserDeclaredMove = I;
6857           break;
6858         }
6859       }
6860       assert(UserDeclaredMove);
6861     }
6862
6863     if (UserDeclaredMove) {
6864       Diag(UserDeclaredMove->getLocation(),
6865            diag::note_deleted_copy_user_declared_move)
6866         << (CSM == CXXCopyAssignment) << RD
6867         << UserDeclaredMove->isMoveAssignmentOperator();
6868       return true;
6869     }
6870   }
6871
6872   // Do access control from the special member function
6873   ContextRAII MethodContext(*this, MD);
6874
6875   // C++11 [class.dtor]p5:
6876   // -- for a virtual destructor, lookup of the non-array deallocation function
6877   //    results in an ambiguity or in a function that is deleted or inaccessible
6878   if (CSM == CXXDestructor && MD->isVirtual()) {
6879     FunctionDecl *OperatorDelete = nullptr;
6880     DeclarationName Name =
6881       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6882     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
6883                                  OperatorDelete, /*Diagnose*/false)) {
6884       if (Diagnose)
6885         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
6886       return true;
6887     }
6888   }
6889
6890   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
6891
6892   // Per DR1611, do not consider virtual bases of constructors of abstract
6893   // classes, since we are not going to construct them.
6894   // Per DR1658, do not consider virtual bases of destructors of abstract
6895   // classes either.
6896   // Per DR2180, for assignment operators we only assign (and thus only
6897   // consider) direct bases.
6898   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
6899                                  : SMI.VisitPotentiallyConstructedBases))
6900     return true;
6901
6902   if (SMI.shouldDeleteForAllConstMembers())
6903     return true;
6904
6905   if (getLangOpts().CUDA) {
6906     // We should delete the special member in CUDA mode if target inference
6907     // failed.
6908     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6909                                                    Diagnose);
6910   }
6911
6912   return false;
6913 }
6914
6915 /// Perform lookup for a special member of the specified kind, and determine
6916 /// whether it is trivial. If the triviality can be determined without the
6917 /// lookup, skip it. This is intended for use when determining whether a
6918 /// special member of a containing object is trivial, and thus does not ever
6919 /// perform overload resolution for default constructors.
6920 ///
6921 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6922 /// member that was most likely to be intended to be trivial, if any.
6923 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6924                                      Sema::CXXSpecialMember CSM, unsigned Quals,
6925                                      bool ConstRHS, CXXMethodDecl **Selected) {
6926   if (Selected)
6927     *Selected = nullptr;
6928
6929   switch (CSM) {
6930   case Sema::CXXInvalid:
6931     llvm_unreachable("not a special member");
6932
6933   case Sema::CXXDefaultConstructor:
6934     // C++11 [class.ctor]p5:
6935     //   A default constructor is trivial if:
6936     //    - all the [direct subobjects] have trivial default constructors
6937     //
6938     // Note, no overload resolution is performed in this case.
6939     if (RD->hasTrivialDefaultConstructor())
6940       return true;
6941
6942     if (Selected) {
6943       // If there's a default constructor which could have been trivial, dig it
6944       // out. Otherwise, if there's any user-provided default constructor, point
6945       // to that as an example of why there's not a trivial one.
6946       CXXConstructorDecl *DefCtor = nullptr;
6947       if (RD->needsImplicitDefaultConstructor())
6948         S.DeclareImplicitDefaultConstructor(RD);
6949       for (auto *CI : RD->ctors()) {
6950         if (!CI->isDefaultConstructor())
6951           continue;
6952         DefCtor = CI;
6953         if (!DefCtor->isUserProvided())
6954           break;
6955       }
6956
6957       *Selected = DefCtor;
6958     }
6959
6960     return false;
6961
6962   case Sema::CXXDestructor:
6963     // C++11 [class.dtor]p5:
6964     //   A destructor is trivial if:
6965     //    - all the direct [subobjects] have trivial destructors
6966     if (RD->hasTrivialDestructor())
6967       return true;
6968
6969     if (Selected) {
6970       if (RD->needsImplicitDestructor())
6971         S.DeclareImplicitDestructor(RD);
6972       *Selected = RD->getDestructor();
6973     }
6974
6975     return false;
6976
6977   case Sema::CXXCopyConstructor:
6978     // C++11 [class.copy]p12:
6979     //   A copy constructor is trivial if:
6980     //    - the constructor selected to copy each direct [subobject] is trivial
6981     if (RD->hasTrivialCopyConstructor()) {
6982       if (Quals == Qualifiers::Const)
6983         // We must either select the trivial copy constructor or reach an
6984         // ambiguity; no need to actually perform overload resolution.
6985         return true;
6986     } else if (!Selected) {
6987       return false;
6988     }
6989     // In C++98, we are not supposed to perform overload resolution here, but we
6990     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6991     // cases like B as having a non-trivial copy constructor:
6992     //   struct A { template<typename T> A(T&); };
6993     //   struct B { mutable A a; };
6994     goto NeedOverloadResolution;
6995
6996   case Sema::CXXCopyAssignment:
6997     // C++11 [class.copy]p25:
6998     //   A copy assignment operator is trivial if:
6999     //    - the assignment operator selected to copy each direct [subobject] is
7000     //      trivial
7001     if (RD->hasTrivialCopyAssignment()) {
7002       if (Quals == Qualifiers::Const)
7003         return true;
7004     } else if (!Selected) {
7005       return false;
7006     }
7007     // In C++98, we are not supposed to perform overload resolution here, but we
7008     // treat that as a language defect.
7009     goto NeedOverloadResolution;
7010
7011   case Sema::CXXMoveConstructor:
7012   case Sema::CXXMoveAssignment:
7013   NeedOverloadResolution:
7014     Sema::SpecialMemberOverloadResult SMOR =
7015         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7016
7017     // The standard doesn't describe how to behave if the lookup is ambiguous.
7018     // We treat it as not making the member non-trivial, just like the standard
7019     // mandates for the default constructor. This should rarely matter, because
7020     // the member will also be deleted.
7021     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7022       return true;
7023
7024     if (!SMOR.getMethod()) {
7025       assert(SMOR.getKind() ==
7026              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7027       return false;
7028     }
7029
7030     // We deliberately don't check if we found a deleted special member. We're
7031     // not supposed to!
7032     if (Selected)
7033       *Selected = SMOR.getMethod();
7034     return SMOR.getMethod()->isTrivial();
7035   }
7036
7037   llvm_unreachable("unknown special method kind");
7038 }
7039
7040 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7041   for (auto *CI : RD->ctors())
7042     if (!CI->isImplicit())
7043       return CI;
7044
7045   // Look for constructor templates.
7046   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7047   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7048     if (CXXConstructorDecl *CD =
7049           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7050       return CD;
7051   }
7052
7053   return nullptr;
7054 }
7055
7056 /// The kind of subobject we are checking for triviality. The values of this
7057 /// enumeration are used in diagnostics.
7058 enum TrivialSubobjectKind {
7059   /// The subobject is a base class.
7060   TSK_BaseClass,
7061   /// The subobject is a non-static data member.
7062   TSK_Field,
7063   /// The object is actually the complete object.
7064   TSK_CompleteObject
7065 };
7066
7067 /// Check whether the special member selected for a given type would be trivial.
7068 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7069                                       QualType SubType, bool ConstRHS,
7070                                       Sema::CXXSpecialMember CSM,
7071                                       TrivialSubobjectKind Kind,
7072                                       bool Diagnose) {
7073   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7074   if (!SubRD)
7075     return true;
7076
7077   CXXMethodDecl *Selected;
7078   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7079                                ConstRHS, Diagnose ? &Selected : nullptr))
7080     return true;
7081
7082   if (Diagnose) {
7083     if (ConstRHS)
7084       SubType.addConst();
7085
7086     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7087       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7088         << Kind << SubType.getUnqualifiedType();
7089       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7090         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7091     } else if (!Selected)
7092       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7093         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7094     else if (Selected->isUserProvided()) {
7095       if (Kind == TSK_CompleteObject)
7096         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7097           << Kind << SubType.getUnqualifiedType() << CSM;
7098       else {
7099         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7100           << Kind << SubType.getUnqualifiedType() << CSM;
7101         S.Diag(Selected->getLocation(), diag::note_declared_at);
7102       }
7103     } else {
7104       if (Kind != TSK_CompleteObject)
7105         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7106           << Kind << SubType.getUnqualifiedType() << CSM;
7107
7108       // Explain why the defaulted or deleted special member isn't trivial.
7109       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
7110     }
7111   }
7112
7113   return false;
7114 }
7115
7116 /// Check whether the members of a class type allow a special member to be
7117 /// trivial.
7118 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7119                                      Sema::CXXSpecialMember CSM,
7120                                      bool ConstArg, bool Diagnose) {
7121   for (const auto *FI : RD->fields()) {
7122     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7123       continue;
7124
7125     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7126
7127     // Pretend anonymous struct or union members are members of this class.
7128     if (FI->isAnonymousStructOrUnion()) {
7129       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7130                                     CSM, ConstArg, Diagnose))
7131         return false;
7132       continue;
7133     }
7134
7135     // C++11 [class.ctor]p5:
7136     //   A default constructor is trivial if [...]
7137     //    -- no non-static data member of its class has a
7138     //       brace-or-equal-initializer
7139     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7140       if (Diagnose)
7141         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7142       return false;
7143     }
7144
7145     // Objective C ARC 4.3.5:
7146     //   [...] nontrivally ownership-qualified types are [...] not trivially
7147     //   default constructible, copy constructible, move constructible, copy
7148     //   assignable, move assignable, or destructible [...]
7149     if (FieldType.hasNonTrivialObjCLifetime()) {
7150       if (Diagnose)
7151         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7152           << RD << FieldType.getObjCLifetime();
7153       return false;
7154     }
7155
7156     bool ConstRHS = ConstArg && !FI->isMutable();
7157     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7158                                    CSM, TSK_Field, Diagnose))
7159       return false;
7160   }
7161
7162   return true;
7163 }
7164
7165 /// Diagnose why the specified class does not have a trivial special member of
7166 /// the given kind.
7167 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7168   QualType Ty = Context.getRecordType(RD);
7169
7170   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7171   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7172                             TSK_CompleteObject, /*Diagnose*/true);
7173 }
7174
7175 /// Determine whether a defaulted or deleted special member function is trivial,
7176 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7177 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7178 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7179                                   bool Diagnose) {
7180   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7181
7182   CXXRecordDecl *RD = MD->getParent();
7183
7184   bool ConstArg = false;
7185
7186   // C++11 [class.copy]p12, p25: [DR1593]
7187   //   A [special member] is trivial if [...] its parameter-type-list is
7188   //   equivalent to the parameter-type-list of an implicit declaration [...]
7189   switch (CSM) {
7190   case CXXDefaultConstructor:
7191   case CXXDestructor:
7192     // Trivial default constructors and destructors cannot have parameters.
7193     break;
7194
7195   case CXXCopyConstructor:
7196   case CXXCopyAssignment: {
7197     // Trivial copy operations always have const, non-volatile parameter types.
7198     ConstArg = true;
7199     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7200     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7201     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7202       if (Diagnose)
7203         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7204           << Param0->getSourceRange() << Param0->getType()
7205           << Context.getLValueReferenceType(
7206                Context.getRecordType(RD).withConst());
7207       return false;
7208     }
7209     break;
7210   }
7211
7212   case CXXMoveConstructor:
7213   case CXXMoveAssignment: {
7214     // Trivial move operations always have non-cv-qualified parameters.
7215     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7216     const RValueReferenceType *RT =
7217       Param0->getType()->getAs<RValueReferenceType>();
7218     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7219       if (Diagnose)
7220         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7221           << Param0->getSourceRange() << Param0->getType()
7222           << Context.getRValueReferenceType(Context.getRecordType(RD));
7223       return false;
7224     }
7225     break;
7226   }
7227
7228   case CXXInvalid:
7229     llvm_unreachable("not a special member");
7230   }
7231
7232   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7233     if (Diagnose)
7234       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7235            diag::note_nontrivial_default_arg)
7236         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7237     return false;
7238   }
7239   if (MD->isVariadic()) {
7240     if (Diagnose)
7241       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7242     return false;
7243   }
7244
7245   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7246   //   A copy/move [constructor or assignment operator] is trivial if
7247   //    -- the [member] selected to copy/move each direct base class subobject
7248   //       is trivial
7249   //
7250   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7251   //   A [default constructor or destructor] is trivial if
7252   //    -- all the direct base classes have trivial [default constructors or
7253   //       destructors]
7254   for (const auto &BI : RD->bases())
7255     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7256                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
7257       return false;
7258
7259   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7260   //   A copy/move [constructor or assignment operator] for a class X is
7261   //   trivial if
7262   //    -- for each non-static data member of X that is of class type (or array
7263   //       thereof), the constructor selected to copy/move that member is
7264   //       trivial
7265   //
7266   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7267   //   A [default constructor or destructor] is trivial if
7268   //    -- for all of the non-static data members of its class that are of class
7269   //       type (or array thereof), each such class has a trivial [default
7270   //       constructor or destructor]
7271   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7272     return false;
7273
7274   // C++11 [class.dtor]p5:
7275   //   A destructor is trivial if [...]
7276   //    -- the destructor is not virtual
7277   if (CSM == CXXDestructor && MD->isVirtual()) {
7278     if (Diagnose)
7279       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7280     return false;
7281   }
7282
7283   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7284   //   A [special member] for class X is trivial if [...]
7285   //    -- class X has no virtual functions and no virtual base classes
7286   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7287     if (!Diagnose)
7288       return false;
7289
7290     if (RD->getNumVBases()) {
7291       // Check for virtual bases. We already know that the corresponding
7292       // member in all bases is trivial, so vbases must all be direct.
7293       CXXBaseSpecifier &BS = *RD->vbases_begin();
7294       assert(BS.isVirtual());
7295       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7296       return false;
7297     }
7298
7299     // Must have a virtual method.
7300     for (const auto *MI : RD->methods()) {
7301       if (MI->isVirtual()) {
7302         SourceLocation MLoc = MI->getLocStart();
7303         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7304         return false;
7305       }
7306     }
7307
7308     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7309   }
7310
7311   // Looks like it's trivial!
7312   return true;
7313 }
7314
7315 namespace {
7316 struct FindHiddenVirtualMethod {
7317   Sema *S;
7318   CXXMethodDecl *Method;
7319   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7320   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7321
7322 private:
7323   /// Check whether any most overriden method from MD in Methods
7324   static bool CheckMostOverridenMethods(
7325       const CXXMethodDecl *MD,
7326       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7327     if (MD->size_overridden_methods() == 0)
7328       return Methods.count(MD->getCanonicalDecl());
7329     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7330                                         E = MD->end_overridden_methods();
7331          I != E; ++I)
7332       if (CheckMostOverridenMethods(*I, Methods))
7333         return true;
7334     return false;
7335   }
7336
7337 public:
7338   /// Member lookup function that determines whether a given C++
7339   /// method overloads virtual methods in a base class without overriding any,
7340   /// to be used with CXXRecordDecl::lookupInBases().
7341   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7342     RecordDecl *BaseRecord =
7343         Specifier->getType()->getAs<RecordType>()->getDecl();
7344
7345     DeclarationName Name = Method->getDeclName();
7346     assert(Name.getNameKind() == DeclarationName::Identifier);
7347
7348     bool foundSameNameMethod = false;
7349     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7350     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7351          Path.Decls = Path.Decls.slice(1)) {
7352       NamedDecl *D = Path.Decls.front();
7353       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7354         MD = MD->getCanonicalDecl();
7355         foundSameNameMethod = true;
7356         // Interested only in hidden virtual methods.
7357         if (!MD->isVirtual())
7358           continue;
7359         // If the method we are checking overrides a method from its base
7360         // don't warn about the other overloaded methods. Clang deviates from
7361         // GCC by only diagnosing overloads of inherited virtual functions that
7362         // do not override any other virtual functions in the base. GCC's
7363         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7364         // function from a base class. These cases may be better served by a
7365         // warning (not specific to virtual functions) on call sites when the
7366         // call would select a different function from the base class, were it
7367         // visible.
7368         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7369         if (!S->IsOverload(Method, MD, false))
7370           return true;
7371         // Collect the overload only if its hidden.
7372         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7373           overloadedMethods.push_back(MD);
7374       }
7375     }
7376
7377     if (foundSameNameMethod)
7378       OverloadedMethods.append(overloadedMethods.begin(),
7379                                overloadedMethods.end());
7380     return foundSameNameMethod;
7381   }
7382 };
7383 } // end anonymous namespace
7384
7385 /// \brief Add the most overriden methods from MD to Methods
7386 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7387                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7388   if (MD->size_overridden_methods() == 0)
7389     Methods.insert(MD->getCanonicalDecl());
7390   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7391                                       E = MD->end_overridden_methods();
7392        I != E; ++I)
7393     AddMostOverridenMethods(*I, Methods);
7394 }
7395
7396 /// \brief Check if a method overloads virtual methods in a base class without
7397 /// overriding any.
7398 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7399                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7400   if (!MD->getDeclName().isIdentifier())
7401     return;
7402
7403   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7404                      /*bool RecordPaths=*/false,
7405                      /*bool DetectVirtual=*/false);
7406   FindHiddenVirtualMethod FHVM;
7407   FHVM.Method = MD;
7408   FHVM.S = this;
7409
7410   // Keep the base methods that were overriden or introduced in the subclass
7411   // by 'using' in a set. A base method not in this set is hidden.
7412   CXXRecordDecl *DC = MD->getParent();
7413   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7414   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7415     NamedDecl *ND = *I;
7416     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7417       ND = shad->getTargetDecl();
7418     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7419       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7420   }
7421
7422   if (DC->lookupInBases(FHVM, Paths))
7423     OverloadedMethods = FHVM.OverloadedMethods;
7424 }
7425
7426 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7427                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7428   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7429     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7430     PartialDiagnostic PD = PDiag(
7431          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7432     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7433     Diag(overloadedMD->getLocation(), PD);
7434   }
7435 }
7436
7437 /// \brief Diagnose methods which overload virtual methods in a base class
7438 /// without overriding any.
7439 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7440   if (MD->isInvalidDecl())
7441     return;
7442
7443   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7444     return;
7445
7446   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7447   FindHiddenVirtualMethods(MD, OverloadedMethods);
7448   if (!OverloadedMethods.empty()) {
7449     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7450       << MD << (OverloadedMethods.size() > 1);
7451
7452     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7453   }
7454 }
7455
7456 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7457                                              Decl *TagDecl,
7458                                              SourceLocation LBrac,
7459                                              SourceLocation RBrac,
7460                                              AttributeList *AttrList) {
7461   if (!TagDecl)
7462     return;
7463
7464   AdjustDeclIfTemplate(TagDecl);
7465
7466   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7467     if (l->getKind() != AttributeList::AT_Visibility)
7468       continue;
7469     l->setInvalid();
7470     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7471       l->getName();
7472   }
7473
7474   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7475               // strict aliasing violation!
7476               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7477               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7478
7479   CheckCompletedCXXClass(
7480                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
7481 }
7482
7483 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7484 /// special functions, such as the default constructor, copy
7485 /// constructor, or destructor, to the given C++ class (C++
7486 /// [special]p1).  This routine can only be executed just before the
7487 /// definition of the class is complete.
7488 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7489   if (ClassDecl->needsImplicitDefaultConstructor()) {
7490     ++ASTContext::NumImplicitDefaultConstructors;
7491
7492     if (ClassDecl->hasInheritedConstructor())
7493       DeclareImplicitDefaultConstructor(ClassDecl);
7494   }
7495
7496   if (ClassDecl->needsImplicitCopyConstructor()) {
7497     ++ASTContext::NumImplicitCopyConstructors;
7498
7499     // If the properties or semantics of the copy constructor couldn't be
7500     // determined while the class was being declared, force a declaration
7501     // of it now.
7502     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7503         ClassDecl->hasInheritedConstructor())
7504       DeclareImplicitCopyConstructor(ClassDecl);
7505     // For the MS ABI we need to know whether the copy ctor is deleted. A
7506     // prerequisite for deleting the implicit copy ctor is that the class has a
7507     // move ctor or move assignment that is either user-declared or whose
7508     // semantics are inherited from a subobject. FIXME: We should provide a more
7509     // direct way for CodeGen to ask whether the constructor was deleted.
7510     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7511              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7512               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7513               ClassDecl->hasUserDeclaredMoveAssignment() ||
7514               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7515       DeclareImplicitCopyConstructor(ClassDecl);
7516   }
7517
7518   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7519     ++ASTContext::NumImplicitMoveConstructors;
7520
7521     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7522         ClassDecl->hasInheritedConstructor())
7523       DeclareImplicitMoveConstructor(ClassDecl);
7524   }
7525
7526   if (ClassDecl->needsImplicitCopyAssignment()) {
7527     ++ASTContext::NumImplicitCopyAssignmentOperators;
7528
7529     // If we have a dynamic class, then the copy assignment operator may be
7530     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7531     // it shows up in the right place in the vtable and that we diagnose
7532     // problems with the implicit exception specification.
7533     if (ClassDecl->isDynamicClass() ||
7534         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7535         ClassDecl->hasInheritedAssignment())
7536       DeclareImplicitCopyAssignment(ClassDecl);
7537   }
7538
7539   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7540     ++ASTContext::NumImplicitMoveAssignmentOperators;
7541
7542     // Likewise for the move assignment operator.
7543     if (ClassDecl->isDynamicClass() ||
7544         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7545         ClassDecl->hasInheritedAssignment())
7546       DeclareImplicitMoveAssignment(ClassDecl);
7547   }
7548
7549   if (ClassDecl->needsImplicitDestructor()) {
7550     ++ASTContext::NumImplicitDestructors;
7551
7552     // If we have a dynamic class, then the destructor may be virtual, so we
7553     // have to declare the destructor immediately. This ensures that, e.g., it
7554     // shows up in the right place in the vtable and that we diagnose problems
7555     // with the implicit exception specification.
7556     if (ClassDecl->isDynamicClass() ||
7557         ClassDecl->needsOverloadResolutionForDestructor())
7558       DeclareImplicitDestructor(ClassDecl);
7559   }
7560 }
7561
7562 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7563   if (!D)
7564     return 0;
7565
7566   // The order of template parameters is not important here. All names
7567   // get added to the same scope.
7568   SmallVector<TemplateParameterList *, 4> ParameterLists;
7569
7570   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7571     D = TD->getTemplatedDecl();
7572
7573   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7574     ParameterLists.push_back(PSD->getTemplateParameters());
7575
7576   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7577     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7578       ParameterLists.push_back(DD->getTemplateParameterList(i));
7579
7580     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7581       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7582         ParameterLists.push_back(FTD->getTemplateParameters());
7583     }
7584   }
7585
7586   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7587     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7588       ParameterLists.push_back(TD->getTemplateParameterList(i));
7589
7590     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7591       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7592         ParameterLists.push_back(CTD->getTemplateParameters());
7593     }
7594   }
7595
7596   unsigned Count = 0;
7597   for (TemplateParameterList *Params : ParameterLists) {
7598     if (Params->size() > 0)
7599       // Ignore explicit specializations; they don't contribute to the template
7600       // depth.
7601       ++Count;
7602     for (NamedDecl *Param : *Params) {
7603       if (Param->getDeclName()) {
7604         S->AddDecl(Param);
7605         IdResolver.AddDecl(Param);
7606       }
7607     }
7608   }
7609
7610   return Count;
7611 }
7612
7613 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7614   if (!RecordD) return;
7615   AdjustDeclIfTemplate(RecordD);
7616   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7617   PushDeclContext(S, Record);
7618 }
7619
7620 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7621   if (!RecordD) return;
7622   PopDeclContext();
7623 }
7624
7625 /// This is used to implement the constant expression evaluation part of the
7626 /// attribute enable_if extension. There is nothing in standard C++ which would
7627 /// require reentering parameters.
7628 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7629   if (!Param)
7630     return;
7631
7632   S->AddDecl(Param);
7633   if (Param->getDeclName())
7634     IdResolver.AddDecl(Param);
7635 }
7636
7637 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7638 /// parsing a top-level (non-nested) C++ class, and we are now
7639 /// parsing those parts of the given Method declaration that could
7640 /// not be parsed earlier (C++ [class.mem]p2), such as default
7641 /// arguments. This action should enter the scope of the given
7642 /// Method declaration as if we had just parsed the qualified method
7643 /// name. However, it should not bring the parameters into scope;
7644 /// that will be performed by ActOnDelayedCXXMethodParameter.
7645 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7646 }
7647
7648 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
7649 /// C++ method declaration. We're (re-)introducing the given
7650 /// function parameter into scope for use in parsing later parts of
7651 /// the method declaration. For example, we could see an
7652 /// ActOnParamDefaultArgument event for this parameter.
7653 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7654   if (!ParamD)
7655     return;
7656
7657   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7658
7659   // If this parameter has an unparsed default argument, clear it out
7660   // to make way for the parsed default argument.
7661   if (Param->hasUnparsedDefaultArg())
7662     Param->setDefaultArg(nullptr);
7663
7664   S->AddDecl(Param);
7665   if (Param->getDeclName())
7666     IdResolver.AddDecl(Param);
7667 }
7668
7669 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7670 /// processing the delayed method declaration for Method. The method
7671 /// declaration is now considered finished. There may be a separate
7672 /// ActOnStartOfFunctionDef action later (not necessarily
7673 /// immediately!) for this method, if it was also defined inside the
7674 /// class body.
7675 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7676   if (!MethodD)
7677     return;
7678
7679   AdjustDeclIfTemplate(MethodD);
7680
7681   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
7682
7683   // Now that we have our default arguments, check the constructor
7684   // again. It could produce additional diagnostics or affect whether
7685   // the class has implicitly-declared destructors, among other
7686   // things.
7687   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7688     CheckConstructor(Constructor);
7689
7690   // Check the default arguments, which we may have added.
7691   if (!Method->isInvalidDecl())
7692     CheckCXXDefaultArguments(Method);
7693 }
7694
7695 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
7696 /// the well-formedness of the constructor declarator @p D with type @p
7697 /// R. If there are any errors in the declarator, this routine will
7698 /// emit diagnostics and set the invalid bit to true.  In any case, the type
7699 /// will be updated to reflect a well-formed type for the constructor and
7700 /// returned.
7701 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
7702                                           StorageClass &SC) {
7703   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7704
7705   // C++ [class.ctor]p3:
7706   //   A constructor shall not be virtual (10.3) or static (9.4). A
7707   //   constructor can be invoked for a const, volatile or const
7708   //   volatile object. A constructor shall not be declared const,
7709   //   volatile, or const volatile (9.3.2).
7710   if (isVirtual) {
7711     if (!D.isInvalidType())
7712       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7713         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7714         << SourceRange(D.getIdentifierLoc());
7715     D.setInvalidType();
7716   }
7717   if (SC == SC_Static) {
7718     if (!D.isInvalidType())
7719       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7720         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7721         << SourceRange(D.getIdentifierLoc());
7722     D.setInvalidType();
7723     SC = SC_None;
7724   }
7725
7726   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7727     diagnoseIgnoredQualifiers(
7728         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7729         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7730         D.getDeclSpec().getRestrictSpecLoc(),
7731         D.getDeclSpec().getAtomicSpecLoc());
7732     D.setInvalidType();
7733   }
7734
7735   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7736   if (FTI.TypeQuals != 0) {
7737     if (FTI.TypeQuals & Qualifiers::Const)
7738       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7739         << "const" << SourceRange(D.getIdentifierLoc());
7740     if (FTI.TypeQuals & Qualifiers::Volatile)
7741       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7742         << "volatile" << SourceRange(D.getIdentifierLoc());
7743     if (FTI.TypeQuals & Qualifiers::Restrict)
7744       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7745         << "restrict" << SourceRange(D.getIdentifierLoc());
7746     D.setInvalidType();
7747   }
7748
7749   // C++0x [class.ctor]p4:
7750   //   A constructor shall not be declared with a ref-qualifier.
7751   if (FTI.hasRefQualifier()) {
7752     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7753       << FTI.RefQualifierIsLValueRef 
7754       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7755     D.setInvalidType();
7756   }
7757   
7758   // Rebuild the function type "R" without any type qualifiers (in
7759   // case any of the errors above fired) and with "void" as the
7760   // return type, since constructors don't have return types.
7761   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7762   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
7763     return R;
7764
7765   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7766   EPI.TypeQuals = 0;
7767   EPI.RefQualifier = RQ_None;
7768
7769   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
7770 }
7771
7772 /// CheckConstructor - Checks a fully-formed constructor for
7773 /// well-formedness, issuing any diagnostics required. Returns true if
7774 /// the constructor declarator is invalid.
7775 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
7776   CXXRecordDecl *ClassDecl
7777     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7778   if (!ClassDecl)
7779     return Constructor->setInvalidDecl();
7780
7781   // C++ [class.copy]p3:
7782   //   A declaration of a constructor for a class X is ill-formed if
7783   //   its first parameter is of type (optionally cv-qualified) X and
7784   //   either there are no other parameters or else all other
7785   //   parameters have default arguments.
7786   if (!Constructor->isInvalidDecl() &&
7787       ((Constructor->getNumParams() == 1) ||
7788        (Constructor->getNumParams() > 1 &&
7789         Constructor->getParamDecl(1)->hasDefaultArg())) &&
7790       Constructor->getTemplateSpecializationKind()
7791                                               != TSK_ImplicitInstantiation) {
7792     QualType ParamType = Constructor->getParamDecl(0)->getType();
7793     QualType ClassTy = Context.getTagDeclType(ClassDecl);
7794     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
7795       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
7796       const char *ConstRef 
7797         = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 
7798                                                         : " const &";
7799       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
7800         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
7801
7802       // FIXME: Rather that making the constructor invalid, we should endeavor
7803       // to fix the type.
7804       Constructor->setInvalidDecl();
7805     }
7806   }
7807 }
7808
7809 /// CheckDestructor - Checks a fully-formed destructor definition for
7810 /// well-formedness, issuing any diagnostics required.  Returns true
7811 /// on error.
7812 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
7813   CXXRecordDecl *RD = Destructor->getParent();
7814   
7815   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
7816     SourceLocation Loc;
7817     
7818     if (!Destructor->isImplicit())
7819       Loc = Destructor->getLocation();
7820     else
7821       Loc = RD->getLocation();
7822     
7823     // If we have a virtual destructor, look up the deallocation function
7824     if (FunctionDecl *OperatorDelete =
7825             FindDeallocationFunctionForDestructor(Loc, RD)) {
7826       MarkFunctionReferenced(Loc, OperatorDelete);
7827       Destructor->setOperatorDelete(OperatorDelete);
7828     }
7829   }
7830   
7831   return false;
7832 }
7833
7834 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7835 /// the well-formednes of the destructor declarator @p D with type @p
7836 /// R. If there are any errors in the declarator, this routine will
7837 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
7838 /// will be updated to reflect a well-formed type for the destructor and
7839 /// returned.
7840 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
7841                                          StorageClass& SC) {
7842   // C++ [class.dtor]p1:
7843   //   [...] A typedef-name that names a class is a class-name
7844   //   (7.1.3); however, a typedef-name that names a class shall not
7845   //   be used as the identifier in the declarator for a destructor
7846   //   declaration.
7847   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
7848   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
7849     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7850       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
7851   else if (const TemplateSpecializationType *TST =
7852              DeclaratorType->getAs<TemplateSpecializationType>())
7853     if (TST->isTypeAlias())
7854       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7855         << DeclaratorType << 1;
7856
7857   // C++ [class.dtor]p2:
7858   //   A destructor is used to destroy objects of its class type. A
7859   //   destructor takes no parameters, and no return type can be
7860   //   specified for it (not even void). The address of a destructor
7861   //   shall not be taken. A destructor shall not be static. A
7862   //   destructor can be invoked for a const, volatile or const
7863   //   volatile object. A destructor shall not be declared const,
7864   //   volatile or const volatile (9.3.2).
7865   if (SC == SC_Static) {
7866     if (!D.isInvalidType())
7867       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7868         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7869         << SourceRange(D.getIdentifierLoc())
7870         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7871     
7872     SC = SC_None;
7873   }
7874   if (!D.isInvalidType()) {
7875     // Destructors don't have return types, but the parser will
7876     // happily parse something like:
7877     //
7878     //   class X {
7879     //     float ~X();
7880     //   };
7881     //
7882     // The return type will be eliminated later.
7883     if (D.getDeclSpec().hasTypeSpecifier())
7884       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7885         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7886         << SourceRange(D.getIdentifierLoc());
7887     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7888       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7889                                 SourceLocation(),
7890                                 D.getDeclSpec().getConstSpecLoc(),
7891                                 D.getDeclSpec().getVolatileSpecLoc(),
7892                                 D.getDeclSpec().getRestrictSpecLoc(),
7893                                 D.getDeclSpec().getAtomicSpecLoc());
7894       D.setInvalidType();
7895     }
7896   }
7897
7898   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7899   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
7900     if (FTI.TypeQuals & Qualifiers::Const)
7901       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7902         << "const" << SourceRange(D.getIdentifierLoc());
7903     if (FTI.TypeQuals & Qualifiers::Volatile)
7904       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7905         << "volatile" << SourceRange(D.getIdentifierLoc());
7906     if (FTI.TypeQuals & Qualifiers::Restrict)
7907       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7908         << "restrict" << SourceRange(D.getIdentifierLoc());
7909     D.setInvalidType();
7910   }
7911
7912   // C++0x [class.dtor]p2:
7913   //   A destructor shall not be declared with a ref-qualifier.
7914   if (FTI.hasRefQualifier()) {
7915     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7916       << FTI.RefQualifierIsLValueRef
7917       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7918     D.setInvalidType();
7919   }
7920   
7921   // Make sure we don't have any parameters.
7922   if (FTIHasNonVoidParameters(FTI)) {
7923     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7924
7925     // Delete the parameters.
7926     FTI.freeParams();
7927     D.setInvalidType();
7928   }
7929
7930   // Make sure the destructor isn't variadic.
7931   if (FTI.isVariadic) {
7932     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
7933     D.setInvalidType();
7934   }
7935
7936   // Rebuild the function type "R" without any type qualifiers or
7937   // parameters (in case any of the errors above fired) and with
7938   // "void" as the return type, since destructors don't have return
7939   // types. 
7940   if (!D.isInvalidType())
7941     return R;
7942
7943   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7944   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7945   EPI.Variadic = false;
7946   EPI.TypeQuals = 0;
7947   EPI.RefQualifier = RQ_None;
7948   return Context.getFunctionType(Context.VoidTy, None, EPI);
7949 }
7950
7951 static void extendLeft(SourceRange &R, SourceRange Before) {
7952   if (Before.isInvalid())
7953     return;
7954   R.setBegin(Before.getBegin());
7955   if (R.getEnd().isInvalid())
7956     R.setEnd(Before.getEnd());
7957 }
7958
7959 static void extendRight(SourceRange &R, SourceRange After) {
7960   if (After.isInvalid())
7961     return;
7962   if (R.getBegin().isInvalid())
7963     R.setBegin(After.getBegin());
7964   R.setEnd(After.getEnd());
7965 }
7966
7967 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7968 /// well-formednes of the conversion function declarator @p D with
7969 /// type @p R. If there are any errors in the declarator, this routine
7970 /// will emit diagnostics and return true. Otherwise, it will return
7971 /// false. Either way, the type @p R will be updated to reflect a
7972 /// well-formed type for the conversion operator.
7973 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
7974                                      StorageClass& SC) {
7975   // C++ [class.conv.fct]p1:
7976   //   Neither parameter types nor return type can be specified. The
7977   //   type of a conversion function (8.3.5) is "function taking no
7978   //   parameter returning conversion-type-id."
7979   if (SC == SC_Static) {
7980     if (!D.isInvalidType())
7981       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
7982         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7983         << D.getName().getSourceRange();
7984     D.setInvalidType();
7985     SC = SC_None;
7986   }
7987
7988   TypeSourceInfo *ConvTSI = nullptr;
7989   QualType ConvType =
7990       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
7991
7992   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
7993     // Conversion functions don't have return types, but the parser will
7994     // happily parse something like:
7995     //
7996     //   class X {
7997     //     float operator bool();
7998     //   };
7999     //
8000     // The return type will be changed later anyway.
8001     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8002       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8003       << SourceRange(D.getIdentifierLoc());
8004     D.setInvalidType();
8005   }
8006
8007   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8008
8009   // Make sure we don't have any parameters.
8010   if (Proto->getNumParams() > 0) {
8011     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8012
8013     // Delete the parameters.
8014     D.getFunctionTypeInfo().freeParams();
8015     D.setInvalidType();
8016   } else if (Proto->isVariadic()) {
8017     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8018     D.setInvalidType();
8019   }
8020
8021   // Diagnose "&operator bool()" and other such nonsense.  This
8022   // is actually a gcc extension which we don't support.
8023   if (Proto->getReturnType() != ConvType) {
8024     bool NeedsTypedef = false;
8025     SourceRange Before, After;
8026
8027     // Walk the chunks and extract information on them for our diagnostic.
8028     bool PastFunctionChunk = false;
8029     for (auto &Chunk : D.type_objects()) {
8030       switch (Chunk.Kind) {
8031       case DeclaratorChunk::Function:
8032         if (!PastFunctionChunk) {
8033           if (Chunk.Fun.HasTrailingReturnType) {
8034             TypeSourceInfo *TRT = nullptr;
8035             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8036             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8037           }
8038           PastFunctionChunk = true;
8039           break;
8040         }
8041         // Fall through.
8042       case DeclaratorChunk::Array:
8043         NeedsTypedef = true;
8044         extendRight(After, Chunk.getSourceRange());
8045         break;
8046
8047       case DeclaratorChunk::Pointer:
8048       case DeclaratorChunk::BlockPointer:
8049       case DeclaratorChunk::Reference:
8050       case DeclaratorChunk::MemberPointer:
8051       case DeclaratorChunk::Pipe:
8052         extendLeft(Before, Chunk.getSourceRange());
8053         break;
8054
8055       case DeclaratorChunk::Paren:
8056         extendLeft(Before, Chunk.Loc);
8057         extendRight(After, Chunk.EndLoc);
8058         break;
8059       }
8060     }
8061
8062     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8063                          After.isValid()  ? After.getBegin() :
8064                                             D.getIdentifierLoc();
8065     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8066     DB << Before << After;
8067
8068     if (!NeedsTypedef) {
8069       DB << /*don't need a typedef*/0;
8070
8071       // If we can provide a correct fix-it hint, do so.
8072       if (After.isInvalid() && ConvTSI) {
8073         SourceLocation InsertLoc =
8074             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
8075         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8076            << FixItHint::CreateInsertionFromRange(
8077                   InsertLoc, CharSourceRange::getTokenRange(Before))
8078            << FixItHint::CreateRemoval(Before);
8079       }
8080     } else if (!Proto->getReturnType()->isDependentType()) {
8081       DB << /*typedef*/1 << Proto->getReturnType();
8082     } else if (getLangOpts().CPlusPlus11) {
8083       DB << /*alias template*/2 << Proto->getReturnType();
8084     } else {
8085       DB << /*might not be fixable*/3;
8086     }
8087
8088     // Recover by incorporating the other type chunks into the result type.
8089     // Note, this does *not* change the name of the function. This is compatible
8090     // with the GCC extension:
8091     //   struct S { &operator int(); } s;
8092     //   int &r = s.operator int(); // ok in GCC
8093     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8094     ConvType = Proto->getReturnType();
8095   }
8096
8097   // C++ [class.conv.fct]p4:
8098   //   The conversion-type-id shall not represent a function type nor
8099   //   an array type.
8100   if (ConvType->isArrayType()) {
8101     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8102     ConvType = Context.getPointerType(ConvType);
8103     D.setInvalidType();
8104   } else if (ConvType->isFunctionType()) {
8105     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8106     ConvType = Context.getPointerType(ConvType);
8107     D.setInvalidType();
8108   }
8109
8110   // Rebuild the function type "R" without any parameters (in case any
8111   // of the errors above fired) and with the conversion type as the
8112   // return type.
8113   if (D.isInvalidType())
8114     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8115
8116   // C++0x explicit conversion operators.
8117   if (D.getDeclSpec().isExplicitSpecified())
8118     Diag(D.getDeclSpec().getExplicitSpecLoc(),
8119          getLangOpts().CPlusPlus11 ?
8120            diag::warn_cxx98_compat_explicit_conversion_functions :
8121            diag::ext_explicit_conversion_functions)
8122       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
8123 }
8124
8125 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8126 /// the declaration of the given C++ conversion function. This routine
8127 /// is responsible for recording the conversion function in the C++
8128 /// class, if possible.
8129 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8130   assert(Conversion && "Expected to receive a conversion function declaration");
8131
8132   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8133
8134   // Make sure we aren't redeclaring the conversion function.
8135   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8136
8137   // C++ [class.conv.fct]p1:
8138   //   [...] A conversion function is never used to convert a
8139   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8140   //   same object type (or a reference to it), to a (possibly
8141   //   cv-qualified) base class of that type (or a reference to it),
8142   //   or to (possibly cv-qualified) void.
8143   // FIXME: Suppress this warning if the conversion function ends up being a
8144   // virtual function that overrides a virtual function in a base class.
8145   QualType ClassType
8146     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8147   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8148     ConvType = ConvTypeRef->getPointeeType();
8149   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8150       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8151     /* Suppress diagnostics for instantiations. */;
8152   else if (ConvType->isRecordType()) {
8153     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8154     if (ConvType == ClassType)
8155       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8156         << ClassType;
8157     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8158       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8159         <<  ClassType << ConvType;
8160   } else if (ConvType->isVoidType()) {
8161     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8162       << ClassType << ConvType;
8163   }
8164
8165   if (FunctionTemplateDecl *ConversionTemplate
8166                                 = Conversion->getDescribedFunctionTemplate())
8167     return ConversionTemplate;
8168   
8169   return Conversion;
8170 }
8171
8172 namespace {
8173 /// Utility class to accumulate and print a diagnostic listing the invalid
8174 /// specifier(s) on a declaration.
8175 struct BadSpecifierDiagnoser {
8176   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8177       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8178   ~BadSpecifierDiagnoser() {
8179     Diagnostic << Specifiers;
8180   }
8181
8182   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8183     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8184   }
8185   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8186     return check(SpecLoc,
8187                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8188   }
8189   void check(SourceLocation SpecLoc, const char *Spec) {
8190     if (SpecLoc.isInvalid()) return;
8191     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8192     if (!Specifiers.empty()) Specifiers += " ";
8193     Specifiers += Spec;
8194   }
8195
8196   Sema &S;
8197   Sema::SemaDiagnosticBuilder Diagnostic;
8198   std::string Specifiers;
8199 };
8200 }
8201
8202 /// Check the validity of a declarator that we parsed for a deduction-guide.
8203 /// These aren't actually declarators in the grammar, so we need to check that
8204 /// the user didn't specify any pieces that are not part of the deduction-guide
8205 /// grammar.
8206 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8207                                          StorageClass &SC) {
8208   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8209   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8210   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8211
8212   // C++ [temp.deduct.guide]p3:
8213   //   A deduction-gide shall be declared in the same scope as the
8214   //   corresponding class template.
8215   if (!CurContext->getRedeclContext()->Equals(
8216           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8217     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8218       << GuidedTemplateDecl;
8219     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8220   }
8221
8222   auto &DS = D.getMutableDeclSpec();
8223   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8224   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8225       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8226       DS.isNoreturnSpecified() || DS.isConstexprSpecified() ||
8227       DS.isConceptSpecified()) {
8228     BadSpecifierDiagnoser Diagnoser(
8229         *this, D.getIdentifierLoc(),
8230         diag::err_deduction_guide_invalid_specifier);
8231
8232     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8233     DS.ClearStorageClassSpecs();
8234     SC = SC_None;
8235
8236     // 'explicit' is permitted.
8237     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8238     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8239     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8240     Diagnoser.check(DS.getConceptSpecLoc(), "concept");
8241     DS.ClearConstexprSpec();
8242     DS.ClearConceptSpec();
8243
8244     Diagnoser.check(DS.getConstSpecLoc(), "const");
8245     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8246     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8247     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8248     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8249     DS.ClearTypeQualifiers();
8250
8251     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8252     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8253     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8254     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8255     DS.ClearTypeSpecType();
8256   }
8257
8258   if (D.isInvalidType())
8259     return;
8260
8261   // Check the declarator is simple enough.
8262   bool FoundFunction = false;
8263   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8264     if (Chunk.Kind == DeclaratorChunk::Paren)
8265       continue;
8266     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8267       Diag(D.getDeclSpec().getLocStart(),
8268           diag::err_deduction_guide_with_complex_decl)
8269         << D.getSourceRange();
8270       break;
8271     }
8272     if (!Chunk.Fun.hasTrailingReturnType()) {
8273       Diag(D.getName().getLocStart(),
8274            diag::err_deduction_guide_no_trailing_return_type);
8275       break;
8276     }
8277
8278     // Check that the return type is written as a specialization of
8279     // the template specified as the deduction-guide's name.
8280     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8281     TypeSourceInfo *TSI = nullptr;
8282     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8283     assert(TSI && "deduction guide has valid type but invalid return type?");
8284     bool AcceptableReturnType = false;
8285     bool MightInstantiateToSpecialization = false;
8286     if (auto RetTST =
8287             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8288       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8289       bool TemplateMatches =
8290           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8291       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8292         AcceptableReturnType = true;
8293       else {
8294         // This could still instantiate to the right type, unless we know it
8295         // names the wrong class template.
8296         auto *TD = SpecifiedName.getAsTemplateDecl();
8297         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8298                                              !TemplateMatches);
8299       }
8300     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8301       MightInstantiateToSpecialization = true;
8302     }
8303
8304     if (!AcceptableReturnType) {
8305       Diag(TSI->getTypeLoc().getLocStart(),
8306            diag::err_deduction_guide_bad_trailing_return_type)
8307         << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8308         << TSI->getTypeLoc().getSourceRange();
8309     }
8310
8311     // Keep going to check that we don't have any inner declarator pieces (we
8312     // could still have a function returning a pointer to a function).
8313     FoundFunction = true;
8314   }
8315
8316   if (D.isFunctionDefinition())
8317     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8318 }
8319
8320 //===----------------------------------------------------------------------===//
8321 // Namespace Handling
8322 //===----------------------------------------------------------------------===//
8323
8324 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8325 /// reopened.
8326 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8327                                             SourceLocation Loc,
8328                                             IdentifierInfo *II, bool *IsInline,
8329                                             NamespaceDecl *PrevNS) {
8330   assert(*IsInline != PrevNS->isInline());
8331
8332   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8333   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8334   // inline namespaces, with the intention of bringing names into namespace std.
8335   //
8336   // We support this just well enough to get that case working; this is not
8337   // sufficient to support reopening namespaces as inline in general.
8338   if (*IsInline && II && II->getName().startswith("__atomic") &&
8339       S.getSourceManager().isInSystemHeader(Loc)) {
8340     // Mark all prior declarations of the namespace as inline.
8341     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8342          NS = NS->getPreviousDecl())
8343       NS->setInline(*IsInline);
8344     // Patch up the lookup table for the containing namespace. This isn't really
8345     // correct, but it's good enough for this particular case.
8346     for (auto *I : PrevNS->decls())
8347       if (auto *ND = dyn_cast<NamedDecl>(I))
8348         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8349     return;
8350   }
8351
8352   if (PrevNS->isInline())
8353     // The user probably just forgot the 'inline', so suggest that it
8354     // be added back.
8355     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8356       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8357   else
8358     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8359
8360   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8361   *IsInline = PrevNS->isInline();
8362 }
8363
8364 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8365 /// definition.
8366 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8367                                    SourceLocation InlineLoc,
8368                                    SourceLocation NamespaceLoc,
8369                                    SourceLocation IdentLoc,
8370                                    IdentifierInfo *II,
8371                                    SourceLocation LBrace,
8372                                    AttributeList *AttrList,
8373                                    UsingDirectiveDecl *&UD) {
8374   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8375   // For anonymous namespace, take the location of the left brace.
8376   SourceLocation Loc = II ? IdentLoc : LBrace;
8377   bool IsInline = InlineLoc.isValid();
8378   bool IsInvalid = false;
8379   bool IsStd = false;
8380   bool AddToKnown = false;
8381   Scope *DeclRegionScope = NamespcScope->getParent();
8382
8383   NamespaceDecl *PrevNS = nullptr;
8384   if (II) {
8385     // C++ [namespace.def]p2:
8386     //   The identifier in an original-namespace-definition shall not
8387     //   have been previously defined in the declarative region in
8388     //   which the original-namespace-definition appears. The
8389     //   identifier in an original-namespace-definition is the name of
8390     //   the namespace. Subsequently in that declarative region, it is
8391     //   treated as an original-namespace-name.
8392     //
8393     // Since namespace names are unique in their scope, and we don't
8394     // look through using directives, just look for any ordinary names
8395     // as if by qualified name lookup.
8396     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8397     LookupQualifiedName(R, CurContext->getRedeclContext());
8398     NamedDecl *PrevDecl =
8399         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8400     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8401
8402     if (PrevNS) {
8403       // This is an extended namespace definition.
8404       if (IsInline != PrevNS->isInline())
8405         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8406                                         &IsInline, PrevNS);
8407     } else if (PrevDecl) {
8408       // This is an invalid name redefinition.
8409       Diag(Loc, diag::err_redefinition_different_kind)
8410         << II;
8411       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8412       IsInvalid = true;
8413       // Continue on to push Namespc as current DeclContext and return it.
8414     } else if (II->isStr("std") &&
8415                CurContext->getRedeclContext()->isTranslationUnit()) {
8416       // This is the first "real" definition of the namespace "std", so update
8417       // our cache of the "std" namespace to point at this definition.
8418       PrevNS = getStdNamespace();
8419       IsStd = true;
8420       AddToKnown = !IsInline;
8421     } else {
8422       // We've seen this namespace for the first time.
8423       AddToKnown = !IsInline;
8424     }
8425   } else {
8426     // Anonymous namespaces.
8427     
8428     // Determine whether the parent already has an anonymous namespace.
8429     DeclContext *Parent = CurContext->getRedeclContext();
8430     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8431       PrevNS = TU->getAnonymousNamespace();
8432     } else {
8433       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8434       PrevNS = ND->getAnonymousNamespace();
8435     }
8436
8437     if (PrevNS && IsInline != PrevNS->isInline())
8438       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8439                                       &IsInline, PrevNS);
8440   }
8441   
8442   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8443                                                  StartLoc, Loc, II, PrevNS);
8444   if (IsInvalid)
8445     Namespc->setInvalidDecl();
8446   
8447   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8448   AddPragmaAttributes(DeclRegionScope, Namespc);
8449
8450   // FIXME: Should we be merging attributes?
8451   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8452     PushNamespaceVisibilityAttr(Attr, Loc);
8453
8454   if (IsStd)
8455     StdNamespace = Namespc;
8456   if (AddToKnown)
8457     KnownNamespaces[Namespc] = false;
8458   
8459   if (II) {
8460     PushOnScopeChains(Namespc, DeclRegionScope);
8461   } else {
8462     // Link the anonymous namespace into its parent.
8463     DeclContext *Parent = CurContext->getRedeclContext();
8464     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8465       TU->setAnonymousNamespace(Namespc);
8466     } else {
8467       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8468     }
8469
8470     CurContext->addDecl(Namespc);
8471
8472     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8473     //   behaves as if it were replaced by
8474     //     namespace unique { /* empty body */ }
8475     //     using namespace unique;
8476     //     namespace unique { namespace-body }
8477     //   where all occurrences of 'unique' in a translation unit are
8478     //   replaced by the same identifier and this identifier differs
8479     //   from all other identifiers in the entire program.
8480
8481     // We just create the namespace with an empty name and then add an
8482     // implicit using declaration, just like the standard suggests.
8483     //
8484     // CodeGen enforces the "universally unique" aspect by giving all
8485     // declarations semantically contained within an anonymous
8486     // namespace internal linkage.
8487
8488     if (!PrevNS) {
8489       UD = UsingDirectiveDecl::Create(Context, Parent,
8490                                       /* 'using' */ LBrace,
8491                                       /* 'namespace' */ SourceLocation(),
8492                                       /* qualifier */ NestedNameSpecifierLoc(),
8493                                       /* identifier */ SourceLocation(),
8494                                       Namespc,
8495                                       /* Ancestor */ Parent);
8496       UD->setImplicit();
8497       Parent->addDecl(UD);
8498     }
8499   }
8500
8501   ActOnDocumentableDecl(Namespc);
8502
8503   // Although we could have an invalid decl (i.e. the namespace name is a
8504   // redefinition), push it as current DeclContext and try to continue parsing.
8505   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8506   // for the namespace has the declarations that showed up in that particular
8507   // namespace definition.
8508   PushDeclContext(NamespcScope, Namespc);
8509   return Namespc;
8510 }
8511
8512 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8513 /// is a namespace alias, returns the namespace it points to.
8514 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8515   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8516     return AD->getNamespace();
8517   return dyn_cast_or_null<NamespaceDecl>(D);
8518 }
8519
8520 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8521 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8522 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8523   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8524   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8525   Namespc->setRBraceLoc(RBrace);
8526   PopDeclContext();
8527   if (Namespc->hasAttr<VisibilityAttr>())
8528     PopPragmaVisibility(true, RBrace);
8529 }
8530
8531 CXXRecordDecl *Sema::getStdBadAlloc() const {
8532   return cast_or_null<CXXRecordDecl>(
8533                                   StdBadAlloc.get(Context.getExternalSource()));
8534 }
8535
8536 EnumDecl *Sema::getStdAlignValT() const {
8537   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8538 }
8539
8540 NamespaceDecl *Sema::getStdNamespace() const {
8541   return cast_or_null<NamespaceDecl>(
8542                                  StdNamespace.get(Context.getExternalSource()));
8543 }
8544
8545 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8546   if (!StdExperimentalNamespaceCache) {
8547     if (auto Std = getStdNamespace()) {
8548       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8549                           SourceLocation(), LookupNamespaceName);
8550       if (!LookupQualifiedName(Result, Std) ||
8551           !(StdExperimentalNamespaceCache =
8552                 Result.getAsSingle<NamespaceDecl>()))
8553         Result.suppressDiagnostics();
8554     }
8555   }
8556   return StdExperimentalNamespaceCache;
8557 }
8558
8559 /// \brief Retrieve the special "std" namespace, which may require us to 
8560 /// implicitly define the namespace.
8561 NamespaceDecl *Sema::getOrCreateStdNamespace() {
8562   if (!StdNamespace) {
8563     // The "std" namespace has not yet been defined, so build one implicitly.
8564     StdNamespace = NamespaceDecl::Create(Context, 
8565                                          Context.getTranslationUnitDecl(),
8566                                          /*Inline=*/false,
8567                                          SourceLocation(), SourceLocation(),
8568                                          &PP.getIdentifierTable().get("std"),
8569                                          /*PrevDecl=*/nullptr);
8570     getStdNamespace()->setImplicit(true);
8571   }
8572
8573   return getStdNamespace();
8574 }
8575
8576 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
8577   assert(getLangOpts().CPlusPlus &&
8578          "Looking for std::initializer_list outside of C++.");
8579
8580   // We're looking for implicit instantiations of
8581   // template <typename E> class std::initializer_list.
8582
8583   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8584     return false;
8585
8586   ClassTemplateDecl *Template = nullptr;
8587   const TemplateArgument *Arguments = nullptr;
8588
8589   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8590
8591     ClassTemplateSpecializationDecl *Specialization =
8592         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8593     if (!Specialization)
8594       return false;
8595
8596     Template = Specialization->getSpecializedTemplate();
8597     Arguments = Specialization->getTemplateArgs().data();
8598   } else if (const TemplateSpecializationType *TST =
8599                  Ty->getAs<TemplateSpecializationType>()) {
8600     Template = dyn_cast_or_null<ClassTemplateDecl>(
8601         TST->getTemplateName().getAsTemplateDecl());
8602     Arguments = TST->getArgs();
8603   }
8604   if (!Template)
8605     return false;
8606
8607   if (!StdInitializerList) {
8608     // Haven't recognized std::initializer_list yet, maybe this is it.
8609     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8610     if (TemplateClass->getIdentifier() !=
8611             &PP.getIdentifierTable().get("initializer_list") ||
8612         !getStdNamespace()->InEnclosingNamespaceSetOf(
8613             TemplateClass->getDeclContext()))
8614       return false;
8615     // This is a template called std::initializer_list, but is it the right
8616     // template?
8617     TemplateParameterList *Params = Template->getTemplateParameters();
8618     if (Params->getMinRequiredArguments() != 1)
8619       return false;
8620     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8621       return false;
8622
8623     // It's the right template.
8624     StdInitializerList = Template;
8625   }
8626
8627   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
8628     return false;
8629
8630   // This is an instance of std::initializer_list. Find the argument type.
8631   if (Element)
8632     *Element = Arguments[0].getAsType();
8633   return true;
8634 }
8635
8636 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8637   NamespaceDecl *Std = S.getStdNamespace();
8638   if (!Std) {
8639     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8640     return nullptr;
8641   }
8642
8643   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8644                       Loc, Sema::LookupOrdinaryName);
8645   if (!S.LookupQualifiedName(Result, Std)) {
8646     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8647     return nullptr;
8648   }
8649   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8650   if (!Template) {
8651     Result.suppressDiagnostics();
8652     // We found something weird. Complain about the first thing we found.
8653     NamedDecl *Found = *Result.begin();
8654     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
8655     return nullptr;
8656   }
8657
8658   // We found some template called std::initializer_list. Now verify that it's
8659   // correct.
8660   TemplateParameterList *Params = Template->getTemplateParameters();
8661   if (Params->getMinRequiredArguments() != 1 ||
8662       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
8663     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
8664     return nullptr;
8665   }
8666
8667   return Template;
8668 }
8669
8670 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8671   if (!StdInitializerList) {
8672     StdInitializerList = LookupStdInitializerList(*this, Loc);
8673     if (!StdInitializerList)
8674       return QualType();
8675   }
8676
8677   TemplateArgumentListInfo Args(Loc, Loc);
8678   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8679                                        Context.getTrivialTypeSourceInfo(Element,
8680                                                                         Loc)));
8681   return Context.getCanonicalType(
8682       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8683 }
8684
8685 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
8686   // C++ [dcl.init.list]p2:
8687   //   A constructor is an initializer-list constructor if its first parameter
8688   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
8689   //   std::initializer_list<E> for some type E, and either there are no other
8690   //   parameters or else all other parameters have default arguments.
8691   if (Ctor->getNumParams() < 1 ||
8692       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8693     return false;
8694
8695   QualType ArgType = Ctor->getParamDecl(0)->getType();
8696   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8697     ArgType = RT->getPointeeType().getUnqualifiedType();
8698
8699   return isStdInitializerList(ArgType, nullptr);
8700 }
8701
8702 /// \brief Determine whether a using statement is in a context where it will be
8703 /// apply in all contexts.
8704 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8705   switch (CurContext->getDeclKind()) {
8706     case Decl::TranslationUnit:
8707       return true;
8708     case Decl::LinkageSpec:
8709       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8710     default:
8711       return false;
8712   }
8713 }
8714
8715 namespace {
8716
8717 // Callback to only accept typo corrections that are namespaces.
8718 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
8719 public:
8720   bool ValidateCandidate(const TypoCorrection &candidate) override {
8721     if (NamedDecl *ND = candidate.getCorrectionDecl())
8722       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
8723     return false;
8724   }
8725 };
8726
8727 }
8728
8729 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8730                                        CXXScopeSpec &SS,
8731                                        SourceLocation IdentLoc,
8732                                        IdentifierInfo *Ident) {
8733   R.clear();
8734   if (TypoCorrection Corrected =
8735           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8736                         llvm::make_unique<NamespaceValidatorCCC>(),
8737                         Sema::CTK_ErrorRecovery)) {
8738     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
8739       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8740       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
8741                               Ident->getName().equals(CorrectedStr);
8742       S.diagnoseTypo(Corrected,
8743                      S.PDiag(diag::err_using_directive_member_suggest)
8744                        << Ident << DC << DroppedSpecifier << SS.getRange(),
8745                      S.PDiag(diag::note_namespace_defined_here));
8746     } else {
8747       S.diagnoseTypo(Corrected,
8748                      S.PDiag(diag::err_using_directive_suggest) << Ident,
8749                      S.PDiag(diag::note_namespace_defined_here));
8750     }
8751     R.addDecl(Corrected.getFoundDecl());
8752     return true;
8753   }
8754   return false;
8755 }
8756
8757 Decl *Sema::ActOnUsingDirective(Scope *S,
8758                                           SourceLocation UsingLoc,
8759                                           SourceLocation NamespcLoc,
8760                                           CXXScopeSpec &SS,
8761                                           SourceLocation IdentLoc,
8762                                           IdentifierInfo *NamespcName,
8763                                           AttributeList *AttrList) {
8764   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8765   assert(NamespcName && "Invalid NamespcName.");
8766   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
8767
8768   // This can only happen along a recovery path.
8769   while (S->isTemplateParamScope())
8770     S = S->getParent();
8771   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8772
8773   UsingDirectiveDecl *UDir = nullptr;
8774   NestedNameSpecifier *Qualifier = nullptr;
8775   if (SS.isSet())
8776     Qualifier = SS.getScopeRep();
8777   
8778   // Lookup namespace name.
8779   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8780   LookupParsedName(R, S, &SS);
8781   if (R.isAmbiguous())
8782     return nullptr;
8783
8784   if (R.empty()) {
8785     R.clear();
8786     // Allow "using namespace std;" or "using namespace ::std;" even if 
8787     // "std" hasn't been defined yet, for GCC compatibility.
8788     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8789         NamespcName->isStr("std")) {
8790       Diag(IdentLoc, diag::ext_using_undefined_std);
8791       R.addDecl(getOrCreateStdNamespace());
8792       R.resolveKind();
8793     } 
8794     // Otherwise, attempt typo correction.
8795     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
8796   }
8797   
8798   if (!R.empty()) {
8799     NamedDecl *Named = R.getRepresentativeDecl();
8800     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8801     assert(NS && "expected namespace decl");
8802
8803     // The use of a nested name specifier may trigger deprecation warnings.
8804     DiagnoseUseOfDecl(Named, IdentLoc);
8805
8806     // C++ [namespace.udir]p1:
8807     //   A using-directive specifies that the names in the nominated
8808     //   namespace can be used in the scope in which the
8809     //   using-directive appears after the using-directive. During
8810     //   unqualified name lookup (3.4.1), the names appear as if they
8811     //   were declared in the nearest enclosing namespace which
8812     //   contains both the using-directive and the nominated
8813     //   namespace. [Note: in this context, "contains" means "contains
8814     //   directly or indirectly". ]
8815
8816     // Find enclosing context containing both using-directive and
8817     // nominated namespace.
8818     DeclContext *CommonAncestor = cast<DeclContext>(NS);
8819     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8820       CommonAncestor = CommonAncestor->getParent();
8821
8822     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
8823                                       SS.getWithLocInContext(Context),
8824                                       IdentLoc, Named, CommonAncestor);
8825
8826     if (IsUsingDirectiveInToplevelContext(CurContext) &&
8827         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
8828       Diag(IdentLoc, diag::warn_using_directive_in_header);
8829     }
8830
8831     PushUsingDirective(S, UDir);
8832   } else {
8833     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8834   }
8835
8836   if (UDir)
8837     ProcessDeclAttributeList(S, UDir, AttrList);
8838
8839   return UDir;
8840 }
8841
8842 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
8843   // If the scope has an associated entity and the using directive is at
8844   // namespace or translation unit scope, add the UsingDirectiveDecl into
8845   // its lookup structure so qualified name lookup can find it.
8846   DeclContext *Ctx = S->getEntity();
8847   if (Ctx && !Ctx->isFunctionOrMethod())
8848     Ctx->addDecl(UDir);
8849   else
8850     // Otherwise, it is at block scope. The using-directives will affect lookup
8851     // only to the end of the scope.
8852     S->PushUsingDirective(UDir);
8853 }
8854
8855
8856 Decl *Sema::ActOnUsingDeclaration(Scope *S,
8857                                   AccessSpecifier AS,
8858                                   SourceLocation UsingLoc,
8859                                   SourceLocation TypenameLoc,
8860                                   CXXScopeSpec &SS,
8861                                   UnqualifiedId &Name,
8862                                   SourceLocation EllipsisLoc,
8863                                   AttributeList *AttrList) {
8864   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8865
8866   if (SS.isEmpty()) {
8867     Diag(Name.getLocStart(), diag::err_using_requires_qualname);
8868     return nullptr;
8869   }
8870
8871   switch (Name.getKind()) {
8872   case UnqualifiedId::IK_ImplicitSelfParam:
8873   case UnqualifiedId::IK_Identifier:
8874   case UnqualifiedId::IK_OperatorFunctionId:
8875   case UnqualifiedId::IK_LiteralOperatorId:
8876   case UnqualifiedId::IK_ConversionFunctionId:
8877     break;
8878       
8879   case UnqualifiedId::IK_ConstructorName:
8880   case UnqualifiedId::IK_ConstructorTemplateId:
8881     // C++11 inheriting constructors.
8882     Diag(Name.getLocStart(),
8883          getLangOpts().CPlusPlus11 ?
8884            diag::warn_cxx98_compat_using_decl_constructor :
8885            diag::err_using_decl_constructor)
8886       << SS.getRange();
8887
8888     if (getLangOpts().CPlusPlus11) break;
8889
8890     return nullptr;
8891
8892   case UnqualifiedId::IK_DestructorName:
8893     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
8894       << SS.getRange();
8895     return nullptr;
8896
8897   case UnqualifiedId::IK_TemplateId:
8898     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
8899       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
8900     return nullptr;
8901
8902   case UnqualifiedId::IK_DeductionGuideName:
8903     llvm_unreachable("cannot parse qualified deduction guide name");
8904   }
8905
8906   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8907   DeclarationName TargetName = TargetNameInfo.getName();
8908   if (!TargetName)
8909     return nullptr;
8910
8911   // Warn about access declarations.
8912   if (UsingLoc.isInvalid()) {
8913     Diag(Name.getLocStart(),
8914          getLangOpts().CPlusPlus11 ? diag::err_access_decl
8915                                    : diag::warn_access_decl_deprecated)
8916       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
8917   }
8918
8919   if (EllipsisLoc.isInvalid()) {
8920     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8921         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
8922       return nullptr;
8923   } else {
8924     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
8925         !TargetNameInfo.containsUnexpandedParameterPack()) {
8926       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
8927         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
8928       EllipsisLoc = SourceLocation();
8929     }
8930   }
8931
8932   NamedDecl *UD =
8933       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
8934                             SS, TargetNameInfo, EllipsisLoc, AttrList,
8935                             /*IsInstantiation*/false);
8936   if (UD)
8937     PushOnScopeChains(UD, S, /*AddToContext*/ false);
8938
8939   return UD;
8940 }
8941
8942 /// \brief Determine whether a using declaration considers the given
8943 /// declarations as "equivalent", e.g., if they are redeclarations of
8944 /// the same entity or are both typedefs of the same type.
8945 static bool
8946 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
8947   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
8948     return true;
8949
8950   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
8951     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
8952       return Context.hasSameType(TD1->getUnderlyingType(),
8953                                  TD2->getUnderlyingType());
8954
8955   return false;
8956 }
8957
8958
8959 /// Determines whether to create a using shadow decl for a particular
8960 /// decl, given the set of decls existing prior to this using lookup.
8961 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
8962                                 const LookupResult &Previous,
8963                                 UsingShadowDecl *&PrevShadow) {
8964   // Diagnose finding a decl which is not from a base class of the
8965   // current class.  We do this now because there are cases where this
8966   // function will silently decide not to build a shadow decl, which
8967   // will pre-empt further diagnostics.
8968   //
8969   // We don't need to do this in C++11 because we do the check once on
8970   // the qualifier.
8971   //
8972   // FIXME: diagnose the following if we care enough:
8973   //   struct A { int foo; };
8974   //   struct B : A { using A::foo; };
8975   //   template <class T> struct C : A {};
8976   //   template <class T> struct D : C<T> { using B::foo; } // <---
8977   // This is invalid (during instantiation) in C++03 because B::foo
8978   // resolves to the using decl in B, which is not a base class of D<T>.
8979   // We can't diagnose it immediately because C<T> is an unknown
8980   // specialization.  The UsingShadowDecl in D<T> then points directly
8981   // to A::foo, which will look well-formed when we instantiate.
8982   // The right solution is to not collapse the shadow-decl chain.
8983   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
8984     DeclContext *OrigDC = Orig->getDeclContext();
8985
8986     // Handle enums and anonymous structs.
8987     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
8988     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
8989     while (OrigRec->isAnonymousStructOrUnion())
8990       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
8991
8992     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
8993       if (OrigDC == CurContext) {
8994         Diag(Using->getLocation(),
8995              diag::err_using_decl_nested_name_specifier_is_current_class)
8996           << Using->getQualifierLoc().getSourceRange();
8997         Diag(Orig->getLocation(), diag::note_using_decl_target);
8998         Using->setInvalidDecl();
8999         return true;
9000       }
9001
9002       Diag(Using->getQualifierLoc().getBeginLoc(),
9003            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9004         << Using->getQualifier()
9005         << cast<CXXRecordDecl>(CurContext)
9006         << Using->getQualifierLoc().getSourceRange();
9007       Diag(Orig->getLocation(), diag::note_using_decl_target);
9008       Using->setInvalidDecl();
9009       return true;
9010     }
9011   }
9012
9013   if (Previous.empty()) return false;
9014
9015   NamedDecl *Target = Orig;
9016   if (isa<UsingShadowDecl>(Target))
9017     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9018
9019   // If the target happens to be one of the previous declarations, we
9020   // don't have a conflict.
9021   // 
9022   // FIXME: but we might be increasing its access, in which case we
9023   // should redeclare it.
9024   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9025   bool FoundEquivalentDecl = false;
9026   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9027          I != E; ++I) {
9028     NamedDecl *D = (*I)->getUnderlyingDecl();
9029     // We can have UsingDecls in our Previous results because we use the same
9030     // LookupResult for checking whether the UsingDecl itself is a valid
9031     // redeclaration.
9032     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9033       continue;
9034
9035     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9036       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9037         PrevShadow = Shadow;
9038       FoundEquivalentDecl = true;
9039     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9040       // We don't conflict with an existing using shadow decl of an equivalent
9041       // declaration, but we're not a redeclaration of it.
9042       FoundEquivalentDecl = true;
9043     }
9044
9045     if (isVisible(D))
9046       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9047   }
9048
9049   if (FoundEquivalentDecl)
9050     return false;
9051
9052   if (FunctionDecl *FD = Target->getAsFunction()) {
9053     NamedDecl *OldDecl = nullptr;
9054     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9055                           /*IsForUsingDecl*/ true)) {
9056     case Ovl_Overload:
9057       return false;
9058
9059     case Ovl_NonFunction:
9060       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9061       break;
9062
9063     // We found a decl with the exact signature.
9064     case Ovl_Match:
9065       // If we're in a record, we want to hide the target, so we
9066       // return true (without a diagnostic) to tell the caller not to
9067       // build a shadow decl.
9068       if (CurContext->isRecord())
9069         return true;
9070
9071       // If we're not in a record, this is an error.
9072       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9073       break;
9074     }
9075
9076     Diag(Target->getLocation(), diag::note_using_decl_target);
9077     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9078     Using->setInvalidDecl();
9079     return true;
9080   }
9081
9082   // Target is not a function.
9083
9084   if (isa<TagDecl>(Target)) {
9085     // No conflict between a tag and a non-tag.
9086     if (!Tag) return false;
9087
9088     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9089     Diag(Target->getLocation(), diag::note_using_decl_target);
9090     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9091     Using->setInvalidDecl();
9092     return true;
9093   }
9094
9095   // No conflict between a tag and a non-tag.
9096   if (!NonTag) return false;
9097
9098   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9099   Diag(Target->getLocation(), diag::note_using_decl_target);
9100   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9101   Using->setInvalidDecl();
9102   return true;
9103 }
9104
9105 /// Determine whether a direct base class is a virtual base class.
9106 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9107   if (!Derived->getNumVBases())
9108     return false;
9109   for (auto &B : Derived->bases())
9110     if (B.getType()->getAsCXXRecordDecl() == Base)
9111       return B.isVirtual();
9112   llvm_unreachable("not a direct base class");
9113 }
9114
9115 /// Builds a shadow declaration corresponding to a 'using' declaration.
9116 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9117                                             UsingDecl *UD,
9118                                             NamedDecl *Orig,
9119                                             UsingShadowDecl *PrevDecl) {
9120   // If we resolved to another shadow declaration, just coalesce them.
9121   NamedDecl *Target = Orig;
9122   if (isa<UsingShadowDecl>(Target)) {
9123     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9124     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9125   }
9126
9127   NamedDecl *NonTemplateTarget = Target;
9128   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9129     NonTemplateTarget = TargetTD->getTemplatedDecl();
9130
9131   UsingShadowDecl *Shadow;
9132   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9133     bool IsVirtualBase =
9134         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9135                             UD->getQualifier()->getAsRecordDecl());
9136     Shadow = ConstructorUsingShadowDecl::Create(
9137         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9138   } else {
9139     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9140                                      Target);
9141   }
9142   UD->addShadowDecl(Shadow);
9143
9144   Shadow->setAccess(UD->getAccess());
9145   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9146     Shadow->setInvalidDecl();
9147
9148   Shadow->setPreviousDecl(PrevDecl);
9149
9150   if (S)
9151     PushOnScopeChains(Shadow, S);
9152   else
9153     CurContext->addDecl(Shadow);
9154
9155
9156   return Shadow;
9157 }
9158
9159 /// Hides a using shadow declaration.  This is required by the current
9160 /// using-decl implementation when a resolvable using declaration in a
9161 /// class is followed by a declaration which would hide or override
9162 /// one or more of the using decl's targets; for example:
9163 ///
9164 ///   struct Base { void foo(int); };
9165 ///   struct Derived : Base {
9166 ///     using Base::foo;
9167 ///     void foo(int);
9168 ///   };
9169 ///
9170 /// The governing language is C++03 [namespace.udecl]p12:
9171 ///
9172 ///   When a using-declaration brings names from a base class into a
9173 ///   derived class scope, member functions in the derived class
9174 ///   override and/or hide member functions with the same name and
9175 ///   parameter types in a base class (rather than conflicting).
9176 ///
9177 /// There are two ways to implement this:
9178 ///   (1) optimistically create shadow decls when they're not hidden
9179 ///       by existing declarations, or
9180 ///   (2) don't create any shadow decls (or at least don't make them
9181 ///       visible) until we've fully parsed/instantiated the class.
9182 /// The problem with (1) is that we might have to retroactively remove
9183 /// a shadow decl, which requires several O(n) operations because the
9184 /// decl structures are (very reasonably) not designed for removal.
9185 /// (2) avoids this but is very fiddly and phase-dependent.
9186 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9187   if (Shadow->getDeclName().getNameKind() ==
9188         DeclarationName::CXXConversionFunctionName)
9189     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9190
9191   // Remove it from the DeclContext...
9192   Shadow->getDeclContext()->removeDecl(Shadow);
9193
9194   // ...and the scope, if applicable...
9195   if (S) {
9196     S->RemoveDecl(Shadow);
9197     IdResolver.RemoveDecl(Shadow);
9198   }
9199
9200   // ...and the using decl.
9201   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9202
9203   // TODO: complain somehow if Shadow was used.  It shouldn't
9204   // be possible for this to happen, because...?
9205 }
9206
9207 /// Find the base specifier for a base class with the given type.
9208 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9209                                                 QualType DesiredBase,
9210                                                 bool &AnyDependentBases) {
9211   // Check whether the named type is a direct base class.
9212   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9213   for (auto &Base : Derived->bases()) {
9214     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9215     if (CanonicalDesiredBase == BaseType)
9216       return &Base;
9217     if (BaseType->isDependentType())
9218       AnyDependentBases = true;
9219   }
9220   return nullptr;
9221 }
9222
9223 namespace {
9224 class UsingValidatorCCC : public CorrectionCandidateCallback {
9225 public:
9226   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9227                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9228       : HasTypenameKeyword(HasTypenameKeyword),
9229         IsInstantiation(IsInstantiation), OldNNS(NNS),
9230         RequireMemberOf(RequireMemberOf) {}
9231
9232   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9233     NamedDecl *ND = Candidate.getCorrectionDecl();
9234
9235     // Keywords are not valid here.
9236     if (!ND || isa<NamespaceDecl>(ND))
9237       return false;
9238
9239     // Completely unqualified names are invalid for a 'using' declaration.
9240     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9241       return false;
9242
9243     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9244     // reject.
9245
9246     if (RequireMemberOf) {
9247       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9248       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9249         // No-one ever wants a using-declaration to name an injected-class-name
9250         // of a base class, unless they're declaring an inheriting constructor.
9251         ASTContext &Ctx = ND->getASTContext();
9252         if (!Ctx.getLangOpts().CPlusPlus11)
9253           return false;
9254         QualType FoundType = Ctx.getRecordType(FoundRecord);
9255
9256         // Check that the injected-class-name is named as a member of its own
9257         // type; we don't want to suggest 'using Derived::Base;', since that
9258         // means something else.
9259         NestedNameSpecifier *Specifier =
9260             Candidate.WillReplaceSpecifier()
9261                 ? Candidate.getCorrectionSpecifier()
9262                 : OldNNS;
9263         if (!Specifier->getAsType() ||
9264             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9265           return false;
9266
9267         // Check that this inheriting constructor declaration actually names a
9268         // direct base class of the current class.
9269         bool AnyDependentBases = false;
9270         if (!findDirectBaseWithType(RequireMemberOf,
9271                                     Ctx.getRecordType(FoundRecord),
9272                                     AnyDependentBases) &&
9273             !AnyDependentBases)
9274           return false;
9275       } else {
9276         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9277         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9278           return false;
9279
9280         // FIXME: Check that the base class member is accessible?
9281       }
9282     } else {
9283       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9284       if (FoundRecord && FoundRecord->isInjectedClassName())
9285         return false;
9286     }
9287
9288     if (isa<TypeDecl>(ND))
9289       return HasTypenameKeyword || !IsInstantiation;
9290
9291     return !HasTypenameKeyword;
9292   }
9293
9294 private:
9295   bool HasTypenameKeyword;
9296   bool IsInstantiation;
9297   NestedNameSpecifier *OldNNS;
9298   CXXRecordDecl *RequireMemberOf;
9299 };
9300 } // end anonymous namespace
9301
9302 /// Builds a using declaration.
9303 ///
9304 /// \param IsInstantiation - Whether this call arises from an
9305 ///   instantiation of an unresolved using declaration.  We treat
9306 ///   the lookup differently for these declarations.
9307 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9308                                        SourceLocation UsingLoc,
9309                                        bool HasTypenameKeyword,
9310                                        SourceLocation TypenameLoc,
9311                                        CXXScopeSpec &SS,
9312                                        DeclarationNameInfo NameInfo,
9313                                        SourceLocation EllipsisLoc,
9314                                        AttributeList *AttrList,
9315                                        bool IsInstantiation) {
9316   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9317   SourceLocation IdentLoc = NameInfo.getLoc();
9318   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9319
9320   // FIXME: We ignore attributes for now.
9321
9322   // For an inheriting constructor declaration, the name of the using
9323   // declaration is the name of a constructor in this class, not in the
9324   // base class.
9325   DeclarationNameInfo UsingName = NameInfo;
9326   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9327     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9328       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9329           Context.getCanonicalType(Context.getRecordType(RD))));
9330
9331   // Do the redeclaration lookup in the current scope.
9332   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9333                         ForRedeclaration);
9334   Previous.setHideTags(false);
9335   if (S) {
9336     LookupName(Previous, S);
9337
9338     // It is really dumb that we have to do this.
9339     LookupResult::Filter F = Previous.makeFilter();
9340     while (F.hasNext()) {
9341       NamedDecl *D = F.next();
9342       if (!isDeclInScope(D, CurContext, S))
9343         F.erase();
9344       // If we found a local extern declaration that's not ordinarily visible,
9345       // and this declaration is being added to a non-block scope, ignore it.
9346       // We're only checking for scope conflicts here, not also for violations
9347       // of the linkage rules.
9348       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9349                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9350         F.erase();
9351     }
9352     F.done();
9353   } else {
9354     assert(IsInstantiation && "no scope in non-instantiation");
9355     if (CurContext->isRecord())
9356       LookupQualifiedName(Previous, CurContext);
9357     else {
9358       // No redeclaration check is needed here; in non-member contexts we
9359       // diagnosed all possible conflicts with other using-declarations when
9360       // building the template:
9361       //
9362       // For a dependent non-type using declaration, the only valid case is
9363       // if we instantiate to a single enumerator. We check for conflicts
9364       // between shadow declarations we introduce, and we check in the template
9365       // definition for conflicts between a non-type using declaration and any
9366       // other declaration, which together covers all cases.
9367       //
9368       // A dependent typename using declaration will never successfully
9369       // instantiate, since it will always name a class member, so we reject
9370       // that in the template definition.
9371     }
9372   }
9373
9374   // Check for invalid redeclarations.
9375   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9376                                   SS, IdentLoc, Previous))
9377     return nullptr;
9378
9379   // Check for bad qualifiers.
9380   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9381                               IdentLoc))
9382     return nullptr;
9383
9384   DeclContext *LookupContext = computeDeclContext(SS);
9385   NamedDecl *D;
9386   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9387   if (!LookupContext || EllipsisLoc.isValid()) {
9388     if (HasTypenameKeyword) {
9389       // FIXME: not all declaration name kinds are legal here
9390       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9391                                               UsingLoc, TypenameLoc,
9392                                               QualifierLoc,
9393                                               IdentLoc, NameInfo.getName(),
9394                                               EllipsisLoc);
9395     } else {
9396       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 
9397                                            QualifierLoc, NameInfo, EllipsisLoc);
9398     }
9399     D->setAccess(AS);
9400     CurContext->addDecl(D);
9401     return D;
9402   }
9403
9404   auto Build = [&](bool Invalid) {
9405     UsingDecl *UD =
9406         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9407                           UsingName, HasTypenameKeyword);
9408     UD->setAccess(AS);
9409     CurContext->addDecl(UD);
9410     UD->setInvalidDecl(Invalid);
9411     return UD;
9412   };
9413   auto BuildInvalid = [&]{ return Build(true); };
9414   auto BuildValid = [&]{ return Build(false); };
9415
9416   if (RequireCompleteDeclContext(SS, LookupContext))
9417     return BuildInvalid();
9418
9419   // Look up the target name.
9420   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9421
9422   // Unlike most lookups, we don't always want to hide tag
9423   // declarations: tag names are visible through the using declaration
9424   // even if hidden by ordinary names, *except* in a dependent context
9425   // where it's important for the sanity of two-phase lookup.
9426   if (!IsInstantiation)
9427     R.setHideTags(false);
9428
9429   // For the purposes of this lookup, we have a base object type
9430   // equal to that of the current context.
9431   if (CurContext->isRecord()) {
9432     R.setBaseObjectType(
9433                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9434   }
9435
9436   LookupQualifiedName(R, LookupContext);
9437
9438   // Try to correct typos if possible. If constructor name lookup finds no
9439   // results, that means the named class has no explicit constructors, and we
9440   // suppressed declaring implicit ones (probably because it's dependent or
9441   // invalid).
9442   if (R.empty() &&
9443       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9444     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9445     // it will believe that glibc provides a ::gets in cases where it does not,
9446     // and will try to pull it into namespace std with a using-declaration.
9447     // Just ignore the using-declaration in that case.
9448     auto *II = NameInfo.getName().getAsIdentifierInfo();
9449     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9450         CurContext->isStdNamespace() &&
9451         isa<TranslationUnitDecl>(LookupContext) &&
9452         getSourceManager().isInSystemHeader(UsingLoc))
9453       return nullptr;
9454     if (TypoCorrection Corrected = CorrectTypo(
9455             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9456             llvm::make_unique<UsingValidatorCCC>(
9457                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9458                 dyn_cast<CXXRecordDecl>(CurContext)),
9459             CTK_ErrorRecovery)) {
9460       // We reject candidates where DroppedSpecifier == true, hence the
9461       // literal '0' below.
9462       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9463                                 << NameInfo.getName() << LookupContext << 0
9464                                 << SS.getRange());
9465
9466       // If we picked a correction with no attached Decl we can't do anything
9467       // useful with it, bail out.
9468       NamedDecl *ND = Corrected.getCorrectionDecl();
9469       if (!ND)
9470         return BuildInvalid();
9471
9472       // If we corrected to an inheriting constructor, handle it as one.
9473       auto *RD = dyn_cast<CXXRecordDecl>(ND);
9474       if (RD && RD->isInjectedClassName()) {
9475         // The parent of the injected class name is the class itself.
9476         RD = cast<CXXRecordDecl>(RD->getParent());
9477
9478         // Fix up the information we'll use to build the using declaration.
9479         if (Corrected.WillReplaceSpecifier()) {
9480           NestedNameSpecifierLocBuilder Builder;
9481           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9482                               QualifierLoc.getSourceRange());
9483           QualifierLoc = Builder.getWithLocInContext(Context);
9484         }
9485
9486         // In this case, the name we introduce is the name of a derived class
9487         // constructor.
9488         auto *CurClass = cast<CXXRecordDecl>(CurContext);
9489         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9490             Context.getCanonicalType(Context.getRecordType(CurClass))));
9491         UsingName.setNamedTypeInfo(nullptr);
9492         for (auto *Ctor : LookupConstructors(RD))
9493           R.addDecl(Ctor);
9494         R.resolveKind();
9495       } else {
9496         // FIXME: Pick up all the declarations if we found an overloaded
9497         // function.
9498         UsingName.setName(ND->getDeclName());
9499         R.addDecl(ND);
9500       }
9501     } else {
9502       Diag(IdentLoc, diag::err_no_member)
9503         << NameInfo.getName() << LookupContext << SS.getRange();
9504       return BuildInvalid();
9505     }
9506   }
9507
9508   if (R.isAmbiguous())
9509     return BuildInvalid();
9510
9511   if (HasTypenameKeyword) {
9512     // If we asked for a typename and got a non-type decl, error out.
9513     if (!R.getAsSingle<TypeDecl>()) {
9514       Diag(IdentLoc, diag::err_using_typename_non_type);
9515       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9516         Diag((*I)->getUnderlyingDecl()->getLocation(),
9517              diag::note_using_decl_target);
9518       return BuildInvalid();
9519     }
9520   } else {
9521     // If we asked for a non-typename and we got a type, error out,
9522     // but only if this is an instantiation of an unresolved using
9523     // decl.  Otherwise just silently find the type name.
9524     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
9525       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9526       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
9527       return BuildInvalid();
9528     }
9529   }
9530
9531   // C++14 [namespace.udecl]p6:
9532   // A using-declaration shall not name a namespace.
9533   if (R.getAsSingle<NamespaceDecl>()) {
9534     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9535       << SS.getRange();
9536     return BuildInvalid();
9537   }
9538
9539   // C++14 [namespace.udecl]p7:
9540   // A using-declaration shall not name a scoped enumerator.
9541   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9542     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9543       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9544         << SS.getRange();
9545       return BuildInvalid();
9546     }
9547   }
9548
9549   UsingDecl *UD = BuildValid();
9550
9551   // Some additional rules apply to inheriting constructors.
9552   if (UsingName.getName().getNameKind() ==
9553         DeclarationName::CXXConstructorName) {
9554     // Suppress access diagnostics; the access check is instead performed at the
9555     // point of use for an inheriting constructor.
9556     R.suppressDiagnostics();
9557     if (CheckInheritingConstructorUsingDecl(UD))
9558       return UD;
9559   }
9560
9561   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9562     UsingShadowDecl *PrevDecl = nullptr;
9563     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9564       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
9565   }
9566
9567   return UD;
9568 }
9569
9570 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
9571                                     ArrayRef<NamedDecl *> Expansions) {
9572   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
9573          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
9574          isa<UsingPackDecl>(InstantiatedFrom));
9575
9576   auto *UPD =
9577       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
9578   UPD->setAccess(InstantiatedFrom->getAccess());
9579   CurContext->addDecl(UPD);
9580   return UPD;
9581 }
9582
9583 /// Additional checks for a using declaration referring to a constructor name.
9584 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
9585   assert(!UD->hasTypename() && "expecting a constructor name");
9586
9587   const Type *SourceType = UD->getQualifier()->getAsType();
9588   assert(SourceType &&
9589          "Using decl naming constructor doesn't have type in scope spec.");
9590   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9591
9592   // Check whether the named type is a direct base class.
9593   bool AnyDependentBases = false;
9594   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9595                                       AnyDependentBases);
9596   if (!Base && !AnyDependentBases) {
9597     Diag(UD->getUsingLoc(),
9598          diag::err_using_decl_constructor_not_in_direct_base)
9599       << UD->getNameInfo().getSourceRange()
9600       << QualType(SourceType, 0) << TargetClass;
9601     UD->setInvalidDecl();
9602     return true;
9603   }
9604
9605   if (Base)
9606     Base->setInheritConstructors();
9607
9608   return false;
9609 }
9610
9611 /// Checks that the given using declaration is not an invalid
9612 /// redeclaration.  Note that this is checking only for the using decl
9613 /// itself, not for any ill-formedness among the UsingShadowDecls.
9614 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
9615                                        bool HasTypenameKeyword,
9616                                        const CXXScopeSpec &SS,
9617                                        SourceLocation NameLoc,
9618                                        const LookupResult &Prev) {
9619   NestedNameSpecifier *Qual = SS.getScopeRep();
9620
9621   // C++03 [namespace.udecl]p8:
9622   // C++0x [namespace.udecl]p10:
9623   //   A using-declaration is a declaration and can therefore be used
9624   //   repeatedly where (and only where) multiple declarations are
9625   //   allowed.
9626   //
9627   // That's in non-member contexts.
9628   if (!CurContext->getRedeclContext()->isRecord()) {
9629     // A dependent qualifier outside a class can only ever resolve to an
9630     // enumeration type. Therefore it conflicts with any other non-type
9631     // declaration in the same scope.
9632     // FIXME: How should we check for dependent type-type conflicts at block
9633     // scope?
9634     if (Qual->isDependent() && !HasTypenameKeyword) {
9635       for (auto *D : Prev) {
9636         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
9637           bool OldCouldBeEnumerator =
9638               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
9639           Diag(NameLoc,
9640                OldCouldBeEnumerator ? diag::err_redefinition
9641                                     : diag::err_redefinition_different_kind)
9642               << Prev.getLookupName();
9643           Diag(D->getLocation(), diag::note_previous_definition);
9644           return true;
9645         }
9646       }
9647     }
9648     return false;
9649   }
9650
9651   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9652     NamedDecl *D = *I;
9653
9654     bool DTypename;
9655     NestedNameSpecifier *DQual;
9656     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
9657       DTypename = UD->hasTypename();
9658       DQual = UD->getQualifier();
9659     } else if (UnresolvedUsingValueDecl *UD
9660                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9661       DTypename = false;
9662       DQual = UD->getQualifier();
9663     } else if (UnresolvedUsingTypenameDecl *UD
9664                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9665       DTypename = true;
9666       DQual = UD->getQualifier();
9667     } else continue;
9668
9669     // using decls differ if one says 'typename' and the other doesn't.
9670     // FIXME: non-dependent using decls?
9671     if (HasTypenameKeyword != DTypename) continue;
9672
9673     // using decls differ if they name different scopes (but note that
9674     // template instantiation can cause this check to trigger when it
9675     // didn't before instantiation).
9676     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9677         Context.getCanonicalNestedNameSpecifier(DQual))
9678       continue;
9679
9680     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
9681     Diag(D->getLocation(), diag::note_using_decl) << 1;
9682     return true;
9683   }
9684
9685   return false;
9686 }
9687
9688
9689 /// Checks that the given nested-name qualifier used in a using decl
9690 /// in the current context is appropriately related to the current
9691 /// scope.  If an error is found, diagnoses it and returns true.
9692 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
9693                                    bool HasTypename,
9694                                    const CXXScopeSpec &SS,
9695                                    const DeclarationNameInfo &NameInfo,
9696                                    SourceLocation NameLoc) {
9697   DeclContext *NamedContext = computeDeclContext(SS);
9698
9699   if (!CurContext->isRecord()) {
9700     // C++03 [namespace.udecl]p3:
9701     // C++0x [namespace.udecl]p8:
9702     //   A using-declaration for a class member shall be a member-declaration.
9703
9704     // If we weren't able to compute a valid scope, it might validly be a
9705     // dependent class scope or a dependent enumeration unscoped scope. If
9706     // we have a 'typename' keyword, the scope must resolve to a class type.
9707     if ((HasTypename && !NamedContext) ||
9708         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
9709       auto *RD = NamedContext
9710                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9711                      : nullptr;
9712       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
9713         RD = nullptr;
9714
9715       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9716         << SS.getRange();
9717
9718       // If we have a complete, non-dependent source type, try to suggest a
9719       // way to get the same effect.
9720       if (!RD)
9721         return true;
9722
9723       // Find what this using-declaration was referring to.
9724       LookupResult R(*this, NameInfo, LookupOrdinaryName);
9725       R.setHideTags(false);
9726       R.suppressDiagnostics();
9727       LookupQualifiedName(R, RD);
9728
9729       if (R.getAsSingle<TypeDecl>()) {
9730         if (getLangOpts().CPlusPlus11) {
9731           // Convert 'using X::Y;' to 'using Y = X::Y;'.
9732           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9733             << 0 // alias declaration
9734             << FixItHint::CreateInsertion(SS.getBeginLoc(),
9735                                           NameInfo.getName().getAsString() +
9736                                               " = ");
9737         } else {
9738           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9739           SourceLocation InsertLoc =
9740               getLocForEndOfToken(NameInfo.getLocEnd());
9741           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9742             << 1 // typedef declaration
9743             << FixItHint::CreateReplacement(UsingLoc, "typedef")
9744             << FixItHint::CreateInsertion(
9745                    InsertLoc, " " + NameInfo.getName().getAsString());
9746         }
9747       } else if (R.getAsSingle<VarDecl>()) {
9748         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9749         // repeating the type of the static data member here.
9750         FixItHint FixIt;
9751         if (getLangOpts().CPlusPlus11) {
9752           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9753           FixIt = FixItHint::CreateReplacement(
9754               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9755         }
9756
9757         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9758           << 2 // reference declaration
9759           << FixIt;
9760       } else if (R.getAsSingle<EnumConstantDecl>()) {
9761         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9762         // repeating the type of the enumeration here, and we can't do so if
9763         // the type is anonymous.
9764         FixItHint FixIt;
9765         if (getLangOpts().CPlusPlus11) {
9766           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9767           FixIt = FixItHint::CreateReplacement(
9768               UsingLoc,
9769               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
9770         }
9771
9772         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9773           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9774           << FixIt;
9775       }
9776       return true;
9777     }
9778
9779     // Otherwise, this might be valid.
9780     return false;
9781   }
9782
9783   // The current scope is a record.
9784
9785   // If the named context is dependent, we can't decide much.
9786   if (!NamedContext) {
9787     // FIXME: in C++0x, we can diagnose if we can prove that the
9788     // nested-name-specifier does not refer to a base class, which is
9789     // still possible in some cases.
9790
9791     // Otherwise we have to conservatively report that things might be
9792     // okay.
9793     return false;
9794   }
9795
9796   if (!NamedContext->isRecord()) {
9797     // Ideally this would point at the last name in the specifier,
9798     // but we don't have that level of source info.
9799     Diag(SS.getRange().getBegin(),
9800          diag::err_using_decl_nested_name_specifier_is_not_class)
9801       << SS.getScopeRep() << SS.getRange();
9802     return true;
9803   }
9804
9805   if (!NamedContext->isDependentContext() &&
9806       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9807     return true;
9808
9809   if (getLangOpts().CPlusPlus11) {
9810     // C++11 [namespace.udecl]p3:
9811     //   In a using-declaration used as a member-declaration, the
9812     //   nested-name-specifier shall name a base class of the class
9813     //   being defined.
9814
9815     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9816                                  cast<CXXRecordDecl>(NamedContext))) {
9817       if (CurContext == NamedContext) {
9818         Diag(NameLoc,
9819              diag::err_using_decl_nested_name_specifier_is_current_class)
9820           << SS.getRange();
9821         return true;
9822       }
9823
9824       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
9825         Diag(SS.getRange().getBegin(),
9826              diag::err_using_decl_nested_name_specifier_is_not_base_class)
9827           << SS.getScopeRep()
9828           << cast<CXXRecordDecl>(CurContext)
9829           << SS.getRange();
9830       }
9831       return true;
9832     }
9833
9834     return false;
9835   }
9836
9837   // C++03 [namespace.udecl]p4:
9838   //   A using-declaration used as a member-declaration shall refer
9839   //   to a member of a base class of the class being defined [etc.].
9840
9841   // Salient point: SS doesn't have to name a base class as long as
9842   // lookup only finds members from base classes.  Therefore we can
9843   // diagnose here only if we can prove that that can't happen,
9844   // i.e. if the class hierarchies provably don't intersect.
9845
9846   // TODO: it would be nice if "definitely valid" results were cached
9847   // in the UsingDecl and UsingShadowDecl so that these checks didn't
9848   // need to be repeated.
9849
9850   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9851   auto Collect = [&Bases](const CXXRecordDecl *Base) {
9852     Bases.insert(Base);
9853     return true;
9854   };
9855
9856   // Collect all bases. Return false if we find a dependent base.
9857   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
9858     return false;
9859
9860   // Returns true if the base is dependent or is one of the accumulated base
9861   // classes.
9862   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9863     return !Bases.count(Base);
9864   };
9865
9866   // Return false if the class has a dependent base or if it or one
9867   // of its bases is present in the base set of the current context.
9868   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9869       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
9870     return false;
9871
9872   Diag(SS.getRange().getBegin(),
9873        diag::err_using_decl_nested_name_specifier_is_not_base_class)
9874     << SS.getScopeRep()
9875     << cast<CXXRecordDecl>(CurContext)
9876     << SS.getRange();
9877
9878   return true;
9879 }
9880
9881 Decl *Sema::ActOnAliasDeclaration(Scope *S,
9882                                   AccessSpecifier AS,
9883                                   MultiTemplateParamsArg TemplateParamLists,
9884                                   SourceLocation UsingLoc,
9885                                   UnqualifiedId &Name,
9886                                   AttributeList *AttrList,
9887                                   TypeResult Type,
9888                                   Decl *DeclFromDeclSpec) {
9889   // Skip up to the relevant declaration scope.
9890   while (S->isTemplateParamScope())
9891     S = S->getParent();
9892   assert((S->getFlags() & Scope::DeclScope) &&
9893          "got alias-declaration outside of declaration scope");
9894
9895   if (Type.isInvalid())
9896     return nullptr;
9897
9898   bool Invalid = false;
9899   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
9900   TypeSourceInfo *TInfo = nullptr;
9901   GetTypeFromParser(Type.get(), &TInfo);
9902
9903   if (DiagnoseClassNameShadow(CurContext, NameInfo))
9904     return nullptr;
9905
9906   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
9907                                       UPPC_DeclarationType)) {
9908     Invalid = true;
9909     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 
9910                                              TInfo->getTypeLoc().getBeginLoc());
9911   }
9912
9913   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9914   LookupName(Previous, S);
9915
9916   // Warn about shadowing the name of a template parameter.
9917   if (Previous.isSingleResult() &&
9918       Previous.getFoundDecl()->isTemplateParameter()) {
9919     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
9920     Previous.clear();
9921   }
9922
9923   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9924          "name in alias declaration must be an identifier");
9925   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9926                                                Name.StartLocation,
9927                                                Name.Identifier, TInfo);
9928
9929   NewTD->setAccess(AS);
9930
9931   if (Invalid)
9932     NewTD->setInvalidDecl();
9933
9934   ProcessDeclAttributeList(S, NewTD, AttrList);
9935   AddPragmaAttributes(S, NewTD);
9936
9937   CheckTypedefForVariablyModifiedType(S, NewTD);
9938   Invalid |= NewTD->isInvalidDecl();
9939
9940   bool Redeclaration = false;
9941
9942   NamedDecl *NewND;
9943   if (TemplateParamLists.size()) {
9944     TypeAliasTemplateDecl *OldDecl = nullptr;
9945     TemplateParameterList *OldTemplateParams = nullptr;
9946
9947     if (TemplateParamLists.size() != 1) {
9948       Diag(UsingLoc, diag::err_alias_template_extra_headers)
9949         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
9950          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
9951     }
9952     TemplateParameterList *TemplateParams = TemplateParamLists[0];
9953
9954     // Check that we can declare a template here.
9955     if (CheckTemplateDeclScope(S, TemplateParams))
9956       return nullptr;
9957
9958     // Only consider previous declarations in the same scope.
9959     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
9960                          /*ExplicitInstantiationOrSpecialization*/false);
9961     if (!Previous.empty()) {
9962       Redeclaration = true;
9963
9964       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
9965       if (!OldDecl && !Invalid) {
9966         Diag(UsingLoc, diag::err_redefinition_different_kind)
9967           << Name.Identifier;
9968
9969         NamedDecl *OldD = Previous.getRepresentativeDecl();
9970         if (OldD->getLocation().isValid())
9971           Diag(OldD->getLocation(), diag::note_previous_definition);
9972
9973         Invalid = true;
9974       }
9975
9976       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
9977         if (TemplateParameterListsAreEqual(TemplateParams,
9978                                            OldDecl->getTemplateParameters(),
9979                                            /*Complain=*/true,
9980                                            TPL_TemplateMatch))
9981           OldTemplateParams = OldDecl->getTemplateParameters();
9982         else
9983           Invalid = true;
9984
9985         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
9986         if (!Invalid &&
9987             !Context.hasSameType(OldTD->getUnderlyingType(),
9988                                  NewTD->getUnderlyingType())) {
9989           // FIXME: The C++0x standard does not clearly say this is ill-formed,
9990           // but we can't reasonably accept it.
9991           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
9992             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
9993           if (OldTD->getLocation().isValid())
9994             Diag(OldTD->getLocation(), diag::note_previous_definition);
9995           Invalid = true;
9996         }
9997       }
9998     }
9999
10000     // Merge any previous default template arguments into our parameters,
10001     // and check the parameter list.
10002     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10003                                    TPC_TypeAliasTemplate))
10004       return nullptr;
10005
10006     TypeAliasTemplateDecl *NewDecl =
10007       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10008                                     Name.Identifier, TemplateParams,
10009                                     NewTD);
10010     NewTD->setDescribedAliasTemplate(NewDecl);
10011
10012     NewDecl->setAccess(AS);
10013
10014     if (Invalid)
10015       NewDecl->setInvalidDecl();
10016     else if (OldDecl)
10017       NewDecl->setPreviousDecl(OldDecl);
10018
10019     NewND = NewDecl;
10020   } else {
10021     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10022       setTagNameForLinkagePurposes(TD, NewTD);
10023       handleTagNumbering(TD, S);
10024     }
10025     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10026     NewND = NewTD;
10027   }
10028
10029   PushOnScopeChains(NewND, S);
10030   ActOnDocumentableDecl(NewND);
10031   return NewND;
10032 }
10033
10034 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10035                                    SourceLocation AliasLoc,
10036                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10037                                    SourceLocation IdentLoc,
10038                                    IdentifierInfo *Ident) {
10039
10040   // Lookup the namespace name.
10041   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10042   LookupParsedName(R, S, &SS);
10043
10044   if (R.isAmbiguous())
10045     return nullptr;
10046
10047   if (R.empty()) {
10048     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10049       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10050       return nullptr;
10051     }
10052   }
10053   assert(!R.isAmbiguous() && !R.empty());
10054   NamedDecl *ND = R.getRepresentativeDecl();
10055
10056   // Check if we have a previous declaration with the same name.
10057   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10058                      ForRedeclaration);
10059   LookupName(PrevR, S);
10060
10061   // Check we're not shadowing a template parameter.
10062   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10063     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10064     PrevR.clear();
10065   }
10066
10067   // Filter out any other lookup result from an enclosing scope.
10068   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10069                        /*AllowInlineNamespace*/false);
10070
10071   // Find the previous declaration and check that we can redeclare it.
10072   NamespaceAliasDecl *Prev = nullptr; 
10073   if (PrevR.isSingleResult()) {
10074     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10075     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10076       // We already have an alias with the same name that points to the same
10077       // namespace; check that it matches.
10078       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10079         Prev = AD;
10080       } else if (isVisible(PrevDecl)) {
10081         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10082           << Alias;
10083         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10084           << AD->getNamespace();
10085         return nullptr;
10086       }
10087     } else if (isVisible(PrevDecl)) {
10088       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10089                             ? diag::err_redefinition
10090                             : diag::err_redefinition_different_kind;
10091       Diag(AliasLoc, DiagID) << Alias;
10092       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10093       return nullptr;
10094     }
10095   }
10096
10097   // The use of a nested name specifier may trigger deprecation warnings.
10098   DiagnoseUseOfDecl(ND, IdentLoc);
10099
10100   NamespaceAliasDecl *AliasDecl =
10101     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10102                                Alias, SS.getWithLocInContext(Context),
10103                                IdentLoc, ND);
10104   if (Prev)
10105     AliasDecl->setPreviousDecl(Prev);
10106
10107   PushOnScopeChains(AliasDecl, S);
10108   return AliasDecl;
10109 }
10110
10111 namespace {
10112 struct SpecialMemberExceptionSpecInfo
10113     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10114   SourceLocation Loc;
10115   Sema::ImplicitExceptionSpecification ExceptSpec;
10116
10117   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10118                                  Sema::CXXSpecialMember CSM,
10119                                  Sema::InheritedConstructorInfo *ICI,
10120                                  SourceLocation Loc)
10121       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10122
10123   bool visitBase(CXXBaseSpecifier *Base);
10124   bool visitField(FieldDecl *FD);
10125
10126   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10127                            unsigned Quals);
10128
10129   void visitSubobjectCall(Subobject Subobj,
10130                           Sema::SpecialMemberOverloadResult SMOR);
10131 };
10132 }
10133
10134 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10135   auto *RT = Base->getType()->getAs<RecordType>();
10136   if (!RT)
10137     return false;
10138
10139   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10140   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10141   if (auto *BaseCtor = SMOR.getMethod()) {
10142     visitSubobjectCall(Base, BaseCtor);
10143     return false;
10144   }
10145
10146   visitClassSubobject(BaseClass, Base, 0);
10147   return false;
10148 }
10149
10150 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10151   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10152     Expr *E = FD->getInClassInitializer();
10153     if (!E)
10154       // FIXME: It's a little wasteful to build and throw away a
10155       // CXXDefaultInitExpr here.
10156       // FIXME: We should have a single context note pointing at Loc, and
10157       // this location should be MD->getLocation() instead, since that's
10158       // the location where we actually use the default init expression.
10159       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10160     if (E)
10161       ExceptSpec.CalledExpr(E);
10162   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10163                             ->getAs<RecordType>()) {
10164     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10165                         FD->getType().getCVRQualifiers());
10166   }
10167   return false;
10168 }
10169
10170 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10171                                                          Subobject Subobj,
10172                                                          unsigned Quals) {
10173   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10174   bool IsMutable = Field && Field->isMutable();
10175   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10176 }
10177
10178 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10179     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10180   // Note, if lookup fails, it doesn't matter what exception specification we
10181   // choose because the special member will be deleted.
10182   if (CXXMethodDecl *MD = SMOR.getMethod())
10183     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10184 }
10185
10186 static Sema::ImplicitExceptionSpecification
10187 ComputeDefaultedSpecialMemberExceptionSpec(
10188     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10189     Sema::InheritedConstructorInfo *ICI) {
10190   CXXRecordDecl *ClassDecl = MD->getParent();
10191
10192   // C++ [except.spec]p14:
10193   //   An implicitly declared special member function (Clause 12) shall have an 
10194   //   exception-specification. [...]
10195   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc);
10196   if (ClassDecl->isInvalidDecl())
10197     return Info.ExceptSpec;
10198
10199   // C++1z [except.spec]p7:
10200   //   [Look for exceptions thrown by] a constructor selected [...] to
10201   //   initialize a potentially constructed subobject,
10202   // C++1z [except.spec]p8:
10203   //   The exception specification for an implicitly-declared destructor, or a
10204   //   destructor without a noexcept-specifier, is potentially-throwing if and
10205   //   only if any of the destructors for any of its potentially constructed
10206   //   subojects is potentially throwing.
10207   // FIXME: We respect the first rule but ignore the "potentially constructed"
10208   // in the second rule to resolve a core issue (no number yet) that would have
10209   // us reject:
10210   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10211   //   struct B : A {};
10212   //   struct C : B { void f(); };
10213   // ... due to giving B::~B() a non-throwing exception specification.
10214   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10215                                 : Info.VisitAllBases);
10216
10217   return Info.ExceptSpec;
10218 }
10219
10220 namespace {
10221 /// RAII object to register a special member as being currently declared.
10222 struct DeclaringSpecialMember {
10223   Sema &S;
10224   Sema::SpecialMemberDecl D;
10225   Sema::ContextRAII SavedContext;
10226   bool WasAlreadyBeingDeclared;
10227
10228   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10229       : S(S), D(RD, CSM), SavedContext(S, RD) {
10230     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10231     if (WasAlreadyBeingDeclared)
10232       // This almost never happens, but if it does, ensure that our cache
10233       // doesn't contain a stale result.
10234       S.SpecialMemberCache.clear();
10235     else {
10236       // Register a note to be produced if we encounter an error while
10237       // declaring the special member.
10238       Sema::CodeSynthesisContext Ctx;
10239       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10240       // FIXME: We don't have a location to use here. Using the class's
10241       // location maintains the fiction that we declare all special members
10242       // with the class, but (1) it's not clear that lying about that helps our
10243       // users understand what's going on, and (2) there may be outer contexts
10244       // on the stack (some of which are relevant) and printing them exposes
10245       // our lies.
10246       Ctx.PointOfInstantiation = RD->getLocation();
10247       Ctx.Entity = RD;
10248       Ctx.SpecialMember = CSM;
10249       S.pushCodeSynthesisContext(Ctx);
10250     }
10251   }
10252   ~DeclaringSpecialMember() {
10253     if (!WasAlreadyBeingDeclared) {
10254       S.SpecialMembersBeingDeclared.erase(D);
10255       S.popCodeSynthesisContext();
10256     }
10257   }
10258
10259   /// \brief Are we already trying to declare this special member?
10260   bool isAlreadyBeingDeclared() const {
10261     return WasAlreadyBeingDeclared;
10262   }
10263 };
10264 }
10265
10266 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10267   // Look up any existing declarations, but don't trigger declaration of all
10268   // implicit special members with this name.
10269   DeclarationName Name = FD->getDeclName();
10270   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10271                  ForRedeclaration);
10272   for (auto *D : FD->getParent()->lookup(Name))
10273     if (auto *Acceptable = R.getAcceptableDecl(D))
10274       R.addDecl(Acceptable);
10275   R.resolveKind();
10276   R.suppressDiagnostics();
10277
10278   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10279 }
10280
10281 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10282                                                      CXXRecordDecl *ClassDecl) {
10283   // C++ [class.ctor]p5:
10284   //   A default constructor for a class X is a constructor of class X
10285   //   that can be called without an argument. If there is no
10286   //   user-declared constructor for class X, a default constructor is
10287   //   implicitly declared. An implicitly-declared default constructor
10288   //   is an inline public member of its class.
10289   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10290          "Should not build implicit default constructor!");
10291
10292   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10293   if (DSM.isAlreadyBeingDeclared())
10294     return nullptr;
10295
10296   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10297                                                      CXXDefaultConstructor,
10298                                                      false);
10299
10300   // Create the actual constructor declaration.
10301   CanQualType ClassType
10302     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10303   SourceLocation ClassLoc = ClassDecl->getLocation();
10304   DeclarationName Name
10305     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10306   DeclarationNameInfo NameInfo(Name, ClassLoc);
10307   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10308       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10309       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10310       /*isImplicitlyDeclared=*/true, Constexpr);
10311   DefaultCon->setAccess(AS_public);
10312   DefaultCon->setDefaulted();
10313
10314   if (getLangOpts().CUDA) {
10315     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10316                                             DefaultCon,
10317                                             /* ConstRHS */ false,
10318                                             /* Diagnose */ false);
10319   }
10320
10321   // Build an exception specification pointing back at this constructor.
10322   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10323   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10324
10325   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10326   // constructors is easy to compute.
10327   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10328
10329   // Note that we have declared this constructor.
10330   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10331
10332   Scope *S = getScopeForContext(ClassDecl);
10333   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10334
10335   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10336     SetDeclDeleted(DefaultCon, ClassLoc);
10337
10338   if (S)
10339     PushOnScopeChains(DefaultCon, S, false);
10340   ClassDecl->addDecl(DefaultCon);
10341
10342   return DefaultCon;
10343 }
10344
10345 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10346                                             CXXConstructorDecl *Constructor) {
10347   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10348           !Constructor->doesThisDeclarationHaveABody() &&
10349           !Constructor->isDeleted()) &&
10350     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10351
10352   CXXRecordDecl *ClassDecl = Constructor->getParent();
10353   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10354
10355   SynthesizedFunctionScope Scope(*this, Constructor);
10356   DiagnosticErrorTrap Trap(Diags);
10357   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
10358       Trap.hasErrorOccurred()) {
10359     Diag(CurrentLocation, diag::note_member_synthesized_at) 
10360       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
10361     Constructor->setInvalidDecl();
10362     return;
10363   }
10364
10365   // The exception specification is needed because we are defining the
10366   // function.
10367   ResolveExceptionSpec(CurrentLocation,
10368                        Constructor->getType()->castAs<FunctionProtoType>());
10369
10370   SourceLocation Loc = Constructor->getLocEnd().isValid()
10371                            ? Constructor->getLocEnd()
10372                            : Constructor->getLocation();
10373   Constructor->setBody(new (Context) CompoundStmt(Loc));
10374
10375   Constructor->markUsed(Context);
10376   MarkVTableUsed(CurrentLocation, ClassDecl);
10377
10378   if (ASTMutationListener *L = getASTMutationListener()) {
10379     L->CompletedImplicitDefinition(Constructor);
10380   }
10381
10382   DiagnoseUninitializedFields(*this, Constructor);
10383 }
10384
10385 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10386   // Perform any delayed checks on exception specifications.
10387   CheckDelayedMemberExceptionSpecs();
10388 }
10389
10390 /// Find or create the fake constructor we synthesize to model constructing an
10391 /// object of a derived class via a constructor of a base class.
10392 CXXConstructorDecl *
10393 Sema::findInheritingConstructor(SourceLocation Loc,
10394                                 CXXConstructorDecl *BaseCtor,
10395                                 ConstructorUsingShadowDecl *Shadow) {
10396   CXXRecordDecl *Derived = Shadow->getParent();
10397   SourceLocation UsingLoc = Shadow->getLocation();
10398
10399   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10400   // For now we use the name of the base class constructor as a member of the
10401   // derived class to indicate a (fake) inherited constructor name.
10402   DeclarationName Name = BaseCtor->getDeclName();
10403
10404   // Check to see if we already have a fake constructor for this inherited
10405   // constructor call.
10406   for (NamedDecl *Ctor : Derived->lookup(Name))
10407     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10408                                ->getInheritedConstructor()
10409                                .getConstructor(),
10410                            BaseCtor))
10411       return cast<CXXConstructorDecl>(Ctor);
10412
10413   DeclarationNameInfo NameInfo(Name, UsingLoc);
10414   TypeSourceInfo *TInfo =
10415       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10416   FunctionProtoTypeLoc ProtoLoc =
10417       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10418
10419   // Check the inherited constructor is valid and find the list of base classes
10420   // from which it was inherited.
10421   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10422
10423   bool Constexpr =
10424       BaseCtor->isConstexpr() &&
10425       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10426                                         false, BaseCtor, &ICI);
10427
10428   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10429       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10430       BaseCtor->isExplicit(), /*Inline=*/true,
10431       /*ImplicitlyDeclared=*/true, Constexpr,
10432       InheritedConstructor(Shadow, BaseCtor));
10433   if (Shadow->isInvalidDecl())
10434     DerivedCtor->setInvalidDecl();
10435
10436   // Build an unevaluated exception specification for this fake constructor.
10437   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10438   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10439   EPI.ExceptionSpec.Type = EST_Unevaluated;
10440   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10441   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10442                                                FPT->getParamTypes(), EPI));
10443
10444   // Build the parameter declarations.
10445   SmallVector<ParmVarDecl *, 16> ParamDecls;
10446   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10447     TypeSourceInfo *TInfo =
10448         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10449     ParmVarDecl *PD = ParmVarDecl::Create(
10450         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10451         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10452     PD->setScopeInfo(0, I);
10453     PD->setImplicit();
10454     // Ensure attributes are propagated onto parameters (this matters for
10455     // format, pass_object_size, ...).
10456     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10457     ParamDecls.push_back(PD);
10458     ProtoLoc.setParam(I, PD);
10459   }
10460
10461   // Set up the new constructor.
10462   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10463   DerivedCtor->setAccess(BaseCtor->getAccess());
10464   DerivedCtor->setParams(ParamDecls);
10465   Derived->addDecl(DerivedCtor);
10466
10467   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10468     SetDeclDeleted(DerivedCtor, UsingLoc);
10469
10470   return DerivedCtor;
10471 }
10472
10473 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10474   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10475                                Ctor->getInheritedConstructor().getShadowDecl());
10476   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10477                             /*Diagnose*/true);
10478 }
10479
10480 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10481                                        CXXConstructorDecl *Constructor) {
10482   CXXRecordDecl *ClassDecl = Constructor->getParent();
10483   assert(Constructor->getInheritedConstructor() &&
10484          !Constructor->doesThisDeclarationHaveABody() &&
10485          !Constructor->isDeleted());
10486   if (Constructor->isInvalidDecl())
10487     return;
10488
10489   ConstructorUsingShadowDecl *Shadow =
10490       Constructor->getInheritedConstructor().getShadowDecl();
10491   CXXConstructorDecl *InheritedCtor =
10492       Constructor->getInheritedConstructor().getConstructor();
10493
10494   // [class.inhctor.init]p1:
10495   //   initialization proceeds as if a defaulted default constructor is used to
10496   //   initialize the D object and each base class subobject from which the
10497   //   constructor was inherited
10498
10499   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10500   CXXRecordDecl *RD = Shadow->getParent();
10501   SourceLocation InitLoc = Shadow->getLocation();
10502
10503   // Initializations are performed "as if by a defaulted default constructor",
10504   // so enter the appropriate scope.
10505   SynthesizedFunctionScope Scope(*this, Constructor);
10506   DiagnosticErrorTrap Trap(Diags);
10507
10508   // Build explicit initializers for all base classes from which the
10509   // constructor was inherited.
10510   SmallVector<CXXCtorInitializer*, 8> Inits;
10511   for (bool VBase : {false, true}) {
10512     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10513       if (B.isVirtual() != VBase)
10514         continue;
10515
10516       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10517       if (!BaseRD)
10518         continue;
10519
10520       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10521       if (!BaseCtor.first)
10522         continue;
10523
10524       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10525       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10526           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10527
10528       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10529       Inits.push_back(new (Context) CXXCtorInitializer(
10530           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10531           SourceLocation()));
10532     }
10533   }
10534
10535   // We now proceed as if for a defaulted default constructor, with the relevant
10536   // initializers replaced.
10537
10538   bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
10539   if (HadError || Trap.hasErrorOccurred()) {
10540     Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
10541     Constructor->setInvalidDecl();
10542     return;
10543   }
10544
10545   // The exception specification is needed because we are defining the
10546   // function.
10547   ResolveExceptionSpec(CurrentLocation,
10548                        Constructor->getType()->castAs<FunctionProtoType>());
10549
10550   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
10551
10552   Constructor->markUsed(Context);
10553   MarkVTableUsed(CurrentLocation, ClassDecl);
10554
10555   if (ASTMutationListener *L = getASTMutationListener()) {
10556     L->CompletedImplicitDefinition(Constructor);
10557   }
10558
10559   DiagnoseUninitializedFields(*this, Constructor);
10560 }
10561
10562 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10563   // C++ [class.dtor]p2:
10564   //   If a class has no user-declared destructor, a destructor is
10565   //   declared implicitly. An implicitly-declared destructor is an
10566   //   inline public member of its class.
10567   assert(ClassDecl->needsImplicitDestructor());
10568
10569   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10570   if (DSM.isAlreadyBeingDeclared())
10571     return nullptr;
10572
10573   // Create the actual destructor declaration.
10574   CanQualType ClassType
10575     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10576   SourceLocation ClassLoc = ClassDecl->getLocation();
10577   DeclarationName Name
10578     = Context.DeclarationNames.getCXXDestructorName(ClassType);
10579   DeclarationNameInfo NameInfo(Name, ClassLoc);
10580   CXXDestructorDecl *Destructor
10581       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
10582                                   QualType(), nullptr, /*isInline=*/true,
10583                                   /*isImplicitlyDeclared=*/true);
10584   Destructor->setAccess(AS_public);
10585   Destructor->setDefaulted();
10586
10587   if (getLangOpts().CUDA) {
10588     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10589                                             Destructor,
10590                                             /* ConstRHS */ false,
10591                                             /* Diagnose */ false);
10592   }
10593
10594   // Build an exception specification pointing back at this destructor.
10595   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
10596   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10597
10598   // We don't need to use SpecialMemberIsTrivial here; triviality for
10599   // destructors is easy to compute.
10600   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10601
10602   // Note that we have declared this destructor.
10603   ++ASTContext::NumImplicitDestructorsDeclared;
10604
10605   Scope *S = getScopeForContext(ClassDecl);
10606   CheckImplicitSpecialMemberDeclaration(S, Destructor);
10607
10608   // We can't check whether an implicit destructor is deleted before we complete
10609   // the definition of the class, because its validity depends on the alignment
10610   // of the class. We'll check this from ActOnFields once the class is complete.
10611   if (ClassDecl->isCompleteDefinition() &&
10612       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
10613     SetDeclDeleted(Destructor, ClassLoc);
10614
10615   // Introduce this destructor into its scope.
10616   if (S)
10617     PushOnScopeChains(Destructor, S, false);
10618   ClassDecl->addDecl(Destructor);
10619
10620   return Destructor;
10621 }
10622
10623 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
10624                                     CXXDestructorDecl *Destructor) {
10625   assert((Destructor->isDefaulted() &&
10626           !Destructor->doesThisDeclarationHaveABody() &&
10627           !Destructor->isDeleted()) &&
10628          "DefineImplicitDestructor - call it for implicit default dtor");
10629   CXXRecordDecl *ClassDecl = Destructor->getParent();
10630   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
10631
10632   if (Destructor->isInvalidDecl())
10633     return;
10634
10635   SynthesizedFunctionScope Scope(*this, Destructor);
10636
10637   DiagnosticErrorTrap Trap(Diags);
10638   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10639                                          Destructor->getParent());
10640
10641   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
10642     Diag(CurrentLocation, diag::note_member_synthesized_at) 
10643       << CXXDestructor << Context.getTagDeclType(ClassDecl);
10644
10645     Destructor->setInvalidDecl();
10646     return;
10647   }
10648
10649   // The exception specification is needed because we are defining the
10650   // function.
10651   ResolveExceptionSpec(CurrentLocation,
10652                        Destructor->getType()->castAs<FunctionProtoType>());
10653
10654   SourceLocation Loc = Destructor->getLocEnd().isValid()
10655                            ? Destructor->getLocEnd()
10656                            : Destructor->getLocation();
10657   Destructor->setBody(new (Context) CompoundStmt(Loc));
10658   Destructor->markUsed(Context);
10659   MarkVTableUsed(CurrentLocation, ClassDecl);
10660
10661   if (ASTMutationListener *L = getASTMutationListener()) {
10662     L->CompletedImplicitDefinition(Destructor);
10663   }
10664 }
10665
10666 /// \brief Perform any semantic analysis which needs to be delayed until all
10667 /// pending class member declarations have been parsed.
10668 void Sema::ActOnFinishCXXMemberDecls() {
10669   // If the context is an invalid C++ class, just suppress these checks.
10670   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10671     if (Record->isInvalidDecl()) {
10672       DelayedDefaultedMemberExceptionSpecs.clear();
10673       DelayedExceptionSpecChecks.clear();
10674       return;
10675     }
10676     checkForMultipleExportedDefaultConstructors(*this, Record);
10677   }
10678 }
10679
10680 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
10681   referenceDLLExportedClassMethods();
10682 }
10683
10684 void Sema::referenceDLLExportedClassMethods() {
10685   if (!DelayedDllExportClasses.empty()) {
10686     // Calling ReferenceDllExportedMethods might cause the current function to
10687     // be called again, so use a local copy of DelayedDllExportClasses.
10688     SmallVector<CXXRecordDecl *, 4> WorkList;
10689     std::swap(DelayedDllExportClasses, WorkList);
10690     for (CXXRecordDecl *Class : WorkList)
10691       ReferenceDllExportedMethods(*this, Class);
10692   }
10693 }
10694
10695 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10696                                          CXXDestructorDecl *Destructor) {
10697   assert(getLangOpts().CPlusPlus11 &&
10698          "adjusting dtor exception specs was introduced in c++11");
10699
10700   // C++11 [class.dtor]p3:
10701   //   A declaration of a destructor that does not have an exception-
10702   //   specification is implicitly considered to have the same exception-
10703   //   specification as an implicit declaration.
10704   const FunctionProtoType *DtorType = Destructor->getType()->
10705                                         getAs<FunctionProtoType>();
10706   if (DtorType->hasExceptionSpec())
10707     return;
10708
10709   // Replace the destructor's type, building off the existing one. Fortunately,
10710   // the only thing of interest in the destructor type is its extended info.
10711   // The return and arguments are fixed.
10712   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
10713   EPI.ExceptionSpec.Type = EST_Unevaluated;
10714   EPI.ExceptionSpec.SourceDecl = Destructor;
10715   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10716
10717   // FIXME: If the destructor has a body that could throw, and the newly created
10718   // spec doesn't allow exceptions, we should emit a warning, because this
10719   // change in behavior can break conforming C++03 programs at runtime.
10720   // However, we don't have a body or an exception specification yet, so it
10721   // needs to be done somewhere else.
10722 }
10723
10724 namespace {
10725 /// \brief An abstract base class for all helper classes used in building the
10726 //  copy/move operators. These classes serve as factory functions and help us
10727 //  avoid using the same Expr* in the AST twice.
10728 class ExprBuilder {
10729   ExprBuilder(const ExprBuilder&) = delete;
10730   ExprBuilder &operator=(const ExprBuilder&) = delete;
10731
10732 protected:
10733   static Expr *assertNotNull(Expr *E) {
10734     assert(E && "Expression construction must not fail.");
10735     return E;
10736   }
10737
10738 public:
10739   ExprBuilder() {}
10740   virtual ~ExprBuilder() {}
10741
10742   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10743 };
10744
10745 class RefBuilder: public ExprBuilder {
10746   VarDecl *Var;
10747   QualType VarType;
10748
10749 public:
10750   Expr *build(Sema &S, SourceLocation Loc) const override {
10751     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
10752   }
10753
10754   RefBuilder(VarDecl *Var, QualType VarType)
10755       : Var(Var), VarType(VarType) {}
10756 };
10757
10758 class ThisBuilder: public ExprBuilder {
10759 public:
10760   Expr *build(Sema &S, SourceLocation Loc) const override {
10761     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
10762   }
10763 };
10764
10765 class CastBuilder: public ExprBuilder {
10766   const ExprBuilder &Builder;
10767   QualType Type;
10768   ExprValueKind Kind;
10769   const CXXCastPath &Path;
10770
10771 public:
10772   Expr *build(Sema &S, SourceLocation Loc) const override {
10773     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10774                                              CK_UncheckedDerivedToBase, Kind,
10775                                              &Path).get());
10776   }
10777
10778   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10779               const CXXCastPath &Path)
10780       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10781 };
10782
10783 class DerefBuilder: public ExprBuilder {
10784   const ExprBuilder &Builder;
10785
10786 public:
10787   Expr *build(Sema &S, SourceLocation Loc) const override {
10788     return assertNotNull(
10789         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
10790   }
10791
10792   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10793 };
10794
10795 class MemberBuilder: public ExprBuilder {
10796   const ExprBuilder &Builder;
10797   QualType Type;
10798   CXXScopeSpec SS;
10799   bool IsArrow;
10800   LookupResult &MemberLookup;
10801
10802 public:
10803   Expr *build(Sema &S, SourceLocation Loc) const override {
10804     return assertNotNull(S.BuildMemberReferenceExpr(
10805         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
10806         nullptr, MemberLookup, nullptr, nullptr).get());
10807   }
10808
10809   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10810                 LookupResult &MemberLookup)
10811       : Builder(Builder), Type(Type), IsArrow(IsArrow),
10812         MemberLookup(MemberLookup) {}
10813 };
10814
10815 class MoveCastBuilder: public ExprBuilder {
10816   const ExprBuilder &Builder;
10817
10818 public:
10819   Expr *build(Sema &S, SourceLocation Loc) const override {
10820     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10821   }
10822
10823   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10824 };
10825
10826 class LvalueConvBuilder: public ExprBuilder {
10827   const ExprBuilder &Builder;
10828
10829 public:
10830   Expr *build(Sema &S, SourceLocation Loc) const override {
10831     return assertNotNull(
10832         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
10833   }
10834
10835   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10836 };
10837
10838 class SubscriptBuilder: public ExprBuilder {
10839   const ExprBuilder &Base;
10840   const ExprBuilder &Index;
10841
10842 public:
10843   Expr *build(Sema &S, SourceLocation Loc) const override {
10844     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
10845         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
10846   }
10847
10848   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10849       : Base(Base), Index(Index) {}
10850 };
10851
10852 } // end anonymous namespace
10853
10854 /// When generating a defaulted copy or move assignment operator, if a field
10855 /// should be copied with __builtin_memcpy rather than via explicit assignments,
10856 /// do so. This optimization only applies for arrays of scalars, and for arrays
10857 /// of class type where the selected copy/move-assignment operator is trivial.
10858 static StmtResult
10859 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
10860                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
10861   // Compute the size of the memory buffer to be copied.
10862   QualType SizeType = S.Context.getSizeType();
10863   llvm::APInt Size(S.Context.getTypeSize(SizeType),
10864                    S.Context.getTypeSizeInChars(T).getQuantity());
10865
10866   // Take the address of the field references for "from" and "to". We
10867   // directly construct UnaryOperators here because semantic analysis
10868   // does not permit us to take the address of an xvalue.
10869   Expr *From = FromB.build(S, Loc);
10870   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10871                          S.Context.getPointerType(From->getType()),
10872                          VK_RValue, OK_Ordinary, Loc);
10873   Expr *To = ToB.build(S, Loc);
10874   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10875                        S.Context.getPointerType(To->getType()),
10876                        VK_RValue, OK_Ordinary, Loc);
10877
10878   const Type *E = T->getBaseElementTypeUnsafe();
10879   bool NeedsCollectableMemCpy =
10880     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10881
10882   // Create a reference to the __builtin_objc_memmove_collectable function
10883   StringRef MemCpyName = NeedsCollectableMemCpy ?
10884     "__builtin_objc_memmove_collectable" :
10885     "__builtin_memcpy";
10886   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10887                  Sema::LookupOrdinaryName);
10888   S.LookupName(R, S.TUScope, true);
10889
10890   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10891   if (!MemCpy)
10892     // Something went horribly wrong earlier, and we will have complained
10893     // about it.
10894     return StmtError();
10895
10896   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
10897                                             VK_RValue, Loc, nullptr);
10898   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10899
10900   Expr *CallArgs[] = {
10901     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10902   };
10903   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
10904                                     Loc, CallArgs, Loc);
10905
10906   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
10907   return Call.getAs<Stmt>();
10908 }
10909
10910 /// \brief Builds a statement that copies/moves the given entity from \p From to
10911 /// \c To.
10912 ///
10913 /// This routine is used to copy/move the members of a class with an
10914 /// implicitly-declared copy/move assignment operator. When the entities being
10915 /// copied are arrays, this routine builds for loops to copy them.
10916 ///
10917 /// \param S The Sema object used for type-checking.
10918 ///
10919 /// \param Loc The location where the implicit copy/move is being generated.
10920 ///
10921 /// \param T The type of the expressions being copied/moved. Both expressions
10922 /// must have this type.
10923 ///
10924 /// \param To The expression we are copying/moving to.
10925 ///
10926 /// \param From The expression we are copying/moving from.
10927 ///
10928 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
10929 /// Otherwise, it's a non-static member subobject.
10930 ///
10931 /// \param Copying Whether we're copying or moving.
10932 ///
10933 /// \param Depth Internal parameter recording the depth of the recursion.
10934 ///
10935 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
10936 /// if a memcpy should be used instead.
10937 static StmtResult
10938 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
10939                                  const ExprBuilder &To, const ExprBuilder &From,
10940                                  bool CopyingBaseSubobject, bool Copying,
10941                                  unsigned Depth = 0) {
10942   // C++11 [class.copy]p28:
10943   //   Each subobject is assigned in the manner appropriate to its type:
10944   //
10945   //     - if the subobject is of class type, as if by a call to operator= with
10946   //       the subobject as the object expression and the corresponding
10947   //       subobject of x as a single function argument (as if by explicit
10948   //       qualification; that is, ignoring any possible virtual overriding
10949   //       functions in more derived classes);
10950   //
10951   // C++03 [class.copy]p13:
10952   //     - if the subobject is of class type, the copy assignment operator for
10953   //       the class is used (as if by explicit qualification; that is,
10954   //       ignoring any possible virtual overriding functions in more derived
10955   //       classes);
10956   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
10957     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
10958
10959     // Look for operator=.
10960     DeclarationName Name
10961       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10962     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
10963     S.LookupQualifiedName(OpLookup, ClassDecl, false);
10964
10965     // Prior to C++11, filter out any result that isn't a copy/move-assignment
10966     // operator.
10967     if (!S.getLangOpts().CPlusPlus11) {
10968       LookupResult::Filter F = OpLookup.makeFilter();
10969       while (F.hasNext()) {
10970         NamedDecl *D = F.next();
10971         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
10972           if (Method->isCopyAssignmentOperator() ||
10973               (!Copying && Method->isMoveAssignmentOperator()))
10974             continue;
10975
10976         F.erase();
10977       }
10978       F.done();
10979     }
10980
10981     // Suppress the protected check (C++ [class.protected]) for each of the
10982     // assignment operators we found. This strange dance is required when
10983     // we're assigning via a base classes's copy-assignment operator. To
10984     // ensure that we're getting the right base class subobject (without
10985     // ambiguities), we need to cast "this" to that subobject type; to
10986     // ensure that we don't go through the virtual call mechanism, we need
10987     // to qualify the operator= name with the base class (see below). However,
10988     // this means that if the base class has a protected copy assignment
10989     // operator, the protected member access check will fail. So, we
10990     // rewrite "protected" access to "public" access in this case, since we
10991     // know by construction that we're calling from a derived class.
10992     if (CopyingBaseSubobject) {
10993       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
10994            L != LEnd; ++L) {
10995         if (L.getAccess() == AS_protected)
10996           L.setAccess(AS_public);
10997       }
10998     }
10999
11000     // Create the nested-name-specifier that will be used to qualify the
11001     // reference to operator=; this is required to suppress the virtual
11002     // call mechanism.
11003     CXXScopeSpec SS;
11004     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11005     SS.MakeTrivial(S.Context,
11006                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11007                                                CanonicalT),
11008                    Loc);
11009
11010     // Create the reference to operator=.
11011     ExprResult OpEqualRef
11012       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11013                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11014                                    /*FirstQualifierInScope=*/nullptr,
11015                                    OpLookup,
11016                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11017                                    /*SuppressQualifierCheck=*/true);
11018     if (OpEqualRef.isInvalid())
11019       return StmtError();
11020
11021     // Build the call to the assignment operator.
11022
11023     Expr *FromInst = From.build(S, Loc);
11024     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11025                                                   OpEqualRef.getAs<Expr>(),
11026                                                   Loc, FromInst, Loc);
11027     if (Call.isInvalid())
11028       return StmtError();
11029
11030     // If we built a call to a trivial 'operator=' while copying an array,
11031     // bail out. We'll replace the whole shebang with a memcpy.
11032     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11033     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11034       return StmtResult((Stmt*)nullptr);
11035
11036     // Convert to an expression-statement, and clean up any produced
11037     // temporaries.
11038     return S.ActOnExprStmt(Call);
11039   }
11040
11041   //     - if the subobject is of scalar type, the built-in assignment
11042   //       operator is used.
11043   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11044   if (!ArrayTy) {
11045     ExprResult Assignment = S.CreateBuiltinBinOp(
11046         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11047     if (Assignment.isInvalid())
11048       return StmtError();
11049     return S.ActOnExprStmt(Assignment);
11050   }
11051
11052   //     - if the subobject is an array, each element is assigned, in the
11053   //       manner appropriate to the element type;
11054
11055   // Construct a loop over the array bounds, e.g.,
11056   //
11057   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11058   //
11059   // that will copy each of the array elements. 
11060   QualType SizeType = S.Context.getSizeType();
11061
11062   // Create the iteration variable.
11063   IdentifierInfo *IterationVarName = nullptr;
11064   {
11065     SmallString<8> Str;
11066     llvm::raw_svector_ostream OS(Str);
11067     OS << "__i" << Depth;
11068     IterationVarName = &S.Context.Idents.get(OS.str());
11069   }
11070   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11071                                           IterationVarName, SizeType,
11072                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11073                                           SC_None);
11074
11075   // Initialize the iteration variable to zero.
11076   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11077   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11078
11079   // Creates a reference to the iteration variable.
11080   RefBuilder IterationVarRef(IterationVar, SizeType);
11081   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11082
11083   // Create the DeclStmt that holds the iteration variable.
11084   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11085
11086   // Subscript the "from" and "to" expressions with the iteration variable.
11087   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11088   MoveCastBuilder FromIndexMove(FromIndexCopy);
11089   const ExprBuilder *FromIndex;
11090   if (Copying)
11091     FromIndex = &FromIndexCopy;
11092   else
11093     FromIndex = &FromIndexMove;
11094
11095   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11096
11097   // Build the copy/move for an individual element of the array.
11098   StmtResult Copy =
11099     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11100                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11101                                      Copying, Depth + 1);
11102   // Bail out if copying fails or if we determined that we should use memcpy.
11103   if (Copy.isInvalid() || !Copy.get())
11104     return Copy;
11105
11106   // Create the comparison against the array bound.
11107   llvm::APInt Upper
11108     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11109   Expr *Comparison
11110     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11111                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11112                                      BO_NE, S.Context.BoolTy,
11113                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11114
11115   // Create the pre-increment of the iteration variable.
11116   Expr *Increment
11117     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
11118                                     SizeType, VK_LValue, OK_Ordinary, Loc);
11119
11120   // Construct the loop that copies all elements of this array.
11121   return S.ActOnForStmt(
11122       Loc, Loc, InitStmt,
11123       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11124       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11125 }
11126
11127 static StmtResult
11128 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11129                       const ExprBuilder &To, const ExprBuilder &From,
11130                       bool CopyingBaseSubobject, bool Copying) {
11131   // Maybe we should use a memcpy?
11132   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11133       T.isTriviallyCopyableType(S.Context))
11134     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11135
11136   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11137                                                      CopyingBaseSubobject,
11138                                                      Copying, 0));
11139
11140   // If we ended up picking a trivial assignment operator for an array of a
11141   // non-trivially-copyable class type, just emit a memcpy.
11142   if (!Result.isInvalid() && !Result.get())
11143     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11144
11145   return Result;
11146 }
11147
11148 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11149   // Note: The following rules are largely analoguous to the copy
11150   // constructor rules. Note that virtual bases are not taken into account
11151   // for determining the argument type of the operator. Note also that
11152   // operators taking an object instead of a reference are allowed.
11153   assert(ClassDecl->needsImplicitCopyAssignment());
11154
11155   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11156   if (DSM.isAlreadyBeingDeclared())
11157     return nullptr;
11158
11159   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11160   QualType RetType = Context.getLValueReferenceType(ArgType);
11161   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11162   if (Const)
11163     ArgType = ArgType.withConst();
11164   ArgType = Context.getLValueReferenceType(ArgType);
11165
11166   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11167                                                      CXXCopyAssignment,
11168                                                      Const);
11169
11170   //   An implicitly-declared copy assignment operator is an inline public
11171   //   member of its class.
11172   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11173   SourceLocation ClassLoc = ClassDecl->getLocation();
11174   DeclarationNameInfo NameInfo(Name, ClassLoc);
11175   CXXMethodDecl *CopyAssignment =
11176       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11177                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11178                             /*isInline=*/true, Constexpr, SourceLocation());
11179   CopyAssignment->setAccess(AS_public);
11180   CopyAssignment->setDefaulted();
11181   CopyAssignment->setImplicit();
11182
11183   if (getLangOpts().CUDA) {
11184     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11185                                             CopyAssignment,
11186                                             /* ConstRHS */ Const,
11187                                             /* Diagnose */ false);
11188   }
11189
11190   // Build an exception specification pointing back at this member.
11191   FunctionProtoType::ExtProtoInfo EPI =
11192       getImplicitMethodEPI(*this, CopyAssignment);
11193   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11194
11195   // Add the parameter to the operator.
11196   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11197                                                ClassLoc, ClassLoc,
11198                                                /*Id=*/nullptr, ArgType,
11199                                                /*TInfo=*/nullptr, SC_None,
11200                                                nullptr);
11201   CopyAssignment->setParams(FromParam);
11202
11203   CopyAssignment->setTrivial(
11204     ClassDecl->needsOverloadResolutionForCopyAssignment()
11205       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11206       : ClassDecl->hasTrivialCopyAssignment());
11207
11208   // Note that we have added this copy-assignment operator.
11209   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11210
11211   Scope *S = getScopeForContext(ClassDecl);
11212   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11213
11214   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11215     SetDeclDeleted(CopyAssignment, ClassLoc);
11216
11217   if (S)
11218     PushOnScopeChains(CopyAssignment, S, false);
11219   ClassDecl->addDecl(CopyAssignment);
11220
11221   return CopyAssignment;
11222 }
11223
11224 /// Diagnose an implicit copy operation for a class which is odr-used, but
11225 /// which is deprecated because the class has a user-declared copy constructor,
11226 /// copy assignment operator, or destructor.
11227 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
11228                                             SourceLocation UseLoc) {
11229   assert(CopyOp->isImplicit());
11230
11231   CXXRecordDecl *RD = CopyOp->getParent();
11232   CXXMethodDecl *UserDeclaredOperation = nullptr;
11233
11234   // In Microsoft mode, assignment operations don't affect constructors and
11235   // vice versa.
11236   if (RD->hasUserDeclaredDestructor()) {
11237     UserDeclaredOperation = RD->getDestructor();
11238   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11239              RD->hasUserDeclaredCopyConstructor() &&
11240              !S.getLangOpts().MSVCCompat) {
11241     // Find any user-declared copy constructor.
11242     for (auto *I : RD->ctors()) {
11243       if (I->isCopyConstructor()) {
11244         UserDeclaredOperation = I;
11245         break;
11246       }
11247     }
11248     assert(UserDeclaredOperation);
11249   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11250              RD->hasUserDeclaredCopyAssignment() &&
11251              !S.getLangOpts().MSVCCompat) {
11252     // Find any user-declared move assignment operator.
11253     for (auto *I : RD->methods()) {
11254       if (I->isCopyAssignmentOperator()) {
11255         UserDeclaredOperation = I;
11256         break;
11257       }
11258     }
11259     assert(UserDeclaredOperation);
11260   }
11261
11262   if (UserDeclaredOperation) {
11263     S.Diag(UserDeclaredOperation->getLocation(),
11264          diag::warn_deprecated_copy_operation)
11265       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11266       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11267     S.Diag(UseLoc, diag::note_member_synthesized_at)
11268       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
11269                                           : Sema::CXXCopyAssignment)
11270       << RD;
11271   }
11272 }
11273
11274 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11275                                         CXXMethodDecl *CopyAssignOperator) {
11276   assert((CopyAssignOperator->isDefaulted() && 
11277           CopyAssignOperator->isOverloadedOperator() &&
11278           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11279           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11280           !CopyAssignOperator->isDeleted()) &&
11281          "DefineImplicitCopyAssignment called for wrong function");
11282
11283   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11284
11285   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
11286     CopyAssignOperator->setInvalidDecl();
11287     return;
11288   }
11289
11290   // C++11 [class.copy]p18:
11291   //   The [definition of an implicitly declared copy assignment operator] is
11292   //   deprecated if the class has a user-declared copy constructor or a
11293   //   user-declared destructor.
11294   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11295     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
11296
11297   CopyAssignOperator->markUsed(Context);
11298
11299   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11300   DiagnosticErrorTrap Trap(Diags);
11301
11302   // C++0x [class.copy]p30:
11303   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11304   //   for a non-union class X performs memberwise copy assignment of its 
11305   //   subobjects. The direct base classes of X are assigned first, in the 
11306   //   order of their declaration in the base-specifier-list, and then the 
11307   //   immediate non-static data members of X are assigned, in the order in 
11308   //   which they were declared in the class definition.
11309   
11310   // The statements that form the synthesized function body.
11311   SmallVector<Stmt*, 8> Statements;
11312   
11313   // The parameter for the "other" object, which we are copying from.
11314   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11315   Qualifiers OtherQuals = Other->getType().getQualifiers();
11316   QualType OtherRefType = Other->getType();
11317   if (const LValueReferenceType *OtherRef
11318                                 = OtherRefType->getAs<LValueReferenceType>()) {
11319     OtherRefType = OtherRef->getPointeeType();
11320     OtherQuals = OtherRefType.getQualifiers();
11321   }
11322   
11323   // Our location for everything implicitly-generated.
11324   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11325                            ? CopyAssignOperator->getLocEnd()
11326                            : CopyAssignOperator->getLocation();
11327
11328   // Builds a DeclRefExpr for the "other" object.
11329   RefBuilder OtherRef(Other, OtherRefType);
11330
11331   // Builds the "this" pointer.
11332   ThisBuilder This;
11333   
11334   // Assign base classes.
11335   bool Invalid = false;
11336   for (auto &Base : ClassDecl->bases()) {
11337     // Form the assignment:
11338     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11339     QualType BaseType = Base.getType().getUnqualifiedType();
11340     if (!BaseType->isRecordType()) {
11341       Invalid = true;
11342       continue;
11343     }
11344
11345     CXXCastPath BasePath;
11346     BasePath.push_back(&Base);
11347
11348     // Construct the "from" expression, which is an implicit cast to the
11349     // appropriately-qualified base type.
11350     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11351                      VK_LValue, BasePath);
11352
11353     // Dereference "this".
11354     DerefBuilder DerefThis(This);
11355     CastBuilder To(DerefThis,
11356                    Context.getCVRQualifiedType(
11357                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11358                    VK_LValue, BasePath);
11359
11360     // Build the copy.
11361     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11362                                             To, From,
11363                                             /*CopyingBaseSubobject=*/true,
11364                                             /*Copying=*/true);
11365     if (Copy.isInvalid()) {
11366       Diag(CurrentLocation, diag::note_member_synthesized_at) 
11367         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11368       CopyAssignOperator->setInvalidDecl();
11369       return;
11370     }
11371     
11372     // Success! Record the copy.
11373     Statements.push_back(Copy.getAs<Expr>());
11374   }
11375   
11376   // Assign non-static members.
11377   for (auto *Field : ClassDecl->fields()) {
11378     // FIXME: We should form some kind of AST representation for the implied
11379     // memcpy in a union copy operation.
11380     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11381       continue;
11382
11383     if (Field->isInvalidDecl()) {
11384       Invalid = true;
11385       continue;
11386     }
11387
11388     // Check for members of reference type; we can't copy those.
11389     if (Field->getType()->isReferenceType()) {
11390       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11391         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11392       Diag(Field->getLocation(), diag::note_declared_at);
11393       Diag(CurrentLocation, diag::note_member_synthesized_at) 
11394         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11395       Invalid = true;
11396       continue;
11397     }
11398     
11399     // Check for members of const-qualified, non-class type.
11400     QualType BaseType = Context.getBaseElementType(Field->getType());
11401     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11402       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11403         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11404       Diag(Field->getLocation(), diag::note_declared_at);
11405       Diag(CurrentLocation, diag::note_member_synthesized_at) 
11406         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11407       Invalid = true;      
11408       continue;
11409     }
11410
11411     // Suppress assigning zero-width bitfields.
11412     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11413       continue;
11414     
11415     QualType FieldType = Field->getType().getNonReferenceType();
11416     if (FieldType->isIncompleteArrayType()) {
11417       assert(ClassDecl->hasFlexibleArrayMember() && 
11418              "Incomplete array type is not valid");
11419       continue;
11420     }
11421     
11422     // Build references to the field in the object we're copying from and to.
11423     CXXScopeSpec SS; // Intentionally empty
11424     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11425                               LookupMemberName);
11426     MemberLookup.addDecl(Field);
11427     MemberLookup.resolveKind();
11428
11429     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11430
11431     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11432
11433     // Build the copy of this field.
11434     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11435                                             To, From,
11436                                             /*CopyingBaseSubobject=*/false,
11437                                             /*Copying=*/true);
11438     if (Copy.isInvalid()) {
11439       Diag(CurrentLocation, diag::note_member_synthesized_at) 
11440         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11441       CopyAssignOperator->setInvalidDecl();
11442       return;
11443     }
11444     
11445     // Success! Record the copy.
11446     Statements.push_back(Copy.getAs<Stmt>());
11447   }
11448
11449   if (!Invalid) {
11450     // Add a "return *this;"
11451     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11452     
11453     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11454     if (Return.isInvalid())
11455       Invalid = true;
11456     else {
11457       Statements.push_back(Return.getAs<Stmt>());
11458
11459       if (Trap.hasErrorOccurred()) {
11460         Diag(CurrentLocation, diag::note_member_synthesized_at) 
11461           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11462         Invalid = true;
11463       }
11464     }
11465   }
11466
11467   // The exception specification is needed because we are defining the
11468   // function.
11469   ResolveExceptionSpec(CurrentLocation,
11470                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11471
11472   if (Invalid) {
11473     CopyAssignOperator->setInvalidDecl();
11474     return;
11475   }
11476
11477   StmtResult Body;
11478   {
11479     CompoundScopeRAII CompoundScope(*this);
11480     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11481                              /*isStmtExpr=*/false);
11482     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11483   }
11484   CopyAssignOperator->setBody(Body.getAs<Stmt>());
11485
11486   if (ASTMutationListener *L = getASTMutationListener()) {
11487     L->CompletedImplicitDefinition(CopyAssignOperator);
11488   }
11489 }
11490
11491 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11492   assert(ClassDecl->needsImplicitMoveAssignment());
11493
11494   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11495   if (DSM.isAlreadyBeingDeclared())
11496     return nullptr;
11497
11498   // Note: The following rules are largely analoguous to the move
11499   // constructor rules.
11500
11501   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11502   QualType RetType = Context.getLValueReferenceType(ArgType);
11503   ArgType = Context.getRValueReferenceType(ArgType);
11504
11505   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11506                                                      CXXMoveAssignment,
11507                                                      false);
11508
11509   //   An implicitly-declared move assignment operator is an inline public
11510   //   member of its class.
11511   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11512   SourceLocation ClassLoc = ClassDecl->getLocation();
11513   DeclarationNameInfo NameInfo(Name, ClassLoc);
11514   CXXMethodDecl *MoveAssignment =
11515       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11516                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11517                             /*isInline=*/true, Constexpr, SourceLocation());
11518   MoveAssignment->setAccess(AS_public);
11519   MoveAssignment->setDefaulted();
11520   MoveAssignment->setImplicit();
11521
11522   if (getLangOpts().CUDA) {
11523     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11524                                             MoveAssignment,
11525                                             /* ConstRHS */ false,
11526                                             /* Diagnose */ false);
11527   }
11528
11529   // Build an exception specification pointing back at this member.
11530   FunctionProtoType::ExtProtoInfo EPI =
11531       getImplicitMethodEPI(*this, MoveAssignment);
11532   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11533
11534   // Add the parameter to the operator.
11535   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
11536                                                ClassLoc, ClassLoc,
11537                                                /*Id=*/nullptr, ArgType,
11538                                                /*TInfo=*/nullptr, SC_None,
11539                                                nullptr);
11540   MoveAssignment->setParams(FromParam);
11541
11542   MoveAssignment->setTrivial(
11543     ClassDecl->needsOverloadResolutionForMoveAssignment()
11544       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11545       : ClassDecl->hasTrivialMoveAssignment());
11546
11547   // Note that we have added this copy-assignment operator.
11548   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11549
11550   Scope *S = getScopeForContext(ClassDecl);
11551   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11552
11553   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
11554     ClassDecl->setImplicitMoveAssignmentIsDeleted();
11555     SetDeclDeleted(MoveAssignment, ClassLoc);
11556   }
11557
11558   if (S)
11559     PushOnScopeChains(MoveAssignment, S, false);
11560   ClassDecl->addDecl(MoveAssignment);
11561
11562   return MoveAssignment;
11563 }
11564
11565 /// Check if we're implicitly defining a move assignment operator for a class
11566 /// with virtual bases. Such a move assignment might move-assign the virtual
11567 /// base multiple times.
11568 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11569                                                SourceLocation CurrentLocation) {
11570   assert(!Class->isDependentContext() && "should not define dependent move");
11571
11572   // Only a virtual base could get implicitly move-assigned multiple times.
11573   // Only a non-trivial move assignment can observe this. We only want to
11574   // diagnose if we implicitly define an assignment operator that assigns
11575   // two base classes, both of which move-assign the same virtual base.
11576   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11577       Class->getNumBases() < 2)
11578     return;
11579
11580   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11581   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11582   VBaseMap VBases;
11583
11584   for (auto &BI : Class->bases()) {
11585     Worklist.push_back(&BI);
11586     while (!Worklist.empty()) {
11587       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11588       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11589
11590       // If the base has no non-trivial move assignment operators,
11591       // we don't care about moves from it.
11592       if (!Base->hasNonTrivialMoveAssignment())
11593         continue;
11594
11595       // If there's nothing virtual here, skip it.
11596       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11597         continue;
11598
11599       // If we're not actually going to call a move assignment for this base,
11600       // or the selected move assignment is trivial, skip it.
11601       Sema::SpecialMemberOverloadResult SMOR =
11602         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11603                               /*ConstArg*/false, /*VolatileArg*/false,
11604                               /*RValueThis*/true, /*ConstThis*/false,
11605                               /*VolatileThis*/false);
11606       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
11607           !SMOR.getMethod()->isMoveAssignmentOperator())
11608         continue;
11609
11610       if (BaseSpec->isVirtual()) {
11611         // We're going to move-assign this virtual base, and its move
11612         // assignment operator is not trivial. If this can happen for
11613         // multiple distinct direct bases of Class, diagnose it. (If it
11614         // only happens in one base, we'll diagnose it when synthesizing
11615         // that base class's move assignment operator.)
11616         CXXBaseSpecifier *&Existing =
11617             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
11618                 .first->second;
11619         if (Existing && Existing != &BI) {
11620           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11621             << Class << Base;
11622           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11623             << (Base->getCanonicalDecl() ==
11624                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11625             << Base << Existing->getType() << Existing->getSourceRange();
11626           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
11627             << (Base->getCanonicalDecl() ==
11628                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11629             << Base << BI.getType() << BaseSpec->getSourceRange();
11630
11631           // Only diagnose each vbase once.
11632           Existing = nullptr;
11633         }
11634       } else {
11635         // Only walk over bases that have defaulted move assignment operators.
11636         // We assume that any user-provided move assignment operator handles
11637         // the multiple-moves-of-vbase case itself somehow.
11638         if (!SMOR.getMethod()->isDefaulted())
11639           continue;
11640
11641         // We're going to move the base classes of Base. Add them to the list.
11642         for (auto &BI : Base->bases())
11643           Worklist.push_back(&BI);
11644       }
11645     }
11646   }
11647 }
11648
11649 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11650                                         CXXMethodDecl *MoveAssignOperator) {
11651   assert((MoveAssignOperator->isDefaulted() && 
11652           MoveAssignOperator->isOverloadedOperator() &&
11653           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
11654           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11655           !MoveAssignOperator->isDeleted()) &&
11656          "DefineImplicitMoveAssignment called for wrong function");
11657
11658   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11659
11660   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
11661     MoveAssignOperator->setInvalidDecl();
11662     return;
11663   }
11664   
11665   MoveAssignOperator->markUsed(Context);
11666
11667   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
11668   DiagnosticErrorTrap Trap(Diags);
11669
11670   // C++0x [class.copy]p28:
11671   //   The implicitly-defined or move assignment operator for a non-union class
11672   //   X performs memberwise move assignment of its subobjects. The direct base
11673   //   classes of X are assigned first, in the order of their declaration in the
11674   //   base-specifier-list, and then the immediate non-static data members of X
11675   //   are assigned, in the order in which they were declared in the class
11676   //   definition.
11677
11678   // Issue a warning if our implicit move assignment operator will move
11679   // from a virtual base more than once.
11680   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
11681
11682   // The statements that form the synthesized function body.
11683   SmallVector<Stmt*, 8> Statements;
11684
11685   // The parameter for the "other" object, which we are move from.
11686   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11687   QualType OtherRefType = Other->getType()->
11688       getAs<RValueReferenceType>()->getPointeeType();
11689   assert(!OtherRefType.getQualifiers() &&
11690          "Bad argument type of defaulted move assignment");
11691
11692   // Our location for everything implicitly-generated.
11693   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11694                            ? MoveAssignOperator->getLocEnd()
11695                            : MoveAssignOperator->getLocation();
11696
11697   // Builds a reference to the "other" object.
11698   RefBuilder OtherRef(Other, OtherRefType);
11699   // Cast to rvalue.
11700   MoveCastBuilder MoveOther(OtherRef);
11701
11702   // Builds the "this" pointer.
11703   ThisBuilder This;
11704
11705   // Assign base classes.
11706   bool Invalid = false;
11707   for (auto &Base : ClassDecl->bases()) {
11708     // C++11 [class.copy]p28:
11709     //   It is unspecified whether subobjects representing virtual base classes
11710     //   are assigned more than once by the implicitly-defined copy assignment
11711     //   operator.
11712     // FIXME: Do not assign to a vbase that will be assigned by some other base
11713     // class. For a move-assignment, this can result in the vbase being moved
11714     // multiple times.
11715
11716     // Form the assignment:
11717     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
11718     QualType BaseType = Base.getType().getUnqualifiedType();
11719     if (!BaseType->isRecordType()) {
11720       Invalid = true;
11721       continue;
11722     }
11723
11724     CXXCastPath BasePath;
11725     BasePath.push_back(&Base);
11726
11727     // Construct the "from" expression, which is an implicit cast to the
11728     // appropriately-qualified base type.
11729     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
11730
11731     // Dereference "this".
11732     DerefBuilder DerefThis(This);
11733
11734     // Implicitly cast "this" to the appropriately-qualified base type.
11735     CastBuilder To(DerefThis,
11736                    Context.getCVRQualifiedType(
11737                        BaseType, MoveAssignOperator->getTypeQualifiers()),
11738                    VK_LValue, BasePath);
11739
11740     // Build the move.
11741     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
11742                                             To, From,
11743                                             /*CopyingBaseSubobject=*/true,
11744                                             /*Copying=*/false);
11745     if (Move.isInvalid()) {
11746       Diag(CurrentLocation, diag::note_member_synthesized_at) 
11747         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11748       MoveAssignOperator->setInvalidDecl();
11749       return;
11750     }
11751
11752     // Success! Record the move.
11753     Statements.push_back(Move.getAs<Expr>());
11754   }
11755
11756   // Assign non-static members.
11757   for (auto *Field : ClassDecl->fields()) {
11758     // FIXME: We should form some kind of AST representation for the implied
11759     // memcpy in a union copy operation.
11760     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11761       continue;
11762
11763     if (Field->isInvalidDecl()) {
11764       Invalid = true;
11765       continue;
11766     }
11767
11768     // Check for members of reference type; we can't move those.
11769     if (Field->getType()->isReferenceType()) {
11770       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11771         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11772       Diag(Field->getLocation(), diag::note_declared_at);
11773       Diag(CurrentLocation, diag::note_member_synthesized_at) 
11774         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11775       Invalid = true;
11776       continue;
11777     }
11778
11779     // Check for members of const-qualified, non-class type.
11780     QualType BaseType = Context.getBaseElementType(Field->getType());
11781     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11782       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11783         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11784       Diag(Field->getLocation(), diag::note_declared_at);
11785       Diag(CurrentLocation, diag::note_member_synthesized_at) 
11786         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11787       Invalid = true;      
11788       continue;
11789     }
11790
11791     // Suppress assigning zero-width bitfields.
11792     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11793       continue;
11794     
11795     QualType FieldType = Field->getType().getNonReferenceType();
11796     if (FieldType->isIncompleteArrayType()) {
11797       assert(ClassDecl->hasFlexibleArrayMember() && 
11798              "Incomplete array type is not valid");
11799       continue;
11800     }
11801     
11802     // Build references to the field in the object we're copying from and to.
11803     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11804                               LookupMemberName);
11805     MemberLookup.addDecl(Field);
11806     MemberLookup.resolveKind();
11807     MemberBuilder From(MoveOther, OtherRefType,
11808                        /*IsArrow=*/false, MemberLookup);
11809     MemberBuilder To(This, getCurrentThisType(),
11810                      /*IsArrow=*/true, MemberLookup);
11811
11812     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
11813         "Member reference with rvalue base must be rvalue except for reference "
11814         "members, which aren't allowed for move assignment.");
11815
11816     // Build the move of this field.
11817     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
11818                                             To, From,
11819                                             /*CopyingBaseSubobject=*/false,
11820                                             /*Copying=*/false);
11821     if (Move.isInvalid()) {
11822       Diag(CurrentLocation, diag::note_member_synthesized_at) 
11823         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11824       MoveAssignOperator->setInvalidDecl();
11825       return;
11826     }
11827
11828     // Success! Record the copy.
11829     Statements.push_back(Move.getAs<Stmt>());
11830   }
11831
11832   if (!Invalid) {
11833     // Add a "return *this;"
11834     ExprResult ThisObj =
11835         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11836
11837     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11838     if (Return.isInvalid())
11839       Invalid = true;
11840     else {
11841       Statements.push_back(Return.getAs<Stmt>());
11842
11843       if (Trap.hasErrorOccurred()) {
11844         Diag(CurrentLocation, diag::note_member_synthesized_at) 
11845           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11846         Invalid = true;
11847       }
11848     }
11849   }
11850
11851   // The exception specification is needed because we are defining the
11852   // function.
11853   ResolveExceptionSpec(CurrentLocation,
11854                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11855
11856   if (Invalid) {
11857     MoveAssignOperator->setInvalidDecl();
11858     return;
11859   }
11860
11861   StmtResult Body;
11862   {
11863     CompoundScopeRAII CompoundScope(*this);
11864     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11865                              /*isStmtExpr=*/false);
11866     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11867   }
11868   MoveAssignOperator->setBody(Body.getAs<Stmt>());
11869
11870   if (ASTMutationListener *L = getASTMutationListener()) {
11871     L->CompletedImplicitDefinition(MoveAssignOperator);
11872   }
11873 }
11874
11875 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11876                                                     CXXRecordDecl *ClassDecl) {
11877   // C++ [class.copy]p4:
11878   //   If the class definition does not explicitly declare a copy
11879   //   constructor, one is declared implicitly.
11880   assert(ClassDecl->needsImplicitCopyConstructor());
11881
11882   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11883   if (DSM.isAlreadyBeingDeclared())
11884     return nullptr;
11885
11886   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11887   QualType ArgType = ClassType;
11888   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
11889   if (Const)
11890     ArgType = ArgType.withConst();
11891   ArgType = Context.getLValueReferenceType(ArgType);
11892
11893   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11894                                                      CXXCopyConstructor,
11895                                                      Const);
11896
11897   DeclarationName Name
11898     = Context.DeclarationNames.getCXXConstructorName(
11899                                            Context.getCanonicalType(ClassType));
11900   SourceLocation ClassLoc = ClassDecl->getLocation();
11901   DeclarationNameInfo NameInfo(Name, ClassLoc);
11902
11903   //   An implicitly-declared copy constructor is an inline public
11904   //   member of its class.
11905   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
11906       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11907       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11908       Constexpr);
11909   CopyConstructor->setAccess(AS_public);
11910   CopyConstructor->setDefaulted();
11911
11912   if (getLangOpts().CUDA) {
11913     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11914                                             CopyConstructor,
11915                                             /* ConstRHS */ Const,
11916                                             /* Diagnose */ false);
11917   }
11918
11919   // Build an exception specification pointing back at this member.
11920   FunctionProtoType::ExtProtoInfo EPI =
11921       getImplicitMethodEPI(*this, CopyConstructor);
11922   CopyConstructor->setType(
11923       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11924
11925   // Add the parameter to the constructor.
11926   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
11927                                                ClassLoc, ClassLoc,
11928                                                /*IdentifierInfo=*/nullptr,
11929                                                ArgType, /*TInfo=*/nullptr,
11930                                                SC_None, nullptr);
11931   CopyConstructor->setParams(FromParam);
11932
11933   CopyConstructor->setTrivial(
11934     ClassDecl->needsOverloadResolutionForCopyConstructor()
11935       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11936       : ClassDecl->hasTrivialCopyConstructor());
11937
11938   // Note that we have declared this constructor.
11939   ++ASTContext::NumImplicitCopyConstructorsDeclared;
11940
11941   Scope *S = getScopeForContext(ClassDecl);
11942   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11943
11944   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11945     SetDeclDeleted(CopyConstructor, ClassLoc);
11946
11947   if (S)
11948     PushOnScopeChains(CopyConstructor, S, false);
11949   ClassDecl->addDecl(CopyConstructor);
11950
11951   return CopyConstructor;
11952 }
11953
11954 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
11955                                    CXXConstructorDecl *CopyConstructor) {
11956   assert((CopyConstructor->isDefaulted() &&
11957           CopyConstructor->isCopyConstructor() &&
11958           !CopyConstructor->doesThisDeclarationHaveABody() &&
11959           !CopyConstructor->isDeleted()) &&
11960          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
11961
11962   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
11963   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
11964
11965   // C++11 [class.copy]p7:
11966   //   The [definition of an implicitly declared copy constructor] is
11967   //   deprecated if the class has a user-declared copy assignment operator
11968   //   or a user-declared destructor.
11969   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11970     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11971
11972   SynthesizedFunctionScope Scope(*this, CopyConstructor);
11973   DiagnosticErrorTrap Trap(Diags);
11974
11975   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
11976       Trap.hasErrorOccurred()) {
11977     Diag(CurrentLocation, diag::note_member_synthesized_at) 
11978       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
11979     CopyConstructor->setInvalidDecl();
11980   }  else {
11981     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11982                              ? CopyConstructor->getLocEnd()
11983                              : CopyConstructor->getLocation();
11984     Sema::CompoundScopeRAII CompoundScope(*this);
11985     CopyConstructor->setBody(
11986         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
11987   }
11988
11989   // The exception specification is needed because we are defining the
11990   // function.
11991   ResolveExceptionSpec(CurrentLocation,
11992                        CopyConstructor->getType()->castAs<FunctionProtoType>());
11993
11994   CopyConstructor->markUsed(Context);
11995   MarkVTableUsed(CurrentLocation, ClassDecl);
11996
11997   if (ASTMutationListener *L = getASTMutationListener()) {
11998     L->CompletedImplicitDefinition(CopyConstructor);
11999   }
12000 }
12001
12002 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12003                                                     CXXRecordDecl *ClassDecl) {
12004   assert(ClassDecl->needsImplicitMoveConstructor());
12005
12006   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12007   if (DSM.isAlreadyBeingDeclared())
12008     return nullptr;
12009
12010   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12011   QualType ArgType = Context.getRValueReferenceType(ClassType);
12012
12013   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12014                                                      CXXMoveConstructor,
12015                                                      false);
12016
12017   DeclarationName Name
12018     = Context.DeclarationNames.getCXXConstructorName(
12019                                            Context.getCanonicalType(ClassType));
12020   SourceLocation ClassLoc = ClassDecl->getLocation();
12021   DeclarationNameInfo NameInfo(Name, ClassLoc);
12022
12023   // C++11 [class.copy]p11:
12024   //   An implicitly-declared copy/move constructor is an inline public
12025   //   member of its class.
12026   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12027       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12028       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12029       Constexpr);
12030   MoveConstructor->setAccess(AS_public);
12031   MoveConstructor->setDefaulted();
12032
12033   if (getLangOpts().CUDA) {
12034     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12035                                             MoveConstructor,
12036                                             /* ConstRHS */ false,
12037                                             /* Diagnose */ false);
12038   }
12039
12040   // Build an exception specification pointing back at this member.
12041   FunctionProtoType::ExtProtoInfo EPI =
12042       getImplicitMethodEPI(*this, MoveConstructor);
12043   MoveConstructor->setType(
12044       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12045
12046   // Add the parameter to the constructor.
12047   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12048                                                ClassLoc, ClassLoc,
12049                                                /*IdentifierInfo=*/nullptr,
12050                                                ArgType, /*TInfo=*/nullptr,
12051                                                SC_None, nullptr);
12052   MoveConstructor->setParams(FromParam);
12053
12054   MoveConstructor->setTrivial(
12055     ClassDecl->needsOverloadResolutionForMoveConstructor()
12056       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12057       : ClassDecl->hasTrivialMoveConstructor());
12058
12059   // Note that we have declared this constructor.
12060   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12061
12062   Scope *S = getScopeForContext(ClassDecl);
12063   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12064
12065   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12066     ClassDecl->setImplicitMoveConstructorIsDeleted();
12067     SetDeclDeleted(MoveConstructor, ClassLoc);
12068   }
12069
12070   if (S)
12071     PushOnScopeChains(MoveConstructor, S, false);
12072   ClassDecl->addDecl(MoveConstructor);
12073
12074   return MoveConstructor;
12075 }
12076
12077 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12078                                    CXXConstructorDecl *MoveConstructor) {
12079   assert((MoveConstructor->isDefaulted() &&
12080           MoveConstructor->isMoveConstructor() &&
12081           !MoveConstructor->doesThisDeclarationHaveABody() &&
12082           !MoveConstructor->isDeleted()) &&
12083          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12084
12085   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12086   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12087
12088   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12089   DiagnosticErrorTrap Trap(Diags);
12090
12091   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
12092       Trap.hasErrorOccurred()) {
12093     Diag(CurrentLocation, diag::note_member_synthesized_at) 
12094       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
12095     MoveConstructor->setInvalidDecl();
12096   }  else {
12097     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12098                              ? MoveConstructor->getLocEnd()
12099                              : MoveConstructor->getLocation();
12100     Sema::CompoundScopeRAII CompoundScope(*this);
12101     MoveConstructor->setBody(ActOnCompoundStmt(
12102         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12103   }
12104
12105   // The exception specification is needed because we are defining the
12106   // function.
12107   ResolveExceptionSpec(CurrentLocation,
12108                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12109
12110   MoveConstructor->markUsed(Context);
12111   MarkVTableUsed(CurrentLocation, ClassDecl);
12112
12113   if (ASTMutationListener *L = getASTMutationListener()) {
12114     L->CompletedImplicitDefinition(MoveConstructor);
12115   }
12116 }
12117
12118 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12119   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12120 }
12121
12122 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12123                             SourceLocation CurrentLocation,
12124                             CXXConversionDecl *Conv) {
12125   CXXRecordDecl *Lambda = Conv->getParent();
12126   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12127   // If we are defining a specialization of a conversion to function-ptr
12128   // cache the deduced template arguments for this specialization
12129   // so that we can use them to retrieve the corresponding call-operator
12130   // and static-invoker. 
12131   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12132
12133   // Retrieve the corresponding call-operator specialization.
12134   if (Lambda->isGenericLambda()) {
12135     assert(Conv->isFunctionTemplateSpecialization());
12136     FunctionTemplateDecl *CallOpTemplate = 
12137         CallOp->getDescribedFunctionTemplate();
12138     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
12139     void *InsertPos = nullptr;
12140     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
12141                                                 DeducedTemplateArgs->asArray(),
12142                                                 InsertPos);
12143     assert(CallOpSpec && 
12144           "Conversion operator must have a corresponding call operator");
12145     CallOp = cast<CXXMethodDecl>(CallOpSpec);
12146   }
12147   // Mark the call operator referenced (and add to pending instantiations
12148   // if necessary).
12149   // For both the conversion and static-invoker template specializations
12150   // we construct their body's in this function, so no need to add them
12151   // to the PendingInstantiations.
12152   MarkFunctionReferenced(CurrentLocation, CallOp);
12153
12154   SynthesizedFunctionScope Scope(*this, Conv);
12155   DiagnosticErrorTrap Trap(Diags);
12156    
12157   // Retrieve the static invoker...
12158   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12159   // ... and get the corresponding specialization for a generic lambda.
12160   if (Lambda->isGenericLambda()) {
12161     assert(DeducedTemplateArgs && 
12162       "Must have deduced template arguments from Conversion Operator");
12163     FunctionTemplateDecl *InvokeTemplate = 
12164                           Invoker->getDescribedFunctionTemplate();
12165     void *InsertPos = nullptr;
12166     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
12167                                                 DeducedTemplateArgs->asArray(),
12168                                                 InsertPos);
12169     assert(InvokeSpec && 
12170       "Must have a corresponding static invoker specialization");
12171     Invoker = cast<CXXMethodDecl>(InvokeSpec);
12172   }
12173   // Construct the body of the conversion function { return __invoke; }.
12174   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12175                                         VK_LValue, Conv->getLocation()).get();
12176    assert(FunctionRef && "Can't refer to __invoke function?");
12177    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12178    Conv->setBody(new (Context) CompoundStmt(Context, Return,
12179                                             Conv->getLocation(),
12180                                             Conv->getLocation()));
12181
12182   Conv->markUsed(Context);
12183   Conv->setReferenced();
12184   
12185   // Fill in the __invoke function with a dummy implementation. IR generation
12186   // will fill in the actual details.
12187   Invoker->markUsed(Context);
12188   Invoker->setReferenced();
12189   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12190    
12191   if (ASTMutationListener *L = getASTMutationListener()) {
12192     L->CompletedImplicitDefinition(Conv);
12193     L->CompletedImplicitDefinition(Invoker);
12194    }
12195 }
12196
12197
12198
12199 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12200        SourceLocation CurrentLocation,
12201        CXXConversionDecl *Conv) 
12202 {
12203   assert(!Conv->getParent()->isGenericLambda());
12204
12205   Conv->markUsed(Context);
12206   
12207   SynthesizedFunctionScope Scope(*this, Conv);
12208   DiagnosticErrorTrap Trap(Diags);
12209   
12210   // Copy-initialize the lambda object as needed to capture it.
12211   Expr *This = ActOnCXXThis(CurrentLocation).get();
12212   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12213   
12214   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12215                                                         Conv->getLocation(),
12216                                                         Conv, DerefThis);
12217
12218   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12219   // behavior.  Note that only the general conversion function does this
12220   // (since it's unusable otherwise); in the case where we inline the
12221   // block literal, it has block literal lifetime semantics.
12222   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12223     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12224                                           CK_CopyAndAutoreleaseBlockObject,
12225                                           BuildBlock.get(), nullptr, VK_RValue);
12226
12227   if (BuildBlock.isInvalid()) {
12228     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12229     Conv->setInvalidDecl();
12230     return;
12231   }
12232
12233   // Create the return statement that returns the block from the conversion
12234   // function.
12235   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12236   if (Return.isInvalid()) {
12237     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12238     Conv->setInvalidDecl();
12239     return;
12240   }
12241
12242   // Set the body of the conversion function.
12243   Stmt *ReturnS = Return.get();
12244   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
12245                                            Conv->getLocation(),
12246                                            Conv->getLocation()));
12247   
12248   // We're done; notify the mutation listener, if any.
12249   if (ASTMutationListener *L = getASTMutationListener()) {
12250     L->CompletedImplicitDefinition(Conv);
12251   }
12252 }
12253
12254 /// \brief Determine whether the given list arguments contains exactly one 
12255 /// "real" (non-default) argument.
12256 static bool hasOneRealArgument(MultiExprArg Args) {
12257   switch (Args.size()) {
12258   case 0:
12259     return false;
12260     
12261   default:
12262     if (!Args[1]->isDefaultArgument())
12263       return false;
12264     
12265     // fall through
12266   case 1:
12267     return !Args[0]->isDefaultArgument();
12268   }
12269   
12270   return false;
12271 }
12272
12273 ExprResult
12274 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12275                             NamedDecl *FoundDecl,
12276                             CXXConstructorDecl *Constructor,
12277                             MultiExprArg ExprArgs,
12278                             bool HadMultipleCandidates,
12279                             bool IsListInitialization,
12280                             bool IsStdInitListInitialization,
12281                             bool RequiresZeroInit,
12282                             unsigned ConstructKind,
12283                             SourceRange ParenRange) {
12284   bool Elidable = false;
12285
12286   // C++0x [class.copy]p34:
12287   //   When certain criteria are met, an implementation is allowed to
12288   //   omit the copy/move construction of a class object, even if the
12289   //   copy/move constructor and/or destructor for the object have
12290   //   side effects. [...]
12291   //     - when a temporary class object that has not been bound to a
12292   //       reference (12.2) would be copied/moved to a class object
12293   //       with the same cv-unqualified type, the copy/move operation
12294   //       can be omitted by constructing the temporary object
12295   //       directly into the target of the omitted copy/move
12296   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12297       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12298     Expr *SubExpr = ExprArgs[0];
12299     Elidable = SubExpr->isTemporaryObject(
12300         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12301   }
12302
12303   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12304                                FoundDecl, Constructor,
12305                                Elidable, ExprArgs, HadMultipleCandidates,
12306                                IsListInitialization,
12307                                IsStdInitListInitialization, RequiresZeroInit,
12308                                ConstructKind, ParenRange);
12309 }
12310
12311 ExprResult
12312 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12313                             NamedDecl *FoundDecl,
12314                             CXXConstructorDecl *Constructor,
12315                             bool Elidable,
12316                             MultiExprArg ExprArgs,
12317                             bool HadMultipleCandidates,
12318                             bool IsListInitialization,
12319                             bool IsStdInitListInitialization,
12320                             bool RequiresZeroInit,
12321                             unsigned ConstructKind,
12322                             SourceRange ParenRange) {
12323   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12324     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12325     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12326       return ExprError(); 
12327   }
12328
12329   return BuildCXXConstructExpr(
12330       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12331       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12332       RequiresZeroInit, ConstructKind, ParenRange);
12333 }
12334
12335 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12336 /// including handling of its default argument expressions.
12337 ExprResult
12338 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12339                             CXXConstructorDecl *Constructor,
12340                             bool Elidable,
12341                             MultiExprArg ExprArgs,
12342                             bool HadMultipleCandidates,
12343                             bool IsListInitialization,
12344                             bool IsStdInitListInitialization,
12345                             bool RequiresZeroInit,
12346                             unsigned ConstructKind,
12347                             SourceRange ParenRange) {
12348   assert(declaresSameEntity(
12349              Constructor->getParent(),
12350              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12351          "given constructor for wrong type");
12352   MarkFunctionReferenced(ConstructLoc, Constructor);
12353   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12354     return ExprError();
12355
12356   return CXXConstructExpr::Create(
12357       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12358       ExprArgs, HadMultipleCandidates, IsListInitialization,
12359       IsStdInitListInitialization, RequiresZeroInit,
12360       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12361       ParenRange);
12362 }
12363
12364 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12365   assert(Field->hasInClassInitializer());
12366
12367   // If we already have the in-class initializer nothing needs to be done.
12368   if (Field->getInClassInitializer())
12369     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12370
12371   // If we might have already tried and failed to instantiate, don't try again.
12372   if (Field->isInvalidDecl())
12373     return ExprError();
12374
12375   // Maybe we haven't instantiated the in-class initializer. Go check the
12376   // pattern FieldDecl to see if it has one.
12377   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12378
12379   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12380     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12381     DeclContext::lookup_result Lookup =
12382         ClassPattern->lookup(Field->getDeclName());
12383
12384     // Lookup can return at most two results: the pattern for the field, or the
12385     // injected class name of the parent record. No other member can have the
12386     // same name as the field.
12387     // In modules mode, lookup can return multiple results (coming from
12388     // different modules).
12389     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12390            "more than two lookup results for field name");
12391     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12392     if (!Pattern) {
12393       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12394              "cannot have other non-field member with same name");
12395       for (auto L : Lookup)
12396         if (isa<FieldDecl>(L)) {
12397           Pattern = cast<FieldDecl>(L);
12398           break;
12399         }
12400       assert(Pattern && "We must have set the Pattern!");
12401     }
12402
12403     if (InstantiateInClassInitializer(Loc, Field, Pattern,
12404                                       getTemplateInstantiationArgs(Field))) {
12405       // Don't diagnose this again.
12406       Field->setInvalidDecl();
12407       return ExprError();
12408     }
12409     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12410   }
12411
12412   // DR1351:
12413   //   If the brace-or-equal-initializer of a non-static data member
12414   //   invokes a defaulted default constructor of its class or of an
12415   //   enclosing class in a potentially evaluated subexpression, the
12416   //   program is ill-formed.
12417   //
12418   // This resolution is unworkable: the exception specification of the
12419   // default constructor can be needed in an unevaluated context, in
12420   // particular, in the operand of a noexcept-expression, and we can be
12421   // unable to compute an exception specification for an enclosed class.
12422   //
12423   // Any attempt to resolve the exception specification of a defaulted default
12424   // constructor before the initializer is lexically complete will ultimately
12425   // come here at which point we can diagnose it.
12426   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12427   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12428       << OutermostClass << Field;
12429   Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
12430   // Recover by marking the field invalid, unless we're in a SFINAE context.
12431   if (!isSFINAEContext())
12432     Field->setInvalidDecl();
12433   return ExprError();
12434 }
12435
12436 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12437   if (VD->isInvalidDecl()) return;
12438
12439   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12440   if (ClassDecl->isInvalidDecl()) return;
12441   if (ClassDecl->hasIrrelevantDestructor()) return;
12442   if (ClassDecl->isDependentContext()) return;
12443
12444   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12445   MarkFunctionReferenced(VD->getLocation(), Destructor);
12446   CheckDestructorAccess(VD->getLocation(), Destructor,
12447                         PDiag(diag::err_access_dtor_var)
12448                         << VD->getDeclName()
12449                         << VD->getType());
12450   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12451
12452   if (Destructor->isTrivial()) return;
12453   if (!VD->hasGlobalStorage()) return;
12454
12455   // Emit warning for non-trivial dtor in global scope (a real global,
12456   // class-static, function-static).
12457   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12458
12459   // TODO: this should be re-enabled for static locals by !CXAAtExit
12460   if (!VD->isStaticLocal())
12461     Diag(VD->getLocation(), diag::warn_global_destructor);
12462 }
12463
12464 /// \brief Given a constructor and the set of arguments provided for the
12465 /// constructor, convert the arguments and add any required default arguments
12466 /// to form a proper call to this constructor.
12467 ///
12468 /// \returns true if an error occurred, false otherwise.
12469 bool 
12470 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12471                               MultiExprArg ArgsPtr,
12472                               SourceLocation Loc,
12473                               SmallVectorImpl<Expr*> &ConvertedArgs,
12474                               bool AllowExplicit,
12475                               bool IsListInitialization) {
12476   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12477   unsigned NumArgs = ArgsPtr.size();
12478   Expr **Args = ArgsPtr.data();
12479
12480   const FunctionProtoType *Proto 
12481     = Constructor->getType()->getAs<FunctionProtoType>();
12482   assert(Proto && "Constructor without a prototype?");
12483   unsigned NumParams = Proto->getNumParams();
12484
12485   // If too few arguments are available, we'll fill in the rest with defaults.
12486   if (NumArgs < NumParams)
12487     ConvertedArgs.reserve(NumParams);
12488   else
12489     ConvertedArgs.reserve(NumArgs);
12490
12491   VariadicCallType CallType = 
12492     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12493   SmallVector<Expr *, 8> AllArgs;
12494   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12495                                         Proto, 0,
12496                                         llvm::makeArrayRef(Args, NumArgs),
12497                                         AllArgs,
12498                                         CallType, AllowExplicit,
12499                                         IsListInitialization);
12500   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12501
12502   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12503
12504   CheckConstructorCall(Constructor,
12505                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12506                        Proto, Loc);
12507
12508   return Invalid;
12509 }
12510
12511 static inline bool
12512 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 
12513                                        const FunctionDecl *FnDecl) {
12514   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12515   if (isa<NamespaceDecl>(DC)) {
12516     return SemaRef.Diag(FnDecl->getLocation(), 
12517                         diag::err_operator_new_delete_declared_in_namespace)
12518       << FnDecl->getDeclName();
12519   }
12520   
12521   if (isa<TranslationUnitDecl>(DC) && 
12522       FnDecl->getStorageClass() == SC_Static) {
12523     return SemaRef.Diag(FnDecl->getLocation(),
12524                         diag::err_operator_new_delete_declared_static)
12525       << FnDecl->getDeclName();
12526   }
12527   
12528   return false;
12529 }
12530
12531 static inline bool
12532 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12533                             CanQualType ExpectedResultType,
12534                             CanQualType ExpectedFirstParamType,
12535                             unsigned DependentParamTypeDiag,
12536                             unsigned InvalidParamTypeDiag) {
12537   QualType ResultType =
12538       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
12539
12540   // Check that the result type is not dependent.
12541   if (ResultType->isDependentType())
12542     return SemaRef.Diag(FnDecl->getLocation(),
12543                         diag::err_operator_new_delete_dependent_result_type)
12544     << FnDecl->getDeclName() << ExpectedResultType;
12545
12546   // Check that the result type is what we expect.
12547   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12548     return SemaRef.Diag(FnDecl->getLocation(),
12549                         diag::err_operator_new_delete_invalid_result_type) 
12550     << FnDecl->getDeclName() << ExpectedResultType;
12551   
12552   // A function template must have at least 2 parameters.
12553   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12554     return SemaRef.Diag(FnDecl->getLocation(),
12555                       diag::err_operator_new_delete_template_too_few_parameters)
12556         << FnDecl->getDeclName();
12557   
12558   // The function decl must have at least 1 parameter.
12559   if (FnDecl->getNumParams() == 0)
12560     return SemaRef.Diag(FnDecl->getLocation(),
12561                         diag::err_operator_new_delete_too_few_parameters)
12562       << FnDecl->getDeclName();
12563  
12564   // Check the first parameter type is not dependent.
12565   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12566   if (FirstParamType->isDependentType())
12567     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12568       << FnDecl->getDeclName() << ExpectedFirstParamType;
12569
12570   // Check that the first parameter type is what we expect.
12571   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 
12572       ExpectedFirstParamType)
12573     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12574     << FnDecl->getDeclName() << ExpectedFirstParamType;
12575   
12576   return false;
12577 }
12578
12579 static bool
12580 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
12581   // C++ [basic.stc.dynamic.allocation]p1:
12582   //   A program is ill-formed if an allocation function is declared in a
12583   //   namespace scope other than global scope or declared static in global 
12584   //   scope.
12585   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12586     return true;
12587
12588   CanQualType SizeTy = 
12589     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12590
12591   // C++ [basic.stc.dynamic.allocation]p1:
12592   //  The return type shall be void*. The first parameter shall have type 
12593   //  std::size_t.
12594   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 
12595                                   SizeTy,
12596                                   diag::err_operator_new_dependent_param_type,
12597                                   diag::err_operator_new_param_type))
12598     return true;
12599
12600   // C++ [basic.stc.dynamic.allocation]p1:
12601   //  The first parameter shall not have an associated default argument.
12602   if (FnDecl->getParamDecl(0)->hasDefaultArg())
12603     return SemaRef.Diag(FnDecl->getLocation(),
12604                         diag::err_operator_new_default_arg)
12605       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12606
12607   return false;
12608 }
12609
12610 static bool
12611 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
12612   // C++ [basic.stc.dynamic.deallocation]p1:
12613   //   A program is ill-formed if deallocation functions are declared in a
12614   //   namespace scope other than global scope or declared static in global 
12615   //   scope.
12616   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12617     return true;
12618
12619   // C++ [basic.stc.dynamic.deallocation]p2:
12620   //   Each deallocation function shall return void and its first parameter 
12621   //   shall be void*.
12622   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 
12623                                   SemaRef.Context.VoidPtrTy,
12624                                  diag::err_operator_delete_dependent_param_type,
12625                                  diag::err_operator_delete_param_type))
12626     return true;
12627
12628   return false;
12629 }
12630
12631 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
12632 /// of this overloaded operator is well-formed. If so, returns false;
12633 /// otherwise, emits appropriate diagnostics and returns true.
12634 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
12635   assert(FnDecl && FnDecl->isOverloadedOperator() &&
12636          "Expected an overloaded operator declaration");
12637
12638   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12639
12640   // C++ [over.oper]p5:
12641   //   The allocation and deallocation functions, operator new,
12642   //   operator new[], operator delete and operator delete[], are
12643   //   described completely in 3.7.3. The attributes and restrictions
12644   //   found in the rest of this subclause do not apply to them unless
12645   //   explicitly stated in 3.7.3.
12646   if (Op == OO_Delete || Op == OO_Array_Delete)
12647     return CheckOperatorDeleteDeclaration(*this, FnDecl);
12648   
12649   if (Op == OO_New || Op == OO_Array_New)
12650     return CheckOperatorNewDeclaration(*this, FnDecl);
12651
12652   // C++ [over.oper]p6:
12653   //   An operator function shall either be a non-static member
12654   //   function or be a non-member function and have at least one
12655   //   parameter whose type is a class, a reference to a class, an
12656   //   enumeration, or a reference to an enumeration.
12657   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12658     if (MethodDecl->isStatic())
12659       return Diag(FnDecl->getLocation(),
12660                   diag::err_operator_overload_static) << FnDecl->getDeclName();
12661   } else {
12662     bool ClassOrEnumParam = false;
12663     for (auto Param : FnDecl->parameters()) {
12664       QualType ParamType = Param->getType().getNonReferenceType();
12665       if (ParamType->isDependentType() || ParamType->isRecordType() ||
12666           ParamType->isEnumeralType()) {
12667         ClassOrEnumParam = true;
12668         break;
12669       }
12670     }
12671
12672     if (!ClassOrEnumParam)
12673       return Diag(FnDecl->getLocation(),
12674                   diag::err_operator_overload_needs_class_or_enum)
12675         << FnDecl->getDeclName();
12676   }
12677
12678   // C++ [over.oper]p8:
12679   //   An operator function cannot have default arguments (8.3.6),
12680   //   except where explicitly stated below.
12681   //
12682   // Only the function-call operator allows default arguments
12683   // (C++ [over.call]p1).
12684   if (Op != OO_Call) {
12685     for (auto Param : FnDecl->parameters()) {
12686       if (Param->hasDefaultArg())
12687         return Diag(Param->getLocation(),
12688                     diag::err_operator_overload_default_arg)
12689           << FnDecl->getDeclName() << Param->getDefaultArgRange();
12690     }
12691   }
12692
12693   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12694     { false, false, false }
12695 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12696     , { Unary, Binary, MemberOnly }
12697 #include "clang/Basic/OperatorKinds.def"
12698   };
12699
12700   bool CanBeUnaryOperator = OperatorUses[Op][0];
12701   bool CanBeBinaryOperator = OperatorUses[Op][1];
12702   bool MustBeMemberOperator = OperatorUses[Op][2];
12703
12704   // C++ [over.oper]p8:
12705   //   [...] Operator functions cannot have more or fewer parameters
12706   //   than the number required for the corresponding operator, as
12707   //   described in the rest of this subclause.
12708   unsigned NumParams = FnDecl->getNumParams()
12709                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
12710   if (Op != OO_Call &&
12711       ((NumParams == 1 && !CanBeUnaryOperator) ||
12712        (NumParams == 2 && !CanBeBinaryOperator) ||
12713        (NumParams < 1) || (NumParams > 2))) {
12714     // We have the wrong number of parameters.
12715     unsigned ErrorKind;
12716     if (CanBeUnaryOperator && CanBeBinaryOperator) {
12717       ErrorKind = 2;  // 2 -> unary or binary.
12718     } else if (CanBeUnaryOperator) {
12719       ErrorKind = 0;  // 0 -> unary
12720     } else {
12721       assert(CanBeBinaryOperator &&
12722              "All non-call overloaded operators are unary or binary!");
12723       ErrorKind = 1;  // 1 -> binary
12724     }
12725
12726     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
12727       << FnDecl->getDeclName() << NumParams << ErrorKind;
12728   }
12729
12730   // Overloaded operators other than operator() cannot be variadic.
12731   if (Op != OO_Call &&
12732       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
12733     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
12734       << FnDecl->getDeclName();
12735   }
12736
12737   // Some operators must be non-static member functions.
12738   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12739     return Diag(FnDecl->getLocation(),
12740                 diag::err_operator_overload_must_be_member)
12741       << FnDecl->getDeclName();
12742   }
12743
12744   // C++ [over.inc]p1:
12745   //   The user-defined function called operator++ implements the
12746   //   prefix and postfix ++ operator. If this function is a member
12747   //   function with no parameters, or a non-member function with one
12748   //   parameter of class or enumeration type, it defines the prefix
12749   //   increment operator ++ for objects of that type. If the function
12750   //   is a member function with one parameter (which shall be of type
12751   //   int) or a non-member function with two parameters (the second
12752   //   of which shall be of type int), it defines the postfix
12753   //   increment operator ++ for objects of that type.
12754   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12755     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
12756     QualType ParamType = LastParam->getType();
12757
12758     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12759         !ParamType->isDependentType())
12760       return Diag(LastParam->getLocation(),
12761                   diag::err_operator_overload_post_incdec_must_be_int)
12762         << LastParam->getType() << (Op == OO_MinusMinus);
12763   }
12764
12765   return false;
12766 }
12767
12768 static bool
12769 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12770                                           FunctionTemplateDecl *TpDecl) {
12771   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12772
12773   // Must have one or two template parameters.
12774   if (TemplateParams->size() == 1) {
12775     NonTypeTemplateParmDecl *PmDecl =
12776         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12777
12778     // The template parameter must be a char parameter pack.
12779     if (PmDecl && PmDecl->isTemplateParameterPack() &&
12780         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12781       return false;
12782
12783   } else if (TemplateParams->size() == 2) {
12784     TemplateTypeParmDecl *PmType =
12785         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12786     NonTypeTemplateParmDecl *PmArgs =
12787         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12788
12789     // The second template parameter must be a parameter pack with the
12790     // first template parameter as its type.
12791     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12792         PmArgs->isTemplateParameterPack()) {
12793       const TemplateTypeParmType *TArgs =
12794           PmArgs->getType()->getAs<TemplateTypeParmType>();
12795       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12796           TArgs->getIndex() == PmType->getIndex()) {
12797         if (!SemaRef.inTemplateInstantiation())
12798           SemaRef.Diag(TpDecl->getLocation(),
12799                        diag::ext_string_literal_operator_template);
12800         return false;
12801       }
12802     }
12803   }
12804
12805   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12806                diag::err_literal_operator_template)
12807       << TpDecl->getTemplateParameters()->getSourceRange();
12808   return true;
12809 }
12810
12811 /// CheckLiteralOperatorDeclaration - Check whether the declaration
12812 /// of this literal operator function is well-formed. If so, returns
12813 /// false; otherwise, emits appropriate diagnostics and returns true.
12814 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
12815   if (isa<CXXMethodDecl>(FnDecl)) {
12816     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12817       << FnDecl->getDeclName();
12818     return true;
12819   }
12820
12821   if (FnDecl->isExternC()) {
12822     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
12823     if (const LinkageSpecDecl *LSD =
12824             FnDecl->getDeclContext()->getExternCContext())
12825       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
12826     return true;
12827   }
12828
12829   // This might be the definition of a literal operator template.
12830   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
12831
12832   // This might be a specialization of a literal operator template.
12833   if (!TpDecl)
12834     TpDecl = FnDecl->getPrimaryTemplate();
12835
12836   // template <char...> type operator "" name() and
12837   // template <class T, T...> type operator "" name() are the only valid
12838   // template signatures, and the only valid signatures with no parameters.
12839   if (TpDecl) {
12840     if (FnDecl->param_size() != 0) {
12841       Diag(FnDecl->getLocation(),
12842            diag::err_literal_operator_template_with_params);
12843       return true;
12844     }
12845
12846     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12847       return true;
12848
12849   } else if (FnDecl->param_size() == 1) {
12850     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12851
12852     QualType ParamType = Param->getType().getUnqualifiedType();
12853
12854     // Only unsigned long long int, long double, any character type, and const
12855     // char * are allowed as the only parameters.
12856     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12857         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12858         Context.hasSameType(ParamType, Context.CharTy) ||
12859         Context.hasSameType(ParamType, Context.WideCharTy) ||
12860         Context.hasSameType(ParamType, Context.Char16Ty) ||
12861         Context.hasSameType(ParamType, Context.Char32Ty)) {
12862     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12863       QualType InnerType = Ptr->getPointeeType();
12864
12865       // Pointer parameter must be a const char *.
12866       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12867                                 Context.CharTy) &&
12868             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12869         Diag(Param->getSourceRange().getBegin(),
12870              diag::err_literal_operator_param)
12871             << ParamType << "'const char *'" << Param->getSourceRange();
12872         return true;
12873       }
12874
12875     } else if (ParamType->isRealFloatingType()) {
12876       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12877           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12878       return true;
12879
12880     } else if (ParamType->isIntegerType()) {
12881       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12882           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12883       return true;
12884
12885     } else {
12886       Diag(Param->getSourceRange().getBegin(),
12887            diag::err_literal_operator_invalid_param)
12888           << ParamType << Param->getSourceRange();
12889       return true;
12890     }
12891
12892   } else if (FnDecl->param_size() == 2) {
12893     FunctionDecl::param_iterator Param = FnDecl->param_begin();
12894
12895     // First, verify that the first parameter is correct.
12896
12897     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12898
12899     // Two parameter function must have a pointer to const as a
12900     // first parameter; let's strip those qualifiers.
12901     const PointerType *PT = FirstParamType->getAs<PointerType>();
12902
12903     if (!PT) {
12904       Diag((*Param)->getSourceRange().getBegin(),
12905            diag::err_literal_operator_param)
12906           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12907       return true;
12908     }
12909
12910     QualType PointeeType = PT->getPointeeType();
12911     // First parameter must be const
12912     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12913       Diag((*Param)->getSourceRange().getBegin(),
12914            diag::err_literal_operator_param)
12915           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12916       return true;
12917     }
12918
12919     QualType InnerType = PointeeType.getUnqualifiedType();
12920     // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12921     // are allowed as the first parameter to a two-parameter function
12922     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12923           Context.hasSameType(InnerType, Context.WideCharTy) ||
12924           Context.hasSameType(InnerType, Context.Char16Ty) ||
12925           Context.hasSameType(InnerType, Context.Char32Ty))) {
12926       Diag((*Param)->getSourceRange().getBegin(),
12927            diag::err_literal_operator_param)
12928           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12929       return true;
12930     }
12931
12932     // Move on to the second and final parameter.
12933     ++Param;
12934
12935     // The second parameter must be a std::size_t.
12936     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12937     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12938       Diag((*Param)->getSourceRange().getBegin(),
12939            diag::err_literal_operator_param)
12940           << SecondParamType << Context.getSizeType()
12941           << (*Param)->getSourceRange();
12942       return true;
12943     }
12944   } else {
12945     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
12946     return true;
12947   }
12948
12949   // Parameters are good.
12950
12951   // A parameter-declaration-clause containing a default argument is not
12952   // equivalent to any of the permitted forms.
12953   for (auto Param : FnDecl->parameters()) {
12954     if (Param->hasDefaultArg()) {
12955       Diag(Param->getDefaultArgRange().getBegin(),
12956            diag::err_literal_operator_default_argument)
12957         << Param->getDefaultArgRange();
12958       break;
12959     }
12960   }
12961
12962   StringRef LiteralName
12963     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12964   if (LiteralName[0] != '_') {
12965     // C++11 [usrlit.suffix]p1:
12966     //   Literal suffix identifiers that do not start with an underscore
12967     //   are reserved for future standardization.
12968     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
12969       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
12970   }
12971
12972   return false;
12973 }
12974
12975 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12976 /// linkage specification, including the language and (if present)
12977 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
12978 /// language string literal. LBraceLoc, if valid, provides the location of
12979 /// the '{' brace. Otherwise, this linkage specification does not
12980 /// have any braces.
12981 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
12982                                            Expr *LangStr,
12983                                            SourceLocation LBraceLoc) {
12984   StringLiteral *Lit = cast<StringLiteral>(LangStr);
12985   if (!Lit->isAscii()) {
12986     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12987       << LangStr->getSourceRange();
12988     return nullptr;
12989   }
12990
12991   StringRef Lang = Lit->getString();
12992   LinkageSpecDecl::LanguageIDs Language;
12993   if (Lang == "C")
12994     Language = LinkageSpecDecl::lang_c;
12995   else if (Lang == "C++")
12996     Language = LinkageSpecDecl::lang_cxx;
12997   else {
12998     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12999       << LangStr->getSourceRange();
13000     return nullptr;
13001   }
13002
13003   // FIXME: Add all the various semantics of linkage specifications
13004
13005   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13006                                                LangStr->getExprLoc(), Language,
13007                                                LBraceLoc.isValid());
13008   CurContext->addDecl(D);
13009   PushDeclContext(S, D);
13010   return D;
13011 }
13012
13013 /// ActOnFinishLinkageSpecification - Complete the definition of
13014 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13015 /// valid, it's the position of the closing '}' brace in a linkage
13016 /// specification that uses braces.
13017 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13018                                             Decl *LinkageSpec,
13019                                             SourceLocation RBraceLoc) {
13020   if (RBraceLoc.isValid()) {
13021     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13022     LSDecl->setRBraceLoc(RBraceLoc);
13023   }
13024   PopDeclContext();
13025   return LinkageSpec;
13026 }
13027
13028 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13029                                   AttributeList *AttrList,
13030                                   SourceLocation SemiLoc) {
13031   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13032   // Attribute declarations appertain to empty declaration so we handle
13033   // them here.
13034   if (AttrList)
13035     ProcessDeclAttributeList(S, ED, AttrList);
13036
13037   CurContext->addDecl(ED);
13038   return ED;
13039 }
13040
13041 /// \brief Perform semantic analysis for the variable declaration that
13042 /// occurs within a C++ catch clause, returning the newly-created
13043 /// variable.
13044 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13045                                          TypeSourceInfo *TInfo,
13046                                          SourceLocation StartLoc,
13047                                          SourceLocation Loc,
13048                                          IdentifierInfo *Name) {
13049   bool Invalid = false;
13050   QualType ExDeclType = TInfo->getType();
13051   
13052   // Arrays and functions decay.
13053   if (ExDeclType->isArrayType())
13054     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13055   else if (ExDeclType->isFunctionType())
13056     ExDeclType = Context.getPointerType(ExDeclType);
13057
13058   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13059   // The exception-declaration shall not denote a pointer or reference to an
13060   // incomplete type, other than [cv] void*.
13061   // N2844 forbids rvalue references.
13062   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13063     Diag(Loc, diag::err_catch_rvalue_ref);
13064     Invalid = true;
13065   }
13066
13067   if (ExDeclType->isVariablyModifiedType()) {
13068     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13069     Invalid = true;
13070   }
13071
13072   QualType BaseType = ExDeclType;
13073   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13074   unsigned DK = diag::err_catch_incomplete;
13075   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13076     BaseType = Ptr->getPointeeType();
13077     Mode = 1;
13078     DK = diag::err_catch_incomplete_ptr;
13079   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13080     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13081     BaseType = Ref->getPointeeType();
13082     Mode = 2;
13083     DK = diag::err_catch_incomplete_ref;
13084   }
13085   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13086       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13087     Invalid = true;
13088
13089   if (!Invalid && !ExDeclType->isDependentType() &&
13090       RequireNonAbstractType(Loc, ExDeclType,
13091                              diag::err_abstract_type_in_decl,
13092                              AbstractVariableType))
13093     Invalid = true;
13094
13095   // Only the non-fragile NeXT runtime currently supports C++ catches
13096   // of ObjC types, and no runtime supports catching ObjC types by value.
13097   if (!Invalid && getLangOpts().ObjC1) {
13098     QualType T = ExDeclType;
13099     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13100       T = RT->getPointeeType();
13101
13102     if (T->isObjCObjectType()) {
13103       Diag(Loc, diag::err_objc_object_catch);
13104       Invalid = true;
13105     } else if (T->isObjCObjectPointerType()) {
13106       // FIXME: should this be a test for macosx-fragile specifically?
13107       if (getLangOpts().ObjCRuntime.isFragile())
13108         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13109     }
13110   }
13111
13112   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13113                                     ExDeclType, TInfo, SC_None);
13114   ExDecl->setExceptionVariable(true);
13115   
13116   // In ARC, infer 'retaining' for variables of retainable type.
13117   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13118     Invalid = true;
13119
13120   if (!Invalid && !ExDeclType->isDependentType()) {
13121     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13122       // Insulate this from anything else we might currently be parsing.
13123       EnterExpressionEvaluationContext scope(
13124           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13125
13126       // C++ [except.handle]p16:
13127       //   The object declared in an exception-declaration or, if the
13128       //   exception-declaration does not specify a name, a temporary (12.2) is
13129       //   copy-initialized (8.5) from the exception object. [...]
13130       //   The object is destroyed when the handler exits, after the destruction
13131       //   of any automatic objects initialized within the handler.
13132       //
13133       // We just pretend to initialize the object with itself, then make sure
13134       // it can be destroyed later.
13135       QualType initType = Context.getExceptionObjectType(ExDeclType);
13136
13137       InitializedEntity entity =
13138         InitializedEntity::InitializeVariable(ExDecl);
13139       InitializationKind initKind =
13140         InitializationKind::CreateCopy(Loc, SourceLocation());
13141
13142       Expr *opaqueValue =
13143         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13144       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13145       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13146       if (result.isInvalid())
13147         Invalid = true;
13148       else {
13149         // If the constructor used was non-trivial, set this as the
13150         // "initializer".
13151         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13152         if (!construct->getConstructor()->isTrivial()) {
13153           Expr *init = MaybeCreateExprWithCleanups(construct);
13154           ExDecl->setInit(init);
13155         }
13156         
13157         // And make sure it's destructable.
13158         FinalizeVarWithDestructor(ExDecl, recordType);
13159       }
13160     }
13161   }
13162   
13163   if (Invalid)
13164     ExDecl->setInvalidDecl();
13165
13166   return ExDecl;
13167 }
13168
13169 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13170 /// handler.
13171 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13172   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13173   bool Invalid = D.isInvalidType();
13174
13175   // Check for unexpanded parameter packs.
13176   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13177                                       UPPC_ExceptionType)) {
13178     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 
13179                                              D.getIdentifierLoc());
13180     Invalid = true;
13181   }
13182
13183   IdentifierInfo *II = D.getIdentifier();
13184   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13185                                              LookupOrdinaryName,
13186                                              ForRedeclaration)) {
13187     // The scope should be freshly made just for us. There is just no way
13188     // it contains any previous declaration, except for function parameters in
13189     // a function-try-block's catch statement.
13190     assert(!S->isDeclScope(PrevDecl));
13191     if (isDeclInScope(PrevDecl, CurContext, S)) {
13192       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13193         << D.getIdentifier();
13194       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13195       Invalid = true;
13196     } else if (PrevDecl->isTemplateParameter())
13197       // Maybe we will complain about the shadowed template parameter.
13198       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13199   }
13200
13201   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13202     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13203       << D.getCXXScopeSpec().getRange();
13204     Invalid = true;
13205   }
13206
13207   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13208                                               D.getLocStart(),
13209                                               D.getIdentifierLoc(),
13210                                               D.getIdentifier());
13211   if (Invalid)
13212     ExDecl->setInvalidDecl();
13213
13214   // Add the exception declaration into this scope.
13215   if (II)
13216     PushOnScopeChains(ExDecl, S);
13217   else
13218     CurContext->addDecl(ExDecl);
13219
13220   ProcessDeclAttributes(S, ExDecl, D);
13221   return ExDecl;
13222 }
13223
13224 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13225                                          Expr *AssertExpr,
13226                                          Expr *AssertMessageExpr,
13227                                          SourceLocation RParenLoc) {
13228   StringLiteral *AssertMessage =
13229       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13230
13231   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13232     return nullptr;
13233
13234   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13235                                       AssertMessage, RParenLoc, false);
13236 }
13237
13238 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13239                                          Expr *AssertExpr,
13240                                          StringLiteral *AssertMessage,
13241                                          SourceLocation RParenLoc,
13242                                          bool Failed) {
13243   assert(AssertExpr != nullptr && "Expected non-null condition");
13244   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13245       !Failed) {
13246     // In a static_assert-declaration, the constant-expression shall be a
13247     // constant expression that can be contextually converted to bool.
13248     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13249     if (Converted.isInvalid())
13250       Failed = true;
13251
13252     llvm::APSInt Cond;
13253     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13254           diag::err_static_assert_expression_is_not_constant,
13255           /*AllowFold=*/false).isInvalid())
13256       Failed = true;
13257
13258     if (!Failed && !Cond) {
13259       SmallString<256> MsgBuffer;
13260       llvm::raw_svector_ostream Msg(MsgBuffer);
13261       if (AssertMessage)
13262         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13263       Diag(StaticAssertLoc, diag::err_static_assert_failed)
13264         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13265       Failed = true;
13266     }
13267   }
13268
13269   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13270                                         AssertExpr, AssertMessage, RParenLoc,
13271                                         Failed);
13272
13273   CurContext->addDecl(Decl);
13274   return Decl;
13275 }
13276
13277 /// \brief Perform semantic analysis of the given friend type declaration.
13278 ///
13279 /// \returns A friend declaration that.
13280 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13281                                       SourceLocation FriendLoc,
13282                                       TypeSourceInfo *TSInfo) {
13283   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13284   
13285   QualType T = TSInfo->getType();
13286   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13287   
13288   // C++03 [class.friend]p2:
13289   //   An elaborated-type-specifier shall be used in a friend declaration
13290   //   for a class.*
13291   //
13292   //   * The class-key of the elaborated-type-specifier is required.
13293   if (!CodeSynthesisContexts.empty()) {
13294     // Do not complain about the form of friend template types during any kind
13295     // of code synthesis. For template instantiation, we will have complained
13296     // when the template was defined.
13297   } else {
13298     if (!T->isElaboratedTypeSpecifier()) {
13299       // If we evaluated the type to a record type, suggest putting
13300       // a tag in front.
13301       if (const RecordType *RT = T->getAs<RecordType>()) {
13302         RecordDecl *RD = RT->getDecl();
13303
13304         SmallString<16> InsertionText(" ");
13305         InsertionText += RD->getKindName();
13306
13307         Diag(TypeRange.getBegin(),
13308              getLangOpts().CPlusPlus11 ?
13309                diag::warn_cxx98_compat_unelaborated_friend_type :
13310                diag::ext_unelaborated_friend_type)
13311           << (unsigned) RD->getTagKind()
13312           << T
13313           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13314                                         InsertionText);
13315       } else {
13316         Diag(FriendLoc,
13317              getLangOpts().CPlusPlus11 ?
13318                diag::warn_cxx98_compat_nonclass_type_friend :
13319                diag::ext_nonclass_type_friend)
13320           << T
13321           << TypeRange;
13322       }
13323     } else if (T->getAs<EnumType>()) {
13324       Diag(FriendLoc,
13325            getLangOpts().CPlusPlus11 ?
13326              diag::warn_cxx98_compat_enum_friend :
13327              diag::ext_enum_friend)
13328         << T
13329         << TypeRange;
13330     }
13331   
13332     // C++11 [class.friend]p3:
13333     //   A friend declaration that does not declare a function shall have one
13334     //   of the following forms:
13335     //     friend elaborated-type-specifier ;
13336     //     friend simple-type-specifier ;
13337     //     friend typename-specifier ;
13338     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13339       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13340   }
13341
13342   //   If the type specifier in a friend declaration designates a (possibly
13343   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13344   //   the friend declaration is ignored.
13345   return FriendDecl::Create(Context, CurContext,
13346                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
13347                             FriendLoc);
13348 }
13349
13350 /// Handle a friend tag declaration where the scope specifier was
13351 /// templated.
13352 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13353                                     unsigned TagSpec, SourceLocation TagLoc,
13354                                     CXXScopeSpec &SS,
13355                                     IdentifierInfo *Name,
13356                                     SourceLocation NameLoc,
13357                                     AttributeList *Attr,
13358                                     MultiTemplateParamsArg TempParamLists) {
13359   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13360
13361   bool IsMemberSpecialization = false;
13362   bool Invalid = false;
13363
13364   if (TemplateParameterList *TemplateParams =
13365           MatchTemplateParametersToScopeSpecifier(
13366               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13367               IsMemberSpecialization, Invalid)) {
13368     if (TemplateParams->size() > 0) {
13369       // This is a declaration of a class template.
13370       if (Invalid)
13371         return nullptr;
13372
13373       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13374                                 NameLoc, Attr, TemplateParams, AS_public,
13375                                 /*ModulePrivateLoc=*/SourceLocation(),
13376                                 FriendLoc, TempParamLists.size() - 1,
13377                                 TempParamLists.data()).get();
13378     } else {
13379       // The "template<>" header is extraneous.
13380       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13381         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13382       IsMemberSpecialization = true;
13383     }
13384   }
13385
13386   if (Invalid) return nullptr;
13387
13388   bool isAllExplicitSpecializations = true;
13389   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13390     if (TempParamLists[I]->size()) {
13391       isAllExplicitSpecializations = false;
13392       break;
13393     }
13394   }
13395
13396   // FIXME: don't ignore attributes.
13397
13398   // If it's explicit specializations all the way down, just forget
13399   // about the template header and build an appropriate non-templated
13400   // friend.  TODO: for source fidelity, remember the headers.
13401   if (isAllExplicitSpecializations) {
13402     if (SS.isEmpty()) {
13403       bool Owned = false;
13404       bool IsDependent = false;
13405       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13406                       Attr, AS_public,
13407                       /*ModulePrivateLoc=*/SourceLocation(),
13408                       MultiTemplateParamsArg(), Owned, IsDependent,
13409                       /*ScopedEnumKWLoc=*/SourceLocation(),
13410                       /*ScopedEnumUsesClassTag=*/false,
13411                       /*UnderlyingType=*/TypeResult(),
13412                       /*IsTypeSpecifier=*/false);
13413     }
13414
13415     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13416     ElaboratedTypeKeyword Keyword
13417       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13418     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13419                                    *Name, NameLoc);
13420     if (T.isNull())
13421       return nullptr;
13422
13423     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13424     if (isa<DependentNameType>(T)) {
13425       DependentNameTypeLoc TL =
13426           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13427       TL.setElaboratedKeywordLoc(TagLoc);
13428       TL.setQualifierLoc(QualifierLoc);
13429       TL.setNameLoc(NameLoc);
13430     } else {
13431       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13432       TL.setElaboratedKeywordLoc(TagLoc);
13433       TL.setQualifierLoc(QualifierLoc);
13434       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13435     }
13436
13437     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13438                                             TSI, FriendLoc, TempParamLists);
13439     Friend->setAccess(AS_public);
13440     CurContext->addDecl(Friend);
13441     return Friend;
13442   }
13443   
13444   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13445   
13446
13447
13448   // Handle the case of a templated-scope friend class.  e.g.
13449   //   template <class T> class A<T>::B;
13450   // FIXME: we don't support these right now.
13451   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13452     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13453   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13454   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13455   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13456   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13457   TL.setElaboratedKeywordLoc(TagLoc);
13458   TL.setQualifierLoc(SS.getWithLocInContext(Context));
13459   TL.setNameLoc(NameLoc);
13460
13461   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13462                                           TSI, FriendLoc, TempParamLists);
13463   Friend->setAccess(AS_public);
13464   Friend->setUnsupportedFriend(true);
13465   CurContext->addDecl(Friend);
13466   return Friend;
13467 }
13468
13469
13470 /// Handle a friend type declaration.  This works in tandem with
13471 /// ActOnTag.
13472 ///
13473 /// Notes on friend class templates:
13474 ///
13475 /// We generally treat friend class declarations as if they were
13476 /// declaring a class.  So, for example, the elaborated type specifier
13477 /// in a friend declaration is required to obey the restrictions of a
13478 /// class-head (i.e. no typedefs in the scope chain), template
13479 /// parameters are required to match up with simple template-ids, &c.
13480 /// However, unlike when declaring a template specialization, it's
13481 /// okay to refer to a template specialization without an empty
13482 /// template parameter declaration, e.g.
13483 ///   friend class A<T>::B<unsigned>;
13484 /// We permit this as a special case; if there are any template
13485 /// parameters present at all, require proper matching, i.e.
13486 ///   template <> template \<class T> friend class A<int>::B;
13487 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
13488                                 MultiTemplateParamsArg TempParams) {
13489   SourceLocation Loc = DS.getLocStart();
13490
13491   assert(DS.isFriendSpecified());
13492   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13493
13494   // Try to convert the decl specifier to a type.  This works for
13495   // friend templates because ActOnTag never produces a ClassTemplateDecl
13496   // for a TUK_Friend.
13497   Declarator TheDeclarator(DS, Declarator::MemberContext);
13498   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13499   QualType T = TSI->getType();
13500   if (TheDeclarator.isInvalidType())
13501     return nullptr;
13502
13503   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
13504     return nullptr;
13505
13506   // This is definitely an error in C++98.  It's probably meant to
13507   // be forbidden in C++0x, too, but the specification is just
13508   // poorly written.
13509   //
13510   // The problem is with declarations like the following:
13511   //   template <T> friend A<T>::foo;
13512   // where deciding whether a class C is a friend or not now hinges
13513   // on whether there exists an instantiation of A that causes
13514   // 'foo' to equal C.  There are restrictions on class-heads
13515   // (which we declare (by fiat) elaborated friend declarations to
13516   // be) that makes this tractable.
13517   //
13518   // FIXME: handle "template <> friend class A<T>;", which
13519   // is possibly well-formed?  Who even knows?
13520   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
13521     Diag(Loc, diag::err_tagless_friend_type_template)
13522       << DS.getSourceRange();
13523     return nullptr;
13524   }
13525   
13526   // C++98 [class.friend]p1: A friend of a class is a function
13527   //   or class that is not a member of the class . . .
13528   // This is fixed in DR77, which just barely didn't make the C++03
13529   // deadline.  It's also a very silly restriction that seriously
13530   // affects inner classes and which nobody else seems to implement;
13531   // thus we never diagnose it, not even in -pedantic.
13532   //
13533   // But note that we could warn about it: it's always useless to
13534   // friend one of your own members (it's not, however, worthless to
13535   // friend a member of an arbitrary specialization of your template).
13536
13537   Decl *D;
13538   if (!TempParams.empty())
13539     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
13540                                    TempParams,
13541                                    TSI,
13542                                    DS.getFriendSpecLoc());
13543   else
13544     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
13545   
13546   if (!D)
13547     return nullptr;
13548
13549   D->setAccess(AS_public);
13550   CurContext->addDecl(D);
13551
13552   return D;
13553 }
13554
13555 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13556                                         MultiTemplateParamsArg TemplateParams) {
13557   const DeclSpec &DS = D.getDeclSpec();
13558
13559   assert(DS.isFriendSpecified());
13560   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13561
13562   SourceLocation Loc = D.getIdentifierLoc();
13563   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13564
13565   // C++ [class.friend]p1
13566   //   A friend of a class is a function or class....
13567   // Note that this sees through typedefs, which is intended.
13568   // It *doesn't* see through dependent types, which is correct
13569   // according to [temp.arg.type]p3:
13570   //   If a declaration acquires a function type through a
13571   //   type dependent on a template-parameter and this causes
13572   //   a declaration that does not use the syntactic form of a
13573   //   function declarator to have a function type, the program
13574   //   is ill-formed.
13575   if (!TInfo->getType()->isFunctionType()) {
13576     Diag(Loc, diag::err_unexpected_friend);
13577
13578     // It might be worthwhile to try to recover by creating an
13579     // appropriate declaration.
13580     return nullptr;
13581   }
13582
13583   // C++ [namespace.memdef]p3
13584   //  - If a friend declaration in a non-local class first declares a
13585   //    class or function, the friend class or function is a member
13586   //    of the innermost enclosing namespace.
13587   //  - The name of the friend is not found by simple name lookup
13588   //    until a matching declaration is provided in that namespace
13589   //    scope (either before or after the class declaration granting
13590   //    friendship).
13591   //  - If a friend function is called, its name may be found by the
13592   //    name lookup that considers functions from namespaces and
13593   //    classes associated with the types of the function arguments.
13594   //  - When looking for a prior declaration of a class or a function
13595   //    declared as a friend, scopes outside the innermost enclosing
13596   //    namespace scope are not considered.
13597
13598   CXXScopeSpec &SS = D.getCXXScopeSpec();
13599   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13600   DeclarationName Name = NameInfo.getName();
13601   assert(Name);
13602
13603   // Check for unexpanded parameter packs.
13604   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13605       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13606       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
13607     return nullptr;
13608
13609   // The context we found the declaration in, or in which we should
13610   // create the declaration.
13611   DeclContext *DC;
13612   Scope *DCScope = S;
13613   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13614                         ForRedeclaration);
13615
13616   // There are five cases here.
13617   //   - There's no scope specifier and we're in a local class. Only look
13618   //     for functions declared in the immediately-enclosing block scope.
13619   // We recover from invalid scope qualifiers as if they just weren't there.
13620   FunctionDecl *FunctionContainingLocalClass = nullptr;
13621   if ((SS.isInvalid() || !SS.isSet()) &&
13622       (FunctionContainingLocalClass =
13623            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13624     // C++11 [class.friend]p11:
13625     //   If a friend declaration appears in a local class and the name
13626     //   specified is an unqualified name, a prior declaration is
13627     //   looked up without considering scopes that are outside the
13628     //   innermost enclosing non-class scope. For a friend function
13629     //   declaration, if there is no prior declaration, the program is
13630     //   ill-formed.
13631
13632     // Find the innermost enclosing non-class scope. This is the block
13633     // scope containing the local class definition (or for a nested class,
13634     // the outer local class).
13635     DCScope = S->getFnParent();
13636
13637     // Look up the function name in the scope.
13638     Previous.clear(LookupLocalFriendName);
13639     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13640
13641     if (!Previous.empty()) {
13642       // All possible previous declarations must have the same context:
13643       // either they were declared at block scope or they are members of
13644       // one of the enclosing local classes.
13645       DC = Previous.getRepresentativeDecl()->getDeclContext();
13646     } else {
13647       // This is ill-formed, but provide the context that we would have
13648       // declared the function in, if we were permitted to, for error recovery.
13649       DC = FunctionContainingLocalClass;
13650     }
13651     adjustContextForLocalExternDecl(DC);
13652
13653     // C++ [class.friend]p6:
13654     //   A function can be defined in a friend declaration of a class if and
13655     //   only if the class is a non-local class (9.8), the function name is
13656     //   unqualified, and the function has namespace scope.
13657     if (D.isFunctionDefinition()) {
13658       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13659     }
13660
13661   //   - There's no scope specifier, in which case we just go to the
13662   //     appropriate scope and look for a function or function template
13663   //     there as appropriate.
13664   } else if (SS.isInvalid() || !SS.isSet()) {
13665     // C++11 [namespace.memdef]p3:
13666     //   If the name in a friend declaration is neither qualified nor
13667     //   a template-id and the declaration is a function or an
13668     //   elaborated-type-specifier, the lookup to determine whether
13669     //   the entity has been previously declared shall not consider
13670     //   any scopes outside the innermost enclosing namespace.
13671     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
13672
13673     // Find the appropriate context according to the above.
13674     DC = CurContext;
13675
13676     // Skip class contexts.  If someone can cite chapter and verse
13677     // for this behavior, that would be nice --- it's what GCC and
13678     // EDG do, and it seems like a reasonable intent, but the spec
13679     // really only says that checks for unqualified existing
13680     // declarations should stop at the nearest enclosing namespace,
13681     // not that they should only consider the nearest enclosing
13682     // namespace.
13683     while (DC->isRecord())
13684       DC = DC->getParent();
13685
13686     DeclContext *LookupDC = DC;
13687     while (LookupDC->isTransparentContext())
13688       LookupDC = LookupDC->getParent();
13689
13690     while (true) {
13691       LookupQualifiedName(Previous, LookupDC);
13692
13693       if (!Previous.empty()) {
13694         DC = LookupDC;
13695         break;
13696       }
13697
13698       if (isTemplateId) {
13699         if (isa<TranslationUnitDecl>(LookupDC)) break;
13700       } else {
13701         if (LookupDC->isFileContext()) break;
13702       }
13703       LookupDC = LookupDC->getParent();
13704     }
13705
13706     DCScope = getScopeForDeclContext(S, DC);
13707
13708   //   - There's a non-dependent scope specifier, in which case we
13709   //     compute it and do a previous lookup there for a function
13710   //     or function template.
13711   } else if (!SS.getScopeRep()->isDependent()) {
13712     DC = computeDeclContext(SS);
13713     if (!DC) return nullptr;
13714
13715     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
13716
13717     LookupQualifiedName(Previous, DC);
13718
13719     // Ignore things found implicitly in the wrong scope.
13720     // TODO: better diagnostics for this case.  Suggesting the right
13721     // qualified scope would be nice...
13722     LookupResult::Filter F = Previous.makeFilter();
13723     while (F.hasNext()) {
13724       NamedDecl *D = F.next();
13725       if (!DC->InEnclosingNamespaceSetOf(
13726               D->getDeclContext()->getRedeclContext()))
13727         F.erase();
13728     }
13729     F.done();
13730
13731     if (Previous.empty()) {
13732       D.setInvalidType();
13733       Diag(Loc, diag::err_qualified_friend_not_found)
13734           << Name << TInfo->getType();
13735       return nullptr;
13736     }
13737
13738     // C++ [class.friend]p1: A friend of a class is a function or
13739     //   class that is not a member of the class . . .
13740     if (DC->Equals(CurContext))
13741       Diag(DS.getFriendSpecLoc(),
13742            getLangOpts().CPlusPlus11 ?
13743              diag::warn_cxx98_compat_friend_is_member :
13744              diag::err_friend_is_member);
13745     
13746     if (D.isFunctionDefinition()) {
13747       // C++ [class.friend]p6:
13748       //   A function can be defined in a friend declaration of a class if and 
13749       //   only if the class is a non-local class (9.8), the function name is
13750       //   unqualified, and the function has namespace scope.
13751       SemaDiagnosticBuilder DB
13752         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13753       
13754       DB << SS.getScopeRep();
13755       if (DC->isFileContext())
13756         DB << FixItHint::CreateRemoval(SS.getRange());
13757       SS.clear();
13758     }
13759
13760   //   - There's a scope specifier that does not match any template
13761   //     parameter lists, in which case we use some arbitrary context,
13762   //     create a method or method template, and wait for instantiation.
13763   //   - There's a scope specifier that does match some template
13764   //     parameter lists, which we don't handle right now.
13765   } else {
13766     if (D.isFunctionDefinition()) {
13767       // C++ [class.friend]p6:
13768       //   A function can be defined in a friend declaration of a class if and 
13769       //   only if the class is a non-local class (9.8), the function name is
13770       //   unqualified, and the function has namespace scope.
13771       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13772         << SS.getScopeRep();
13773     }
13774     
13775     DC = CurContext;
13776     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
13777   }
13778
13779   if (!DC->isRecord()) {
13780     int DiagArg = -1;
13781     switch (D.getName().getKind()) {
13782     case UnqualifiedId::IK_ConstructorTemplateId:
13783     case UnqualifiedId::IK_ConstructorName:
13784       DiagArg = 0;
13785       break;
13786     case UnqualifiedId::IK_DestructorName:
13787       DiagArg = 1;
13788       break;
13789     case UnqualifiedId::IK_ConversionFunctionId:
13790       DiagArg = 2;
13791       break;
13792     case UnqualifiedId::IK_DeductionGuideName:
13793       DiagArg = 3;
13794       break;
13795     case UnqualifiedId::IK_Identifier:
13796     case UnqualifiedId::IK_ImplicitSelfParam:
13797     case UnqualifiedId::IK_LiteralOperatorId:
13798     case UnqualifiedId::IK_OperatorFunctionId:
13799     case UnqualifiedId::IK_TemplateId:
13800       break;
13801     }
13802     // This implies that it has to be an operator or function.
13803     if (DiagArg >= 0) {
13804       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
13805       return nullptr;
13806     }
13807   }
13808
13809   // FIXME: This is an egregious hack to cope with cases where the scope stack
13810   // does not contain the declaration context, i.e., in an out-of-line 
13811   // definition of a class.
13812   Scope FakeDCScope(S, Scope::DeclScope, Diags);
13813   if (!DCScope) {
13814     FakeDCScope.setEntity(DC);
13815     DCScope = &FakeDCScope;
13816   }
13817
13818   bool AddToScope = true;
13819   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
13820                                           TemplateParams, AddToScope);
13821   if (!ND) return nullptr;
13822
13823   assert(ND->getLexicalDeclContext() == CurContext);
13824
13825   // If we performed typo correction, we might have added a scope specifier
13826   // and changed the decl context.
13827   DC = ND->getDeclContext();
13828
13829   // Add the function declaration to the appropriate lookup tables,
13830   // adjusting the redeclarations list as necessary.  We don't
13831   // want to do this yet if the friending class is dependent.
13832   //
13833   // Also update the scope-based lookup if the target context's
13834   // lookup context is in lexical scope.
13835   if (!CurContext->isDependentContext()) {
13836     DC = DC->getRedeclContext();
13837     DC->makeDeclVisibleInContext(ND);
13838     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13839       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
13840   }
13841
13842   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
13843                                        D.getIdentifierLoc(), ND,
13844                                        DS.getFriendSpecLoc());
13845   FrD->setAccess(AS_public);
13846   CurContext->addDecl(FrD);
13847
13848   if (ND->isInvalidDecl()) {
13849     FrD->setInvalidDecl();
13850   } else {
13851     if (DC->isRecord()) CheckFriendAccess(ND);
13852
13853     FunctionDecl *FD;
13854     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13855       FD = FTD->getTemplatedDecl();
13856     else
13857       FD = cast<FunctionDecl>(ND);
13858
13859     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13860     // default argument expression, that declaration shall be a definition
13861     // and shall be the only declaration of the function or function
13862     // template in the translation unit.
13863     if (functionDeclHasDefaultArgument(FD)) {
13864       // We can't look at FD->getPreviousDecl() because it may not have been set
13865       // if we're in a dependent context. If the function is known to be a
13866       // redeclaration, we will have narrowed Previous down to the right decl.
13867       if (D.isRedeclaration()) {
13868         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
13869         Diag(Previous.getRepresentativeDecl()->getLocation(),
13870              diag::note_previous_declaration);
13871       } else if (!D.isFunctionDefinition())
13872         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13873     }
13874
13875     // Mark templated-scope function declarations as unsupported.
13876     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13877       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13878         << SS.getScopeRep() << SS.getRange()
13879         << cast<CXXRecordDecl>(CurContext);
13880       FrD->setUnsupportedFriend(true);
13881     }
13882   }
13883
13884   return ND;
13885 }
13886
13887 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13888   AdjustDeclIfTemplate(Dcl);
13889
13890   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
13891   if (!Fn) {
13892     Diag(DelLoc, diag::err_deleted_non_function);
13893     return;
13894   }
13895
13896   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
13897     // Don't consider the implicit declaration we generate for explicit
13898     // specializations. FIXME: Do not generate these implicit declarations.
13899     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13900          Prev->getPreviousDecl()) &&
13901         !Prev->isDefined()) {
13902       Diag(DelLoc, diag::err_deleted_decl_not_first);
13903       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13904            Prev->isImplicit() ? diag::note_previous_implicit_declaration
13905                               : diag::note_previous_declaration);
13906     }
13907     // If the declaration wasn't the first, we delete the function anyway for
13908     // recovery.
13909     Fn = Fn->getCanonicalDecl();
13910   }
13911
13912   // dllimport/dllexport cannot be deleted.
13913   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13914     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13915     Fn->setInvalidDecl();
13916   }
13917
13918   if (Fn->isDeleted())
13919     return;
13920
13921   // See if we're deleting a function which is already known to override a
13922   // non-deleted virtual function.
13923   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
13924     bool IssuedDiagnostic = false;
13925     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13926                                         E = MD->end_overridden_methods();
13927          I != E; ++I) {
13928       if (!(*MD->begin_overridden_methods())->isDeleted()) {
13929         if (!IssuedDiagnostic) {
13930           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13931           IssuedDiagnostic = true;
13932         }
13933         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13934       }
13935     }
13936     // If this function was implicitly deleted because it was defaulted,
13937     // explain why it was deleted.
13938     if (IssuedDiagnostic && MD->isDefaulted())
13939       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
13940                                 /*Diagnose*/true);
13941   }
13942
13943   // C++11 [basic.start.main]p3:
13944   //   A program that defines main as deleted [...] is ill-formed.
13945   if (Fn->isMain())
13946     Diag(DelLoc, diag::err_deleted_main);
13947
13948   // C++11 [dcl.fct.def.delete]p4:
13949   //  A deleted function is implicitly inline.
13950   Fn->setImplicitlyInline();
13951   Fn->setDeletedAsWritten();
13952 }
13953
13954 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
13955   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
13956
13957   if (MD) {
13958     if (MD->getParent()->isDependentType()) {
13959       MD->setDefaulted();
13960       MD->setExplicitlyDefaulted();
13961       return;
13962     }
13963
13964     CXXSpecialMember Member = getSpecialMember(MD);
13965     if (Member == CXXInvalid) {
13966       if (!MD->isInvalidDecl())
13967         Diag(DefaultLoc, diag::err_default_special_members);
13968       return;
13969     }
13970
13971     MD->setDefaulted();
13972     MD->setExplicitlyDefaulted();
13973
13974     // If this definition appears within the record, do the checking when
13975     // the record is complete.
13976     const FunctionDecl *Primary = MD;
13977     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
13978       // Ask the template instantiation pattern that actually had the
13979       // '= default' on it.
13980       Primary = Pattern;
13981
13982     // If the method was defaulted on its first declaration, we will have
13983     // already performed the checking in CheckCompletedCXXClass. Such a
13984     // declaration doesn't trigger an implicit definition.
13985     if (Primary->getCanonicalDecl()->isDefaulted())
13986       return;
13987
13988     CheckExplicitlyDefaultedSpecialMember(MD);
13989
13990     if (!MD->isInvalidDecl())
13991       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
13992   } else {
13993     Diag(DefaultLoc, diag::err_default_special_members);
13994   }
13995 }
13996
13997 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
13998   for (Stmt *SubStmt : S->children()) {
13999     if (!SubStmt)
14000       continue;
14001     if (isa<ReturnStmt>(SubStmt))
14002       Self.Diag(SubStmt->getLocStart(),
14003            diag::err_return_in_constructor_handler);
14004     if (!isa<Expr>(SubStmt))
14005       SearchForReturnInStmt(Self, SubStmt);
14006   }
14007 }
14008
14009 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14010   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14011     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14012     SearchForReturnInStmt(*this, Handler);
14013   }
14014 }
14015
14016 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14017                                              const CXXMethodDecl *Old) {
14018   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
14019   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
14020
14021   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14022
14023   // If the calling conventions match, everything is fine
14024   if (NewCC == OldCC)
14025     return false;
14026
14027   // If the calling conventions mismatch because the new function is static,
14028   // suppress the calling convention mismatch error; the error about static
14029   // function override (err_static_overrides_virtual from
14030   // Sema::CheckFunctionDeclaration) is more clear.
14031   if (New->getStorageClass() == SC_Static)
14032     return false;
14033
14034   Diag(New->getLocation(),
14035        diag::err_conflicting_overriding_cc_attributes)
14036     << New->getDeclName() << New->getType() << Old->getType();
14037   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14038   return true;
14039 }
14040
14041 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14042                                              const CXXMethodDecl *Old) {
14043   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14044   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14045
14046   if (Context.hasSameType(NewTy, OldTy) ||
14047       NewTy->isDependentType() || OldTy->isDependentType())
14048     return false;
14049
14050   // Check if the return types are covariant
14051   QualType NewClassTy, OldClassTy;
14052
14053   /// Both types must be pointers or references to classes.
14054   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14055     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14056       NewClassTy = NewPT->getPointeeType();
14057       OldClassTy = OldPT->getPointeeType();
14058     }
14059   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14060     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14061       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14062         NewClassTy = NewRT->getPointeeType();
14063         OldClassTy = OldRT->getPointeeType();
14064       }
14065     }
14066   }
14067
14068   // The return types aren't either both pointers or references to a class type.
14069   if (NewClassTy.isNull()) {
14070     Diag(New->getLocation(),
14071          diag::err_different_return_type_for_overriding_virtual_function)
14072         << New->getDeclName() << NewTy << OldTy
14073         << New->getReturnTypeSourceRange();
14074     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14075         << Old->getReturnTypeSourceRange();
14076
14077     return true;
14078   }
14079
14080   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14081     // C++14 [class.virtual]p8:
14082     //   If the class type in the covariant return type of D::f differs from
14083     //   that of B::f, the class type in the return type of D::f shall be
14084     //   complete at the point of declaration of D::f or shall be the class
14085     //   type D.
14086     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14087       if (!RT->isBeingDefined() &&
14088           RequireCompleteType(New->getLocation(), NewClassTy,
14089                               diag::err_covariant_return_incomplete,
14090                               New->getDeclName()))
14091         return true;
14092     }
14093
14094     // Check if the new class derives from the old class.
14095     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14096       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14097           << New->getDeclName() << NewTy << OldTy
14098           << New->getReturnTypeSourceRange();
14099       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14100           << Old->getReturnTypeSourceRange();
14101       return true;
14102     }
14103
14104     // Check if we the conversion from derived to base is valid.
14105     if (CheckDerivedToBaseConversion(
14106             NewClassTy, OldClassTy,
14107             diag::err_covariant_return_inaccessible_base,
14108             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14109             New->getLocation(), New->getReturnTypeSourceRange(),
14110             New->getDeclName(), nullptr)) {
14111       // FIXME: this note won't trigger for delayed access control
14112       // diagnostics, and it's impossible to get an undelayed error
14113       // here from access control during the original parse because
14114       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14115       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14116           << Old->getReturnTypeSourceRange();
14117       return true;
14118     }
14119   }
14120
14121   // The qualifiers of the return types must be the same.
14122   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14123     Diag(New->getLocation(),
14124          diag::err_covariant_return_type_different_qualifications)
14125         << New->getDeclName() << NewTy << OldTy
14126         << New->getReturnTypeSourceRange();
14127     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14128         << Old->getReturnTypeSourceRange();
14129     return true;
14130   }
14131
14132
14133   // The new class type must have the same or less qualifiers as the old type.
14134   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14135     Diag(New->getLocation(),
14136          diag::err_covariant_return_type_class_type_more_qualified)
14137         << New->getDeclName() << NewTy << OldTy
14138         << New->getReturnTypeSourceRange();
14139     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14140         << Old->getReturnTypeSourceRange();
14141     return true;
14142   }
14143
14144   return false;
14145 }
14146
14147 /// \brief Mark the given method pure.
14148 ///
14149 /// \param Method the method to be marked pure.
14150 ///
14151 /// \param InitRange the source range that covers the "0" initializer.
14152 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14153   SourceLocation EndLoc = InitRange.getEnd();
14154   if (EndLoc.isValid())
14155     Method->setRangeEnd(EndLoc);
14156
14157   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14158     Method->setPure();
14159     return false;
14160   }
14161
14162   if (!Method->isInvalidDecl())
14163     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14164       << Method->getDeclName() << InitRange;
14165   return true;
14166 }
14167
14168 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14169   if (D->getFriendObjectKind())
14170     Diag(D->getLocation(), diag::err_pure_friend);
14171   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14172     CheckPureMethod(M, ZeroLoc);
14173   else
14174     Diag(D->getLocation(), diag::err_illegal_initializer);
14175 }
14176
14177 /// \brief Determine whether the given declaration is a static data member.
14178 static bool isStaticDataMember(const Decl *D) {
14179   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14180     return Var->isStaticDataMember();
14181
14182   return false;
14183 }
14184
14185 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
14186 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
14187 /// is a fresh scope pushed for just this purpose.
14188 ///
14189 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14190 /// static data member of class X, names should be looked up in the scope of
14191 /// class X.
14192 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14193   // If there is no declaration, there was an error parsing it.
14194   if (!D || D->isInvalidDecl())
14195     return;
14196
14197   // We will always have a nested name specifier here, but this declaration
14198   // might not be out of line if the specifier names the current namespace:
14199   //   extern int n;
14200   //   int ::n = 0;
14201   if (D->isOutOfLine())
14202     EnterDeclaratorContext(S, D->getDeclContext());
14203
14204   // If we are parsing the initializer for a static data member, push a
14205   // new expression evaluation context that is associated with this static
14206   // data member.
14207   if (isStaticDataMember(D))
14208     PushExpressionEvaluationContext(
14209         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14210 }
14211
14212 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
14213 /// initializer for the out-of-line declaration 'D'.
14214 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14215   // If there is no declaration, there was an error parsing it.
14216   if (!D || D->isInvalidDecl())
14217     return;
14218
14219   if (isStaticDataMember(D))
14220     PopExpressionEvaluationContext();
14221
14222   if (D->isOutOfLine())
14223     ExitDeclaratorContext(S);
14224 }
14225
14226 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14227 /// C++ if/switch/while/for statement.
14228 /// e.g: "if (int x = f()) {...}"
14229 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14230   // C++ 6.4p2:
14231   // The declarator shall not specify a function or an array.
14232   // The type-specifier-seq shall not contain typedef and shall not declare a
14233   // new class or enumeration.
14234   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14235          "Parser allowed 'typedef' as storage class of condition decl.");
14236
14237   Decl *Dcl = ActOnDeclarator(S, D);
14238   if (!Dcl)
14239     return true;
14240
14241   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14242     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14243       << D.getSourceRange();
14244     return true;
14245   }
14246
14247   return Dcl;
14248 }
14249
14250 void Sema::LoadExternalVTableUses() {
14251   if (!ExternalSource)
14252     return;
14253   
14254   SmallVector<ExternalVTableUse, 4> VTables;
14255   ExternalSource->ReadUsedVTables(VTables);
14256   SmallVector<VTableUse, 4> NewUses;
14257   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14258     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14259       = VTablesUsed.find(VTables[I].Record);
14260     // Even if a definition wasn't required before, it may be required now.
14261     if (Pos != VTablesUsed.end()) {
14262       if (!Pos->second && VTables[I].DefinitionRequired)
14263         Pos->second = true;
14264       continue;
14265     }
14266     
14267     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14268     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14269   }
14270   
14271   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14272 }
14273
14274 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14275                           bool DefinitionRequired) {
14276   // Ignore any vtable uses in unevaluated operands or for classes that do
14277   // not have a vtable.
14278   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14279       CurContext->isDependentContext() || isUnevaluatedContext())
14280     return;
14281
14282   // Try to insert this class into the map.
14283   LoadExternalVTableUses();
14284   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14285   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14286     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14287   if (!Pos.second) {
14288     // If we already had an entry, check to see if we are promoting this vtable
14289     // to require a definition. If so, we need to reappend to the VTableUses
14290     // list, since we may have already processed the first entry.
14291     if (DefinitionRequired && !Pos.first->second) {
14292       Pos.first->second = true;
14293     } else {
14294       // Otherwise, we can early exit.
14295       return;
14296     }
14297   } else {
14298     // The Microsoft ABI requires that we perform the destructor body
14299     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14300     // the deleting destructor is emitted with the vtable, not with the
14301     // destructor definition as in the Itanium ABI.
14302     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14303       CXXDestructorDecl *DD = Class->getDestructor();
14304       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14305         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14306           // If this is an out-of-line declaration, marking it referenced will
14307           // not do anything. Manually call CheckDestructor to look up operator
14308           // delete().
14309           ContextRAII SavedContext(*this, DD);
14310           CheckDestructor(DD);
14311         } else {
14312           MarkFunctionReferenced(Loc, Class->getDestructor());
14313         }
14314       }
14315     }
14316   }
14317
14318   // Local classes need to have their virtual members marked
14319   // immediately. For all other classes, we mark their virtual members
14320   // at the end of the translation unit.
14321   if (Class->isLocalClass())
14322     MarkVirtualMembersReferenced(Loc, Class);
14323   else
14324     VTableUses.push_back(std::make_pair(Class, Loc));
14325 }
14326
14327 bool Sema::DefineUsedVTables() {
14328   LoadExternalVTableUses();
14329   if (VTableUses.empty())
14330     return false;
14331
14332   // Note: The VTableUses vector could grow as a result of marking
14333   // the members of a class as "used", so we check the size each
14334   // time through the loop and prefer indices (which are stable) to
14335   // iterators (which are not).
14336   bool DefinedAnything = false;
14337   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14338     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14339     if (!Class)
14340       continue;
14341     TemplateSpecializationKind ClassTSK =
14342         Class->getTemplateSpecializationKind();
14343
14344     SourceLocation Loc = VTableUses[I].second;
14345
14346     bool DefineVTable = true;
14347
14348     // If this class has a key function, but that key function is
14349     // defined in another translation unit, we don't need to emit the
14350     // vtable even though we're using it.
14351     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14352     if (KeyFunction && !KeyFunction->hasBody()) {
14353       // The key function is in another translation unit.
14354       DefineVTable = false;
14355       TemplateSpecializationKind TSK =
14356           KeyFunction->getTemplateSpecializationKind();
14357       assert(TSK != TSK_ExplicitInstantiationDefinition &&
14358              TSK != TSK_ImplicitInstantiation &&
14359              "Instantiations don't have key functions");
14360       (void)TSK;
14361     } else if (!KeyFunction) {
14362       // If we have a class with no key function that is the subject
14363       // of an explicit instantiation declaration, suppress the
14364       // vtable; it will live with the explicit instantiation
14365       // definition.
14366       bool IsExplicitInstantiationDeclaration =
14367           ClassTSK == TSK_ExplicitInstantiationDeclaration;
14368       for (auto R : Class->redecls()) {
14369         TemplateSpecializationKind TSK
14370           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14371         if (TSK == TSK_ExplicitInstantiationDeclaration)
14372           IsExplicitInstantiationDeclaration = true;
14373         else if (TSK == TSK_ExplicitInstantiationDefinition) {
14374           IsExplicitInstantiationDeclaration = false;
14375           break;
14376         }
14377       }
14378
14379       if (IsExplicitInstantiationDeclaration)
14380         DefineVTable = false;
14381     }
14382
14383     // The exception specifications for all virtual members may be needed even
14384     // if we are not providing an authoritative form of the vtable in this TU.
14385     // We may choose to emit it available_externally anyway.
14386     if (!DefineVTable) {
14387       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14388       continue;
14389     }
14390
14391     // Mark all of the virtual members of this class as referenced, so
14392     // that we can build a vtable. Then, tell the AST consumer that a
14393     // vtable for this class is required.
14394     DefinedAnything = true;
14395     MarkVirtualMembersReferenced(Loc, Class);
14396     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14397     if (VTablesUsed[Canonical])
14398       Consumer.HandleVTable(Class);
14399
14400     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14401     // no key function or the key function is inlined. Don't warn in C++ ABIs
14402     // that lack key functions, since the user won't be able to make one.
14403     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14404         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
14405       const FunctionDecl *KeyFunctionDef = nullptr;
14406       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14407                            KeyFunctionDef->isInlined())) {
14408         Diag(Class->getLocation(),
14409              ClassTSK == TSK_ExplicitInstantiationDefinition
14410                  ? diag::warn_weak_template_vtable
14411                  : diag::warn_weak_vtable)
14412             << Class;
14413       }
14414     }
14415   }
14416   VTableUses.clear();
14417
14418   return DefinedAnything;
14419 }
14420
14421 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14422                                                  const CXXRecordDecl *RD) {
14423   for (const auto *I : RD->methods())
14424     if (I->isVirtual() && !I->isPure())
14425       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
14426 }
14427
14428 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14429                                         const CXXRecordDecl *RD) {
14430   // Mark all functions which will appear in RD's vtable as used.
14431   CXXFinalOverriderMap FinalOverriders;
14432   RD->getFinalOverriders(FinalOverriders);
14433   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14434                                             E = FinalOverriders.end();
14435        I != E; ++I) {
14436     for (OverridingMethods::const_iterator OI = I->second.begin(),
14437                                            OE = I->second.end();
14438          OI != OE; ++OI) {
14439       assert(OI->second.size() > 0 && "no final overrider");
14440       CXXMethodDecl *Overrider = OI->second.front().Method;
14441
14442       // C++ [basic.def.odr]p2:
14443       //   [...] A virtual member function is used if it is not pure. [...]
14444       if (!Overrider->isPure())
14445         MarkFunctionReferenced(Loc, Overrider);
14446     }
14447   }
14448
14449   // Only classes that have virtual bases need a VTT.
14450   if (RD->getNumVBases() == 0)
14451     return;
14452
14453   for (const auto &I : RD->bases()) {
14454     const CXXRecordDecl *Base =
14455         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
14456     if (Base->getNumVBases() == 0)
14457       continue;
14458     MarkVirtualMembersReferenced(Loc, Base);
14459   }
14460 }
14461
14462 /// SetIvarInitializers - This routine builds initialization ASTs for the
14463 /// Objective-C implementation whose ivars need be initialized.
14464 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
14465   if (!getLangOpts().CPlusPlus)
14466     return;
14467   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
14468     SmallVector<ObjCIvarDecl*, 8> ivars;
14469     CollectIvarsToConstructOrDestruct(OID, ivars);
14470     if (ivars.empty())
14471       return;
14472     SmallVector<CXXCtorInitializer*, 32> AllToInit;
14473     for (unsigned i = 0; i < ivars.size(); i++) {
14474       FieldDecl *Field = ivars[i];
14475       if (Field->isInvalidDecl())
14476         continue;
14477       
14478       CXXCtorInitializer *Member;
14479       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14480       InitializationKind InitKind = 
14481         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
14482
14483       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14484       ExprResult MemberInit =
14485         InitSeq.Perform(*this, InitEntity, InitKind, None);
14486       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
14487       // Note, MemberInit could actually come back empty if no initialization 
14488       // is required (e.g., because it would call a trivial default constructor)
14489       if (!MemberInit.get() || MemberInit.isInvalid())
14490         continue;
14491
14492       Member =
14493         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14494                                          SourceLocation(),
14495                                          MemberInit.getAs<Expr>(),
14496                                          SourceLocation());
14497       AllToInit.push_back(Member);
14498       
14499       // Be sure that the destructor is accessible and is marked as referenced.
14500       if (const RecordType *RecordTy =
14501               Context.getBaseElementType(Field->getType())
14502                   ->getAs<RecordType>()) {
14503         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
14504         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
14505           MarkFunctionReferenced(Field->getLocation(), Destructor);
14506           CheckDestructorAccess(Field->getLocation(), Destructor,
14507                             PDiag(diag::err_access_dtor_ivar)
14508                               << Context.getBaseElementType(Field->getType()));
14509         }
14510       }      
14511     }
14512     ObjCImplementation->setIvarInitializers(Context, 
14513                                             AllToInit.data(), AllToInit.size());
14514   }
14515 }
14516
14517 static
14518 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14519                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14520                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14521                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14522                            Sema &S) {
14523   if (Ctor->isInvalidDecl())
14524     return;
14525
14526   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14527
14528   // Target may not be determinable yet, for instance if this is a dependent
14529   // call in an uninstantiated template.
14530   if (Target) {
14531     const FunctionDecl *FNTarget = nullptr;
14532     (void)Target->hasBody(FNTarget);
14533     Target = const_cast<CXXConstructorDecl*>(
14534       cast_or_null<CXXConstructorDecl>(FNTarget));
14535   }
14536
14537   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14538                      // Avoid dereferencing a null pointer here.
14539                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
14540
14541   if (!Current.insert(Canonical).second)
14542     return;
14543
14544   // We know that beyond here, we aren't chaining into a cycle.
14545   if (!Target || !Target->isDelegatingConstructor() ||
14546       Target->isInvalidDecl() || Valid.count(TCanonical)) {
14547     Valid.insert(Current.begin(), Current.end());
14548     Current.clear();
14549   // We've hit a cycle.
14550   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14551              Current.count(TCanonical)) {
14552     // If we haven't diagnosed this cycle yet, do so now.
14553     if (!Invalid.count(TCanonical)) {
14554       S.Diag((*Ctor->init_begin())->getSourceLocation(),
14555              diag::warn_delegating_ctor_cycle)
14556         << Ctor;
14557
14558       // Don't add a note for a function delegating directly to itself.
14559       if (TCanonical != Canonical)
14560         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14561
14562       CXXConstructorDecl *C = Target;
14563       while (C->getCanonicalDecl() != Canonical) {
14564         const FunctionDecl *FNTarget = nullptr;
14565         (void)C->getTargetConstructor()->hasBody(FNTarget);
14566         assert(FNTarget && "Ctor cycle through bodiless function");
14567
14568         C = const_cast<CXXConstructorDecl*>(
14569           cast<CXXConstructorDecl>(FNTarget));
14570         S.Diag(C->getLocation(), diag::note_which_delegates_to);
14571       }
14572     }
14573
14574     Invalid.insert(Current.begin(), Current.end());
14575     Current.clear();
14576   } else {
14577     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14578   }
14579 }
14580    
14581
14582 void Sema::CheckDelegatingCtorCycles() {
14583   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14584
14585   for (DelegatingCtorDeclsType::iterator
14586          I = DelegatingCtorDecls.begin(ExternalSource),
14587          E = DelegatingCtorDecls.end();
14588        I != E; ++I)
14589     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
14590
14591   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14592                                                          CE = Invalid.end();
14593        CI != CE; ++CI)
14594     (*CI)->setInvalidDecl();
14595 }
14596
14597 namespace {
14598   /// \brief AST visitor that finds references to the 'this' expression.
14599   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14600     Sema &S;
14601     
14602   public:
14603     explicit FindCXXThisExpr(Sema &S) : S(S) { }
14604     
14605     bool VisitCXXThisExpr(CXXThisExpr *E) {
14606       S.Diag(E->getLocation(), diag::err_this_static_member_func)
14607         << E->isImplicit();
14608       return false;
14609     }
14610   };
14611 }
14612
14613 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14614   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14615   if (!TSInfo)
14616     return false;
14617   
14618   TypeLoc TL = TSInfo->getTypeLoc();
14619   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14620   if (!ProtoTL)
14621     return false;
14622   
14623   // C++11 [expr.prim.general]p3:
14624   //   [The expression this] shall not appear before the optional 
14625   //   cv-qualifier-seq and it shall not appear within the declaration of a 
14626   //   static member function (although its type and value category are defined
14627   //   within a static member function as they are within a non-static member
14628   //   function). [ Note: this is because declaration matching does not occur
14629   //  until the complete declarator is known. - end note ]
14630   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14631   FindCXXThisExpr Finder(*this);
14632   
14633   // If the return type came after the cv-qualifier-seq, check it now.
14634   if (Proto->hasTrailingReturn() &&
14635       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
14636     return true;
14637
14638   // Check the exception specification.
14639   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14640     return true;
14641   
14642   return checkThisInStaticMemberFunctionAttributes(Method);
14643 }
14644
14645 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14646   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14647   if (!TSInfo)
14648     return false;
14649   
14650   TypeLoc TL = TSInfo->getTypeLoc();
14651   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14652   if (!ProtoTL)
14653     return false;
14654   
14655   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14656   FindCXXThisExpr Finder(*this);
14657
14658   switch (Proto->getExceptionSpecType()) {
14659   case EST_Unparsed:
14660   case EST_Uninstantiated:
14661   case EST_Unevaluated:
14662   case EST_BasicNoexcept:
14663   case EST_DynamicNone:
14664   case EST_MSAny:
14665   case EST_None:
14666     break;
14667     
14668   case EST_ComputedNoexcept:
14669     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14670       return true;
14671     
14672   case EST_Dynamic:
14673     for (const auto &E : Proto->exceptions()) {
14674       if (!Finder.TraverseType(E))
14675         return true;
14676     }
14677     break;
14678   }
14679
14680   return false;
14681 }
14682
14683 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14684   FindCXXThisExpr Finder(*this);
14685
14686   // Check attributes.
14687   for (const auto *A : Method->attrs()) {
14688     // FIXME: This should be emitted by tblgen.
14689     Expr *Arg = nullptr;
14690     ArrayRef<Expr *> Args;
14691     if (const auto *G = dyn_cast<GuardedByAttr>(A))
14692       Arg = G->getArg();
14693     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
14694       Arg = G->getArg();
14695     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
14696       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
14697     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
14698       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
14699     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
14700       Arg = ETLF->getSuccessValue();
14701       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
14702     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
14703       Arg = STLF->getSuccessValue();
14704       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
14705     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
14706       Arg = LR->getArg();
14707     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
14708       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
14709     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
14710       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14711     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
14712       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14713     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
14714       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14715     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
14716       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14717
14718     if (Arg && !Finder.TraverseStmt(Arg))
14719       return true;
14720     
14721     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14722       if (!Finder.TraverseStmt(Args[I]))
14723         return true;
14724     }
14725   }
14726   
14727   return false;
14728 }
14729
14730 void Sema::checkExceptionSpecification(
14731     bool IsTopLevel, ExceptionSpecificationType EST,
14732     ArrayRef<ParsedType> DynamicExceptions,
14733     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14734     SmallVectorImpl<QualType> &Exceptions,
14735     FunctionProtoType::ExceptionSpecInfo &ESI) {
14736   Exceptions.clear();
14737   ESI.Type = EST;
14738   if (EST == EST_Dynamic) {
14739     Exceptions.reserve(DynamicExceptions.size());
14740     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14741       // FIXME: Preserve type source info.
14742       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14743
14744       if (IsTopLevel) {
14745         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14746         collectUnexpandedParameterPacks(ET, Unexpanded);
14747         if (!Unexpanded.empty()) {
14748           DiagnoseUnexpandedParameterPacks(
14749               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14750               Unexpanded);
14751           continue;
14752         }
14753       }
14754
14755       // Check that the type is valid for an exception spec, and
14756       // drop it if not.
14757       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14758         Exceptions.push_back(ET);
14759     }
14760     ESI.Exceptions = Exceptions;
14761     return;
14762   }
14763
14764   if (EST == EST_ComputedNoexcept) {
14765     // If an error occurred, there's no expression here.
14766     if (NoexceptExpr) {
14767       assert((NoexceptExpr->isTypeDependent() ||
14768               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14769               Context.BoolTy) &&
14770              "Parser should have made sure that the expression is boolean");
14771       if (IsTopLevel && NoexceptExpr &&
14772           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
14773         ESI.Type = EST_BasicNoexcept;
14774         return;
14775       }
14776
14777       if (!NoexceptExpr->isValueDependent())
14778         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
14779                          diag::err_noexcept_needs_constant_expression,
14780                          /*AllowFold*/ false).get();
14781       ESI.NoexceptExpr = NoexceptExpr;
14782     }
14783     return;
14784   }
14785 }
14786
14787 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14788              ExceptionSpecificationType EST,
14789              SourceRange SpecificationRange,
14790              ArrayRef<ParsedType> DynamicExceptions,
14791              ArrayRef<SourceRange> DynamicExceptionRanges,
14792              Expr *NoexceptExpr) {
14793   if (!MethodD)
14794     return;
14795
14796   // Dig out the method we're referring to.
14797   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14798     MethodD = FunTmpl->getTemplatedDecl();
14799
14800   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14801   if (!Method)
14802     return;
14803
14804   // Check the exception specification.
14805   llvm::SmallVector<QualType, 4> Exceptions;
14806   FunctionProtoType::ExceptionSpecInfo ESI;
14807   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14808                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
14809                               ESI);
14810
14811   // Update the exception specification on the function type.
14812   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14813
14814   if (Method->isStatic())
14815     checkThisInStaticMemberFunctionExceptionSpec(Method);
14816
14817   if (Method->isVirtual()) {
14818     // Check overrides, which we previously had to delay.
14819     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14820                                      OEnd = Method->end_overridden_methods();
14821          O != OEnd; ++O)
14822       CheckOverridingFunctionExceptionSpec(Method, *O);
14823   }
14824 }
14825
14826 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14827 ///
14828 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14829                                        SourceLocation DeclStart,
14830                                        Declarator &D, Expr *BitWidth,
14831                                        InClassInitStyle InitStyle,
14832                                        AccessSpecifier AS,
14833                                        AttributeList *MSPropertyAttr) {
14834   IdentifierInfo *II = D.getIdentifier();
14835   if (!II) {
14836     Diag(DeclStart, diag::err_anonymous_property);
14837     return nullptr;
14838   }
14839   SourceLocation Loc = D.getIdentifierLoc();
14840
14841   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14842   QualType T = TInfo->getType();
14843   if (getLangOpts().CPlusPlus) {
14844     CheckExtraCXXDefaultArguments(D);
14845
14846     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14847                                         UPPC_DataMemberType)) {
14848       D.setInvalidType();
14849       T = Context.IntTy;
14850       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14851     }
14852   }
14853
14854   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14855
14856   if (D.getDeclSpec().isInlineSpecified())
14857     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14858         << getLangOpts().CPlusPlus1z;
14859   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14860     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14861          diag::err_invalid_thread)
14862       << DeclSpec::getSpecifierName(TSCS);
14863
14864   // Check to see if this name was declared as a member previously
14865   NamedDecl *PrevDecl = nullptr;
14866   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14867   LookupName(Previous, S);
14868   switch (Previous.getResultKind()) {
14869   case LookupResult::Found:
14870   case LookupResult::FoundUnresolvedValue:
14871     PrevDecl = Previous.getAsSingle<NamedDecl>();
14872     break;
14873
14874   case LookupResult::FoundOverloaded:
14875     PrevDecl = Previous.getRepresentativeDecl();
14876     break;
14877
14878   case LookupResult::NotFound:
14879   case LookupResult::NotFoundInCurrentInstantiation:
14880   case LookupResult::Ambiguous:
14881     break;
14882   }
14883
14884   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14885     // Maybe we will complain about the shadowed template parameter.
14886     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14887     // Just pretend that we didn't see the previous declaration.
14888     PrevDecl = nullptr;
14889   }
14890
14891   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14892     PrevDecl = nullptr;
14893
14894   SourceLocation TSSL = D.getLocStart();
14895   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
14896   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14897       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
14898   ProcessDeclAttributes(TUScope, NewPD, D);
14899   NewPD->setAccess(AS);
14900
14901   if (NewPD->isInvalidDecl())
14902     Record->setInvalidDecl();
14903
14904   if (D.getDeclSpec().isModulePrivateSpecified())
14905     NewPD->setModulePrivate();
14906
14907   if (NewPD->isInvalidDecl() && PrevDecl) {
14908     // Don't introduce NewFD into scope; there's already something
14909     // with the same name in the same scope.
14910   } else if (II) {
14911     PushOnScopeChains(NewPD, S);
14912   } else
14913     Record->addDecl(NewPD);
14914
14915   return NewPD;
14916 }