]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaDeclCXX.cpp
Upgrade to Unbound 1.5.7.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / 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/Sema/SemaInternal.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include <map>
43 #include <set>
44
45 using namespace clang;
46
47 //===----------------------------------------------------------------------===//
48 // CheckDefaultArgumentVisitor
49 //===----------------------------------------------------------------------===//
50
51 namespace {
52   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53   /// the default argument of a parameter to determine whether it
54   /// contains any ill-formed subexpressions. For example, this will
55   /// diagnose the use of local variables or parameters within the
56   /// default argument expression.
57   class CheckDefaultArgumentVisitor
58     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
59     Expr *DefaultArg;
60     Sema *S;
61
62   public:
63     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
64       : DefaultArg(defarg), S(s) {}
65
66     bool VisitExpr(Expr *Node);
67     bool VisitDeclRefExpr(DeclRefExpr *DRE);
68     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
69     bool VisitLambdaExpr(LambdaExpr *Lambda);
70     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
71   };
72
73   /// VisitExpr - Visit all of the children of this expression.
74   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75     bool IsInvalid = false;
76     for (Stmt *SubStmt : Node->children())
77       IsInvalid |= Visit(SubStmt);
78     return IsInvalid;
79   }
80
81   /// VisitDeclRefExpr - Visit a reference to a declaration, to
82   /// determine whether this declaration can be used in the default
83   /// argument expression.
84   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
85     NamedDecl *Decl = DRE->getDecl();
86     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87       // C++ [dcl.fct.default]p9
88       //   Default arguments are evaluated each time the function is
89       //   called. The order of evaluation of function arguments is
90       //   unspecified. Consequently, parameters of a function shall not
91       //   be used in default argument expressions, even if they are not
92       //   evaluated. Parameters of a function declared before a default
93       //   argument expression are in scope and can hide namespace and
94       //   class member names.
95       return S->Diag(DRE->getLocStart(),
96                      diag::err_param_default_argument_references_param)
97          << Param->getDeclName() << DefaultArg->getSourceRange();
98     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
99       // C++ [dcl.fct.default]p7
100       //   Local variables shall not be used in default argument
101       //   expressions.
102       if (VDecl->isLocalVarDecl())
103         return S->Diag(DRE->getLocStart(),
104                        diag::err_param_default_argument_references_local)
105           << VDecl->getDeclName() << DefaultArg->getSourceRange();
106     }
107
108     return false;
109   }
110
111   /// VisitCXXThisExpr - Visit a C++ "this" expression.
112   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113     // C++ [dcl.fct.default]p8:
114     //   The keyword this shall not be used in a default argument of a
115     //   member function.
116     return S->Diag(ThisE->getLocStart(),
117                    diag::err_param_default_argument_references_this)
118                << ThisE->getSourceRange();
119   }
120
121   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122     bool Invalid = false;
123     for (PseudoObjectExpr::semantics_iterator
124            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125       Expr *E = *i;
126
127       // Look through bindings.
128       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129         E = OVE->getSourceExpr();
130         assert(E && "pseudo-object binding without source expression?");
131       }
132
133       Invalid |= Visit(E);
134     }
135     return Invalid;
136   }
137
138   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139     // C++11 [expr.lambda.prim]p13:
140     //   A lambda-expression appearing in a default argument shall not
141     //   implicitly or explicitly capture any entity.
142     if (Lambda->capture_begin() == Lambda->capture_end())
143       return false;
144
145     return S->Diag(Lambda->getLocStart(), 
146                    diag::err_lambda_capture_default_arg);
147   }
148 }
149
150 void
151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152                                                  const CXXMethodDecl *Method) {
153   // If we have an MSAny spec already, don't bother.
154   if (!Method || ComputedEST == EST_MSAny)
155     return;
156
157   const FunctionProtoType *Proto
158     = Method->getType()->getAs<FunctionProtoType>();
159   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160   if (!Proto)
161     return;
162
163   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165   // If this function can throw any exceptions, make a note of that.
166   if (EST == EST_MSAny || EST == EST_None) {
167     ClearExceptions();
168     ComputedEST = EST;
169     return;
170   }
171
172   // FIXME: If the call to this decl is using any of its default arguments, we
173   // need to search them for potentially-throwing calls.
174
175   // If this function has a basic noexcept, it doesn't affect the outcome.
176   if (EST == EST_BasicNoexcept)
177     return;
178
179   // If we have a throw-all spec at this point, ignore the function.
180   if (ComputedEST == EST_None)
181     return;
182
183   // If we're still at noexcept(true) and there's a nothrow() callee,
184   // change to that specification.
185   if (EST == EST_DynamicNone) {
186     if (ComputedEST == EST_BasicNoexcept)
187       ComputedEST = EST_DynamicNone;
188     return;
189   }
190
191   // Check out noexcept specs.
192   if (EST == EST_ComputedNoexcept) {
193     FunctionProtoType::NoexceptResult NR =
194         Proto->getNoexceptSpec(Self->Context);
195     assert(NR != FunctionProtoType::NR_NoNoexcept &&
196            "Must have noexcept result for EST_ComputedNoexcept.");
197     assert(NR != FunctionProtoType::NR_Dependent &&
198            "Should not generate implicit declarations for dependent cases, "
199            "and don't know how to handle them anyway.");
200
201     // noexcept(false) -> no spec on the new function
202     if (NR == FunctionProtoType::NR_Throw) {
203       ClearExceptions();
204       ComputedEST = EST_None;
205     }
206     // noexcept(true) won't change anything either.
207     return;
208   }
209
210   assert(EST == EST_Dynamic && "EST case not considered earlier.");
211   assert(ComputedEST != EST_None &&
212          "Shouldn't collect exceptions when throw-all is guaranteed.");
213   ComputedEST = EST_Dynamic;
214   // Record the exceptions in this function's exception specification.
215   for (const auto &E : Proto->exceptions())
216     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
217       Exceptions.push_back(E);
218 }
219
220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
221   if (!E || ComputedEST == EST_MSAny)
222     return;
223
224   // FIXME:
225   //
226   // C++0x [except.spec]p14:
227   //   [An] implicit exception-specification specifies the type-id T if and
228   // only if T is allowed by the exception-specification of a function directly
229   // invoked by f's implicit definition; f shall allow all exceptions if any
230   // function it directly invokes allows all exceptions, and f shall allow no
231   // exceptions if every function it directly invokes allows no exceptions.
232   //
233   // Note in particular that if an implicit exception-specification is generated
234   // for a function containing a throw-expression, that specification can still
235   // be noexcept(true).
236   //
237   // Note also that 'directly invoked' is not defined in the standard, and there
238   // is no indication that we should only consider potentially-evaluated calls.
239   //
240   // Ultimately we should implement the intent of the standard: the exception
241   // specification should be the set of exceptions which can be thrown by the
242   // implicit definition. For now, we assume that any non-nothrow expression can
243   // throw any exception.
244
245   if (Self->canThrow(E))
246     ComputedEST = EST_None;
247 }
248
249 bool
250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
251                               SourceLocation EqualLoc) {
252   if (RequireCompleteType(Param->getLocation(), Param->getType(),
253                           diag::err_typecheck_decl_incomplete_type)) {
254     Param->setInvalidDecl();
255     return true;
256   }
257
258   // C++ [dcl.fct.default]p5
259   //   A default argument expression is implicitly converted (clause
260   //   4) to the parameter type. The default argument expression has
261   //   the same semantic constraints as the initializer expression in
262   //   a declaration of a variable of the parameter type, using the
263   //   copy-initialization semantics (8.5).
264   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265                                                                     Param);
266   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267                                                            EqualLoc);
268   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
269   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
270   if (Result.isInvalid())
271     return true;
272   Arg = Result.getAs<Expr>();
273
274   CheckCompletedExpr(Arg, EqualLoc);
275   Arg = MaybeCreateExprWithCleanups(Arg);
276
277   // Okay: add the default argument to the parameter
278   Param->setDefaultArg(Arg);
279
280   // We have already instantiated this parameter; provide each of the 
281   // instantiations with the uninstantiated default argument.
282   UnparsedDefaultArgInstantiationsMap::iterator InstPos
283     = UnparsedDefaultArgInstantiations.find(Param);
284   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287     
288     // We're done tracking this parameter's instantiations.
289     UnparsedDefaultArgInstantiations.erase(InstPos);
290   }
291   
292   return false;
293 }
294
295 /// ActOnParamDefaultArgument - Check whether the default argument
296 /// provided for a function parameter is well-formed. If so, attach it
297 /// to the parameter declaration.
298 void
299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
300                                 Expr *DefaultArg) {
301   if (!param || !DefaultArg)
302     return;
303
304   ParmVarDecl *Param = cast<ParmVarDecl>(param);
305   UnparsedDefaultArgLocs.erase(Param);
306
307   // Default arguments are only permitted in C++
308   if (!getLangOpts().CPlusPlus) {
309     Diag(EqualLoc, diag::err_param_default_argument)
310       << DefaultArg->getSourceRange();
311     Param->setInvalidDecl();
312     return;
313   }
314
315   // Check for unexpanded parameter packs.
316   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317     Param->setInvalidDecl();
318     return;
319   }
320
321   // C++11 [dcl.fct.default]p3
322   //   A default argument expression [...] shall not be specified for a
323   //   parameter pack.
324   if (Param->isParameterPack()) {
325     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
326         << DefaultArg->getSourceRange();
327     return;
328   }
329
330   // Check that the default argument is well-formed
331   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
332   if (DefaultArgChecker.Visit(DefaultArg)) {
333     Param->setInvalidDecl();
334     return;
335   }
336
337   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
338 }
339
340 /// ActOnParamUnparsedDefaultArgument - We've seen a default
341 /// argument for a function parameter, but we can't parse it yet
342 /// because we're inside a class definition. Note that this default
343 /// argument will be parsed later.
344 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
345                                              SourceLocation EqualLoc,
346                                              SourceLocation ArgLoc) {
347   if (!param)
348     return;
349
350   ParmVarDecl *Param = cast<ParmVarDecl>(param);
351   Param->setUnparsedDefaultArg();
352   UnparsedDefaultArgLocs[Param] = ArgLoc;
353 }
354
355 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
356 /// the default argument for the parameter param failed.
357 void Sema::ActOnParamDefaultArgumentError(Decl *param,
358                                           SourceLocation EqualLoc) {
359   if (!param)
360     return;
361
362   ParmVarDecl *Param = cast<ParmVarDecl>(param);
363   Param->setInvalidDecl();
364   UnparsedDefaultArgLocs.erase(Param);
365   Param->setDefaultArg(new(Context)
366                        OpaqueValueExpr(EqualLoc,
367                                        Param->getType().getNonReferenceType(),
368                                        VK_RValue));
369 }
370
371 /// CheckExtraCXXDefaultArguments - Check for any extra default
372 /// arguments in the declarator, which is not a function declaration
373 /// or definition and therefore is not permitted to have default
374 /// arguments. This routine should be invoked for every declarator
375 /// that is not a function declaration or definition.
376 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
377   // C++ [dcl.fct.default]p3
378   //   A default argument expression shall be specified only in the
379   //   parameter-declaration-clause of a function declaration or in a
380   //   template-parameter (14.1). It shall not be specified for a
381   //   parameter pack. If it is specified in a
382   //   parameter-declaration-clause, it shall not occur within a
383   //   declarator or abstract-declarator of a parameter-declaration.
384   bool MightBeFunction = D.isFunctionDeclarationContext();
385   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
386     DeclaratorChunk &chunk = D.getTypeObject(i);
387     if (chunk.Kind == DeclaratorChunk::Function) {
388       if (MightBeFunction) {
389         // This is a function declaration. It can have default arguments, but
390         // keep looking in case its return type is a function type with default
391         // arguments.
392         MightBeFunction = false;
393         continue;
394       }
395       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
396            ++argIdx) {
397         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
398         if (Param->hasUnparsedDefaultArg()) {
399           CachedTokens *Toks = 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           delete Toks;
409           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
410         } else if (Param->getDefaultArg()) {
411           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
412             << Param->getDefaultArg()->getSourceRange();
413           Param->setDefaultArg(nullptr);
414         }
415       }
416     } else if (chunk.Kind != DeclaratorChunk::Paren) {
417       MightBeFunction = false;
418     }
419   }
420 }
421
422 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
423   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
424     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
425     if (!PVD->hasDefaultArg())
426       return false;
427     if (!PVD->hasInheritedDefaultArg())
428       return true;
429   }
430   return false;
431 }
432
433 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
434 /// function, once we already know that they have the same
435 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
436 /// error, false otherwise.
437 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
438                                 Scope *S) {
439   bool Invalid = false;
440
441   // The declaration context corresponding to the scope is the semantic
442   // parent, unless this is a local function declaration, in which case
443   // it is that surrounding function.
444   DeclContext *ScopeDC = New->isLocalExternDecl()
445                              ? New->getLexicalDeclContext()
446                              : New->getDeclContext();
447
448   // Find the previous declaration for the purpose of default arguments.
449   FunctionDecl *PrevForDefaultArgs = Old;
450   for (/**/; PrevForDefaultArgs;
451        // Don't bother looking back past the latest decl if this is a local
452        // extern declaration; nothing else could work.
453        PrevForDefaultArgs = New->isLocalExternDecl()
454                                 ? nullptr
455                                 : PrevForDefaultArgs->getPreviousDecl()) {
456     // Ignore hidden declarations.
457     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
458       continue;
459
460     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
461         !New->isCXXClassMember()) {
462       // Ignore default arguments of old decl if they are not in
463       // the same scope and this is not an out-of-line definition of
464       // a member function.
465       continue;
466     }
467
468     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
469       // If only one of these is a local function declaration, then they are
470       // declared in different scopes, even though isDeclInScope may think
471       // they're in the same scope. (If both are local, the scope check is
472       // sufficent, and if neither is local, then they are in the same scope.)
473       continue;
474     }
475
476     // We found our guy.
477     break;
478   }
479
480   // C++ [dcl.fct.default]p4:
481   //   For non-template functions, default arguments can be added in
482   //   later declarations of a function in the same
483   //   scope. Declarations in different scopes have completely
484   //   distinct sets of default arguments. That is, declarations in
485   //   inner scopes do not acquire default arguments from
486   //   declarations in outer scopes, and vice versa. In a given
487   //   function declaration, all parameters subsequent to a
488   //   parameter with a default argument shall have default
489   //   arguments supplied in this or previous declarations. A
490   //   default argument shall not be redefined by a later
491   //   declaration (not even to the same value).
492   //
493   // C++ [dcl.fct.default]p6:
494   //   Except for member functions of class templates, the default arguments
495   //   in a member function definition that appears outside of the class
496   //   definition are added to the set of default arguments provided by the
497   //   member function declaration in the class definition.
498   for (unsigned p = 0, NumParams = PrevForDefaultArgs
499                                        ? PrevForDefaultArgs->getNumParams()
500                                        : 0;
501        p < NumParams; ++p) {
502     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
503     ParmVarDecl *NewParam = New->getParamDecl(p);
504
505     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
506     bool NewParamHasDfl = NewParam->hasDefaultArg();
507
508     if (OldParamHasDfl && NewParamHasDfl) {
509       unsigned DiagDefaultParamID =
510         diag::err_param_default_argument_redefinition;
511
512       // MSVC accepts that default parameters be redefined for member functions
513       // of template class. The new default parameter's value is ignored.
514       Invalid = true;
515       if (getLangOpts().MicrosoftExt) {
516         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
517         if (MD && MD->getParent()->getDescribedClassTemplate()) {
518           // Merge the old default argument into the new parameter.
519           NewParam->setHasInheritedDefaultArg();
520           if (OldParam->hasUninstantiatedDefaultArg())
521             NewParam->setUninstantiatedDefaultArg(
522                                       OldParam->getUninstantiatedDefaultArg());
523           else
524             NewParam->setDefaultArg(OldParam->getInit());
525           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
526           Invalid = false;
527         }
528       }
529       
530       // FIXME: If we knew where the '=' was, we could easily provide a fix-it 
531       // hint here. Alternatively, we could walk the type-source information
532       // for NewParam to find the last source location in the type... but it
533       // isn't worth the effort right now. This is the kind of test case that
534       // is hard to get right:
535       //   int f(int);
536       //   void g(int (*fp)(int) = f);
537       //   void g(int (*fp)(int) = &f);
538       Diag(NewParam->getLocation(), DiagDefaultParamID)
539         << NewParam->getDefaultArgRange();
540       
541       // Look for the function declaration where the default argument was
542       // actually written, which may be a declaration prior to Old.
543       for (auto Older = PrevForDefaultArgs;
544            OldParam->hasInheritedDefaultArg(); /**/) {
545         Older = Older->getPreviousDecl();
546         OldParam = Older->getParamDecl(p);
547       }
548
549       Diag(OldParam->getLocation(), diag::note_previous_definition)
550         << OldParam->getDefaultArgRange();
551     } else if (OldParamHasDfl) {
552       // Merge the old default argument into the new parameter.
553       // It's important to use getInit() here;  getDefaultArg()
554       // strips off any top-level ExprWithCleanups.
555       NewParam->setHasInheritedDefaultArg();
556       if (OldParam->hasUnparsedDefaultArg())
557         NewParam->setUnparsedDefaultArg();
558       else if (OldParam->hasUninstantiatedDefaultArg())
559         NewParam->setUninstantiatedDefaultArg(
560                                       OldParam->getUninstantiatedDefaultArg());
561       else
562         NewParam->setDefaultArg(OldParam->getInit());
563     } else if (NewParamHasDfl) {
564       if (New->getDescribedFunctionTemplate()) {
565         // Paragraph 4, quoted above, only applies to non-template functions.
566         Diag(NewParam->getLocation(),
567              diag::err_param_default_argument_template_redecl)
568           << NewParam->getDefaultArgRange();
569         Diag(PrevForDefaultArgs->getLocation(),
570              diag::note_template_prev_declaration)
571             << false;
572       } else if (New->getTemplateSpecializationKind()
573                    != TSK_ImplicitInstantiation &&
574                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
575         // C++ [temp.expr.spec]p21:
576         //   Default function arguments shall not be specified in a declaration
577         //   or a definition for one of the following explicit specializations:
578         //     - the explicit specialization of a function template;
579         //     - the explicit specialization of a member function template;
580         //     - the explicit specialization of a member function of a class 
581         //       template where the class template specialization to which the
582         //       member function specialization belongs is implicitly 
583         //       instantiated.
584         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
585           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
586           << New->getDeclName()
587           << NewParam->getDefaultArgRange();
588       } else if (New->getDeclContext()->isDependentContext()) {
589         // C++ [dcl.fct.default]p6 (DR217):
590         //   Default arguments for a member function of a class template shall 
591         //   be specified on the initial declaration of the member function 
592         //   within the class template.
593         //
594         // Reading the tea leaves a bit in DR217 and its reference to DR205 
595         // leads me to the conclusion that one cannot add default function 
596         // arguments for an out-of-line definition of a member function of a 
597         // dependent type.
598         int WhichKind = 2;
599         if (CXXRecordDecl *Record 
600               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
601           if (Record->getDescribedClassTemplate())
602             WhichKind = 0;
603           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
604             WhichKind = 1;
605           else
606             WhichKind = 2;
607         }
608         
609         Diag(NewParam->getLocation(), 
610              diag::err_param_default_argument_member_template_redecl)
611           << WhichKind
612           << NewParam->getDefaultArgRange();
613       }
614     }
615   }
616
617   // DR1344: If a default argument is added outside a class definition and that
618   // default argument makes the function a special member function, the program
619   // is ill-formed. This can only happen for constructors.
620   if (isa<CXXConstructorDecl>(New) &&
621       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
622     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
623                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
624     if (NewSM != OldSM) {
625       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
626       assert(NewParam->hasDefaultArg());
627       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
628         << NewParam->getDefaultArgRange() << NewSM;
629       Diag(Old->getLocation(), diag::note_previous_declaration);
630     }
631   }
632
633   const FunctionDecl *Def;
634   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
635   // template has a constexpr specifier then all its declarations shall
636   // contain the constexpr specifier.
637   if (New->isConstexpr() != Old->isConstexpr()) {
638     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
639       << New << New->isConstexpr();
640     Diag(Old->getLocation(), diag::note_previous_declaration);
641     Invalid = true;
642   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
643              Old->isDefined(Def)) {
644     // C++11 [dcl.fcn.spec]p4:
645     //   If the definition of a function appears in a translation unit before its
646     //   first declaration as inline, the program is ill-formed.
647     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
648     Diag(Def->getLocation(), diag::note_previous_definition);
649     Invalid = true;
650   }
651
652   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
653   // argument expression, that declaration shall be a definition and shall be
654   // the only declaration of the function or function template in the
655   // translation unit.
656   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
657       functionDeclHasDefaultArgument(Old)) {
658     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
659     Diag(Old->getLocation(), diag::note_previous_declaration);
660     Invalid = true;
661   }
662
663   if (CheckEquivalentExceptionSpec(Old, New))
664     Invalid = true;
665
666   return Invalid;
667 }
668
669 /// \brief Merge the exception specifications of two variable declarations.
670 ///
671 /// This is called when there's a redeclaration of a VarDecl. The function
672 /// checks if the redeclaration might have an exception specification and
673 /// validates compatibility and merges the specs if necessary.
674 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
675   // Shortcut if exceptions are disabled.
676   if (!getLangOpts().CXXExceptions)
677     return;
678
679   assert(Context.hasSameType(New->getType(), Old->getType()) &&
680          "Should only be called if types are otherwise the same.");
681
682   QualType NewType = New->getType();
683   QualType OldType = Old->getType();
684
685   // We're only interested in pointers and references to functions, as well
686   // as pointers to member functions.
687   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
688     NewType = R->getPointeeType();
689     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
690   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
691     NewType = P->getPointeeType();
692     OldType = OldType->getAs<PointerType>()->getPointeeType();
693   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
694     NewType = M->getPointeeType();
695     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
696   }
697
698   if (!NewType->isFunctionProtoType())
699     return;
700
701   // There's lots of special cases for functions. For function pointers, system
702   // libraries are hopefully not as broken so that we don't need these
703   // workarounds.
704   if (CheckEquivalentExceptionSpec(
705         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
706         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
707     New->setInvalidDecl();
708   }
709 }
710
711 /// CheckCXXDefaultArguments - Verify that the default arguments for a
712 /// function declaration are well-formed according to C++
713 /// [dcl.fct.default].
714 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
715   unsigned NumParams = FD->getNumParams();
716   unsigned p;
717
718   // Find first parameter with a default argument
719   for (p = 0; p < NumParams; ++p) {
720     ParmVarDecl *Param = FD->getParamDecl(p);
721     if (Param->hasDefaultArg())
722       break;
723   }
724
725   // C++11 [dcl.fct.default]p4:
726   //   In a given function declaration, each parameter subsequent to a parameter
727   //   with a default argument shall have a default argument supplied in this or
728   //   a previous declaration or shall be a function parameter pack. A default
729   //   argument shall not be redefined by a later declaration (not even to the
730   //   same value).
731   unsigned LastMissingDefaultArg = 0;
732   for (; p < NumParams; ++p) {
733     ParmVarDecl *Param = FD->getParamDecl(p);
734     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
735       if (Param->isInvalidDecl())
736         /* We already complained about this parameter. */;
737       else if (Param->getIdentifier())
738         Diag(Param->getLocation(),
739              diag::err_param_default_argument_missing_name)
740           << Param->getIdentifier();
741       else
742         Diag(Param->getLocation(),
743              diag::err_param_default_argument_missing);
744
745       LastMissingDefaultArg = p;
746     }
747   }
748
749   if (LastMissingDefaultArg > 0) {
750     // Some default arguments were missing. Clear out all of the
751     // default arguments up to (and including) the last missing
752     // default argument, so that we leave the function parameters
753     // in a semantically valid state.
754     for (p = 0; p <= LastMissingDefaultArg; ++p) {
755       ParmVarDecl *Param = FD->getParamDecl(p);
756       if (Param->hasDefaultArg()) {
757         Param->setDefaultArg(nullptr);
758       }
759     }
760   }
761 }
762
763 // CheckConstexprParameterTypes - Check whether a function's parameter types
764 // are all literal types. If so, return true. If not, produce a suitable
765 // diagnostic and return false.
766 static bool CheckConstexprParameterTypes(Sema &SemaRef,
767                                          const FunctionDecl *FD) {
768   unsigned ArgIndex = 0;
769   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
770   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
771                                               e = FT->param_type_end();
772        i != e; ++i, ++ArgIndex) {
773     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
774     SourceLocation ParamLoc = PD->getLocation();
775     if (!(*i)->isDependentType() &&
776         SemaRef.RequireLiteralType(ParamLoc, *i,
777                                    diag::err_constexpr_non_literal_param,
778                                    ArgIndex+1, PD->getSourceRange(),
779                                    isa<CXXConstructorDecl>(FD)))
780       return false;
781   }
782   return true;
783 }
784
785 /// \brief Get diagnostic %select index for tag kind for
786 /// record diagnostic message.
787 /// WARNING: Indexes apply to particular diagnostics only!
788 ///
789 /// \returns diagnostic %select index.
790 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
791   switch (Tag) {
792   case TTK_Struct: return 0;
793   case TTK_Interface: return 1;
794   case TTK_Class:  return 2;
795   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
796   }
797 }
798
799 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
800 // the requirements of a constexpr function definition or a constexpr
801 // constructor definition. If so, return true. If not, produce appropriate
802 // diagnostics and return false.
803 //
804 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
805 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
806   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
807   if (MD && MD->isInstance()) {
808     // C++11 [dcl.constexpr]p4:
809     //  The definition of a constexpr constructor shall satisfy the following
810     //  constraints:
811     //  - the class shall not have any virtual base classes;
812     const CXXRecordDecl *RD = MD->getParent();
813     if (RD->getNumVBases()) {
814       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
815         << isa<CXXConstructorDecl>(NewFD)
816         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
817       for (const auto &I : RD->vbases())
818         Diag(I.getLocStart(),
819              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
820       return false;
821     }
822   }
823
824   if (!isa<CXXConstructorDecl>(NewFD)) {
825     // C++11 [dcl.constexpr]p3:
826     //  The definition of a constexpr function shall satisfy the following
827     //  constraints:
828     // - it shall not be virtual;
829     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
830     if (Method && Method->isVirtual()) {
831       Method = Method->getCanonicalDecl();
832       Diag(Method->getLocation(), diag::err_constexpr_virtual);
833
834       // If it's not obvious why this function is virtual, find an overridden
835       // function which uses the 'virtual' keyword.
836       const CXXMethodDecl *WrittenVirtual = Method;
837       while (!WrittenVirtual->isVirtualAsWritten())
838         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
839       if (WrittenVirtual != Method)
840         Diag(WrittenVirtual->getLocation(),
841              diag::note_overridden_virtual_function);
842       return false;
843     }
844
845     // - its return type shall be a literal type;
846     QualType RT = NewFD->getReturnType();
847     if (!RT->isDependentType() &&
848         RequireLiteralType(NewFD->getLocation(), RT,
849                            diag::err_constexpr_non_literal_return))
850       return false;
851   }
852
853   // - each of its parameter types shall be a literal type;
854   if (!CheckConstexprParameterTypes(*this, NewFD))
855     return false;
856
857   return true;
858 }
859
860 /// Check the given declaration statement is legal within a constexpr function
861 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
862 ///
863 /// \return true if the body is OK (maybe only as an extension), false if we
864 ///         have diagnosed a problem.
865 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
866                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
867   // C++11 [dcl.constexpr]p3 and p4:
868   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
869   //  contain only
870   for (const auto *DclIt : DS->decls()) {
871     switch (DclIt->getKind()) {
872     case Decl::StaticAssert:
873     case Decl::Using:
874     case Decl::UsingShadow:
875     case Decl::UsingDirective:
876     case Decl::UnresolvedUsingTypename:
877     case Decl::UnresolvedUsingValue:
878       //   - static_assert-declarations
879       //   - using-declarations,
880       //   - using-directives,
881       continue;
882
883     case Decl::Typedef:
884     case Decl::TypeAlias: {
885       //   - typedef declarations and alias-declarations that do not define
886       //     classes or enumerations,
887       const auto *TN = cast<TypedefNameDecl>(DclIt);
888       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
889         // Don't allow variably-modified types in constexpr functions.
890         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
891         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
892           << TL.getSourceRange() << TL.getType()
893           << isa<CXXConstructorDecl>(Dcl);
894         return false;
895       }
896       continue;
897     }
898
899     case Decl::Enum:
900     case Decl::CXXRecord:
901       // C++1y allows types to be defined, not just declared.
902       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
903         SemaRef.Diag(DS->getLocStart(),
904                      SemaRef.getLangOpts().CPlusPlus14
905                        ? diag::warn_cxx11_compat_constexpr_type_definition
906                        : diag::ext_constexpr_type_definition)
907           << isa<CXXConstructorDecl>(Dcl);
908       continue;
909
910     case Decl::EnumConstant:
911     case Decl::IndirectField:
912     case Decl::ParmVar:
913       // These can only appear with other declarations which are banned in
914       // C++11 and permitted in C++1y, so ignore them.
915       continue;
916
917     case Decl::Var: {
918       // C++1y [dcl.constexpr]p3 allows anything except:
919       //   a definition of a variable of non-literal type or of static or
920       //   thread storage duration or for which no initialization is performed.
921       const auto *VD = cast<VarDecl>(DclIt);
922       if (VD->isThisDeclarationADefinition()) {
923         if (VD->isStaticLocal()) {
924           SemaRef.Diag(VD->getLocation(),
925                        diag::err_constexpr_local_var_static)
926             << isa<CXXConstructorDecl>(Dcl)
927             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
928           return false;
929         }
930         if (!VD->getType()->isDependentType() &&
931             SemaRef.RequireLiteralType(
932               VD->getLocation(), VD->getType(),
933               diag::err_constexpr_local_var_non_literal_type,
934               isa<CXXConstructorDecl>(Dcl)))
935           return false;
936         if (!VD->getType()->isDependentType() &&
937             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
938           SemaRef.Diag(VD->getLocation(),
939                        diag::err_constexpr_local_var_no_init)
940             << isa<CXXConstructorDecl>(Dcl);
941           return false;
942         }
943       }
944       SemaRef.Diag(VD->getLocation(),
945                    SemaRef.getLangOpts().CPlusPlus14
946                     ? diag::warn_cxx11_compat_constexpr_local_var
947                     : diag::ext_constexpr_local_var)
948         << isa<CXXConstructorDecl>(Dcl);
949       continue;
950     }
951
952     case Decl::NamespaceAlias:
953     case Decl::Function:
954       // These are disallowed in C++11 and permitted in C++1y. Allow them
955       // everywhere as an extension.
956       if (!Cxx1yLoc.isValid())
957         Cxx1yLoc = DS->getLocStart();
958       continue;
959
960     default:
961       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
962         << isa<CXXConstructorDecl>(Dcl);
963       return false;
964     }
965   }
966
967   return true;
968 }
969
970 /// Check that the given field is initialized within a constexpr constructor.
971 ///
972 /// \param Dcl The constexpr constructor being checked.
973 /// \param Field The field being checked. This may be a member of an anonymous
974 ///        struct or union nested within the class being checked.
975 /// \param Inits All declarations, including anonymous struct/union members and
976 ///        indirect members, for which any initialization was provided.
977 /// \param Diagnosed Set to true if an error is produced.
978 static void CheckConstexprCtorInitializer(Sema &SemaRef,
979                                           const FunctionDecl *Dcl,
980                                           FieldDecl *Field,
981                                           llvm::SmallSet<Decl*, 16> &Inits,
982                                           bool &Diagnosed) {
983   if (Field->isInvalidDecl())
984     return;
985
986   if (Field->isUnnamedBitfield())
987     return;
988
989   // Anonymous unions with no variant members and empty anonymous structs do not
990   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
991   // indirect fields don't need initializing.
992   if (Field->isAnonymousStructOrUnion() &&
993       (Field->getType()->isUnionType()
994            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
995            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
996     return;
997
998   if (!Inits.count(Field)) {
999     if (!Diagnosed) {
1000       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1001       Diagnosed = true;
1002     }
1003     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1004   } else if (Field->isAnonymousStructOrUnion()) {
1005     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1006     for (auto *I : RD->fields())
1007       // If an anonymous union contains an anonymous struct of which any member
1008       // is initialized, all members must be initialized.
1009       if (!RD->isUnion() || Inits.count(I))
1010         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1011   }
1012 }
1013
1014 /// Check the provided statement is allowed in a constexpr function
1015 /// definition.
1016 static bool
1017 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1018                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1019                            SourceLocation &Cxx1yLoc) {
1020   // - its function-body shall be [...] a compound-statement that contains only
1021   switch (S->getStmtClass()) {
1022   case Stmt::NullStmtClass:
1023     //   - null statements,
1024     return true;
1025
1026   case Stmt::DeclStmtClass:
1027     //   - static_assert-declarations
1028     //   - using-declarations,
1029     //   - using-directives,
1030     //   - typedef declarations and alias-declarations that do not define
1031     //     classes or enumerations,
1032     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1033       return false;
1034     return true;
1035
1036   case Stmt::ReturnStmtClass:
1037     //   - and exactly one return statement;
1038     if (isa<CXXConstructorDecl>(Dcl)) {
1039       // C++1y allows return statements in constexpr constructors.
1040       if (!Cxx1yLoc.isValid())
1041         Cxx1yLoc = S->getLocStart();
1042       return true;
1043     }
1044
1045     ReturnStmts.push_back(S->getLocStart());
1046     return true;
1047
1048   case Stmt::CompoundStmtClass: {
1049     // C++1y allows compound-statements.
1050     if (!Cxx1yLoc.isValid())
1051       Cxx1yLoc = S->getLocStart();
1052
1053     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1054     for (auto *BodyIt : CompStmt->body()) {
1055       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1056                                       Cxx1yLoc))
1057         return false;
1058     }
1059     return true;
1060   }
1061
1062   case Stmt::AttributedStmtClass:
1063     if (!Cxx1yLoc.isValid())
1064       Cxx1yLoc = S->getLocStart();
1065     return true;
1066
1067   case Stmt::IfStmtClass: {
1068     // C++1y allows if-statements.
1069     if (!Cxx1yLoc.isValid())
1070       Cxx1yLoc = S->getLocStart();
1071
1072     IfStmt *If = cast<IfStmt>(S);
1073     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1074                                     Cxx1yLoc))
1075       return false;
1076     if (If->getElse() &&
1077         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1078                                     Cxx1yLoc))
1079       return false;
1080     return true;
1081   }
1082
1083   case Stmt::WhileStmtClass:
1084   case Stmt::DoStmtClass:
1085   case Stmt::ForStmtClass:
1086   case Stmt::CXXForRangeStmtClass:
1087   case Stmt::ContinueStmtClass:
1088     // C++1y allows all of these. We don't allow them as extensions in C++11,
1089     // because they don't make sense without variable mutation.
1090     if (!SemaRef.getLangOpts().CPlusPlus14)
1091       break;
1092     if (!Cxx1yLoc.isValid())
1093       Cxx1yLoc = S->getLocStart();
1094     for (Stmt *SubStmt : S->children())
1095       if (SubStmt &&
1096           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1097                                       Cxx1yLoc))
1098         return false;
1099     return true;
1100
1101   case Stmt::SwitchStmtClass:
1102   case Stmt::CaseStmtClass:
1103   case Stmt::DefaultStmtClass:
1104   case Stmt::BreakStmtClass:
1105     // C++1y allows switch-statements, and since they don't need variable
1106     // mutation, we can reasonably allow them in C++11 as an extension.
1107     if (!Cxx1yLoc.isValid())
1108       Cxx1yLoc = S->getLocStart();
1109     for (Stmt *SubStmt : S->children())
1110       if (SubStmt &&
1111           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1112                                       Cxx1yLoc))
1113         return false;
1114     return true;
1115
1116   default:
1117     if (!isa<Expr>(S))
1118       break;
1119
1120     // C++1y allows expression-statements.
1121     if (!Cxx1yLoc.isValid())
1122       Cxx1yLoc = S->getLocStart();
1123     return true;
1124   }
1125
1126   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1127     << isa<CXXConstructorDecl>(Dcl);
1128   return false;
1129 }
1130
1131 /// Check the body for the given constexpr function declaration only contains
1132 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1133 ///
1134 /// \return true if the body is OK, false if we have diagnosed a problem.
1135 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1136   if (isa<CXXTryStmt>(Body)) {
1137     // C++11 [dcl.constexpr]p3:
1138     //  The definition of a constexpr function shall satisfy the following
1139     //  constraints: [...]
1140     // - its function-body shall be = delete, = default, or a
1141     //   compound-statement
1142     //
1143     // C++11 [dcl.constexpr]p4:
1144     //  In the definition of a constexpr constructor, [...]
1145     // - its function-body shall not be a function-try-block;
1146     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1147       << isa<CXXConstructorDecl>(Dcl);
1148     return false;
1149   }
1150
1151   SmallVector<SourceLocation, 4> ReturnStmts;
1152
1153   // - its function-body shall be [...] a compound-statement that contains only
1154   //   [... list of cases ...]
1155   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1156   SourceLocation Cxx1yLoc;
1157   for (auto *BodyIt : CompBody->body()) {
1158     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1159       return false;
1160   }
1161
1162   if (Cxx1yLoc.isValid())
1163     Diag(Cxx1yLoc,
1164          getLangOpts().CPlusPlus14
1165            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1166            : diag::ext_constexpr_body_invalid_stmt)
1167       << isa<CXXConstructorDecl>(Dcl);
1168
1169   if (const CXXConstructorDecl *Constructor
1170         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1171     const CXXRecordDecl *RD = Constructor->getParent();
1172     // DR1359:
1173     // - every non-variant non-static data member and base class sub-object
1174     //   shall be initialized;
1175     // DR1460:
1176     // - if the class is a union having variant members, exactly one of them
1177     //   shall be initialized;
1178     if (RD->isUnion()) {
1179       if (Constructor->getNumCtorInitializers() == 0 &&
1180           RD->hasVariantMembers()) {
1181         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1182         return false;
1183       }
1184     } else if (!Constructor->isDependentContext() &&
1185                !Constructor->isDelegatingConstructor()) {
1186       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1187
1188       // Skip detailed checking if we have enough initializers, and we would
1189       // allow at most one initializer per member.
1190       bool AnyAnonStructUnionMembers = false;
1191       unsigned Fields = 0;
1192       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1193            E = RD->field_end(); I != E; ++I, ++Fields) {
1194         if (I->isAnonymousStructOrUnion()) {
1195           AnyAnonStructUnionMembers = true;
1196           break;
1197         }
1198       }
1199       // DR1460:
1200       // - if the class is a union-like class, but is not a union, for each of
1201       //   its anonymous union members having variant members, exactly one of
1202       //   them shall be initialized;
1203       if (AnyAnonStructUnionMembers ||
1204           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1205         // Check initialization of non-static data members. Base classes are
1206         // always initialized so do not need to be checked. Dependent bases
1207         // might not have initializers in the member initializer list.
1208         llvm::SmallSet<Decl*, 16> Inits;
1209         for (const auto *I: Constructor->inits()) {
1210           if (FieldDecl *FD = I->getMember())
1211             Inits.insert(FD);
1212           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1213             Inits.insert(ID->chain_begin(), ID->chain_end());
1214         }
1215
1216         bool Diagnosed = false;
1217         for (auto *I : RD->fields())
1218           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1219         if (Diagnosed)
1220           return false;
1221       }
1222     }
1223   } else {
1224     if (ReturnStmts.empty()) {
1225       // C++1y doesn't require constexpr functions to contain a 'return'
1226       // statement. We still do, unless the return type might be void, because
1227       // otherwise if there's no return statement, the function cannot
1228       // be used in a core constant expression.
1229       bool OK = getLangOpts().CPlusPlus14 &&
1230                 (Dcl->getReturnType()->isVoidType() ||
1231                  Dcl->getReturnType()->isDependentType());
1232       Diag(Dcl->getLocation(),
1233            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1234               : diag::err_constexpr_body_no_return);
1235       return OK;
1236     }
1237     if (ReturnStmts.size() > 1) {
1238       Diag(ReturnStmts.back(),
1239            getLangOpts().CPlusPlus14
1240              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1241              : diag::ext_constexpr_body_multiple_return);
1242       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1243         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1244     }
1245   }
1246
1247   // C++11 [dcl.constexpr]p5:
1248   //   if no function argument values exist such that the function invocation
1249   //   substitution would produce a constant expression, the program is
1250   //   ill-formed; no diagnostic required.
1251   // C++11 [dcl.constexpr]p3:
1252   //   - every constructor call and implicit conversion used in initializing the
1253   //     return value shall be one of those allowed in a constant expression.
1254   // C++11 [dcl.constexpr]p4:
1255   //   - every constructor involved in initializing non-static data members and
1256   //     base class sub-objects shall be a constexpr constructor.
1257   SmallVector<PartialDiagnosticAt, 8> Diags;
1258   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1259     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1260       << isa<CXXConstructorDecl>(Dcl);
1261     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1262       Diag(Diags[I].first, Diags[I].second);
1263     // Don't return false here: we allow this for compatibility in
1264     // system headers.
1265   }
1266
1267   return true;
1268 }
1269
1270 /// isCurrentClassName - Determine whether the identifier II is the
1271 /// name of the class type currently being defined. In the case of
1272 /// nested classes, this will only return true if II is the name of
1273 /// the innermost class.
1274 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1275                               const CXXScopeSpec *SS) {
1276   assert(getLangOpts().CPlusPlus && "No class names in C!");
1277
1278   CXXRecordDecl *CurDecl;
1279   if (SS && SS->isSet() && !SS->isInvalid()) {
1280     DeclContext *DC = computeDeclContext(*SS, true);
1281     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1282   } else
1283     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1284
1285   if (CurDecl && CurDecl->getIdentifier())
1286     return &II == CurDecl->getIdentifier();
1287   return false;
1288 }
1289
1290 /// \brief Determine whether the identifier II is a typo for the name of
1291 /// the class type currently being defined. If so, update it to the identifier
1292 /// that should have been used.
1293 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1294   assert(getLangOpts().CPlusPlus && "No class names in C!");
1295
1296   if (!getLangOpts().SpellChecking)
1297     return false;
1298
1299   CXXRecordDecl *CurDecl;
1300   if (SS && SS->isSet() && !SS->isInvalid()) {
1301     DeclContext *DC = computeDeclContext(*SS, true);
1302     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1303   } else
1304     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1305
1306   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1307       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1308           < II->getLength()) {
1309     II = CurDecl->getIdentifier();
1310     return true;
1311   }
1312
1313   return false;
1314 }
1315
1316 /// \brief Determine whether the given class is a base class of the given
1317 /// class, including looking at dependent bases.
1318 static bool findCircularInheritance(const CXXRecordDecl *Class,
1319                                     const CXXRecordDecl *Current) {
1320   SmallVector<const CXXRecordDecl*, 8> Queue;
1321
1322   Class = Class->getCanonicalDecl();
1323   while (true) {
1324     for (const auto &I : Current->bases()) {
1325       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1326       if (!Base)
1327         continue;
1328
1329       Base = Base->getDefinition();
1330       if (!Base)
1331         continue;
1332
1333       if (Base->getCanonicalDecl() == Class)
1334         return true;
1335
1336       Queue.push_back(Base);
1337     }
1338
1339     if (Queue.empty())
1340       return false;
1341
1342     Current = Queue.pop_back_val();
1343   }
1344
1345   return false;
1346 }
1347
1348 /// \brief Check the validity of a C++ base class specifier.
1349 ///
1350 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1351 /// and returns NULL otherwise.
1352 CXXBaseSpecifier *
1353 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1354                          SourceRange SpecifierRange,
1355                          bool Virtual, AccessSpecifier Access,
1356                          TypeSourceInfo *TInfo,
1357                          SourceLocation EllipsisLoc) {
1358   QualType BaseType = TInfo->getType();
1359
1360   // C++ [class.union]p1:
1361   //   A union shall not have base classes.
1362   if (Class->isUnion()) {
1363     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1364       << SpecifierRange;
1365     return nullptr;
1366   }
1367
1368   if (EllipsisLoc.isValid() && 
1369       !TInfo->getType()->containsUnexpandedParameterPack()) {
1370     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1371       << TInfo->getTypeLoc().getSourceRange();
1372     EllipsisLoc = SourceLocation();
1373   }
1374
1375   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1376
1377   if (BaseType->isDependentType()) {
1378     // Make sure that we don't have circular inheritance among our dependent
1379     // bases. For non-dependent bases, the check for completeness below handles
1380     // this.
1381     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1382       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1383           ((BaseDecl = BaseDecl->getDefinition()) &&
1384            findCircularInheritance(Class, BaseDecl))) {
1385         Diag(BaseLoc, diag::err_circular_inheritance)
1386           << BaseType << Context.getTypeDeclType(Class);
1387
1388         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1389           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1390             << BaseType;
1391
1392         return nullptr;
1393       }
1394     }
1395
1396     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1397                                           Class->getTagKind() == TTK_Class,
1398                                           Access, TInfo, EllipsisLoc);
1399   }
1400
1401   // Base specifiers must be record types.
1402   if (!BaseType->isRecordType()) {
1403     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1404     return nullptr;
1405   }
1406
1407   // C++ [class.union]p1:
1408   //   A union shall not be used as a base class.
1409   if (BaseType->isUnionType()) {
1410     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1411     return nullptr;
1412   }
1413
1414   // For the MS ABI, propagate DLL attributes to base class templates.
1415   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1416     if (Attr *ClassAttr = getDLLAttr(Class)) {
1417       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1418               BaseType->getAsCXXRecordDecl())) {
1419         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
1420                                             BaseLoc);
1421       }
1422     }
1423   }
1424
1425   // C++ [class.derived]p2:
1426   //   The class-name in a base-specifier shall not be an incompletely
1427   //   defined class.
1428   if (RequireCompleteType(BaseLoc, BaseType,
1429                           diag::err_incomplete_base_class, SpecifierRange)) {
1430     Class->setInvalidDecl();
1431     return nullptr;
1432   }
1433
1434   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1435   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1436   assert(BaseDecl && "Record type has no declaration");
1437   BaseDecl = BaseDecl->getDefinition();
1438   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1439   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1440   assert(CXXBaseDecl && "Base type is not a C++ type");
1441
1442   // A class which contains a flexible array member is not suitable for use as a
1443   // base class:
1444   //   - If the layout determines that a base comes before another base,
1445   //     the flexible array member would index into the subsequent base.
1446   //   - If the layout determines that base comes before the derived class,
1447   //     the flexible array member would index into the derived class.
1448   if (CXXBaseDecl->hasFlexibleArrayMember()) {
1449     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1450       << CXXBaseDecl->getDeclName();
1451     return nullptr;
1452   }
1453
1454   // C++ [class]p3:
1455   //   If a class is marked final and it appears as a base-type-specifier in
1456   //   base-clause, the program is ill-formed.
1457   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1458     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1459       << CXXBaseDecl->getDeclName()
1460       << FA->isSpelledAsSealed();
1461     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1462         << CXXBaseDecl->getDeclName() << FA->getRange();
1463     return nullptr;
1464   }
1465
1466   if (BaseDecl->isInvalidDecl())
1467     Class->setInvalidDecl();
1468
1469   // Create the base specifier.
1470   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1471                                         Class->getTagKind() == TTK_Class,
1472                                         Access, TInfo, EllipsisLoc);
1473 }
1474
1475 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1476 /// one entry in the base class list of a class specifier, for
1477 /// example:
1478 ///    class foo : public bar, virtual private baz {
1479 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1480 BaseResult
1481 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1482                          ParsedAttributes &Attributes,
1483                          bool Virtual, AccessSpecifier Access,
1484                          ParsedType basetype, SourceLocation BaseLoc,
1485                          SourceLocation EllipsisLoc) {
1486   if (!classdecl)
1487     return true;
1488
1489   AdjustDeclIfTemplate(classdecl);
1490   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1491   if (!Class)
1492     return true;
1493
1494   // We haven't yet attached the base specifiers.
1495   Class->setIsParsingBaseSpecifiers();
1496
1497   // We do not support any C++11 attributes on base-specifiers yet.
1498   // Diagnose any attributes we see.
1499   if (!Attributes.empty()) {
1500     for (AttributeList *Attr = Attributes.getList(); Attr;
1501          Attr = Attr->getNext()) {
1502       if (Attr->isInvalid() ||
1503           Attr->getKind() == AttributeList::IgnoredAttribute)
1504         continue;
1505       Diag(Attr->getLoc(),
1506            Attr->getKind() == AttributeList::UnknownAttribute
1507              ? diag::warn_unknown_attribute_ignored
1508              : diag::err_base_specifier_attribute)
1509         << Attr->getName();
1510     }
1511   }
1512
1513   TypeSourceInfo *TInfo = nullptr;
1514   GetTypeFromParser(basetype, &TInfo);
1515
1516   if (EllipsisLoc.isInvalid() &&
1517       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 
1518                                       UPPC_BaseType))
1519     return true;
1520   
1521   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1522                                                       Virtual, Access, TInfo,
1523                                                       EllipsisLoc))
1524     return BaseSpec;
1525   else
1526     Class->setInvalidDecl();
1527
1528   return true;
1529 }
1530
1531 /// Use small set to collect indirect bases.  As this is only used
1532 /// locally, there's no need to abstract the small size parameter.
1533 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1534
1535 /// \brief Recursively add the bases of Type.  Don't add Type itself.
1536 static void
1537 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1538                   const QualType &Type)
1539 {
1540   // Even though the incoming type is a base, it might not be
1541   // a class -- it could be a template parm, for instance.
1542   if (auto Rec = Type->getAs<RecordType>()) {
1543     auto Decl = Rec->getAsCXXRecordDecl();
1544
1545     // Iterate over its bases.
1546     for (const auto &BaseSpec : Decl->bases()) {
1547       QualType Base = Context.getCanonicalType(BaseSpec.getType())
1548         .getUnqualifiedType();
1549       if (Set.insert(Base).second)
1550         // If we've not already seen it, recurse.
1551         NoteIndirectBases(Context, Set, Base);
1552     }
1553   }
1554 }
1555
1556 /// \brief Performs the actual work of attaching the given base class
1557 /// specifiers to a C++ class.
1558 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1559                                 unsigned NumBases) {
1560  if (NumBases == 0)
1561     return false;
1562
1563   // Used to keep track of which base types we have already seen, so
1564   // that we can properly diagnose redundant direct base types. Note
1565   // that the key is always the unqualified canonical type of the base
1566   // class.
1567   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1568
1569   // Used to track indirect bases so we can see if a direct base is
1570   // ambiguous.
1571   IndirectBaseSet IndirectBaseTypes;
1572
1573   // Copy non-redundant base specifiers into permanent storage.
1574   unsigned NumGoodBases = 0;
1575   bool Invalid = false;
1576   for (unsigned idx = 0; idx < NumBases; ++idx) {
1577     QualType NewBaseType
1578       = Context.getCanonicalType(Bases[idx]->getType());
1579     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1580
1581     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1582     if (KnownBase) {
1583       // C++ [class.mi]p3:
1584       //   A class shall not be specified as a direct base class of a
1585       //   derived class more than once.
1586       Diag(Bases[idx]->getLocStart(),
1587            diag::err_duplicate_base_class)
1588         << KnownBase->getType()
1589         << Bases[idx]->getSourceRange();
1590
1591       // Delete the duplicate base class specifier; we're going to
1592       // overwrite its pointer later.
1593       Context.Deallocate(Bases[idx]);
1594
1595       Invalid = true;
1596     } else {
1597       // Okay, add this new base class.
1598       KnownBase = Bases[idx];
1599       Bases[NumGoodBases++] = Bases[idx];
1600
1601       // Note this base's direct & indirect bases, if there could be ambiguity.
1602       if (NumBases > 1)
1603         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1604       
1605       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1606         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1607         if (Class->isInterface() &&
1608               (!RD->isInterface() ||
1609                KnownBase->getAccessSpecifier() != AS_public)) {
1610           // The Microsoft extension __interface does not permit bases that
1611           // are not themselves public interfaces.
1612           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1613             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1614             << RD->getSourceRange();
1615           Invalid = true;
1616         }
1617         if (RD->hasAttr<WeakAttr>())
1618           Class->addAttr(WeakAttr::CreateImplicit(Context));
1619       }
1620     }
1621   }
1622
1623   // Attach the remaining base class specifiers to the derived class.
1624   Class->setBases(Bases, NumGoodBases);
1625   
1626   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1627     // Check whether this direct base is inaccessible due to ambiguity.
1628     QualType BaseType = Bases[idx]->getType();
1629     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1630       .getUnqualifiedType();
1631
1632     if (IndirectBaseTypes.count(CanonicalBase)) {
1633       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1634                          /*DetectVirtual=*/true);
1635       bool found
1636         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1637       assert(found);
1638       (void)found;
1639
1640       if (Paths.isAmbiguous(CanonicalBase))
1641         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1642           << BaseType << getAmbiguousPathsDisplayString(Paths)
1643           << Bases[idx]->getSourceRange();
1644       else
1645         assert(Bases[idx]->isVirtual());
1646     }
1647
1648     // Delete the base class specifier, since its data has been copied
1649     // into the CXXRecordDecl.
1650     Context.Deallocate(Bases[idx]);
1651   }
1652
1653   return Invalid;
1654 }
1655
1656 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1657 /// class, after checking whether there are any duplicate base
1658 /// classes.
1659 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1660                                unsigned NumBases) {
1661   if (!ClassDecl || !Bases || !NumBases)
1662     return;
1663
1664   AdjustDeclIfTemplate(ClassDecl);
1665   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1666 }
1667
1668 /// \brief Determine whether the type \p Derived is a C++ class that is
1669 /// derived from the type \p Base.
1670 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1671   if (!getLangOpts().CPlusPlus)
1672     return false;
1673   
1674   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1675   if (!DerivedRD)
1676     return false;
1677   
1678   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1679   if (!BaseRD)
1680     return false;
1681
1682   // If either the base or the derived type is invalid, don't try to
1683   // check whether one is derived from the other.
1684   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1685     return false;
1686
1687   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1688   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1689 }
1690
1691 /// \brief Determine whether the type \p Derived is a C++ class that is
1692 /// derived from the type \p Base.
1693 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1694   if (!getLangOpts().CPlusPlus)
1695     return false;
1696   
1697   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1698   if (!DerivedRD)
1699     return false;
1700   
1701   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1702   if (!BaseRD)
1703     return false;
1704   
1705   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1706 }
1707
1708 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 
1709                               CXXCastPath &BasePathArray) {
1710   assert(BasePathArray.empty() && "Base path array must be empty!");
1711   assert(Paths.isRecordingPaths() && "Must record paths!");
1712   
1713   const CXXBasePath &Path = Paths.front();
1714        
1715   // We first go backward and check if we have a virtual base.
1716   // FIXME: It would be better if CXXBasePath had the base specifier for
1717   // the nearest virtual base.
1718   unsigned Start = 0;
1719   for (unsigned I = Path.size(); I != 0; --I) {
1720     if (Path[I - 1].Base->isVirtual()) {
1721       Start = I - 1;
1722       break;
1723     }
1724   }
1725
1726   // Now add all bases.
1727   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1728     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1729 }
1730
1731 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1732 /// conversion (where Derived and Base are class types) is
1733 /// well-formed, meaning that the conversion is unambiguous (and
1734 /// that all of the base classes are accessible). Returns true
1735 /// and emits a diagnostic if the code is ill-formed, returns false
1736 /// otherwise. Loc is the location where this routine should point to
1737 /// if there is an error, and Range is the source range to highlight
1738 /// if there is an error.
1739 bool
1740 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1741                                    unsigned InaccessibleBaseID,
1742                                    unsigned AmbigiousBaseConvID,
1743                                    SourceLocation Loc, SourceRange Range,
1744                                    DeclarationName Name,
1745                                    CXXCastPath *BasePath) {
1746   // First, determine whether the path from Derived to Base is
1747   // ambiguous. This is slightly more expensive than checking whether
1748   // the Derived to Base conversion exists, because here we need to
1749   // explore multiple paths to determine if there is an ambiguity.
1750   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1751                      /*DetectVirtual=*/false);
1752   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1753   assert(DerivationOkay &&
1754          "Can only be used with a derived-to-base conversion");
1755   (void)DerivationOkay;
1756   
1757   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1758     if (InaccessibleBaseID) {
1759       // Check that the base class can be accessed.
1760       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1761                                    InaccessibleBaseID)) {
1762         case AR_inaccessible: 
1763           return true;
1764         case AR_accessible: 
1765         case AR_dependent:
1766         case AR_delayed:
1767           break;
1768       }
1769     }
1770     
1771     // Build a base path if necessary.
1772     if (BasePath)
1773       BuildBasePathArray(Paths, *BasePath);
1774     return false;
1775   }
1776   
1777   if (AmbigiousBaseConvID) {
1778     // We know that the derived-to-base conversion is ambiguous, and
1779     // we're going to produce a diagnostic. Perform the derived-to-base
1780     // search just one more time to compute all of the possible paths so
1781     // that we can print them out. This is more expensive than any of
1782     // the previous derived-to-base checks we've done, but at this point
1783     // performance isn't as much of an issue.
1784     Paths.clear();
1785     Paths.setRecordingPaths(true);
1786     bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1787     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1788     (void)StillOkay;
1789
1790     // Build up a textual representation of the ambiguous paths, e.g.,
1791     // D -> B -> A, that will be used to illustrate the ambiguous
1792     // conversions in the diagnostic. We only print one of the paths
1793     // to each base class subobject.
1794     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1795
1796     Diag(Loc, AmbigiousBaseConvID)
1797     << Derived << Base << PathDisplayStr << Range << Name;
1798   }
1799   return true;
1800 }
1801
1802 bool
1803 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1804                                    SourceLocation Loc, SourceRange Range,
1805                                    CXXCastPath *BasePath,
1806                                    bool IgnoreAccess) {
1807   return CheckDerivedToBaseConversion(Derived, Base,
1808                                       IgnoreAccess ? 0
1809                                        : diag::err_upcast_to_inaccessible_base,
1810                                       diag::err_ambiguous_derived_to_base_conv,
1811                                       Loc, Range, DeclarationName(), 
1812                                       BasePath);
1813 }
1814
1815
1816 /// @brief Builds a string representing ambiguous paths from a
1817 /// specific derived class to different subobjects of the same base
1818 /// class.
1819 ///
1820 /// This function builds a string that can be used in error messages
1821 /// to show the different paths that one can take through the
1822 /// inheritance hierarchy to go from the derived class to different
1823 /// subobjects of a base class. The result looks something like this:
1824 /// @code
1825 /// struct D -> struct B -> struct A
1826 /// struct D -> struct C -> struct A
1827 /// @endcode
1828 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1829   std::string PathDisplayStr;
1830   std::set<unsigned> DisplayedPaths;
1831   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1832        Path != Paths.end(); ++Path) {
1833     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1834       // We haven't displayed a path to this particular base
1835       // class subobject yet.
1836       PathDisplayStr += "\n    ";
1837       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1838       for (CXXBasePath::const_iterator Element = Path->begin();
1839            Element != Path->end(); ++Element)
1840         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1841     }
1842   }
1843   
1844   return PathDisplayStr;
1845 }
1846
1847 //===----------------------------------------------------------------------===//
1848 // C++ class member Handling
1849 //===----------------------------------------------------------------------===//
1850
1851 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1852 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1853                                 SourceLocation ASLoc,
1854                                 SourceLocation ColonLoc,
1855                                 AttributeList *Attrs) {
1856   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1857   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1858                                                   ASLoc, ColonLoc);
1859   CurContext->addHiddenDecl(ASDecl);
1860   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1861 }
1862
1863 /// CheckOverrideControl - Check C++11 override control semantics.
1864 void Sema::CheckOverrideControl(NamedDecl *D) {
1865   if (D->isInvalidDecl())
1866     return;
1867
1868   // We only care about "override" and "final" declarations.
1869   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1870     return;
1871
1872   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1873
1874   // We can't check dependent instance methods.
1875   if (MD && MD->isInstance() &&
1876       (MD->getParent()->hasAnyDependentBases() ||
1877        MD->getType()->isDependentType()))
1878     return;
1879
1880   if (MD && !MD->isVirtual()) {
1881     // If we have a non-virtual method, check if if hides a virtual method.
1882     // (In that case, it's most likely the method has the wrong type.)
1883     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1884     FindHiddenVirtualMethods(MD, OverloadedMethods);
1885
1886     if (!OverloadedMethods.empty()) {
1887       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1888         Diag(OA->getLocation(),
1889              diag::override_keyword_hides_virtual_member_function)
1890           << "override" << (OverloadedMethods.size() > 1);
1891       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1892         Diag(FA->getLocation(),
1893              diag::override_keyword_hides_virtual_member_function)
1894           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1895           << (OverloadedMethods.size() > 1);
1896       }
1897       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1898       MD->setInvalidDecl();
1899       return;
1900     }
1901     // Fall through into the general case diagnostic.
1902     // FIXME: We might want to attempt typo correction here.
1903   }
1904
1905   if (!MD || !MD->isVirtual()) {
1906     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1907       Diag(OA->getLocation(),
1908            diag::override_keyword_only_allowed_on_virtual_member_functions)
1909         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1910       D->dropAttr<OverrideAttr>();
1911     }
1912     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1913       Diag(FA->getLocation(),
1914            diag::override_keyword_only_allowed_on_virtual_member_functions)
1915         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1916         << FixItHint::CreateRemoval(FA->getLocation());
1917       D->dropAttr<FinalAttr>();
1918     }
1919     return;
1920   }
1921
1922   // C++11 [class.virtual]p5:
1923   //   If a function is marked with the virt-specifier override and
1924   //   does not override a member function of a base class, the program is
1925   //   ill-formed.
1926   bool HasOverriddenMethods =
1927     MD->begin_overridden_methods() != MD->end_overridden_methods();
1928   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1929     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1930       << MD->getDeclName();
1931 }
1932
1933 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1934   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1935     return;
1936   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1937   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1938       isa<CXXDestructorDecl>(MD))
1939     return;
1940
1941   SourceLocation Loc = MD->getLocation();
1942   SourceLocation SpellingLoc = Loc;
1943   if (getSourceManager().isMacroArgExpansion(Loc))
1944     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1945   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1946   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
1947       return;
1948     
1949   if (MD->size_overridden_methods() > 0) {
1950     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1951       << MD->getDeclName();
1952     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1953     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1954   }
1955 }
1956
1957 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1958 /// function overrides a virtual member function marked 'final', according to
1959 /// C++11 [class.virtual]p4.
1960 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1961                                                   const CXXMethodDecl *Old) {
1962   FinalAttr *FA = Old->getAttr<FinalAttr>();
1963   if (!FA)
1964     return false;
1965
1966   Diag(New->getLocation(), diag::err_final_function_overridden)
1967     << New->getDeclName()
1968     << FA->isSpelledAsSealed();
1969   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1970   return true;
1971 }
1972
1973 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1974   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1975   // FIXME: Destruction of ObjC lifetime types has side-effects.
1976   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1977     return !RD->isCompleteDefinition() ||
1978            !RD->hasTrivialDefaultConstructor() ||
1979            !RD->hasTrivialDestructor();
1980   return false;
1981 }
1982
1983 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1984   for (AttributeList *it = list; it != nullptr; it = it->getNext())
1985     if (it->isDeclspecPropertyAttribute())
1986       return it;
1987   return nullptr;
1988 }
1989
1990 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1991 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1992 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1993 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1994 /// present (but parsing it has been deferred).
1995 NamedDecl *
1996 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1997                                MultiTemplateParamsArg TemplateParameterLists,
1998                                Expr *BW, const VirtSpecifiers &VS,
1999                                InClassInitStyle InitStyle) {
2000   const DeclSpec &DS = D.getDeclSpec();
2001   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2002   DeclarationName Name = NameInfo.getName();
2003   SourceLocation Loc = NameInfo.getLoc();
2004
2005   // For anonymous bitfields, the location should point to the type.
2006   if (Loc.isInvalid())
2007     Loc = D.getLocStart();
2008
2009   Expr *BitWidth = static_cast<Expr*>(BW);
2010
2011   assert(isa<CXXRecordDecl>(CurContext));
2012   assert(!DS.isFriendSpecified());
2013
2014   bool isFunc = D.isDeclarationOfFunction();
2015
2016   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2017     // The Microsoft extension __interface only permits public member functions
2018     // and prohibits constructors, destructors, operators, non-public member
2019     // functions, static methods and data members.
2020     unsigned InvalidDecl;
2021     bool ShowDeclName = true;
2022     if (!isFunc)
2023       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2024     else if (AS != AS_public)
2025       InvalidDecl = 2;
2026     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2027       InvalidDecl = 3;
2028     else switch (Name.getNameKind()) {
2029       case DeclarationName::CXXConstructorName:
2030         InvalidDecl = 4;
2031         ShowDeclName = false;
2032         break;
2033
2034       case DeclarationName::CXXDestructorName:
2035         InvalidDecl = 5;
2036         ShowDeclName = false;
2037         break;
2038
2039       case DeclarationName::CXXOperatorName:
2040       case DeclarationName::CXXConversionFunctionName:
2041         InvalidDecl = 6;
2042         break;
2043
2044       default:
2045         InvalidDecl = 0;
2046         break;
2047     }
2048
2049     if (InvalidDecl) {
2050       if (ShowDeclName)
2051         Diag(Loc, diag::err_invalid_member_in_interface)
2052           << (InvalidDecl-1) << Name;
2053       else
2054         Diag(Loc, diag::err_invalid_member_in_interface)
2055           << (InvalidDecl-1) << "";
2056       return nullptr;
2057     }
2058   }
2059
2060   // C++ 9.2p6: A member shall not be declared to have automatic storage
2061   // duration (auto, register) or with the extern storage-class-specifier.
2062   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2063   // data members and cannot be applied to names declared const or static,
2064   // and cannot be applied to reference members.
2065   switch (DS.getStorageClassSpec()) {
2066   case DeclSpec::SCS_unspecified:
2067   case DeclSpec::SCS_typedef:
2068   case DeclSpec::SCS_static:
2069     break;
2070   case DeclSpec::SCS_mutable:
2071     if (isFunc) {
2072       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2073
2074       // FIXME: It would be nicer if the keyword was ignored only for this
2075       // declarator. Otherwise we could get follow-up errors.
2076       D.getMutableDeclSpec().ClearStorageClassSpecs();
2077     }
2078     break;
2079   default:
2080     Diag(DS.getStorageClassSpecLoc(),
2081          diag::err_storageclass_invalid_for_member);
2082     D.getMutableDeclSpec().ClearStorageClassSpecs();
2083     break;
2084   }
2085
2086   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2087                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2088                       !isFunc);
2089
2090   if (DS.isConstexprSpecified() && isInstField) {
2091     SemaDiagnosticBuilder B =
2092         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2093     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2094     if (InitStyle == ICIS_NoInit) {
2095       B << 0 << 0;
2096       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2097         B << FixItHint::CreateRemoval(ConstexprLoc);
2098       else {
2099         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2100         D.getMutableDeclSpec().ClearConstexprSpec();
2101         const char *PrevSpec;
2102         unsigned DiagID;
2103         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2104             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2105         (void)Failed;
2106         assert(!Failed && "Making a constexpr member const shouldn't fail");
2107       }
2108     } else {
2109       B << 1;
2110       const char *PrevSpec;
2111       unsigned DiagID;
2112       if (D.getMutableDeclSpec().SetStorageClassSpec(
2113           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2114           Context.getPrintingPolicy())) {
2115         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2116                "This is the only DeclSpec that should fail to be applied");
2117         B << 1;
2118       } else {
2119         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2120         isInstField = false;
2121       }
2122     }
2123   }
2124
2125   NamedDecl *Member;
2126   if (isInstField) {
2127     CXXScopeSpec &SS = D.getCXXScopeSpec();
2128
2129     // Data members must have identifiers for names.
2130     if (!Name.isIdentifier()) {
2131       Diag(Loc, diag::err_bad_variable_name)
2132         << Name;
2133       return nullptr;
2134     }
2135
2136     IdentifierInfo *II = Name.getAsIdentifierInfo();
2137
2138     // Member field could not be with "template" keyword.
2139     // So TemplateParameterLists should be empty in this case.
2140     if (TemplateParameterLists.size()) {
2141       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2142       if (TemplateParams->size()) {
2143         // There is no such thing as a member field template.
2144         Diag(D.getIdentifierLoc(), diag::err_template_member)
2145             << II
2146             << SourceRange(TemplateParams->getTemplateLoc(),
2147                 TemplateParams->getRAngleLoc());
2148       } else {
2149         // There is an extraneous 'template<>' for this member.
2150         Diag(TemplateParams->getTemplateLoc(),
2151             diag::err_template_member_noparams)
2152             << II
2153             << SourceRange(TemplateParams->getTemplateLoc(),
2154                 TemplateParams->getRAngleLoc());
2155       }
2156       return nullptr;
2157     }
2158
2159     if (SS.isSet() && !SS.isInvalid()) {
2160       // The user provided a superfluous scope specifier inside a class
2161       // definition:
2162       //
2163       // class X {
2164       //   int X::member;
2165       // };
2166       if (DeclContext *DC = computeDeclContext(SS, false))
2167         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2168       else
2169         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2170           << Name << SS.getRange();
2171       
2172       SS.clear();
2173     }
2174
2175     AttributeList *MSPropertyAttr =
2176       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2177     if (MSPropertyAttr) {
2178       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2179                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2180       if (!Member)
2181         return nullptr;
2182       isInstField = false;
2183     } else {
2184       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2185                                 BitWidth, InitStyle, AS);
2186       assert(Member && "HandleField never returns null");
2187     }
2188   } else {
2189     Member = HandleDeclarator(S, D, TemplateParameterLists);
2190     if (!Member)
2191       return nullptr;
2192
2193     // Non-instance-fields can't have a bitfield.
2194     if (BitWidth) {
2195       if (Member->isInvalidDecl()) {
2196         // don't emit another diagnostic.
2197       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2198         // C++ 9.6p3: A bit-field shall not be a static member.
2199         // "static member 'A' cannot be a bit-field"
2200         Diag(Loc, diag::err_static_not_bitfield)
2201           << Name << BitWidth->getSourceRange();
2202       } else if (isa<TypedefDecl>(Member)) {
2203         // "typedef member 'x' cannot be a bit-field"
2204         Diag(Loc, diag::err_typedef_not_bitfield)
2205           << Name << BitWidth->getSourceRange();
2206       } else {
2207         // A function typedef ("typedef int f(); f a;").
2208         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2209         Diag(Loc, diag::err_not_integral_type_bitfield)
2210           << Name << cast<ValueDecl>(Member)->getType()
2211           << BitWidth->getSourceRange();
2212       }
2213
2214       BitWidth = nullptr;
2215       Member->setInvalidDecl();
2216     }
2217
2218     Member->setAccess(AS);
2219
2220     // If we have declared a member function template or static data member
2221     // template, set the access of the templated declaration as well.
2222     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2223       FunTmpl->getTemplatedDecl()->setAccess(AS);
2224     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2225       VarTmpl->getTemplatedDecl()->setAccess(AS);
2226   }
2227
2228   if (VS.isOverrideSpecified())
2229     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2230   if (VS.isFinalSpecified())
2231     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2232                                             VS.isFinalSpelledSealed()));
2233
2234   if (VS.getLastLocation().isValid()) {
2235     // Update the end location of a method that has a virt-specifiers.
2236     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2237       MD->setRangeEnd(VS.getLastLocation());
2238   }
2239
2240   CheckOverrideControl(Member);
2241
2242   assert((Name || isInstField) && "No identifier for non-field ?");
2243
2244   if (isInstField) {
2245     FieldDecl *FD = cast<FieldDecl>(Member);
2246     FieldCollector->Add(FD);
2247
2248     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2249       // Remember all explicit private FieldDecls that have a name, no side
2250       // effects and are not part of a dependent type declaration.
2251       if (!FD->isImplicit() && FD->getDeclName() &&
2252           FD->getAccess() == AS_private &&
2253           !FD->hasAttr<UnusedAttr>() &&
2254           !FD->getParent()->isDependentContext() &&
2255           !InitializationHasSideEffects(*FD))
2256         UnusedPrivateFields.insert(FD);
2257     }
2258   }
2259
2260   return Member;
2261 }
2262
2263 namespace {
2264   class UninitializedFieldVisitor
2265       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2266     Sema &S;
2267     // List of Decls to generate a warning on.  Also remove Decls that become
2268     // initialized.
2269     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2270     // List of base classes of the record.  Classes are removed after their
2271     // initializers.
2272     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
2273     // Vector of decls to be removed from the Decl set prior to visiting the
2274     // nodes.  These Decls may have been initialized in the prior initializer.
2275     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2276     // If non-null, add a note to the warning pointing back to the constructor.
2277     const CXXConstructorDecl *Constructor;
2278     // Variables to hold state when processing an initializer list.  When
2279     // InitList is true, special case initialization of FieldDecls matching
2280     // InitListFieldDecl.
2281     bool InitList;
2282     FieldDecl *InitListFieldDecl;
2283     llvm::SmallVector<unsigned, 4> InitFieldIndex;
2284
2285   public:
2286     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2287     UninitializedFieldVisitor(Sema &S,
2288                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2289                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2290       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2291         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
2292
2293     // Returns true if the use of ME is not an uninitialized use.
2294     bool IsInitListMemberExprInitialized(MemberExpr *ME,
2295                                          bool CheckReferenceOnly) {
2296       llvm::SmallVector<FieldDecl*, 4> Fields;
2297       bool ReferenceField = false;
2298       while (ME) {
2299         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2300         if (!FD)
2301           return false;
2302         Fields.push_back(FD);
2303         if (FD->getType()->isReferenceType())
2304           ReferenceField = true;
2305         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2306       }
2307
2308       // Binding a reference to an unintialized field is not an
2309       // uninitialized use.
2310       if (CheckReferenceOnly && !ReferenceField)
2311         return true;
2312
2313       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2314       // Discard the first field since it is the field decl that is being
2315       // initialized.
2316       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2317         UsedFieldIndex.push_back((*I)->getFieldIndex());
2318       }
2319
2320       for (auto UsedIter = UsedFieldIndex.begin(),
2321                 UsedEnd = UsedFieldIndex.end(),
2322                 OrigIter = InitFieldIndex.begin(),
2323                 OrigEnd = InitFieldIndex.end();
2324            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2325         if (*UsedIter < *OrigIter)
2326           return true;
2327         if (*UsedIter > *OrigIter)
2328           break;
2329       }
2330
2331       return false;
2332     }
2333
2334     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2335                           bool AddressOf) {
2336       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2337         return;
2338
2339       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2340       // or union.
2341       MemberExpr *FieldME = ME;
2342
2343       bool AllPODFields = FieldME->getType().isPODType(S.Context);
2344
2345       Expr *Base = ME;
2346       while (MemberExpr *SubME =
2347                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
2348
2349         if (isa<VarDecl>(SubME->getMemberDecl()))
2350           return;
2351
2352         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
2353           if (!FD->isAnonymousStructOrUnion())
2354             FieldME = SubME;
2355
2356         if (!FieldME->getType().isPODType(S.Context))
2357           AllPODFields = false;
2358
2359         Base = SubME->getBase();
2360       }
2361
2362       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
2363         return;
2364
2365       if (AddressOf && AllPODFields)
2366         return;
2367
2368       ValueDecl* FoundVD = FieldME->getMemberDecl();
2369
2370       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2371         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2372           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2373         }
2374
2375         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2376           QualType T = BaseCast->getType();
2377           if (T->isPointerType() &&
2378               BaseClasses.count(T->getPointeeType())) {
2379             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2380                 << T->getPointeeType() << FoundVD;
2381           }
2382         }
2383       }
2384
2385       if (!Decls.count(FoundVD))
2386         return;
2387
2388       const bool IsReference = FoundVD->getType()->isReferenceType();
2389
2390       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2391         // Special checking for initializer lists.
2392         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2393           return;
2394         }
2395       } else {
2396         // Prevent double warnings on use of unbounded references.
2397         if (CheckReferenceOnly && !IsReference)
2398           return;
2399       }
2400
2401       unsigned diag = IsReference
2402           ? diag::warn_reference_field_is_uninit
2403           : diag::warn_field_is_uninit;
2404       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2405       if (Constructor)
2406         S.Diag(Constructor->getLocation(),
2407                diag::note_uninit_in_this_constructor)
2408           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2409
2410     }
2411
2412     void HandleValue(Expr *E, bool AddressOf) {
2413       E = E->IgnoreParens();
2414
2415       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2416         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2417                          AddressOf /*AddressOf*/);
2418         return;
2419       }
2420
2421       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2422         Visit(CO->getCond());
2423         HandleValue(CO->getTrueExpr(), AddressOf);
2424         HandleValue(CO->getFalseExpr(), AddressOf);
2425         return;
2426       }
2427
2428       if (BinaryConditionalOperator *BCO =
2429               dyn_cast<BinaryConditionalOperator>(E)) {
2430         Visit(BCO->getCond());
2431         HandleValue(BCO->getFalseExpr(), AddressOf);
2432         return;
2433       }
2434
2435       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2436         HandleValue(OVE->getSourceExpr(), AddressOf);
2437         return;
2438       }
2439
2440       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2441         switch (BO->getOpcode()) {
2442         default:
2443           break;
2444         case(BO_PtrMemD):
2445         case(BO_PtrMemI):
2446           HandleValue(BO->getLHS(), AddressOf);
2447           Visit(BO->getRHS());
2448           return;
2449         case(BO_Comma):
2450           Visit(BO->getLHS());
2451           HandleValue(BO->getRHS(), AddressOf);
2452           return;
2453         }
2454       }
2455
2456       Visit(E);
2457     }
2458
2459     void CheckInitListExpr(InitListExpr *ILE) {
2460       InitFieldIndex.push_back(0);
2461       for (auto Child : ILE->children()) {
2462         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2463           CheckInitListExpr(SubList);
2464         } else {
2465           Visit(Child);
2466         }
2467         ++InitFieldIndex.back();
2468       }
2469       InitFieldIndex.pop_back();
2470     }
2471
2472     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2473                           FieldDecl *Field, const Type *BaseClass) {
2474       // Remove Decls that may have been initialized in the previous
2475       // initializer.
2476       for (ValueDecl* VD : DeclsToRemove)
2477         Decls.erase(VD);
2478       DeclsToRemove.clear();
2479
2480       Constructor = FieldConstructor;
2481       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2482
2483       if (ILE && Field) {
2484         InitList = true;
2485         InitListFieldDecl = Field;
2486         InitFieldIndex.clear();
2487         CheckInitListExpr(ILE);
2488       } else {
2489         InitList = false;
2490         Visit(E);
2491       }
2492
2493       if (Field)
2494         Decls.erase(Field);
2495       if (BaseClass)
2496         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
2497     }
2498
2499     void VisitMemberExpr(MemberExpr *ME) {
2500       // All uses of unbounded reference fields will warn.
2501       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
2502     }
2503
2504     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2505       if (E->getCastKind() == CK_LValueToRValue) {
2506         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2507         return;
2508       }
2509
2510       Inherited::VisitImplicitCastExpr(E);
2511     }
2512
2513     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2514       if (E->getConstructor()->isCopyConstructor()) {
2515         Expr *ArgExpr = E->getArg(0);
2516         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2517           if (ILE->getNumInits() == 1)
2518             ArgExpr = ILE->getInit(0);
2519         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2520           if (ICE->getCastKind() == CK_NoOp)
2521             ArgExpr = ICE->getSubExpr();
2522         HandleValue(ArgExpr, false /*AddressOf*/);
2523         return;
2524       }
2525       Inherited::VisitCXXConstructExpr(E);
2526     }
2527
2528     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2529       Expr *Callee = E->getCallee();
2530       if (isa<MemberExpr>(Callee)) {
2531         HandleValue(Callee, false /*AddressOf*/);
2532         for (auto Arg : E->arguments())
2533           Visit(Arg);
2534         return;
2535       }
2536
2537       Inherited::VisitCXXMemberCallExpr(E);
2538     }
2539
2540     void VisitCallExpr(CallExpr *E) {
2541       // Treat std::move as a use.
2542       if (E->getNumArgs() == 1) {
2543         if (FunctionDecl *FD = E->getDirectCallee()) {
2544           if (FD->isInStdNamespace() && FD->getIdentifier() &&
2545               FD->getIdentifier()->isStr("move")) {
2546             HandleValue(E->getArg(0), false /*AddressOf*/);
2547             return;
2548           }
2549         }
2550       }
2551
2552       Inherited::VisitCallExpr(E);
2553     }
2554
2555     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2556       Expr *Callee = E->getCallee();
2557
2558       if (isa<UnresolvedLookupExpr>(Callee))
2559         return Inherited::VisitCXXOperatorCallExpr(E);
2560
2561       Visit(Callee);
2562       for (auto Arg : E->arguments())
2563         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2564     }
2565
2566     void VisitBinaryOperator(BinaryOperator *E) {
2567       // If a field assignment is detected, remove the field from the
2568       // uninitiailized field set.
2569       if (E->getOpcode() == BO_Assign)
2570         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2571           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2572             if (!FD->getType()->isReferenceType())
2573               DeclsToRemove.push_back(FD);
2574
2575       if (E->isCompoundAssignmentOp()) {
2576         HandleValue(E->getLHS(), false /*AddressOf*/);
2577         Visit(E->getRHS());
2578         return;
2579       }
2580
2581       Inherited::VisitBinaryOperator(E);
2582     }
2583
2584     void VisitUnaryOperator(UnaryOperator *E) {
2585       if (E->isIncrementDecrementOp()) {
2586         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2587         return;
2588       }
2589       if (E->getOpcode() == UO_AddrOf) {
2590         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2591           HandleValue(ME->getBase(), true /*AddressOf*/);
2592           return;
2593         }
2594       }
2595
2596       Inherited::VisitUnaryOperator(E);
2597     }
2598   };
2599
2600   // Diagnose value-uses of fields to initialize themselves, e.g.
2601   //   foo(foo)
2602   // where foo is not also a parameter to the constructor.
2603   // Also diagnose across field uninitialized use such as
2604   //   x(y), y(x)
2605   // TODO: implement -Wuninitialized and fold this into that framework.
2606   static void DiagnoseUninitializedFields(
2607       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2608
2609     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2610                                            Constructor->getLocation())) {
2611       return;
2612     }
2613
2614     if (Constructor->isInvalidDecl())
2615       return;
2616
2617     const CXXRecordDecl *RD = Constructor->getParent();
2618
2619     if (RD->getDescribedClassTemplate())
2620       return;
2621
2622     // Holds fields that are uninitialized.
2623     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2624
2625     // At the beginning, all fields are uninitialized.
2626     for (auto *I : RD->decls()) {
2627       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2628         UninitializedFields.insert(FD);
2629       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2630         UninitializedFields.insert(IFD->getAnonField());
2631       }
2632     }
2633
2634     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2635     for (auto I : RD->bases())
2636       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2637
2638     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2639       return;
2640
2641     UninitializedFieldVisitor UninitializedChecker(SemaRef,
2642                                                    UninitializedFields,
2643                                                    UninitializedBaseClasses);
2644
2645     for (const auto *FieldInit : Constructor->inits()) {
2646       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2647         break;
2648
2649       Expr *InitExpr = FieldInit->getInit();
2650       if (!InitExpr)
2651         continue;
2652
2653       if (CXXDefaultInitExpr *Default =
2654               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2655         InitExpr = Default->getExpr();
2656         if (!InitExpr)
2657           continue;
2658         // In class initializers will point to the constructor.
2659         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2660                                               FieldInit->getAnyMember(),
2661                                               FieldInit->getBaseClass());
2662       } else {
2663         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2664                                               FieldInit->getAnyMember(),
2665                                               FieldInit->getBaseClass());
2666       }
2667     }
2668   }
2669 } // namespace
2670
2671 /// \brief Enter a new C++ default initializer scope. After calling this, the
2672 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2673 /// parsing or instantiating the initializer failed.
2674 void Sema::ActOnStartCXXInClassMemberInitializer() {
2675   // Create a synthetic function scope to represent the call to the constructor
2676   // that notionally surrounds a use of this initializer.
2677   PushFunctionScope();
2678 }
2679
2680 /// \brief This is invoked after parsing an in-class initializer for a
2681 /// non-static C++ class member, and after instantiating an in-class initializer
2682 /// in a class template. Such actions are deferred until the class is complete.
2683 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2684                                                   SourceLocation InitLoc,
2685                                                   Expr *InitExpr) {
2686   // Pop the notional constructor scope we created earlier.
2687   PopFunctionScopeInfo(nullptr, D);
2688
2689   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2690   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
2691          "must set init style when field is created");
2692
2693   if (!InitExpr) {
2694     D->setInvalidDecl();
2695     if (FD)
2696       FD->removeInClassInitializer();
2697     return;
2698   }
2699
2700   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2701     FD->setInvalidDecl();
2702     FD->removeInClassInitializer();
2703     return;
2704   }
2705
2706   ExprResult Init = InitExpr;
2707   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2708     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2709     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2710         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2711         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2712     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2713     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2714     if (Init.isInvalid()) {
2715       FD->setInvalidDecl();
2716       return;
2717     }
2718   }
2719
2720   // C++11 [class.base.init]p7:
2721   //   The initialization of each base and member constitutes a
2722   //   full-expression.
2723   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2724   if (Init.isInvalid()) {
2725     FD->setInvalidDecl();
2726     return;
2727   }
2728
2729   InitExpr = Init.get();
2730
2731   FD->setInClassInitializer(InitExpr);
2732 }
2733
2734 /// \brief Find the direct and/or virtual base specifiers that
2735 /// correspond to the given base type, for use in base initialization
2736 /// within a constructor.
2737 static bool FindBaseInitializer(Sema &SemaRef, 
2738                                 CXXRecordDecl *ClassDecl,
2739                                 QualType BaseType,
2740                                 const CXXBaseSpecifier *&DirectBaseSpec,
2741                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2742   // First, check for a direct base class.
2743   DirectBaseSpec = nullptr;
2744   for (const auto &Base : ClassDecl->bases()) {
2745     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2746       // We found a direct base of this type. That's what we're
2747       // initializing.
2748       DirectBaseSpec = &Base;
2749       break;
2750     }
2751   }
2752
2753   // Check for a virtual base class.
2754   // FIXME: We might be able to short-circuit this if we know in advance that
2755   // there are no virtual bases.
2756   VirtualBaseSpec = nullptr;
2757   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2758     // We haven't found a base yet; search the class hierarchy for a
2759     // virtual base class.
2760     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2761                        /*DetectVirtual=*/false);
2762     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 
2763                               BaseType, Paths)) {
2764       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2765            Path != Paths.end(); ++Path) {
2766         if (Path->back().Base->isVirtual()) {
2767           VirtualBaseSpec = Path->back().Base;
2768           break;
2769         }
2770       }
2771     }
2772   }
2773
2774   return DirectBaseSpec || VirtualBaseSpec;
2775 }
2776
2777 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2778 MemInitResult
2779 Sema::ActOnMemInitializer(Decl *ConstructorD,
2780                           Scope *S,
2781                           CXXScopeSpec &SS,
2782                           IdentifierInfo *MemberOrBase,
2783                           ParsedType TemplateTypeTy,
2784                           const DeclSpec &DS,
2785                           SourceLocation IdLoc,
2786                           Expr *InitList,
2787                           SourceLocation EllipsisLoc) {
2788   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2789                              DS, IdLoc, InitList,
2790                              EllipsisLoc);
2791 }
2792
2793 /// \brief Handle a C++ member initializer using parentheses syntax.
2794 MemInitResult
2795 Sema::ActOnMemInitializer(Decl *ConstructorD,
2796                           Scope *S,
2797                           CXXScopeSpec &SS,
2798                           IdentifierInfo *MemberOrBase,
2799                           ParsedType TemplateTypeTy,
2800                           const DeclSpec &DS,
2801                           SourceLocation IdLoc,
2802                           SourceLocation LParenLoc,
2803                           ArrayRef<Expr *> Args,
2804                           SourceLocation RParenLoc,
2805                           SourceLocation EllipsisLoc) {
2806   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2807                                            Args, RParenLoc);
2808   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2809                              DS, IdLoc, List, EllipsisLoc);
2810 }
2811
2812 namespace {
2813
2814 // Callback to only accept typo corrections that can be a valid C++ member
2815 // intializer: either a non-static field member or a base class.
2816 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2817 public:
2818   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2819       : ClassDecl(ClassDecl) {}
2820
2821   bool ValidateCandidate(const TypoCorrection &candidate) override {
2822     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2823       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2824         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2825       return isa<TypeDecl>(ND);
2826     }
2827     return false;
2828   }
2829
2830 private:
2831   CXXRecordDecl *ClassDecl;
2832 };
2833
2834 }
2835
2836 /// \brief Handle a C++ member initializer.
2837 MemInitResult
2838 Sema::BuildMemInitializer(Decl *ConstructorD,
2839                           Scope *S,
2840                           CXXScopeSpec &SS,
2841                           IdentifierInfo *MemberOrBase,
2842                           ParsedType TemplateTypeTy,
2843                           const DeclSpec &DS,
2844                           SourceLocation IdLoc,
2845                           Expr *Init,
2846                           SourceLocation EllipsisLoc) {
2847   ExprResult Res = CorrectDelayedTyposInExpr(Init);
2848   if (!Res.isUsable())
2849     return true;
2850   Init = Res.get();
2851
2852   if (!ConstructorD)
2853     return true;
2854
2855   AdjustDeclIfTemplate(ConstructorD);
2856
2857   CXXConstructorDecl *Constructor
2858     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2859   if (!Constructor) {
2860     // The user wrote a constructor initializer on a function that is
2861     // not a C++ constructor. Ignore the error for now, because we may
2862     // have more member initializers coming; we'll diagnose it just
2863     // once in ActOnMemInitializers.
2864     return true;
2865   }
2866
2867   CXXRecordDecl *ClassDecl = Constructor->getParent();
2868
2869   // C++ [class.base.init]p2:
2870   //   Names in a mem-initializer-id are looked up in the scope of the
2871   //   constructor's class and, if not found in that scope, are looked
2872   //   up in the scope containing the constructor's definition.
2873   //   [Note: if the constructor's class contains a member with the
2874   //   same name as a direct or virtual base class of the class, a
2875   //   mem-initializer-id naming the member or base class and composed
2876   //   of a single identifier refers to the class member. A
2877   //   mem-initializer-id for the hidden base class may be specified
2878   //   using a qualified name. ]
2879   if (!SS.getScopeRep() && !TemplateTypeTy) {
2880     // Look for a member, first.
2881     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
2882     if (!Result.empty()) {
2883       ValueDecl *Member;
2884       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2885           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2886         if (EllipsisLoc.isValid())
2887           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2888             << MemberOrBase
2889             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2890
2891         return BuildMemberInitializer(Member, Init, IdLoc);
2892       }
2893     }
2894   }
2895   // It didn't name a member, so see if it names a class.
2896   QualType BaseType;
2897   TypeSourceInfo *TInfo = nullptr;
2898
2899   if (TemplateTypeTy) {
2900     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2901   } else if (DS.getTypeSpecType() == TST_decltype) {
2902     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2903   } else {
2904     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2905     LookupParsedName(R, S, &SS);
2906
2907     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2908     if (!TyD) {
2909       if (R.isAmbiguous()) return true;
2910
2911       // We don't want access-control diagnostics here.
2912       R.suppressDiagnostics();
2913
2914       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2915         bool NotUnknownSpecialization = false;
2916         DeclContext *DC = computeDeclContext(SS, false);
2917         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 
2918           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2919
2920         if (!NotUnknownSpecialization) {
2921           // When the scope specifier can refer to a member of an unknown
2922           // specialization, we take it as a type name.
2923           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2924                                        SS.getWithLocInContext(Context),
2925                                        *MemberOrBase, IdLoc);
2926           if (BaseType.isNull())
2927             return true;
2928
2929           R.clear();
2930           R.setLookupName(MemberOrBase);
2931         }
2932       }
2933
2934       // If no results were found, try to correct typos.
2935       TypoCorrection Corr;
2936       if (R.empty() && BaseType.isNull() &&
2937           (Corr = CorrectTypo(
2938                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2939                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2940                CTK_ErrorRecovery, ClassDecl))) {
2941         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2942           // We have found a non-static data member with a similar
2943           // name to what was typed; complain and initialize that
2944           // member.
2945           diagnoseTypo(Corr,
2946                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2947                          << MemberOrBase << true);
2948           return BuildMemberInitializer(Member, Init, IdLoc);
2949         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2950           const CXXBaseSpecifier *DirectBaseSpec;
2951           const CXXBaseSpecifier *VirtualBaseSpec;
2952           if (FindBaseInitializer(*this, ClassDecl, 
2953                                   Context.getTypeDeclType(Type),
2954                                   DirectBaseSpec, VirtualBaseSpec)) {
2955             // We have found a direct or virtual base class with a
2956             // similar name to what was typed; complain and initialize
2957             // that base class.
2958             diagnoseTypo(Corr,
2959                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2960                            << MemberOrBase << false,
2961                          PDiag() /*Suppress note, we provide our own.*/);
2962
2963             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2964                                                               : VirtualBaseSpec;
2965             Diag(BaseSpec->getLocStart(),
2966                  diag::note_base_class_specified_here)
2967               << BaseSpec->getType()
2968               << BaseSpec->getSourceRange();
2969
2970             TyD = Type;
2971           }
2972         }
2973       }
2974
2975       if (!TyD && BaseType.isNull()) {
2976         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2977           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2978         return true;
2979       }
2980     }
2981
2982     if (BaseType.isNull()) {
2983       BaseType = Context.getTypeDeclType(TyD);
2984       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
2985       if (SS.isSet())
2986         // FIXME: preserve source range information
2987         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2988                                              BaseType);
2989     }
2990   }
2991
2992   if (!TInfo)
2993     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2994
2995   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2996 }
2997
2998 /// Checks a member initializer expression for cases where reference (or
2999 /// pointer) members are bound to by-value parameters (or their addresses).
3000 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3001                                                Expr *Init,
3002                                                SourceLocation IdLoc) {
3003   QualType MemberTy = Member->getType();
3004
3005   // We only handle pointers and references currently.
3006   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3007   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3008     return;
3009
3010   const bool IsPointer = MemberTy->isPointerType();
3011   if (IsPointer) {
3012     if (const UnaryOperator *Op
3013           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3014       // The only case we're worried about with pointers requires taking the
3015       // address.
3016       if (Op->getOpcode() != UO_AddrOf)
3017         return;
3018
3019       Init = Op->getSubExpr();
3020     } else {
3021       // We only handle address-of expression initializers for pointers.
3022       return;
3023     }
3024   }
3025
3026   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3027     // We only warn when referring to a non-reference parameter declaration.
3028     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3029     if (!Parameter || Parameter->getType()->isReferenceType())
3030       return;
3031
3032     S.Diag(Init->getExprLoc(),
3033            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3034                      : diag::warn_bind_ref_member_to_parameter)
3035       << Member << Parameter << Init->getSourceRange();
3036   } else {
3037     // Other initializers are fine.
3038     return;
3039   }
3040
3041   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3042     << (unsigned)IsPointer;
3043 }
3044
3045 MemInitResult
3046 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3047                              SourceLocation IdLoc) {
3048   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3049   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3050   assert((DirectMember || IndirectMember) &&
3051          "Member must be a FieldDecl or IndirectFieldDecl");
3052
3053   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3054     return true;
3055
3056   if (Member->isInvalidDecl())
3057     return true;
3058
3059   MultiExprArg Args;
3060   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3061     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3062   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3063     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3064   } else {
3065     // Template instantiation doesn't reconstruct ParenListExprs for us.
3066     Args = Init;
3067   }
3068
3069   SourceRange InitRange = Init->getSourceRange();
3070
3071   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3072     // Can't check initialization for a member of dependent type or when
3073     // any of the arguments are type-dependent expressions.
3074     DiscardCleanupsInEvaluationContext();
3075   } else {
3076     bool InitList = false;
3077     if (isa<InitListExpr>(Init)) {
3078       InitList = true;
3079       Args = Init;
3080     }
3081
3082     // Initialize the member.
3083     InitializedEntity MemberEntity =
3084       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3085                    : InitializedEntity::InitializeMember(IndirectMember,
3086                                                          nullptr);
3087     InitializationKind Kind =
3088       InitList ? InitializationKind::CreateDirectList(IdLoc)
3089                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3090                                                   InitRange.getEnd());
3091
3092     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3093     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3094                                             nullptr);
3095     if (MemberInit.isInvalid())
3096       return true;
3097
3098     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3099
3100     // C++11 [class.base.init]p7:
3101     //   The initialization of each base and member constitutes a
3102     //   full-expression.
3103     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3104     if (MemberInit.isInvalid())
3105       return true;
3106
3107     Init = MemberInit.get();
3108   }
3109
3110   if (DirectMember) {
3111     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3112                                             InitRange.getBegin(), Init,
3113                                             InitRange.getEnd());
3114   } else {
3115     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3116                                             InitRange.getBegin(), Init,
3117                                             InitRange.getEnd());
3118   }
3119 }
3120
3121 MemInitResult
3122 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3123                                  CXXRecordDecl *ClassDecl) {
3124   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3125   if (!LangOpts.CPlusPlus11)
3126     return Diag(NameLoc, diag::err_delegating_ctor)
3127       << TInfo->getTypeLoc().getLocalSourceRange();
3128   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3129
3130   bool InitList = true;
3131   MultiExprArg Args = Init;
3132   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3133     InitList = false;
3134     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3135   }
3136
3137   SourceRange InitRange = Init->getSourceRange();
3138   // Initialize the object.
3139   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3140                                      QualType(ClassDecl->getTypeForDecl(), 0));
3141   InitializationKind Kind =
3142     InitList ? InitializationKind::CreateDirectList(NameLoc)
3143              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3144                                                 InitRange.getEnd());
3145   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3146   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3147                                               Args, nullptr);
3148   if (DelegationInit.isInvalid())
3149     return true;
3150
3151   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3152          "Delegating constructor with no target?");
3153
3154   // C++11 [class.base.init]p7:
3155   //   The initialization of each base and member constitutes a
3156   //   full-expression.
3157   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3158                                        InitRange.getBegin());
3159   if (DelegationInit.isInvalid())
3160     return true;
3161
3162   // If we are in a dependent context, template instantiation will
3163   // perform this type-checking again. Just save the arguments that we
3164   // received in a ParenListExpr.
3165   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3166   // of the information that we have about the base
3167   // initializer. However, deconstructing the ASTs is a dicey process,
3168   // and this approach is far more likely to get the corner cases right.
3169   if (CurContext->isDependentContext())
3170     DelegationInit = Init;
3171
3172   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 
3173                                           DelegationInit.getAs<Expr>(),
3174                                           InitRange.getEnd());
3175 }
3176
3177 MemInitResult
3178 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3179                            Expr *Init, CXXRecordDecl *ClassDecl,
3180                            SourceLocation EllipsisLoc) {
3181   SourceLocation BaseLoc
3182     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3183
3184   if (!BaseType->isDependentType() && !BaseType->isRecordType())
3185     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3186              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3187
3188   // C++ [class.base.init]p2:
3189   //   [...] Unless the mem-initializer-id names a nonstatic data
3190   //   member of the constructor's class or a direct or virtual base
3191   //   of that class, the mem-initializer is ill-formed. A
3192   //   mem-initializer-list can initialize a base class using any
3193   //   name that denotes that base class type.
3194   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3195
3196   SourceRange InitRange = Init->getSourceRange();
3197   if (EllipsisLoc.isValid()) {
3198     // This is a pack expansion.
3199     if (!BaseType->containsUnexpandedParameterPack())  {
3200       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3201         << SourceRange(BaseLoc, InitRange.getEnd());
3202
3203       EllipsisLoc = SourceLocation();
3204     }
3205   } else {
3206     // Check for any unexpanded parameter packs.
3207     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3208       return true;
3209
3210     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3211       return true;
3212   }
3213
3214   // Check for direct and virtual base classes.
3215   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3216   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3217   if (!Dependent) { 
3218     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3219                                        BaseType))
3220       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3221
3222     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 
3223                         VirtualBaseSpec);
3224
3225     // C++ [base.class.init]p2:
3226     // Unless the mem-initializer-id names a nonstatic data member of the
3227     // constructor's class or a direct or virtual base of that class, the
3228     // mem-initializer is ill-formed.
3229     if (!DirectBaseSpec && !VirtualBaseSpec) {
3230       // If the class has any dependent bases, then it's possible that
3231       // one of those types will resolve to the same type as
3232       // BaseType. Therefore, just treat this as a dependent base
3233       // class initialization.  FIXME: Should we try to check the
3234       // initialization anyway? It seems odd.
3235       if (ClassDecl->hasAnyDependentBases())
3236         Dependent = true;
3237       else
3238         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3239           << BaseType << Context.getTypeDeclType(ClassDecl)
3240           << BaseTInfo->getTypeLoc().getLocalSourceRange();
3241     }
3242   }
3243
3244   if (Dependent) {
3245     DiscardCleanupsInEvaluationContext();
3246
3247     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3248                                             /*IsVirtual=*/false,
3249                                             InitRange.getBegin(), Init,
3250                                             InitRange.getEnd(), EllipsisLoc);
3251   }
3252
3253   // C++ [base.class.init]p2:
3254   //   If a mem-initializer-id is ambiguous because it designates both
3255   //   a direct non-virtual base class and an inherited virtual base
3256   //   class, the mem-initializer is ill-formed.
3257   if (DirectBaseSpec && VirtualBaseSpec)
3258     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3259       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3260
3261   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3262   if (!BaseSpec)
3263     BaseSpec = VirtualBaseSpec;
3264
3265   // Initialize the base.
3266   bool InitList = true;
3267   MultiExprArg Args = Init;
3268   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3269     InitList = false;
3270     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3271   }
3272
3273   InitializedEntity BaseEntity =
3274     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3275   InitializationKind Kind =
3276     InitList ? InitializationKind::CreateDirectList(BaseLoc)
3277              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3278                                                 InitRange.getEnd());
3279   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3280   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3281   if (BaseInit.isInvalid())
3282     return true;
3283
3284   // C++11 [class.base.init]p7:
3285   //   The initialization of each base and member constitutes a
3286   //   full-expression.
3287   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3288   if (BaseInit.isInvalid())
3289     return true;
3290
3291   // If we are in a dependent context, template instantiation will
3292   // perform this type-checking again. Just save the arguments that we
3293   // received in a ParenListExpr.
3294   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3295   // of the information that we have about the base
3296   // initializer. However, deconstructing the ASTs is a dicey process,
3297   // and this approach is far more likely to get the corner cases right.
3298   if (CurContext->isDependentContext())
3299     BaseInit = Init;
3300
3301   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3302                                           BaseSpec->isVirtual(),
3303                                           InitRange.getBegin(),
3304                                           BaseInit.getAs<Expr>(),
3305                                           InitRange.getEnd(), EllipsisLoc);
3306 }
3307
3308 // Create a static_cast\<T&&>(expr).
3309 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3310   if (T.isNull()) T = E->getType();
3311   QualType TargetType = SemaRef.BuildReferenceType(
3312       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3313   SourceLocation ExprLoc = E->getLocStart();
3314   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3315       TargetType, ExprLoc);
3316
3317   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3318                                    SourceRange(ExprLoc, ExprLoc),
3319                                    E->getSourceRange()).get();
3320 }
3321
3322 /// ImplicitInitializerKind - How an implicit base or member initializer should
3323 /// initialize its base or member.
3324 enum ImplicitInitializerKind {
3325   IIK_Default,
3326   IIK_Copy,
3327   IIK_Move,
3328   IIK_Inherit
3329 };
3330
3331 static bool
3332 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3333                              ImplicitInitializerKind ImplicitInitKind,
3334                              CXXBaseSpecifier *BaseSpec,
3335                              bool IsInheritedVirtualBase,
3336                              CXXCtorInitializer *&CXXBaseInit) {
3337   InitializedEntity InitEntity
3338     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3339                                         IsInheritedVirtualBase);
3340
3341   ExprResult BaseInit;
3342   
3343   switch (ImplicitInitKind) {
3344   case IIK_Inherit: {
3345     const CXXRecordDecl *Inherited =
3346         Constructor->getInheritedConstructor()->getParent();
3347     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3348     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3349       // C++11 [class.inhctor]p8:
3350       //   Each expression in the expression-list is of the form
3351       //   static_cast<T&&>(p), where p is the name of the corresponding
3352       //   constructor parameter and T is the declared type of p.
3353       SmallVector<Expr*, 16> Args;
3354       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3355         ParmVarDecl *PD = Constructor->getParamDecl(I);
3356         ExprResult ArgExpr =
3357             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3358                                      VK_LValue, SourceLocation());
3359         if (ArgExpr.isInvalid())
3360           return true;
3361         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3362       }
3363
3364       InitializationKind InitKind = InitializationKind::CreateDirect(
3365           Constructor->getLocation(), SourceLocation(), SourceLocation());
3366       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3367       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3368       break;
3369     }
3370   }
3371   // Fall through.
3372   case IIK_Default: {
3373     InitializationKind InitKind
3374       = InitializationKind::CreateDefault(Constructor->getLocation());
3375     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3376     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3377     break;
3378   }
3379
3380   case IIK_Move:
3381   case IIK_Copy: {
3382     bool Moving = ImplicitInitKind == IIK_Move;
3383     ParmVarDecl *Param = Constructor->getParamDecl(0);
3384     QualType ParamType = Param->getType().getNonReferenceType();
3385
3386     Expr *CopyCtorArg = 
3387       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3388                           SourceLocation(), Param, false,
3389                           Constructor->getLocation(), ParamType,
3390                           VK_LValue, nullptr);
3391
3392     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3393
3394     // Cast to the base class to avoid ambiguities.
3395     QualType ArgTy = 
3396       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 
3397                                        ParamType.getQualifiers());
3398
3399     if (Moving) {
3400       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3401     }
3402
3403     CXXCastPath BasePath;
3404     BasePath.push_back(BaseSpec);
3405     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3406                                             CK_UncheckedDerivedToBase,
3407                                             Moving ? VK_XValue : VK_LValue,
3408                                             &BasePath).get();
3409
3410     InitializationKind InitKind
3411       = InitializationKind::CreateDirect(Constructor->getLocation(),
3412                                          SourceLocation(), SourceLocation());
3413     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3414     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3415     break;
3416   }
3417   }
3418
3419   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3420   if (BaseInit.isInvalid())
3421     return true;
3422         
3423   CXXBaseInit =
3424     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3425                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 
3426                                                         SourceLocation()),
3427                                              BaseSpec->isVirtual(),
3428                                              SourceLocation(),
3429                                              BaseInit.getAs<Expr>(),
3430                                              SourceLocation(),
3431                                              SourceLocation());
3432
3433   return false;
3434 }
3435
3436 static bool RefersToRValueRef(Expr *MemRef) {
3437   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3438   return Referenced->getType()->isRValueReferenceType();
3439 }
3440
3441 static bool
3442 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3443                                ImplicitInitializerKind ImplicitInitKind,
3444                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3445                                CXXCtorInitializer *&CXXMemberInit) {
3446   if (Field->isInvalidDecl())
3447     return true;
3448
3449   SourceLocation Loc = Constructor->getLocation();
3450
3451   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3452     bool Moving = ImplicitInitKind == IIK_Move;
3453     ParmVarDecl *Param = Constructor->getParamDecl(0);
3454     QualType ParamType = Param->getType().getNonReferenceType();
3455
3456     // Suppress copying zero-width bitfields.
3457     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3458       return false;
3459         
3460     Expr *MemberExprBase = 
3461       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3462                           SourceLocation(), Param, false,
3463                           Loc, ParamType, VK_LValue, nullptr);
3464
3465     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3466
3467     if (Moving) {
3468       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3469     }
3470
3471     // Build a reference to this field within the parameter.
3472     CXXScopeSpec SS;
3473     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3474                               Sema::LookupMemberName);
3475     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3476                                   : cast<ValueDecl>(Field), AS_public);
3477     MemberLookup.resolveKind();
3478     ExprResult CtorArg 
3479       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3480                                          ParamType, Loc,
3481                                          /*IsArrow=*/false,
3482                                          SS,
3483                                          /*TemplateKWLoc=*/SourceLocation(),
3484                                          /*FirstQualifierInScope=*/nullptr,
3485                                          MemberLookup,
3486                                          /*TemplateArgs=*/nullptr);
3487     if (CtorArg.isInvalid())
3488       return true;
3489
3490     // C++11 [class.copy]p15:
3491     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3492     //     with static_cast<T&&>(x.m);
3493     if (RefersToRValueRef(CtorArg.get())) {
3494       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3495     }
3496
3497     // When the field we are copying is an array, create index variables for 
3498     // each dimension of the array. We use these index variables to subscript
3499     // the source array, and other clients (e.g., CodeGen) will perform the
3500     // necessary iteration with these index variables.
3501     SmallVector<VarDecl *, 4> IndexVariables;
3502     QualType BaseType = Field->getType();
3503     QualType SizeType = SemaRef.Context.getSizeType();
3504     bool InitializingArray = false;
3505     while (const ConstantArrayType *Array
3506                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3507       InitializingArray = true;
3508       // Create the iteration variable for this array index.
3509       IdentifierInfo *IterationVarName = nullptr;
3510       {
3511         SmallString<8> Str;
3512         llvm::raw_svector_ostream OS(Str);
3513         OS << "__i" << IndexVariables.size();
3514         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3515       }
3516       VarDecl *IterationVar
3517         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3518                           IterationVarName, SizeType,
3519                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3520                           SC_None);
3521       IndexVariables.push_back(IterationVar);
3522       
3523       // Create a reference to the iteration variable.
3524       ExprResult IterationVarRef
3525         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3526       assert(!IterationVarRef.isInvalid() &&
3527              "Reference to invented variable cannot fail!");
3528       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3529       assert(!IterationVarRef.isInvalid() &&
3530              "Conversion of invented variable cannot fail!");
3531
3532       // Subscript the array with this iteration variable.
3533       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3534                                                         IterationVarRef.get(),
3535                                                         Loc);
3536       if (CtorArg.isInvalid())
3537         return true;
3538
3539       BaseType = Array->getElementType();
3540     }
3541
3542     // The array subscript expression is an lvalue, which is wrong for moving.
3543     if (Moving && InitializingArray)
3544       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3545
3546     // Construct the entity that we will be initializing. For an array, this
3547     // will be first element in the array, which may require several levels
3548     // of array-subscript entities. 
3549     SmallVector<InitializedEntity, 4> Entities;
3550     Entities.reserve(1 + IndexVariables.size());
3551     if (Indirect)
3552       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3553     else
3554       Entities.push_back(InitializedEntity::InitializeMember(Field));
3555     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3556       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3557                                                               0,
3558                                                               Entities.back()));
3559     
3560     // Direct-initialize to use the copy constructor.
3561     InitializationKind InitKind =
3562       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3563     
3564     Expr *CtorArgE = CtorArg.getAs<Expr>();
3565     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3566                                    CtorArgE);
3567
3568     ExprResult MemberInit
3569       = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 
3570                         MultiExprArg(&CtorArgE, 1));
3571     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3572     if (MemberInit.isInvalid())
3573       return true;
3574
3575     if (Indirect) {
3576       assert(IndexVariables.size() == 0 && 
3577              "Indirect field improperly initialized");
3578       CXXMemberInit
3579         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 
3580                                                    Loc, Loc, 
3581                                                    MemberInit.getAs<Expr>(), 
3582                                                    Loc);
3583     } else
3584       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 
3585                                                  Loc, MemberInit.getAs<Expr>(), 
3586                                                  Loc,
3587                                                  IndexVariables.data(),
3588                                                  IndexVariables.size());
3589     return false;
3590   }
3591
3592   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3593          "Unhandled implicit init kind!");
3594
3595   QualType FieldBaseElementType = 
3596     SemaRef.Context.getBaseElementType(Field->getType());
3597   
3598   if (FieldBaseElementType->isRecordType()) {
3599     InitializedEntity InitEntity 
3600       = Indirect? InitializedEntity::InitializeMember(Indirect)
3601                 : InitializedEntity::InitializeMember(Field);
3602     InitializationKind InitKind = 
3603       InitializationKind::CreateDefault(Loc);
3604
3605     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3606     ExprResult MemberInit =
3607       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3608
3609     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3610     if (MemberInit.isInvalid())
3611       return true;
3612     
3613     if (Indirect)
3614       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3615                                                                Indirect, Loc, 
3616                                                                Loc,
3617                                                                MemberInit.get(),
3618                                                                Loc);
3619     else
3620       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3621                                                                Field, Loc, Loc,
3622                                                                MemberInit.get(),
3623                                                                Loc);
3624     return false;
3625   }
3626
3627   if (!Field->getParent()->isUnion()) {
3628     if (FieldBaseElementType->isReferenceType()) {
3629       SemaRef.Diag(Constructor->getLocation(), 
3630                    diag::err_uninitialized_member_in_ctor)
3631       << (int)Constructor->isImplicit() 
3632       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3633       << 0 << Field->getDeclName();
3634       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3635       return true;
3636     }
3637
3638     if (FieldBaseElementType.isConstQualified()) {
3639       SemaRef.Diag(Constructor->getLocation(), 
3640                    diag::err_uninitialized_member_in_ctor)
3641       << (int)Constructor->isImplicit() 
3642       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3643       << 1 << Field->getDeclName();
3644       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3645       return true;
3646     }
3647   }
3648   
3649   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3650       FieldBaseElementType->isObjCRetainableType() &&
3651       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3652       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3653     // ARC:
3654     //   Default-initialize Objective-C pointers to NULL.
3655     CXXMemberInit
3656       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 
3657                                                  Loc, Loc, 
3658                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 
3659                                                  Loc);
3660     return false;
3661   }
3662       
3663   // Nothing to initialize.
3664   CXXMemberInit = nullptr;
3665   return false;
3666 }
3667
3668 namespace {
3669 struct BaseAndFieldInfo {
3670   Sema &S;
3671   CXXConstructorDecl *Ctor;
3672   bool AnyErrorsInInits;
3673   ImplicitInitializerKind IIK;
3674   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3675   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3676   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3677
3678   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3679     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3680     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3681     if (Generated && Ctor->isCopyConstructor())
3682       IIK = IIK_Copy;
3683     else if (Generated && Ctor->isMoveConstructor())
3684       IIK = IIK_Move;
3685     else if (Ctor->getInheritedConstructor())
3686       IIK = IIK_Inherit;
3687     else
3688       IIK = IIK_Default;
3689   }
3690   
3691   bool isImplicitCopyOrMove() const {
3692     switch (IIK) {
3693     case IIK_Copy:
3694     case IIK_Move:
3695       return true;
3696       
3697     case IIK_Default:
3698     case IIK_Inherit:
3699       return false;
3700     }
3701
3702     llvm_unreachable("Invalid ImplicitInitializerKind!");
3703   }
3704
3705   bool addFieldInitializer(CXXCtorInitializer *Init) {
3706     AllToInit.push_back(Init);
3707
3708     // Check whether this initializer makes the field "used".
3709     if (Init->getInit()->HasSideEffects(S.Context))
3710       S.UnusedPrivateFields.remove(Init->getAnyMember());
3711
3712     return false;
3713   }
3714
3715   bool isInactiveUnionMember(FieldDecl *Field) {
3716     RecordDecl *Record = Field->getParent();
3717     if (!Record->isUnion())
3718       return false;
3719
3720     if (FieldDecl *Active =
3721             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3722       return Active != Field->getCanonicalDecl();
3723
3724     // In an implicit copy or move constructor, ignore any in-class initializer.
3725     if (isImplicitCopyOrMove())
3726       return true;
3727
3728     // If there's no explicit initialization, the field is active only if it
3729     // has an in-class initializer...
3730     if (Field->hasInClassInitializer())
3731       return false;
3732     // ... or it's an anonymous struct or union whose class has an in-class
3733     // initializer.
3734     if (!Field->isAnonymousStructOrUnion())
3735       return true;
3736     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3737     return !FieldRD->hasInClassInitializer();
3738   }
3739
3740   /// \brief Determine whether the given field is, or is within, a union member
3741   /// that is inactive (because there was an initializer given for a different
3742   /// member of the union, or because the union was not initialized at all).
3743   bool isWithinInactiveUnionMember(FieldDecl *Field,
3744                                    IndirectFieldDecl *Indirect) {
3745     if (!Indirect)
3746       return isInactiveUnionMember(Field);
3747
3748     for (auto *C : Indirect->chain()) {
3749       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3750       if (Field && isInactiveUnionMember(Field))
3751         return true;
3752     }
3753     return false;
3754   }
3755 };
3756 }
3757
3758 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3759 /// array type.
3760 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3761   if (T->isIncompleteArrayType())
3762     return true;
3763   
3764   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3765     if (!ArrayT->getSize())
3766       return true;
3767     
3768     T = ArrayT->getElementType();
3769   }
3770   
3771   return false;
3772 }
3773
3774 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3775                                     FieldDecl *Field, 
3776                                     IndirectFieldDecl *Indirect = nullptr) {
3777   if (Field->isInvalidDecl())
3778     return false;
3779
3780   // Overwhelmingly common case: we have a direct initializer for this field.
3781   if (CXXCtorInitializer *Init =
3782           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3783     return Info.addFieldInitializer(Init);
3784
3785   // C++11 [class.base.init]p8:
3786   //   if the entity is a non-static data member that has a
3787   //   brace-or-equal-initializer and either
3788   //   -- the constructor's class is a union and no other variant member of that
3789   //      union is designated by a mem-initializer-id or
3790   //   -- the constructor's class is not a union, and, if the entity is a member
3791   //      of an anonymous union, no other member of that union is designated by
3792   //      a mem-initializer-id,
3793   //   the entity is initialized as specified in [dcl.init].
3794   //
3795   // We also apply the same rules to handle anonymous structs within anonymous
3796   // unions.
3797   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3798     return false;
3799
3800   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3801     ExprResult DIE =
3802         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3803     if (DIE.isInvalid())
3804       return true;
3805     CXXCtorInitializer *Init;
3806     if (Indirect)
3807       Init = new (SemaRef.Context)
3808           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3809                              SourceLocation(), DIE.get(), SourceLocation());
3810     else
3811       Init = new (SemaRef.Context)
3812           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3813                              SourceLocation(), DIE.get(), SourceLocation());
3814     return Info.addFieldInitializer(Init);
3815   }
3816
3817   // Don't initialize incomplete or zero-length arrays.
3818   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3819     return false;
3820
3821   // Don't try to build an implicit initializer if there were semantic
3822   // errors in any of the initializers (and therefore we might be
3823   // missing some that the user actually wrote).
3824   if (Info.AnyErrorsInInits)
3825     return false;
3826
3827   CXXCtorInitializer *Init = nullptr;
3828   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3829                                      Indirect, Init))
3830     return true;
3831
3832   if (!Init)
3833     return false;
3834
3835   return Info.addFieldInitializer(Init);
3836 }
3837
3838 bool
3839 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3840                                CXXCtorInitializer *Initializer) {
3841   assert(Initializer->isDelegatingInitializer());
3842   Constructor->setNumCtorInitializers(1);
3843   CXXCtorInitializer **initializer =
3844     new (Context) CXXCtorInitializer*[1];
3845   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3846   Constructor->setCtorInitializers(initializer);
3847
3848   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3849     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3850     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3851   }
3852
3853   DelegatingCtorDecls.push_back(Constructor);
3854
3855   DiagnoseUninitializedFields(*this, Constructor);
3856
3857   return false;
3858 }
3859
3860 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3861                                ArrayRef<CXXCtorInitializer *> Initializers) {
3862   if (Constructor->isDependentContext()) {
3863     // Just store the initializers as written, they will be checked during
3864     // instantiation.
3865     if (!Initializers.empty()) {
3866       Constructor->setNumCtorInitializers(Initializers.size());
3867       CXXCtorInitializer **baseOrMemberInitializers =
3868         new (Context) CXXCtorInitializer*[Initializers.size()];
3869       memcpy(baseOrMemberInitializers, Initializers.data(),
3870              Initializers.size() * sizeof(CXXCtorInitializer*));
3871       Constructor->setCtorInitializers(baseOrMemberInitializers);
3872     }
3873
3874     // Let template instantiation know whether we had errors.
3875     if (AnyErrors)
3876       Constructor->setInvalidDecl();
3877
3878     return false;
3879   }
3880
3881   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3882
3883   // We need to build the initializer AST according to order of construction
3884   // and not what user specified in the Initializers list.
3885   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3886   if (!ClassDecl)
3887     return true;
3888   
3889   bool HadError = false;
3890
3891   for (unsigned i = 0; i < Initializers.size(); i++) {
3892     CXXCtorInitializer *Member = Initializers[i];
3893
3894     if (Member->isBaseInitializer())
3895       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3896     else {
3897       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3898
3899       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3900         for (auto *C : F->chain()) {
3901           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3902           if (FD && FD->getParent()->isUnion())
3903             Info.ActiveUnionMember.insert(std::make_pair(
3904                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3905         }
3906       } else if (FieldDecl *FD = Member->getMember()) {
3907         if (FD->getParent()->isUnion())
3908           Info.ActiveUnionMember.insert(std::make_pair(
3909               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3910       }
3911     }
3912   }
3913
3914   // Keep track of the direct virtual bases.
3915   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3916   for (auto &I : ClassDecl->bases()) {
3917     if (I.isVirtual())
3918       DirectVBases.insert(&I);
3919   }
3920
3921   // Push virtual bases before others.
3922   for (auto &VBase : ClassDecl->vbases()) {
3923     if (CXXCtorInitializer *Value
3924         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3925       // [class.base.init]p7, per DR257:
3926       //   A mem-initializer where the mem-initializer-id names a virtual base
3927       //   class is ignored during execution of a constructor of any class that
3928       //   is not the most derived class.
3929       if (ClassDecl->isAbstract()) {
3930         // FIXME: Provide a fixit to remove the base specifier. This requires
3931         // tracking the location of the associated comma for a base specifier.
3932         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3933           << VBase.getType() << ClassDecl;
3934         DiagnoseAbstractType(ClassDecl);
3935       }
3936
3937       Info.AllToInit.push_back(Value);
3938     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3939       // [class.base.init]p8, per DR257:
3940       //   If a given [...] base class is not named by a mem-initializer-id
3941       //   [...] and the entity is not a virtual base class of an abstract
3942       //   class, then [...] the entity is default-initialized.
3943       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3944       CXXCtorInitializer *CXXBaseInit;
3945       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3946                                        &VBase, IsInheritedVirtualBase,
3947                                        CXXBaseInit)) {
3948         HadError = true;
3949         continue;
3950       }
3951
3952       Info.AllToInit.push_back(CXXBaseInit);
3953     }
3954   }
3955
3956   // Non-virtual bases.
3957   for (auto &Base : ClassDecl->bases()) {
3958     // Virtuals are in the virtual base list and already constructed.
3959     if (Base.isVirtual())
3960       continue;
3961
3962     if (CXXCtorInitializer *Value
3963           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3964       Info.AllToInit.push_back(Value);
3965     } else if (!AnyErrors) {
3966       CXXCtorInitializer *CXXBaseInit;
3967       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3968                                        &Base, /*IsInheritedVirtualBase=*/false,
3969                                        CXXBaseInit)) {
3970         HadError = true;
3971         continue;
3972       }
3973
3974       Info.AllToInit.push_back(CXXBaseInit);
3975     }
3976   }
3977
3978   // Fields.
3979   for (auto *Mem : ClassDecl->decls()) {
3980     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3981       // C++ [class.bit]p2:
3982       //   A declaration for a bit-field that omits the identifier declares an
3983       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3984       //   initialized.
3985       if (F->isUnnamedBitfield())
3986         continue;
3987             
3988       // If we're not generating the implicit copy/move constructor, then we'll
3989       // handle anonymous struct/union fields based on their individual
3990       // indirect fields.
3991       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3992         continue;
3993           
3994       if (CollectFieldInitializer(*this, Info, F))
3995         HadError = true;
3996       continue;
3997     }
3998     
3999     // Beyond this point, we only consider default initialization.
4000     if (Info.isImplicitCopyOrMove())
4001       continue;
4002     
4003     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4004       if (F->getType()->isIncompleteArrayType()) {
4005         assert(ClassDecl->hasFlexibleArrayMember() &&
4006                "Incomplete array type is not valid");
4007         continue;
4008       }
4009       
4010       // Initialize each field of an anonymous struct individually.
4011       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4012         HadError = true;
4013       
4014       continue;        
4015     }
4016   }
4017
4018   unsigned NumInitializers = Info.AllToInit.size();
4019   if (NumInitializers > 0) {
4020     Constructor->setNumCtorInitializers(NumInitializers);
4021     CXXCtorInitializer **baseOrMemberInitializers =
4022       new (Context) CXXCtorInitializer*[NumInitializers];
4023     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4024            NumInitializers * sizeof(CXXCtorInitializer*));
4025     Constructor->setCtorInitializers(baseOrMemberInitializers);
4026
4027     // Constructors implicitly reference the base and member
4028     // destructors.
4029     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4030                                            Constructor->getParent());
4031   }
4032
4033   return HadError;
4034 }
4035
4036 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4037   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4038     const RecordDecl *RD = RT->getDecl();
4039     if (RD->isAnonymousStructOrUnion()) {
4040       for (auto *Field : RD->fields())
4041         PopulateKeysForFields(Field, IdealInits);
4042       return;
4043     }
4044   }
4045   IdealInits.push_back(Field->getCanonicalDecl());
4046 }
4047
4048 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4049   return Context.getCanonicalType(BaseType).getTypePtr();
4050 }
4051
4052 static const void *GetKeyForMember(ASTContext &Context,
4053                                    CXXCtorInitializer *Member) {
4054   if (!Member->isAnyMemberInitializer())
4055     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4056     
4057   return Member->getAnyMember()->getCanonicalDecl();
4058 }
4059
4060 static void DiagnoseBaseOrMemInitializerOrder(
4061     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4062     ArrayRef<CXXCtorInitializer *> Inits) {
4063   if (Constructor->getDeclContext()->isDependentContext())
4064     return;
4065
4066   // Don't check initializers order unless the warning is enabled at the
4067   // location of at least one initializer. 
4068   bool ShouldCheckOrder = false;
4069   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4070     CXXCtorInitializer *Init = Inits[InitIndex];
4071     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4072                                  Init->getSourceLocation())) {
4073       ShouldCheckOrder = true;
4074       break;
4075     }
4076   }
4077   if (!ShouldCheckOrder)
4078     return;
4079   
4080   // Build the list of bases and members in the order that they'll
4081   // actually be initialized.  The explicit initializers should be in
4082   // this same order but may be missing things.
4083   SmallVector<const void*, 32> IdealInitKeys;
4084
4085   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4086
4087   // 1. Virtual bases.
4088   for (const auto &VBase : ClassDecl->vbases())
4089     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4090
4091   // 2. Non-virtual bases.
4092   for (const auto &Base : ClassDecl->bases()) {
4093     if (Base.isVirtual())
4094       continue;
4095     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4096   }
4097
4098   // 3. Direct fields.
4099   for (auto *Field : ClassDecl->fields()) {
4100     if (Field->isUnnamedBitfield())
4101       continue;
4102     
4103     PopulateKeysForFields(Field, IdealInitKeys);
4104   }
4105   
4106   unsigned NumIdealInits = IdealInitKeys.size();
4107   unsigned IdealIndex = 0;
4108
4109   CXXCtorInitializer *PrevInit = nullptr;
4110   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4111     CXXCtorInitializer *Init = Inits[InitIndex];
4112     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4113
4114     // Scan forward to try to find this initializer in the idealized
4115     // initializers list.
4116     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4117       if (InitKey == IdealInitKeys[IdealIndex])
4118         break;
4119
4120     // If we didn't find this initializer, it must be because we
4121     // scanned past it on a previous iteration.  That can only
4122     // happen if we're out of order;  emit a warning.
4123     if (IdealIndex == NumIdealInits && PrevInit) {
4124       Sema::SemaDiagnosticBuilder D =
4125         SemaRef.Diag(PrevInit->getSourceLocation(),
4126                      diag::warn_initializer_out_of_order);
4127
4128       if (PrevInit->isAnyMemberInitializer())
4129         D << 0 << PrevInit->getAnyMember()->getDeclName();
4130       else
4131         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4132       
4133       if (Init->isAnyMemberInitializer())
4134         D << 0 << Init->getAnyMember()->getDeclName();
4135       else
4136         D << 1 << Init->getTypeSourceInfo()->getType();
4137
4138       // Move back to the initializer's location in the ideal list.
4139       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4140         if (InitKey == IdealInitKeys[IdealIndex])
4141           break;
4142
4143       assert(IdealIndex != NumIdealInits &&
4144              "initializer not found in initializer list");
4145     }
4146
4147     PrevInit = Init;
4148   }
4149 }
4150
4151 namespace {
4152 bool CheckRedundantInit(Sema &S,
4153                         CXXCtorInitializer *Init,
4154                         CXXCtorInitializer *&PrevInit) {
4155   if (!PrevInit) {
4156     PrevInit = Init;
4157     return false;
4158   }
4159
4160   if (FieldDecl *Field = Init->getAnyMember())
4161     S.Diag(Init->getSourceLocation(),
4162            diag::err_multiple_mem_initialization)
4163       << Field->getDeclName()
4164       << Init->getSourceRange();
4165   else {
4166     const Type *BaseClass = Init->getBaseClass();
4167     assert(BaseClass && "neither field nor base");
4168     S.Diag(Init->getSourceLocation(),
4169            diag::err_multiple_base_initialization)
4170       << QualType(BaseClass, 0)
4171       << Init->getSourceRange();
4172   }
4173   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4174     << 0 << PrevInit->getSourceRange();
4175
4176   return true;
4177 }
4178
4179 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4180 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4181
4182 bool CheckRedundantUnionInit(Sema &S,
4183                              CXXCtorInitializer *Init,
4184                              RedundantUnionMap &Unions) {
4185   FieldDecl *Field = Init->getAnyMember();
4186   RecordDecl *Parent = Field->getParent();
4187   NamedDecl *Child = Field;
4188
4189   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4190     if (Parent->isUnion()) {
4191       UnionEntry &En = Unions[Parent];
4192       if (En.first && En.first != Child) {
4193         S.Diag(Init->getSourceLocation(),
4194                diag::err_multiple_mem_union_initialization)
4195           << Field->getDeclName()
4196           << Init->getSourceRange();
4197         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4198           << 0 << En.second->getSourceRange();
4199         return true;
4200       } 
4201       if (!En.first) {
4202         En.first = Child;
4203         En.second = Init;
4204       }
4205       if (!Parent->isAnonymousStructOrUnion())
4206         return false;
4207     }
4208
4209     Child = Parent;
4210     Parent = cast<RecordDecl>(Parent->getDeclContext());
4211   }
4212
4213   return false;
4214 }
4215 }
4216
4217 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4218 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4219                                 SourceLocation ColonLoc,
4220                                 ArrayRef<CXXCtorInitializer*> MemInits,
4221                                 bool AnyErrors) {
4222   if (!ConstructorDecl)
4223     return;
4224
4225   AdjustDeclIfTemplate(ConstructorDecl);
4226
4227   CXXConstructorDecl *Constructor
4228     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4229
4230   if (!Constructor) {
4231     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4232     return;
4233   }
4234   
4235   // Mapping for the duplicate initializers check.
4236   // For member initializers, this is keyed with a FieldDecl*.
4237   // For base initializers, this is keyed with a Type*.
4238   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4239
4240   // Mapping for the inconsistent anonymous-union initializers check.
4241   RedundantUnionMap MemberUnions;
4242
4243   bool HadError = false;
4244   for (unsigned i = 0; i < MemInits.size(); i++) {
4245     CXXCtorInitializer *Init = MemInits[i];
4246
4247     // Set the source order index.
4248     Init->setSourceOrder(i);
4249
4250     if (Init->isAnyMemberInitializer()) {
4251       const void *Key = GetKeyForMember(Context, Init);
4252       if (CheckRedundantInit(*this, Init, Members[Key]) ||
4253           CheckRedundantUnionInit(*this, Init, MemberUnions))
4254         HadError = true;
4255     } else if (Init->isBaseInitializer()) {
4256       const void *Key = GetKeyForMember(Context, Init);
4257       if (CheckRedundantInit(*this, Init, Members[Key]))
4258         HadError = true;
4259     } else {
4260       assert(Init->isDelegatingInitializer());
4261       // This must be the only initializer
4262       if (MemInits.size() != 1) {
4263         Diag(Init->getSourceLocation(),
4264              diag::err_delegating_initializer_alone)
4265           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4266         // We will treat this as being the only initializer.
4267       }
4268       SetDelegatingInitializer(Constructor, MemInits[i]);
4269       // Return immediately as the initializer is set.
4270       return;
4271     }
4272   }
4273
4274   if (HadError)
4275     return;
4276
4277   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4278
4279   SetCtorInitializers(Constructor, AnyErrors, MemInits);
4280
4281   DiagnoseUninitializedFields(*this, Constructor);
4282 }
4283
4284 void
4285 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4286                                              CXXRecordDecl *ClassDecl) {
4287   // Ignore dependent contexts. Also ignore unions, since their members never
4288   // have destructors implicitly called.
4289   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4290     return;
4291
4292   // FIXME: all the access-control diagnostics are positioned on the
4293   // field/base declaration.  That's probably good; that said, the
4294   // user might reasonably want to know why the destructor is being
4295   // emitted, and we currently don't say.
4296   
4297   // Non-static data members.
4298   for (auto *Field : ClassDecl->fields()) {
4299     if (Field->isInvalidDecl())
4300       continue;
4301     
4302     // Don't destroy incomplete or zero-length arrays.
4303     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4304       continue;
4305
4306     QualType FieldType = Context.getBaseElementType(Field->getType());
4307     
4308     const RecordType* RT = FieldType->getAs<RecordType>();
4309     if (!RT)
4310       continue;
4311     
4312     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4313     if (FieldClassDecl->isInvalidDecl())
4314       continue;
4315     if (FieldClassDecl->hasIrrelevantDestructor())
4316       continue;
4317     // The destructor for an implicit anonymous union member is never invoked.
4318     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4319       continue;
4320
4321     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4322     assert(Dtor && "No dtor found for FieldClassDecl!");
4323     CheckDestructorAccess(Field->getLocation(), Dtor,
4324                           PDiag(diag::err_access_dtor_field)
4325                             << Field->getDeclName()
4326                             << FieldType);
4327
4328     MarkFunctionReferenced(Location, Dtor);
4329     DiagnoseUseOfDecl(Dtor, Location);
4330   }
4331
4332   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4333
4334   // Bases.
4335   for (const auto &Base : ClassDecl->bases()) {
4336     // Bases are always records in a well-formed non-dependent class.
4337     const RecordType *RT = Base.getType()->getAs<RecordType>();
4338
4339     // Remember direct virtual bases.
4340     if (Base.isVirtual())
4341       DirectVirtualBases.insert(RT);
4342
4343     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4344     // If our base class is invalid, we probably can't get its dtor anyway.
4345     if (BaseClassDecl->isInvalidDecl())
4346       continue;
4347     if (BaseClassDecl->hasIrrelevantDestructor())
4348       continue;
4349
4350     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4351     assert(Dtor && "No dtor found for BaseClassDecl!");
4352
4353     // FIXME: caret should be on the start of the class name
4354     CheckDestructorAccess(Base.getLocStart(), Dtor,
4355                           PDiag(diag::err_access_dtor_base)
4356                             << Base.getType()
4357                             << Base.getSourceRange(),
4358                           Context.getTypeDeclType(ClassDecl));
4359     
4360     MarkFunctionReferenced(Location, Dtor);
4361     DiagnoseUseOfDecl(Dtor, Location);
4362   }
4363   
4364   // Virtual bases.
4365   for (const auto &VBase : ClassDecl->vbases()) {
4366     // Bases are always records in a well-formed non-dependent class.
4367     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4368
4369     // Ignore direct virtual bases.
4370     if (DirectVirtualBases.count(RT))
4371       continue;
4372
4373     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4374     // If our base class is invalid, we probably can't get its dtor anyway.
4375     if (BaseClassDecl->isInvalidDecl())
4376       continue;
4377     if (BaseClassDecl->hasIrrelevantDestructor())
4378       continue;
4379
4380     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4381     assert(Dtor && "No dtor found for BaseClassDecl!");
4382     if (CheckDestructorAccess(
4383             ClassDecl->getLocation(), Dtor,
4384             PDiag(diag::err_access_dtor_vbase)
4385                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4386             Context.getTypeDeclType(ClassDecl)) ==
4387         AR_accessible) {
4388       CheckDerivedToBaseConversion(
4389           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4390           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4391           SourceRange(), DeclarationName(), nullptr);
4392     }
4393
4394     MarkFunctionReferenced(Location, Dtor);
4395     DiagnoseUseOfDecl(Dtor, Location);
4396   }
4397 }
4398
4399 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4400   if (!CDtorDecl)
4401     return;
4402
4403   if (CXXConstructorDecl *Constructor
4404       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4405     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4406     DiagnoseUninitializedFields(*this, Constructor);
4407   }
4408 }
4409
4410 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4411                                   unsigned DiagID, AbstractDiagSelID SelID) {
4412   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4413     unsigned DiagID;
4414     AbstractDiagSelID SelID;
4415     
4416   public:
4417     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4418       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4419
4420     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4421       if (Suppressed) return;
4422       if (SelID == -1)
4423         S.Diag(Loc, DiagID) << T;
4424       else
4425         S.Diag(Loc, DiagID) << SelID << T;
4426     }
4427   } Diagnoser(DiagID, SelID);
4428   
4429   return RequireNonAbstractType(Loc, T, Diagnoser);
4430 }
4431
4432 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4433                                   TypeDiagnoser &Diagnoser) {
4434   if (!getLangOpts().CPlusPlus)
4435     return false;
4436
4437   if (const ArrayType *AT = Context.getAsArrayType(T))
4438     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4439
4440   if (const PointerType *PT = T->getAs<PointerType>()) {
4441     // Find the innermost pointer type.
4442     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4443       PT = T;
4444
4445     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4446       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4447   }
4448
4449   const RecordType *RT = T->getAs<RecordType>();
4450   if (!RT)
4451     return false;
4452
4453   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4454
4455   // We can't answer whether something is abstract until it has a
4456   // definition.  If it's currently being defined, we'll walk back
4457   // over all the declarations when we have a full definition.
4458   const CXXRecordDecl *Def = RD->getDefinition();
4459   if (!Def || Def->isBeingDefined())
4460     return false;
4461
4462   if (!RD->isAbstract())
4463     return false;
4464
4465   Diagnoser.diagnose(*this, Loc, T);
4466   DiagnoseAbstractType(RD);
4467
4468   return true;
4469 }
4470
4471 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4472   // Check if we've already emitted the list of pure virtual functions
4473   // for this class.
4474   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4475     return;
4476
4477   // If the diagnostic is suppressed, don't emit the notes. We're only
4478   // going to emit them once, so try to attach them to a diagnostic we're
4479   // actually going to show.
4480   if (Diags.isLastDiagnosticIgnored())
4481     return;
4482
4483   CXXFinalOverriderMap FinalOverriders;
4484   RD->getFinalOverriders(FinalOverriders);
4485
4486   // Keep a set of seen pure methods so we won't diagnose the same method
4487   // more than once.
4488   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4489   
4490   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 
4491                                    MEnd = FinalOverriders.end();
4492        M != MEnd; 
4493        ++M) {
4494     for (OverridingMethods::iterator SO = M->second.begin(), 
4495                                   SOEnd = M->second.end();
4496          SO != SOEnd; ++SO) {
4497       // C++ [class.abstract]p4:
4498       //   A class is abstract if it contains or inherits at least one
4499       //   pure virtual function for which the final overrider is pure
4500       //   virtual.
4501
4502       // 
4503       if (SO->second.size() != 1)
4504         continue;
4505
4506       if (!SO->second.front().Method->isPure())
4507         continue;
4508
4509       if (!SeenPureMethods.insert(SO->second.front().Method).second)
4510         continue;
4511
4512       Diag(SO->second.front().Method->getLocation(), 
4513            diag::note_pure_virtual_function) 
4514         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4515     }
4516   }
4517
4518   if (!PureVirtualClassDiagSet)
4519     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4520   PureVirtualClassDiagSet->insert(RD);
4521 }
4522
4523 namespace {
4524 struct AbstractUsageInfo {
4525   Sema &S;
4526   CXXRecordDecl *Record;
4527   CanQualType AbstractType;
4528   bool Invalid;
4529
4530   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4531     : S(S), Record(Record),
4532       AbstractType(S.Context.getCanonicalType(
4533                    S.Context.getTypeDeclType(Record))),
4534       Invalid(false) {}
4535
4536   void DiagnoseAbstractType() {
4537     if (Invalid) return;
4538     S.DiagnoseAbstractType(Record);
4539     Invalid = true;
4540   }
4541
4542   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4543 };
4544
4545 struct CheckAbstractUsage {
4546   AbstractUsageInfo &Info;
4547   const NamedDecl *Ctx;
4548
4549   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4550     : Info(Info), Ctx(Ctx) {}
4551
4552   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4553     switch (TL.getTypeLocClass()) {
4554 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4555 #define TYPELOC(CLASS, PARENT) \
4556     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4557 #include "clang/AST/TypeLocNodes.def"
4558     }
4559   }
4560
4561   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4562     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4563     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4564       if (!TL.getParam(I))
4565         continue;
4566
4567       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4568       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4569     }
4570   }
4571
4572   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4573     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4574   }
4575
4576   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4577     // Visit the type parameters from a permissive context.
4578     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4579       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4580       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4581         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4582           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4583       // TODO: other template argument types?
4584     }
4585   }
4586
4587   // Visit pointee types from a permissive context.
4588 #define CheckPolymorphic(Type) \
4589   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4590     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4591   }
4592   CheckPolymorphic(PointerTypeLoc)
4593   CheckPolymorphic(ReferenceTypeLoc)
4594   CheckPolymorphic(MemberPointerTypeLoc)
4595   CheckPolymorphic(BlockPointerTypeLoc)
4596   CheckPolymorphic(AtomicTypeLoc)
4597
4598   /// Handle all the types we haven't given a more specific
4599   /// implementation for above.
4600   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4601     // Every other kind of type that we haven't called out already
4602     // that has an inner type is either (1) sugar or (2) contains that
4603     // inner type in some way as a subobject.
4604     if (TypeLoc Next = TL.getNextTypeLoc())
4605       return Visit(Next, Sel);
4606
4607     // If there's no inner type and we're in a permissive context,
4608     // don't diagnose.
4609     if (Sel == Sema::AbstractNone) return;
4610
4611     // Check whether the type matches the abstract type.
4612     QualType T = TL.getType();
4613     if (T->isArrayType()) {
4614       Sel = Sema::AbstractArrayType;
4615       T = Info.S.Context.getBaseElementType(T);
4616     }
4617     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4618     if (CT != Info.AbstractType) return;
4619
4620     // It matched; do some magic.
4621     if (Sel == Sema::AbstractArrayType) {
4622       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4623         << T << TL.getSourceRange();
4624     } else {
4625       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4626         << Sel << T << TL.getSourceRange();
4627     }
4628     Info.DiagnoseAbstractType();
4629   }
4630 };
4631
4632 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4633                                   Sema::AbstractDiagSelID Sel) {
4634   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4635 }
4636
4637 }
4638
4639 /// Check for invalid uses of an abstract type in a method declaration.
4640 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4641                                     CXXMethodDecl *MD) {
4642   // No need to do the check on definitions, which require that
4643   // the return/param types be complete.
4644   if (MD->doesThisDeclarationHaveABody())
4645     return;
4646
4647   // For safety's sake, just ignore it if we don't have type source
4648   // information.  This should never happen for non-implicit methods,
4649   // but...
4650   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4651     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4652 }
4653
4654 /// Check for invalid uses of an abstract type within a class definition.
4655 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4656                                     CXXRecordDecl *RD) {
4657   for (auto *D : RD->decls()) {
4658     if (D->isImplicit()) continue;
4659
4660     // Methods and method templates.
4661     if (isa<CXXMethodDecl>(D)) {
4662       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4663     } else if (isa<FunctionTemplateDecl>(D)) {
4664       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4665       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4666
4667     // Fields and static variables.
4668     } else if (isa<FieldDecl>(D)) {
4669       FieldDecl *FD = cast<FieldDecl>(D);
4670       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4671         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4672     } else if (isa<VarDecl>(D)) {
4673       VarDecl *VD = cast<VarDecl>(D);
4674       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4675         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4676
4677     // Nested classes and class templates.
4678     } else if (isa<CXXRecordDecl>(D)) {
4679       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4680     } else if (isa<ClassTemplateDecl>(D)) {
4681       CheckAbstractClassUsage(Info,
4682                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4683     }
4684   }
4685 }
4686
4687 /// \brief Check class-level dllimport/dllexport attribute.
4688 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
4689   Attr *ClassAttr = getDLLAttr(Class);
4690
4691   // MSVC inherits DLL attributes to partial class template specializations.
4692   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4693     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4694       if (Attr *TemplateAttr =
4695               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4696         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
4697         A->setInherited(true);
4698         ClassAttr = A;
4699       }
4700     }
4701   }
4702
4703   if (!ClassAttr)
4704     return;
4705
4706   if (!Class->isExternallyVisible()) {
4707     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4708         << Class << ClassAttr;
4709     return;
4710   }
4711
4712   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4713       !ClassAttr->isInherited()) {
4714     // Diagnose dll attributes on members of class with dll attribute.
4715     for (Decl *Member : Class->decls()) {
4716       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4717         continue;
4718       InheritableAttr *MemberAttr = getDLLAttr(Member);
4719       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4720         continue;
4721
4722       Diag(MemberAttr->getLocation(),
4723              diag::err_attribute_dll_member_of_dll_class)
4724           << MemberAttr << ClassAttr;
4725       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4726       Member->setInvalidDecl();
4727     }
4728   }
4729
4730   if (Class->getDescribedClassTemplate())
4731     // Don't inherit dll attribute until the template is instantiated.
4732     return;
4733
4734   // The class is either imported or exported.
4735   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4736   const bool ClassImported = !ClassExported;
4737
4738   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4739
4740   // Ignore explicit dllexport on explicit class template instantiation declarations.
4741   if (ClassExported && !ClassAttr->isInherited() &&
4742       TSK == TSK_ExplicitInstantiationDeclaration) {
4743     Class->dropAttr<DLLExportAttr>();
4744     return;
4745   }
4746
4747   // Force declaration of implicit members so they can inherit the attribute.
4748   ForceDeclarationOfImplicitMembers(Class);
4749
4750   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4751   // seem to be true in practice?
4752
4753   for (Decl *Member : Class->decls()) {
4754     VarDecl *VD = dyn_cast<VarDecl>(Member);
4755     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4756
4757     // Only methods and static fields inherit the attributes.
4758     if (!VD && !MD)
4759       continue;
4760
4761     if (MD) {
4762       // Don't process deleted methods.
4763       if (MD->isDeleted())
4764         continue;
4765
4766       if (MD->isInlined()) {
4767         // MinGW does not import or export inline methods.
4768         if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
4769           continue;
4770
4771         // MSVC versions before 2015 don't export the move assignment operators,
4772         // so don't attempt to import them if we have a definition.
4773         if (ClassImported && MD->isMoveAssignmentOperator() &&
4774             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
4775           continue;
4776       }
4777     }
4778
4779     if (!cast<NamedDecl>(Member)->isExternallyVisible())
4780       continue;
4781
4782     if (!getDLLAttr(Member)) {
4783       auto *NewAttr =
4784           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4785       NewAttr->setInherited(true);
4786       Member->addAttr(NewAttr);
4787     }
4788
4789     if (MD && ClassExported) {
4790       if (TSK == TSK_ExplicitInstantiationDeclaration)
4791         // Don't go any further if this is just an explicit instantiation
4792         // declaration.
4793         continue;
4794
4795       if (MD->isUserProvided()) {
4796         // Instantiate non-default class member functions ...
4797
4798         // .. except for certain kinds of template specializations.
4799         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4800           continue;
4801
4802         MarkFunctionReferenced(Class->getLocation(), MD);
4803
4804         // The function will be passed to the consumer when its definition is
4805         // encountered.
4806       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4807                  MD->isCopyAssignmentOperator() ||
4808                  MD->isMoveAssignmentOperator()) {
4809         // Synthesize and instantiate non-trivial implicit methods, explicitly
4810         // defaulted methods, and the copy and move assignment operators. The
4811         // latter are exported even if they are trivial, because the address of
4812         // an operator can be taken and should compare equal accross libraries.
4813         DiagnosticErrorTrap Trap(Diags);
4814         MarkFunctionReferenced(Class->getLocation(), MD);
4815         if (Trap.hasErrorOccurred()) {
4816           Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4817               << Class->getName() << !getLangOpts().CPlusPlus11;
4818           break;
4819         }
4820
4821         // There is no later point when we will see the definition of this
4822         // function, so pass it to the consumer now.
4823         Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
4824       }
4825     }
4826   }
4827 }
4828
4829 /// \brief Perform propagation of DLL attributes from a derived class to a
4830 /// templated base class for MS compatibility.
4831 void Sema::propagateDLLAttrToBaseClassTemplate(
4832     CXXRecordDecl *Class, Attr *ClassAttr,
4833     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
4834   if (getDLLAttr(
4835           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
4836     // If the base class template has a DLL attribute, don't try to change it.
4837     return;
4838   }
4839
4840   auto TSK = BaseTemplateSpec->getSpecializationKind();
4841   if (!getDLLAttr(BaseTemplateSpec) &&
4842       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
4843        TSK == TSK_ImplicitInstantiation)) {
4844     // The template hasn't been instantiated yet (or it has, but only as an
4845     // explicit instantiation declaration or implicit instantiation, which means
4846     // we haven't codegenned any members yet), so propagate the attribute.
4847     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4848     NewAttr->setInherited(true);
4849     BaseTemplateSpec->addAttr(NewAttr);
4850
4851     // If the template is already instantiated, checkDLLAttributeRedeclaration()
4852     // needs to be run again to work see the new attribute. Otherwise this will
4853     // get run whenever the template is instantiated.
4854     if (TSK != TSK_Undeclared)
4855       checkClassLevelDLLAttribute(BaseTemplateSpec);
4856
4857     return;
4858   }
4859
4860   if (getDLLAttr(BaseTemplateSpec)) {
4861     // The template has already been specialized or instantiated with an
4862     // attribute, explicitly or through propagation. We should not try to change
4863     // it.
4864     return;
4865   }
4866
4867   // The template was previously instantiated or explicitly specialized without
4868   // a dll attribute, It's too late for us to add an attribute, so warn that
4869   // this is unsupported.
4870   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
4871       << BaseTemplateSpec->isExplicitSpecialization();
4872   Diag(ClassAttr->getLocation(), diag::note_attribute);
4873   if (BaseTemplateSpec->isExplicitSpecialization()) {
4874     Diag(BaseTemplateSpec->getLocation(),
4875            diag::note_template_class_explicit_specialization_was_here)
4876         << BaseTemplateSpec;
4877   } else {
4878     Diag(BaseTemplateSpec->getPointOfInstantiation(),
4879            diag::note_template_class_instantiation_was_here)
4880         << BaseTemplateSpec;
4881   }
4882 }
4883
4884 /// \brief Perform semantic checks on a class definition that has been
4885 /// completing, introducing implicitly-declared members, checking for
4886 /// abstract types, etc.
4887 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4888   if (!Record)
4889     return;
4890
4891   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4892     AbstractUsageInfo Info(*this, Record);
4893     CheckAbstractClassUsage(Info, Record);
4894   }
4895   
4896   // If this is not an aggregate type and has no user-declared constructor,
4897   // complain about any non-static data members of reference or const scalar
4898   // type, since they will never get initializers.
4899   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4900       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4901       !Record->isLambda()) {
4902     bool Complained = false;
4903     for (const auto *F : Record->fields()) {
4904       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4905         continue;
4906
4907       if (F->getType()->isReferenceType() ||
4908           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4909         if (!Complained) {
4910           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4911             << Record->getTagKind() << Record;
4912           Complained = true;
4913         }
4914         
4915         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4916           << F->getType()->isReferenceType()
4917           << F->getDeclName();
4918       }
4919     }
4920   }
4921
4922   if (Record->getIdentifier()) {
4923     // C++ [class.mem]p13:
4924     //   If T is the name of a class, then each of the following shall have a 
4925     //   name different from T:
4926     //     - every member of every anonymous union that is a member of class T.
4927     //
4928     // C++ [class.mem]p14:
4929     //   In addition, if class T has a user-declared constructor (12.1), every 
4930     //   non-static data member of class T shall have a name different from T.
4931     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4932     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4933          ++I) {
4934       NamedDecl *D = *I;
4935       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4936           isa<IndirectFieldDecl>(D)) {
4937         Diag(D->getLocation(), diag::err_member_name_of_class)
4938           << D->getDeclName();
4939         break;
4940       }
4941     }
4942   }
4943
4944   // Warn if the class has virtual methods but non-virtual public destructor.
4945   if (Record->isPolymorphic() && !Record->isDependentType()) {
4946     CXXDestructorDecl *dtor = Record->getDestructor();
4947     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4948         !Record->hasAttr<FinalAttr>())
4949       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4950            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4951   }
4952
4953   if (Record->isAbstract()) {
4954     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4955       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4956         << FA->isSpelledAsSealed();
4957       DiagnoseAbstractType(Record);
4958     }
4959   }
4960
4961   bool HasMethodWithOverrideControl = false,
4962        HasOverridingMethodWithoutOverrideControl = false;
4963   if (!Record->isDependentType()) {
4964     for (auto *M : Record->methods()) {
4965       // See if a method overloads virtual methods in a base
4966       // class without overriding any.
4967       if (!M->isStatic())
4968         DiagnoseHiddenVirtualMethods(M);
4969       if (M->hasAttr<OverrideAttr>())
4970         HasMethodWithOverrideControl = true;
4971       else if (M->size_overridden_methods() > 0)
4972         HasOverridingMethodWithoutOverrideControl = true;
4973       // Check whether the explicitly-defaulted special members are valid.
4974       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4975         CheckExplicitlyDefaultedSpecialMember(M);
4976
4977       // For an explicitly defaulted or deleted special member, we defer
4978       // determining triviality until the class is complete. That time is now!
4979       if (!M->isImplicit() && !M->isUserProvided()) {
4980         CXXSpecialMember CSM = getSpecialMember(M);
4981         if (CSM != CXXInvalid) {
4982           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4983
4984           // Inform the class that we've finished declaring this member.
4985           Record->finishedDefaultedOrDeletedMember(M);
4986         }
4987       }
4988     }
4989   }
4990
4991   if (HasMethodWithOverrideControl &&
4992       HasOverridingMethodWithoutOverrideControl) {
4993     // At least one method has the 'override' control declared.
4994     // Diagnose all other overridden methods which do not have 'override' specified on them.
4995     for (auto *M : Record->methods())
4996       DiagnoseAbsenceOfOverrideControl(M);
4997   }
4998
4999   // ms_struct is a request to use the same ABI rules as MSVC.  Check
5000   // whether this class uses any C++ features that are implemented
5001   // completely differently in MSVC, and if so, emit a diagnostic.
5002   // That diagnostic defaults to an error, but we allow projects to
5003   // map it down to a warning (or ignore it).  It's a fairly common
5004   // practice among users of the ms_struct pragma to mass-annotate
5005   // headers, sweeping up a bunch of types that the project doesn't
5006   // really rely on MSVC-compatible layout for.  We must therefore
5007   // support "ms_struct except for C++ stuff" as a secondary ABI.
5008   if (Record->isMsStruct(Context) &&
5009       (Record->isPolymorphic() || Record->getNumBases())) {
5010     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5011   }
5012
5013   // Declare inheriting constructors. We do this eagerly here because:
5014   // - The standard requires an eager diagnostic for conflicting inheriting
5015   //   constructors from different classes.
5016   // - The lazy declaration of the other implicit constructors is so as to not
5017   //   waste space and performance on classes that are not meant to be
5018   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
5019   //   have inheriting constructors.
5020   DeclareInheritingConstructors(Record);
5021
5022   checkClassLevelDLLAttribute(Record);
5023 }
5024
5025 /// Look up the special member function that would be called by a special
5026 /// member function for a subobject of class type.
5027 ///
5028 /// \param Class The class type of the subobject.
5029 /// \param CSM The kind of special member function.
5030 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5031 /// \param ConstRHS True if this is a copy operation with a const object
5032 ///        on its RHS, that is, if the argument to the outer special member
5033 ///        function is 'const' and this is not a field marked 'mutable'.
5034 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5035     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5036     unsigned FieldQuals, bool ConstRHS) {
5037   unsigned LHSQuals = 0;
5038   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5039     LHSQuals = FieldQuals;
5040
5041   unsigned RHSQuals = FieldQuals;
5042   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5043     RHSQuals = 0;
5044   else if (ConstRHS)
5045     RHSQuals |= Qualifiers::Const;
5046
5047   return S.LookupSpecialMember(Class, CSM,
5048                                RHSQuals & Qualifiers::Const,
5049                                RHSQuals & Qualifiers::Volatile,
5050                                false,
5051                                LHSQuals & Qualifiers::Const,
5052                                LHSQuals & Qualifiers::Volatile);
5053 }
5054
5055 /// Is the special member function which would be selected to perform the
5056 /// specified operation on the specified class type a constexpr constructor?
5057 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5058                                      Sema::CXXSpecialMember CSM,
5059                                      unsigned Quals, bool ConstRHS) {
5060   Sema::SpecialMemberOverloadResult *SMOR =
5061       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5062   if (!SMOR || !SMOR->getMethod())
5063     // A constructor we wouldn't select can't be "involved in initializing"
5064     // anything.
5065     return true;
5066   return SMOR->getMethod()->isConstexpr();
5067 }
5068
5069 /// Determine whether the specified special member function would be constexpr
5070 /// if it were implicitly defined.
5071 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5072                                               Sema::CXXSpecialMember CSM,
5073                                               bool ConstArg) {
5074   if (!S.getLangOpts().CPlusPlus11)
5075     return false;
5076
5077   // C++11 [dcl.constexpr]p4:
5078   // In the definition of a constexpr constructor [...]
5079   bool Ctor = true;
5080   switch (CSM) {
5081   case Sema::CXXDefaultConstructor:
5082     // Since default constructor lookup is essentially trivial (and cannot
5083     // involve, for instance, template instantiation), we compute whether a
5084     // defaulted default constructor is constexpr directly within CXXRecordDecl.
5085     //
5086     // This is important for performance; we need to know whether the default
5087     // constructor is constexpr to determine whether the type is a literal type.
5088     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5089
5090   case Sema::CXXCopyConstructor:
5091   case Sema::CXXMoveConstructor:
5092     // For copy or move constructors, we need to perform overload resolution.
5093     break;
5094
5095   case Sema::CXXCopyAssignment:
5096   case Sema::CXXMoveAssignment:
5097     if (!S.getLangOpts().CPlusPlus14)
5098       return false;
5099     // In C++1y, we need to perform overload resolution.
5100     Ctor = false;
5101     break;
5102
5103   case Sema::CXXDestructor:
5104   case Sema::CXXInvalid:
5105     return false;
5106   }
5107
5108   //   -- if the class is a non-empty union, or for each non-empty anonymous
5109   //      union member of a non-union class, exactly one non-static data member
5110   //      shall be initialized; [DR1359]
5111   //
5112   // If we squint, this is guaranteed, since exactly one non-static data member
5113   // will be initialized (if the constructor isn't deleted), we just don't know
5114   // which one.
5115   if (Ctor && ClassDecl->isUnion())
5116     return true;
5117
5118   //   -- the class shall not have any virtual base classes;
5119   if (Ctor && ClassDecl->getNumVBases())
5120     return false;
5121
5122   // C++1y [class.copy]p26:
5123   //   -- [the class] is a literal type, and
5124   if (!Ctor && !ClassDecl->isLiteral())
5125     return false;
5126
5127   //   -- every constructor involved in initializing [...] base class
5128   //      sub-objects shall be a constexpr constructor;
5129   //   -- the assignment operator selected to copy/move each direct base
5130   //      class is a constexpr function, and
5131   for (const auto &B : ClassDecl->bases()) {
5132     const RecordType *BaseType = B.getType()->getAs<RecordType>();
5133     if (!BaseType) continue;
5134
5135     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5136     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
5137       return false;
5138   }
5139
5140   //   -- every constructor involved in initializing non-static data members
5141   //      [...] shall be a constexpr constructor;
5142   //   -- every non-static data member and base class sub-object shall be
5143   //      initialized
5144   //   -- for each non-static data member of X that is of class type (or array
5145   //      thereof), the assignment operator selected to copy/move that member is
5146   //      a constexpr function
5147   for (const auto *F : ClassDecl->fields()) {
5148     if (F->isInvalidDecl())
5149       continue;
5150     QualType BaseType = S.Context.getBaseElementType(F->getType());
5151     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
5152       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5153       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5154                                     BaseType.getCVRQualifiers(),
5155                                     ConstArg && !F->isMutable()))
5156         return false;
5157     }
5158   }
5159
5160   // All OK, it's constexpr!
5161   return true;
5162 }
5163
5164 static Sema::ImplicitExceptionSpecification
5165 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5166   switch (S.getSpecialMember(MD)) {
5167   case Sema::CXXDefaultConstructor:
5168     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5169   case Sema::CXXCopyConstructor:
5170     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5171   case Sema::CXXCopyAssignment:
5172     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5173   case Sema::CXXMoveConstructor:
5174     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5175   case Sema::CXXMoveAssignment:
5176     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5177   case Sema::CXXDestructor:
5178     return S.ComputeDefaultedDtorExceptionSpec(MD);
5179   case Sema::CXXInvalid:
5180     break;
5181   }
5182   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5183          "only special members have implicit exception specs");
5184   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
5185 }
5186
5187 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5188                                                             CXXMethodDecl *MD) {
5189   FunctionProtoType::ExtProtoInfo EPI;
5190
5191   // Build an exception specification pointing back at this member.
5192   EPI.ExceptionSpec.Type = EST_Unevaluated;
5193   EPI.ExceptionSpec.SourceDecl = MD;
5194
5195   // Set the calling convention to the default for C++ instance methods.
5196   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5197       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5198                                             /*IsCXXMethod=*/true));
5199   return EPI;
5200 }
5201
5202 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5203   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5204   if (FPT->getExceptionSpecType() != EST_Unevaluated)
5205     return;
5206
5207   // Evaluate the exception specification.
5208   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
5209
5210   // Update the type of the special member to use it.
5211   UpdateExceptionSpec(MD, ESI);
5212
5213   // A user-provided destructor can be defined outside the class. When that
5214   // happens, be sure to update the exception specification on both
5215   // declarations.
5216   const FunctionProtoType *CanonicalFPT =
5217     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5218   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
5219     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
5220 }
5221
5222 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5223   CXXRecordDecl *RD = MD->getParent();
5224   CXXSpecialMember CSM = getSpecialMember(MD);
5225
5226   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5227          "not an explicitly-defaulted special member");
5228
5229   // Whether this was the first-declared instance of the constructor.
5230   // This affects whether we implicitly add an exception spec and constexpr.
5231   bool First = MD == MD->getCanonicalDecl();
5232
5233   bool HadError = false;
5234
5235   // C++11 [dcl.fct.def.default]p1:
5236   //   A function that is explicitly defaulted shall
5237   //     -- be a special member function (checked elsewhere),
5238   //     -- have the same type (except for ref-qualifiers, and except that a
5239   //        copy operation can take a non-const reference) as an implicit
5240   //        declaration, and
5241   //     -- not have default arguments.
5242   unsigned ExpectedParams = 1;
5243   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5244     ExpectedParams = 0;
5245   if (MD->getNumParams() != ExpectedParams) {
5246     // This also checks for default arguments: a copy or move constructor with a
5247     // default argument is classified as a default constructor, and assignment
5248     // operations and destructors can't have default arguments.
5249     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5250       << CSM << MD->getSourceRange();
5251     HadError = true;
5252   } else if (MD->isVariadic()) {
5253     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5254       << CSM << MD->getSourceRange();
5255     HadError = true;
5256   }
5257
5258   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
5259
5260   bool CanHaveConstParam = false;
5261   if (CSM == CXXCopyConstructor)
5262     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
5263   else if (CSM == CXXCopyAssignment)
5264     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
5265
5266   QualType ReturnType = Context.VoidTy;
5267   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5268     // Check for return type matching.
5269     ReturnType = Type->getReturnType();
5270     QualType ExpectedReturnType =
5271         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5272     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5273       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5274         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5275       HadError = true;
5276     }
5277
5278     // A defaulted special member cannot have cv-qualifiers.
5279     if (Type->getTypeQuals()) {
5280       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
5281         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
5282       HadError = true;
5283     }
5284   }
5285
5286   // Check for parameter type matching.
5287   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
5288   bool HasConstParam = false;
5289   if (ExpectedParams && ArgType->isReferenceType()) {
5290     // Argument must be reference to possibly-const T.
5291     QualType ReferentType = ArgType->getPointeeType();
5292     HasConstParam = ReferentType.isConstQualified();
5293
5294     if (ReferentType.isVolatileQualified()) {
5295       Diag(MD->getLocation(),
5296            diag::err_defaulted_special_member_volatile_param) << CSM;
5297       HadError = true;
5298     }
5299
5300     if (HasConstParam && !CanHaveConstParam) {
5301       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5302         Diag(MD->getLocation(),
5303              diag::err_defaulted_special_member_copy_const_param)
5304           << (CSM == CXXCopyAssignment);
5305         // FIXME: Explain why this special member can't be const.
5306       } else {
5307         Diag(MD->getLocation(),
5308              diag::err_defaulted_special_member_move_const_param)
5309           << (CSM == CXXMoveAssignment);
5310       }
5311       HadError = true;
5312     }
5313   } else if (ExpectedParams) {
5314     // A copy assignment operator can take its argument by value, but a
5315     // defaulted one cannot.
5316     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5317     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5318     HadError = true;
5319   }
5320
5321   // C++11 [dcl.fct.def.default]p2:
5322   //   An explicitly-defaulted function may be declared constexpr only if it
5323   //   would have been implicitly declared as constexpr,
5324   // Do not apply this rule to members of class templates, since core issue 1358
5325   // makes such functions always instantiate to constexpr functions. For
5326   // functions which cannot be constexpr (for non-constructors in C++11 and for
5327   // destructors in C++1y), this is checked elsewhere.
5328   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5329                                                      HasConstParam);
5330   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5331                                  : isa<CXXConstructorDecl>(MD)) &&
5332       MD->isConstexpr() && !Constexpr &&
5333       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5334     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5335     // FIXME: Explain why the special member can't be constexpr.
5336     HadError = true;
5337   }
5338
5339   //   and may have an explicit exception-specification only if it is compatible
5340   //   with the exception-specification on the implicit declaration.
5341   if (Type->hasExceptionSpec()) {
5342     // Delay the check if this is the first declaration of the special member,
5343     // since we may not have parsed some necessary in-class initializers yet.
5344     if (First) {
5345       // If the exception specification needs to be instantiated, do so now,
5346       // before we clobber it with an EST_Unevaluated specification below.
5347       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5348         InstantiateExceptionSpec(MD->getLocStart(), MD);
5349         Type = MD->getType()->getAs<FunctionProtoType>();
5350       }
5351       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5352     } else
5353       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5354   }
5355
5356   //   If a function is explicitly defaulted on its first declaration,
5357   if (First) {
5358     //  -- it is implicitly considered to be constexpr if the implicit
5359     //     definition would be,
5360     MD->setConstexpr(Constexpr);
5361
5362     //  -- it is implicitly considered to have the same exception-specification
5363     //     as if it had been implicitly declared,
5364     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5365     EPI.ExceptionSpec.Type = EST_Unevaluated;
5366     EPI.ExceptionSpec.SourceDecl = MD;
5367     MD->setType(Context.getFunctionType(ReturnType,
5368                                         llvm::makeArrayRef(&ArgType,
5369                                                            ExpectedParams),
5370                                         EPI));
5371   }
5372
5373   if (ShouldDeleteSpecialMember(MD, CSM)) {
5374     if (First) {
5375       SetDeclDeleted(MD, MD->getLocation());
5376     } else {
5377       // C++11 [dcl.fct.def.default]p4:
5378       //   [For a] user-provided explicitly-defaulted function [...] if such a
5379       //   function is implicitly defined as deleted, the program is ill-formed.
5380       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5381       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5382       HadError = true;
5383     }
5384   }
5385
5386   if (HadError)
5387     MD->setInvalidDecl();
5388 }
5389
5390 /// Check whether the exception specification provided for an
5391 /// explicitly-defaulted special member matches the exception specification
5392 /// that would have been generated for an implicit special member, per
5393 /// C++11 [dcl.fct.def.default]p2.
5394 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5395     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5396   // If the exception specification was explicitly specified but hadn't been
5397   // parsed when the method was defaulted, grab it now.
5398   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5399     SpecifiedType =
5400         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5401
5402   // Compute the implicit exception specification.
5403   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5404                                                        /*IsCXXMethod=*/true);
5405   FunctionProtoType::ExtProtoInfo EPI(CC);
5406   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5407                           .getExceptionSpec();
5408   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5409     Context.getFunctionType(Context.VoidTy, None, EPI));
5410
5411   // Ensure that it matches.
5412   CheckEquivalentExceptionSpec(
5413     PDiag(diag::err_incorrect_defaulted_exception_spec)
5414       << getSpecialMember(MD), PDiag(),
5415     ImplicitType, SourceLocation(),
5416     SpecifiedType, MD->getLocation());
5417 }
5418
5419 void Sema::CheckDelayedMemberExceptionSpecs() {
5420   decltype(DelayedExceptionSpecChecks) Checks;
5421   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
5422
5423   std::swap(Checks, DelayedExceptionSpecChecks);
5424   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5425
5426   // Perform any deferred checking of exception specifications for virtual
5427   // destructors.
5428   for (auto &Check : Checks)
5429     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
5430
5431   // Check that any explicitly-defaulted methods have exception specifications
5432   // compatible with their implicit exception specifications.
5433   for (auto &Spec : Specs)
5434     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
5435 }
5436
5437 namespace {
5438 struct SpecialMemberDeletionInfo {
5439   Sema &S;
5440   CXXMethodDecl *MD;
5441   Sema::CXXSpecialMember CSM;
5442   bool Diagnose;
5443
5444   // Properties of the special member, computed for convenience.
5445   bool IsConstructor, IsAssignment, IsMove, ConstArg;
5446   SourceLocation Loc;
5447
5448   bool AllFieldsAreConst;
5449
5450   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5451                             Sema::CXXSpecialMember CSM, bool Diagnose)
5452     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5453       IsConstructor(false), IsAssignment(false), IsMove(false),
5454       ConstArg(false), Loc(MD->getLocation()),
5455       AllFieldsAreConst(true) {
5456     switch (CSM) {
5457       case Sema::CXXDefaultConstructor:
5458       case Sema::CXXCopyConstructor:
5459         IsConstructor = true;
5460         break;
5461       case Sema::CXXMoveConstructor:
5462         IsConstructor = true;
5463         IsMove = true;
5464         break;
5465       case Sema::CXXCopyAssignment:
5466         IsAssignment = true;
5467         break;
5468       case Sema::CXXMoveAssignment:
5469         IsAssignment = true;
5470         IsMove = true;
5471         break;
5472       case Sema::CXXDestructor:
5473         break;
5474       case Sema::CXXInvalid:
5475         llvm_unreachable("invalid special member kind");
5476     }
5477
5478     if (MD->getNumParams()) {
5479       if (const ReferenceType *RT =
5480               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5481         ConstArg = RT->getPointeeType().isConstQualified();
5482     }
5483   }
5484
5485   bool inUnion() const { return MD->getParent()->isUnion(); }
5486
5487   /// Look up the corresponding special member in the given class.
5488   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5489                                               unsigned Quals, bool IsMutable) {
5490     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5491                                        ConstArg && !IsMutable);
5492   }
5493
5494   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5495
5496   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5497   bool shouldDeleteForField(FieldDecl *FD);
5498   bool shouldDeleteForAllConstMembers();
5499
5500   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5501                                      unsigned Quals);
5502   bool shouldDeleteForSubobjectCall(Subobject Subobj,
5503                                     Sema::SpecialMemberOverloadResult *SMOR,
5504                                     bool IsDtorCallInCtor);
5505
5506   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5507 };
5508 }
5509
5510 /// Is the given special member inaccessible when used on the given
5511 /// sub-object.
5512 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5513                                              CXXMethodDecl *target) {
5514   /// If we're operating on a base class, the object type is the
5515   /// type of this special member.
5516   QualType objectTy;
5517   AccessSpecifier access = target->getAccess();
5518   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5519     objectTy = S.Context.getTypeDeclType(MD->getParent());
5520     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5521
5522   // If we're operating on a field, the object type is the type of the field.
5523   } else {
5524     objectTy = S.Context.getTypeDeclType(target->getParent());
5525   }
5526
5527   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5528 }
5529
5530 /// Check whether we should delete a special member due to the implicit
5531 /// definition containing a call to a special member of a subobject.
5532 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5533     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5534     bool IsDtorCallInCtor) {
5535   CXXMethodDecl *Decl = SMOR->getMethod();
5536   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5537
5538   int DiagKind = -1;
5539
5540   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5541     DiagKind = !Decl ? 0 : 1;
5542   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5543     DiagKind = 2;
5544   else if (!isAccessible(Subobj, Decl))
5545     DiagKind = 3;
5546   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5547            !Decl->isTrivial()) {
5548     // A member of a union must have a trivial corresponding special member.
5549     // As a weird special case, a destructor call from a union's constructor
5550     // must be accessible and non-deleted, but need not be trivial. Such a
5551     // destructor is never actually called, but is semantically checked as
5552     // if it were.
5553     DiagKind = 4;
5554   }
5555
5556   if (DiagKind == -1)
5557     return false;
5558
5559   if (Diagnose) {
5560     if (Field) {
5561       S.Diag(Field->getLocation(),
5562              diag::note_deleted_special_member_class_subobject)
5563         << CSM << MD->getParent() << /*IsField*/true
5564         << Field << DiagKind << IsDtorCallInCtor;
5565     } else {
5566       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5567       S.Diag(Base->getLocStart(),
5568              diag::note_deleted_special_member_class_subobject)
5569         << CSM << MD->getParent() << /*IsField*/false
5570         << Base->getType() << DiagKind << IsDtorCallInCtor;
5571     }
5572
5573     if (DiagKind == 1)
5574       S.NoteDeletedFunction(Decl);
5575     // FIXME: Explain inaccessibility if DiagKind == 3.
5576   }
5577
5578   return true;
5579 }
5580
5581 /// Check whether we should delete a special member function due to having a
5582 /// direct or virtual base class or non-static data member of class type M.
5583 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5584     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5585   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5586   bool IsMutable = Field && Field->isMutable();
5587
5588   // C++11 [class.ctor]p5:
5589   // -- any direct or virtual base class, or non-static data member with no
5590   //    brace-or-equal-initializer, has class type M (or array thereof) and
5591   //    either M has no default constructor or overload resolution as applied
5592   //    to M's default constructor results in an ambiguity or in a function
5593   //    that is deleted or inaccessible
5594   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5595   // -- a direct or virtual base class B that cannot be copied/moved because
5596   //    overload resolution, as applied to B's corresponding special member,
5597   //    results in an ambiguity or a function that is deleted or inaccessible
5598   //    from the defaulted special member
5599   // C++11 [class.dtor]p5:
5600   // -- any direct or virtual base class [...] has a type with a destructor
5601   //    that is deleted or inaccessible
5602   if (!(CSM == Sema::CXXDefaultConstructor &&
5603         Field && Field->hasInClassInitializer()) &&
5604       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5605                                    false))
5606     return true;
5607
5608   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5609   // -- any direct or virtual base class or non-static data member has a
5610   //    type with a destructor that is deleted or inaccessible
5611   if (IsConstructor) {
5612     Sema::SpecialMemberOverloadResult *SMOR =
5613         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5614                               false, false, false, false, false);
5615     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5616       return true;
5617   }
5618
5619   return false;
5620 }
5621
5622 /// Check whether we should delete a special member function due to the class
5623 /// having a particular direct or virtual base class.
5624 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5625   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5626   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5627 }
5628
5629 /// Check whether we should delete a special member function due to the class
5630 /// having a particular non-static data member.
5631 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5632   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5633   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5634
5635   if (CSM == Sema::CXXDefaultConstructor) {
5636     // For a default constructor, all references must be initialized in-class
5637     // and, if a union, it must have a non-const member.
5638     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5639       if (Diagnose)
5640         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5641           << MD->getParent() << FD << FieldType << /*Reference*/0;
5642       return true;
5643     }
5644     // C++11 [class.ctor]p5: any non-variant non-static data member of
5645     // const-qualified type (or array thereof) with no
5646     // brace-or-equal-initializer does not have a user-provided default
5647     // constructor.
5648     if (!inUnion() && FieldType.isConstQualified() &&
5649         !FD->hasInClassInitializer() &&
5650         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5651       if (Diagnose)
5652         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5653           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5654       return true;
5655     }
5656
5657     if (inUnion() && !FieldType.isConstQualified())
5658       AllFieldsAreConst = false;
5659   } else if (CSM == Sema::CXXCopyConstructor) {
5660     // For a copy constructor, data members must not be of rvalue reference
5661     // type.
5662     if (FieldType->isRValueReferenceType()) {
5663       if (Diagnose)
5664         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5665           << MD->getParent() << FD << FieldType;
5666       return true;
5667     }
5668   } else if (IsAssignment) {
5669     // For an assignment operator, data members must not be of reference type.
5670     if (FieldType->isReferenceType()) {
5671       if (Diagnose)
5672         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5673           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5674       return true;
5675     }
5676     if (!FieldRecord && FieldType.isConstQualified()) {
5677       // C++11 [class.copy]p23:
5678       // -- a non-static data member of const non-class type (or array thereof)
5679       if (Diagnose)
5680         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5681           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5682       return true;
5683     }
5684   }
5685
5686   if (FieldRecord) {
5687     // Some additional restrictions exist on the variant members.
5688     if (!inUnion() && FieldRecord->isUnion() &&
5689         FieldRecord->isAnonymousStructOrUnion()) {
5690       bool AllVariantFieldsAreConst = true;
5691
5692       // FIXME: Handle anonymous unions declared within anonymous unions.
5693       for (auto *UI : FieldRecord->fields()) {
5694         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5695
5696         if (!UnionFieldType.isConstQualified())
5697           AllVariantFieldsAreConst = false;
5698
5699         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5700         if (UnionFieldRecord &&
5701             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5702                                           UnionFieldType.getCVRQualifiers()))
5703           return true;
5704       }
5705
5706       // At least one member in each anonymous union must be non-const
5707       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5708           !FieldRecord->field_empty()) {
5709         if (Diagnose)
5710           S.Diag(FieldRecord->getLocation(),
5711                  diag::note_deleted_default_ctor_all_const)
5712             << MD->getParent() << /*anonymous union*/1;
5713         return true;
5714       }
5715
5716       // Don't check the implicit member of the anonymous union type.
5717       // This is technically non-conformant, but sanity demands it.
5718       return false;
5719     }
5720
5721     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5722                                       FieldType.getCVRQualifiers()))
5723       return true;
5724   }
5725
5726   return false;
5727 }
5728
5729 /// C++11 [class.ctor] p5:
5730 ///   A defaulted default constructor for a class X is defined as deleted if
5731 /// X is a union and all of its variant members are of const-qualified type.
5732 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5733   // This is a silly definition, because it gives an empty union a deleted
5734   // default constructor. Don't do that.
5735   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5736       !MD->getParent()->field_empty()) {
5737     if (Diagnose)
5738       S.Diag(MD->getParent()->getLocation(),
5739              diag::note_deleted_default_ctor_all_const)
5740         << MD->getParent() << /*not anonymous union*/0;
5741     return true;
5742   }
5743   return false;
5744 }
5745
5746 /// Determine whether a defaulted special member function should be defined as
5747 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5748 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5749 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5750                                      bool Diagnose) {
5751   if (MD->isInvalidDecl())
5752     return false;
5753   CXXRecordDecl *RD = MD->getParent();
5754   assert(!RD->isDependentType() && "do deletion after instantiation");
5755   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5756     return false;
5757
5758   // C++11 [expr.lambda.prim]p19:
5759   //   The closure type associated with a lambda-expression has a
5760   //   deleted (8.4.3) default constructor and a deleted copy
5761   //   assignment operator.
5762   if (RD->isLambda() &&
5763       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5764     if (Diagnose)
5765       Diag(RD->getLocation(), diag::note_lambda_decl);
5766     return true;
5767   }
5768
5769   // For an anonymous struct or union, the copy and assignment special members
5770   // will never be used, so skip the check. For an anonymous union declared at
5771   // namespace scope, the constructor and destructor are used.
5772   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5773       RD->isAnonymousStructOrUnion())
5774     return false;
5775
5776   // C++11 [class.copy]p7, p18:
5777   //   If the class definition declares a move constructor or move assignment
5778   //   operator, an implicitly declared copy constructor or copy assignment
5779   //   operator is defined as deleted.
5780   if (MD->isImplicit() &&
5781       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5782     CXXMethodDecl *UserDeclaredMove = nullptr;
5783
5784     // In Microsoft mode, a user-declared move only causes the deletion of the
5785     // corresponding copy operation, not both copy operations.
5786     if (RD->hasUserDeclaredMoveConstructor() &&
5787         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5788       if (!Diagnose) return true;
5789
5790       // Find any user-declared move constructor.
5791       for (auto *I : RD->ctors()) {
5792         if (I->isMoveConstructor()) {
5793           UserDeclaredMove = I;
5794           break;
5795         }
5796       }
5797       assert(UserDeclaredMove);
5798     } else if (RD->hasUserDeclaredMoveAssignment() &&
5799                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5800       if (!Diagnose) return true;
5801
5802       // Find any user-declared move assignment operator.
5803       for (auto *I : RD->methods()) {
5804         if (I->isMoveAssignmentOperator()) {
5805           UserDeclaredMove = I;
5806           break;
5807         }
5808       }
5809       assert(UserDeclaredMove);
5810     }
5811
5812     if (UserDeclaredMove) {
5813       Diag(UserDeclaredMove->getLocation(),
5814            diag::note_deleted_copy_user_declared_move)
5815         << (CSM == CXXCopyAssignment) << RD
5816         << UserDeclaredMove->isMoveAssignmentOperator();
5817       return true;
5818     }
5819   }
5820
5821   // Do access control from the special member function
5822   ContextRAII MethodContext(*this, MD);
5823
5824   // C++11 [class.dtor]p5:
5825   // -- for a virtual destructor, lookup of the non-array deallocation function
5826   //    results in an ambiguity or in a function that is deleted or inaccessible
5827   if (CSM == CXXDestructor && MD->isVirtual()) {
5828     FunctionDecl *OperatorDelete = nullptr;
5829     DeclarationName Name =
5830       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5831     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5832                                  OperatorDelete, false)) {
5833       if (Diagnose)
5834         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5835       return true;
5836     }
5837   }
5838
5839   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5840
5841   for (auto &BI : RD->bases())
5842     if (!BI.isVirtual() &&
5843         SMI.shouldDeleteForBase(&BI))
5844       return true;
5845
5846   // Per DR1611, do not consider virtual bases of constructors of abstract
5847   // classes, since we are not going to construct them.
5848   if (!RD->isAbstract() || !SMI.IsConstructor) {
5849     for (auto &BI : RD->vbases())
5850       if (SMI.shouldDeleteForBase(&BI))
5851         return true;
5852   }
5853
5854   for (auto *FI : RD->fields())
5855     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5856         SMI.shouldDeleteForField(FI))
5857       return true;
5858
5859   if (SMI.shouldDeleteForAllConstMembers())
5860     return true;
5861
5862   if (getLangOpts().CUDA) {
5863     // We should delete the special member in CUDA mode if target inference
5864     // failed.
5865     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5866                                                    Diagnose);
5867   }
5868
5869   return false;
5870 }
5871
5872 /// Perform lookup for a special member of the specified kind, and determine
5873 /// whether it is trivial. If the triviality can be determined without the
5874 /// lookup, skip it. This is intended for use when determining whether a
5875 /// special member of a containing object is trivial, and thus does not ever
5876 /// perform overload resolution for default constructors.
5877 ///
5878 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5879 /// member that was most likely to be intended to be trivial, if any.
5880 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5881                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5882                                      bool ConstRHS, CXXMethodDecl **Selected) {
5883   if (Selected)
5884     *Selected = nullptr;
5885
5886   switch (CSM) {
5887   case Sema::CXXInvalid:
5888     llvm_unreachable("not a special member");
5889
5890   case Sema::CXXDefaultConstructor:
5891     // C++11 [class.ctor]p5:
5892     //   A default constructor is trivial if:
5893     //    - all the [direct subobjects] have trivial default constructors
5894     //
5895     // Note, no overload resolution is performed in this case.
5896     if (RD->hasTrivialDefaultConstructor())
5897       return true;
5898
5899     if (Selected) {
5900       // If there's a default constructor which could have been trivial, dig it
5901       // out. Otherwise, if there's any user-provided default constructor, point
5902       // to that as an example of why there's not a trivial one.
5903       CXXConstructorDecl *DefCtor = nullptr;
5904       if (RD->needsImplicitDefaultConstructor())
5905         S.DeclareImplicitDefaultConstructor(RD);
5906       for (auto *CI : RD->ctors()) {
5907         if (!CI->isDefaultConstructor())
5908           continue;
5909         DefCtor = CI;
5910         if (!DefCtor->isUserProvided())
5911           break;
5912       }
5913
5914       *Selected = DefCtor;
5915     }
5916
5917     return false;
5918
5919   case Sema::CXXDestructor:
5920     // C++11 [class.dtor]p5:
5921     //   A destructor is trivial if:
5922     //    - all the direct [subobjects] have trivial destructors
5923     if (RD->hasTrivialDestructor())
5924       return true;
5925
5926     if (Selected) {
5927       if (RD->needsImplicitDestructor())
5928         S.DeclareImplicitDestructor(RD);
5929       *Selected = RD->getDestructor();
5930     }
5931
5932     return false;
5933
5934   case Sema::CXXCopyConstructor:
5935     // C++11 [class.copy]p12:
5936     //   A copy constructor is trivial if:
5937     //    - the constructor selected to copy each direct [subobject] is trivial
5938     if (RD->hasTrivialCopyConstructor()) {
5939       if (Quals == Qualifiers::Const)
5940         // We must either select the trivial copy constructor or reach an
5941         // ambiguity; no need to actually perform overload resolution.
5942         return true;
5943     } else if (!Selected) {
5944       return false;
5945     }
5946     // In C++98, we are not supposed to perform overload resolution here, but we
5947     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5948     // cases like B as having a non-trivial copy constructor:
5949     //   struct A { template<typename T> A(T&); };
5950     //   struct B { mutable A a; };
5951     goto NeedOverloadResolution;
5952
5953   case Sema::CXXCopyAssignment:
5954     // C++11 [class.copy]p25:
5955     //   A copy assignment operator is trivial if:
5956     //    - the assignment operator selected to copy each direct [subobject] is
5957     //      trivial
5958     if (RD->hasTrivialCopyAssignment()) {
5959       if (Quals == Qualifiers::Const)
5960         return true;
5961     } else if (!Selected) {
5962       return false;
5963     }
5964     // In C++98, we are not supposed to perform overload resolution here, but we
5965     // treat that as a language defect.
5966     goto NeedOverloadResolution;
5967
5968   case Sema::CXXMoveConstructor:
5969   case Sema::CXXMoveAssignment:
5970   NeedOverloadResolution:
5971     Sema::SpecialMemberOverloadResult *SMOR =
5972         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5973
5974     // The standard doesn't describe how to behave if the lookup is ambiguous.
5975     // We treat it as not making the member non-trivial, just like the standard
5976     // mandates for the default constructor. This should rarely matter, because
5977     // the member will also be deleted.
5978     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5979       return true;
5980
5981     if (!SMOR->getMethod()) {
5982       assert(SMOR->getKind() ==
5983              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5984       return false;
5985     }
5986
5987     // We deliberately don't check if we found a deleted special member. We're
5988     // not supposed to!
5989     if (Selected)
5990       *Selected = SMOR->getMethod();
5991     return SMOR->getMethod()->isTrivial();
5992   }
5993
5994   llvm_unreachable("unknown special method kind");
5995 }
5996
5997 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5998   for (auto *CI : RD->ctors())
5999     if (!CI->isImplicit())
6000       return CI;
6001
6002   // Look for constructor templates.
6003   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6004   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6005     if (CXXConstructorDecl *CD =
6006           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6007       return CD;
6008   }
6009
6010   return nullptr;
6011 }
6012
6013 /// The kind of subobject we are checking for triviality. The values of this
6014 /// enumeration are used in diagnostics.
6015 enum TrivialSubobjectKind {
6016   /// The subobject is a base class.
6017   TSK_BaseClass,
6018   /// The subobject is a non-static data member.
6019   TSK_Field,
6020   /// The object is actually the complete object.
6021   TSK_CompleteObject
6022 };
6023
6024 /// Check whether the special member selected for a given type would be trivial.
6025 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
6026                                       QualType SubType, bool ConstRHS,
6027                                       Sema::CXXSpecialMember CSM,
6028                                       TrivialSubobjectKind Kind,
6029                                       bool Diagnose) {
6030   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6031   if (!SubRD)
6032     return true;
6033
6034   CXXMethodDecl *Selected;
6035   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6036                                ConstRHS, Diagnose ? &Selected : nullptr))
6037     return true;
6038
6039   if (Diagnose) {
6040     if (ConstRHS)
6041       SubType.addConst();
6042
6043     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6044       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6045         << Kind << SubType.getUnqualifiedType();
6046       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6047         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6048     } else if (!Selected)
6049       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6050         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6051     else if (Selected->isUserProvided()) {
6052       if (Kind == TSK_CompleteObject)
6053         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6054           << Kind << SubType.getUnqualifiedType() << CSM;
6055       else {
6056         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6057           << Kind << SubType.getUnqualifiedType() << CSM;
6058         S.Diag(Selected->getLocation(), diag::note_declared_at);
6059       }
6060     } else {
6061       if (Kind != TSK_CompleteObject)
6062         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6063           << Kind << SubType.getUnqualifiedType() << CSM;
6064
6065       // Explain why the defaulted or deleted special member isn't trivial.
6066       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6067     }
6068   }
6069
6070   return false;
6071 }
6072
6073 /// Check whether the members of a class type allow a special member to be
6074 /// trivial.
6075 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6076                                      Sema::CXXSpecialMember CSM,
6077                                      bool ConstArg, bool Diagnose) {
6078   for (const auto *FI : RD->fields()) {
6079     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6080       continue;
6081
6082     QualType FieldType = S.Context.getBaseElementType(FI->getType());
6083
6084     // Pretend anonymous struct or union members are members of this class.
6085     if (FI->isAnonymousStructOrUnion()) {
6086       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6087                                     CSM, ConstArg, Diagnose))
6088         return false;
6089       continue;
6090     }
6091
6092     // C++11 [class.ctor]p5:
6093     //   A default constructor is trivial if [...]
6094     //    -- no non-static data member of its class has a
6095     //       brace-or-equal-initializer
6096     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6097       if (Diagnose)
6098         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
6099       return false;
6100     }
6101
6102     // Objective C ARC 4.3.5:
6103     //   [...] nontrivally ownership-qualified types are [...] not trivially
6104     //   default constructible, copy constructible, move constructible, copy
6105     //   assignable, move assignable, or destructible [...]
6106     if (S.getLangOpts().ObjCAutoRefCount &&
6107         FieldType.hasNonTrivialObjCLifetime()) {
6108       if (Diagnose)
6109         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6110           << RD << FieldType.getObjCLifetime();
6111       return false;
6112     }
6113
6114     bool ConstRHS = ConstArg && !FI->isMutable();
6115     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6116                                    CSM, TSK_Field, Diagnose))
6117       return false;
6118   }
6119
6120   return true;
6121 }
6122
6123 /// Diagnose why the specified class does not have a trivial special member of
6124 /// the given kind.
6125 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6126   QualType Ty = Context.getRecordType(RD);
6127
6128   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6129   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
6130                             TSK_CompleteObject, /*Diagnose*/true);
6131 }
6132
6133 /// Determine whether a defaulted or deleted special member function is trivial,
6134 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6135 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6136 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6137                                   bool Diagnose) {
6138   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6139
6140   CXXRecordDecl *RD = MD->getParent();
6141
6142   bool ConstArg = false;
6143
6144   // C++11 [class.copy]p12, p25: [DR1593]
6145   //   A [special member] is trivial if [...] its parameter-type-list is
6146   //   equivalent to the parameter-type-list of an implicit declaration [...]
6147   switch (CSM) {
6148   case CXXDefaultConstructor:
6149   case CXXDestructor:
6150     // Trivial default constructors and destructors cannot have parameters.
6151     break;
6152
6153   case CXXCopyConstructor:
6154   case CXXCopyAssignment: {
6155     // Trivial copy operations always have const, non-volatile parameter types.
6156     ConstArg = true;
6157     const ParmVarDecl *Param0 = MD->getParamDecl(0);
6158     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6159     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6160       if (Diagnose)
6161         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6162           << Param0->getSourceRange() << Param0->getType()
6163           << Context.getLValueReferenceType(
6164                Context.getRecordType(RD).withConst());
6165       return false;
6166     }
6167     break;
6168   }
6169
6170   case CXXMoveConstructor:
6171   case CXXMoveAssignment: {
6172     // Trivial move operations always have non-cv-qualified parameters.
6173     const ParmVarDecl *Param0 = MD->getParamDecl(0);
6174     const RValueReferenceType *RT =
6175       Param0->getType()->getAs<RValueReferenceType>();
6176     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6177       if (Diagnose)
6178         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6179           << Param0->getSourceRange() << Param0->getType()
6180           << Context.getRValueReferenceType(Context.getRecordType(RD));
6181       return false;
6182     }
6183     break;
6184   }
6185
6186   case CXXInvalid:
6187     llvm_unreachable("not a special member");
6188   }
6189
6190   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6191     if (Diagnose)
6192       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6193            diag::note_nontrivial_default_arg)
6194         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6195     return false;
6196   }
6197   if (MD->isVariadic()) {
6198     if (Diagnose)
6199       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6200     return false;
6201   }
6202
6203   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6204   //   A copy/move [constructor or assignment operator] is trivial if
6205   //    -- the [member] selected to copy/move each direct base class subobject
6206   //       is trivial
6207   //
6208   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6209   //   A [default constructor or destructor] is trivial if
6210   //    -- all the direct base classes have trivial [default constructors or
6211   //       destructors]
6212   for (const auto &BI : RD->bases())
6213     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6214                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
6215       return false;
6216
6217   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6218   //   A copy/move [constructor or assignment operator] for a class X is
6219   //   trivial if
6220   //    -- for each non-static data member of X that is of class type (or array
6221   //       thereof), the constructor selected to copy/move that member is
6222   //       trivial
6223   //
6224   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6225   //   A [default constructor or destructor] is trivial if
6226   //    -- for all of the non-static data members of its class that are of class
6227   //       type (or array thereof), each such class has a trivial [default
6228   //       constructor or destructor]
6229   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6230     return false;
6231
6232   // C++11 [class.dtor]p5:
6233   //   A destructor is trivial if [...]
6234   //    -- the destructor is not virtual
6235   if (CSM == CXXDestructor && MD->isVirtual()) {
6236     if (Diagnose)
6237       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6238     return false;
6239   }
6240
6241   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6242   //   A [special member] for class X is trivial if [...]
6243   //    -- class X has no virtual functions and no virtual base classes
6244   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6245     if (!Diagnose)
6246       return false;
6247
6248     if (RD->getNumVBases()) {
6249       // Check for virtual bases. We already know that the corresponding
6250       // member in all bases is trivial, so vbases must all be direct.
6251       CXXBaseSpecifier &BS = *RD->vbases_begin();
6252       assert(BS.isVirtual());
6253       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6254       return false;
6255     }
6256
6257     // Must have a virtual method.
6258     for (const auto *MI : RD->methods()) {
6259       if (MI->isVirtual()) {
6260         SourceLocation MLoc = MI->getLocStart();
6261         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6262         return false;
6263       }
6264     }
6265
6266     llvm_unreachable("dynamic class with no vbases and no virtual functions");
6267   }
6268
6269   // Looks like it's trivial!
6270   return true;
6271 }
6272
6273 /// \brief Data used with FindHiddenVirtualMethod
6274 namespace {
6275   struct FindHiddenVirtualMethodData {
6276     Sema *S;
6277     CXXMethodDecl *Method;
6278     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6279     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6280   };
6281 }
6282
6283 /// \brief Check whether any most overriden method from MD in Methods
6284 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
6285                   const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6286   if (MD->size_overridden_methods() == 0)
6287     return Methods.count(MD->getCanonicalDecl());
6288   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6289                                       E = MD->end_overridden_methods();
6290        I != E; ++I)
6291     if (CheckMostOverridenMethods(*I, Methods))
6292       return true;
6293   return false;
6294 }
6295
6296 /// \brief Member lookup function that determines whether a given C++
6297 /// method overloads virtual methods in a base class without overriding any,
6298 /// to be used with CXXRecordDecl::lookupInBases().
6299 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6300                                     CXXBasePath &Path,
6301                                     void *UserData) {
6302   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6303
6304   FindHiddenVirtualMethodData &Data
6305     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6306
6307   DeclarationName Name = Data.Method->getDeclName();
6308   assert(Name.getNameKind() == DeclarationName::Identifier);
6309
6310   bool foundSameNameMethod = false;
6311   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6312   for (Path.Decls = BaseRecord->lookup(Name);
6313        !Path.Decls.empty();
6314        Path.Decls = Path.Decls.slice(1)) {
6315     NamedDecl *D = Path.Decls.front();
6316     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6317       MD = MD->getCanonicalDecl();
6318       foundSameNameMethod = true;
6319       // Interested only in hidden virtual methods.
6320       if (!MD->isVirtual())
6321         continue;
6322       // If the method we are checking overrides a method from its base
6323       // don't warn about the other overloaded methods. Clang deviates from GCC
6324       // by only diagnosing overloads of inherited virtual functions that do not
6325       // override any other virtual functions in the base. GCC's
6326       // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6327       // function from a base class. These cases may be better served by a
6328       // warning (not specific to virtual functions) on call sites when the call
6329       // would select a different function from the base class, were it visible.
6330       // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6331       if (!Data.S->IsOverload(Data.Method, MD, false))
6332         return true;
6333       // Collect the overload only if its hidden.
6334       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
6335         overloadedMethods.push_back(MD);
6336     }
6337   }
6338
6339   if (foundSameNameMethod)
6340     Data.OverloadedMethods.append(overloadedMethods.begin(),
6341                                    overloadedMethods.end());
6342   return foundSameNameMethod;
6343 }
6344
6345 /// \brief Add the most overriden methods from MD to Methods
6346 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6347                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6348   if (MD->size_overridden_methods() == 0)
6349     Methods.insert(MD->getCanonicalDecl());
6350   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6351                                       E = MD->end_overridden_methods();
6352        I != E; ++I)
6353     AddMostOverridenMethods(*I, Methods);
6354 }
6355
6356 /// \brief Check if a method overloads virtual methods in a base class without
6357 /// overriding any.
6358 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6359                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6360   if (!MD->getDeclName().isIdentifier())
6361     return;
6362
6363   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6364                      /*bool RecordPaths=*/false,
6365                      /*bool DetectVirtual=*/false);
6366   FindHiddenVirtualMethodData Data;
6367   Data.Method = MD;
6368   Data.S = this;
6369
6370   // Keep the base methods that were overriden or introduced in the subclass
6371   // by 'using' in a set. A base method not in this set is hidden.
6372   CXXRecordDecl *DC = MD->getParent();
6373   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6374   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6375     NamedDecl *ND = *I;
6376     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6377       ND = shad->getTargetDecl();
6378     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6379       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
6380   }
6381
6382   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6383     OverloadedMethods = Data.OverloadedMethods;
6384 }
6385
6386 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6387                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6388   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6389     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6390     PartialDiagnostic PD = PDiag(
6391          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6392     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6393     Diag(overloadedMD->getLocation(), PD);
6394   }
6395 }
6396
6397 /// \brief Diagnose methods which overload virtual methods in a base class
6398 /// without overriding any.
6399 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6400   if (MD->isInvalidDecl())
6401     return;
6402
6403   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6404     return;
6405
6406   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6407   FindHiddenVirtualMethods(MD, OverloadedMethods);
6408   if (!OverloadedMethods.empty()) {
6409     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6410       << MD << (OverloadedMethods.size() > 1);
6411
6412     NoteHiddenVirtualMethods(MD, OverloadedMethods);
6413   }
6414 }
6415
6416 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6417                                              Decl *TagDecl,
6418                                              SourceLocation LBrac,
6419                                              SourceLocation RBrac,
6420                                              AttributeList *AttrList) {
6421   if (!TagDecl)
6422     return;
6423
6424   AdjustDeclIfTemplate(TagDecl);
6425
6426   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6427     if (l->getKind() != AttributeList::AT_Visibility)
6428       continue;
6429     l->setInvalid();
6430     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6431       l->getName();
6432   }
6433
6434   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6435               // strict aliasing violation!
6436               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6437               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6438
6439   CheckCompletedCXXClass(
6440                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6441 }
6442
6443 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6444 /// special functions, such as the default constructor, copy
6445 /// constructor, or destructor, to the given C++ class (C++
6446 /// [special]p1).  This routine can only be executed just before the
6447 /// definition of the class is complete.
6448 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6449   if (!ClassDecl->hasUserDeclaredConstructor())
6450     ++ASTContext::NumImplicitDefaultConstructors;
6451
6452   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6453     ++ASTContext::NumImplicitCopyConstructors;
6454
6455     // If the properties or semantics of the copy constructor couldn't be
6456     // determined while the class was being declared, force a declaration
6457     // of it now.
6458     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6459       DeclareImplicitCopyConstructor(ClassDecl);
6460   }
6461
6462   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6463     ++ASTContext::NumImplicitMoveConstructors;
6464
6465     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6466       DeclareImplicitMoveConstructor(ClassDecl);
6467   }
6468
6469   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6470     ++ASTContext::NumImplicitCopyAssignmentOperators;
6471
6472     // If we have a dynamic class, then the copy assignment operator may be
6473     // virtual, so we have to declare it immediately. This ensures that, e.g.,
6474     // it shows up in the right place in the vtable and that we diagnose
6475     // problems with the implicit exception specification.
6476     if (ClassDecl->isDynamicClass() ||
6477         ClassDecl->needsOverloadResolutionForCopyAssignment())
6478       DeclareImplicitCopyAssignment(ClassDecl);
6479   }
6480
6481   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6482     ++ASTContext::NumImplicitMoveAssignmentOperators;
6483
6484     // Likewise for the move assignment operator.
6485     if (ClassDecl->isDynamicClass() ||
6486         ClassDecl->needsOverloadResolutionForMoveAssignment())
6487       DeclareImplicitMoveAssignment(ClassDecl);
6488   }
6489
6490   if (!ClassDecl->hasUserDeclaredDestructor()) {
6491     ++ASTContext::NumImplicitDestructors;
6492
6493     // If we have a dynamic class, then the destructor may be virtual, so we
6494     // have to declare the destructor immediately. This ensures that, e.g., it
6495     // shows up in the right place in the vtable and that we diagnose problems
6496     // with the implicit exception specification.
6497     if (ClassDecl->isDynamicClass() ||
6498         ClassDecl->needsOverloadResolutionForDestructor())
6499       DeclareImplicitDestructor(ClassDecl);
6500   }
6501 }
6502
6503 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6504   if (!D)
6505     return 0;
6506
6507   // The order of template parameters is not important here. All names
6508   // get added to the same scope.
6509   SmallVector<TemplateParameterList *, 4> ParameterLists;
6510
6511   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6512     D = TD->getTemplatedDecl();
6513
6514   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6515     ParameterLists.push_back(PSD->getTemplateParameters());
6516
6517   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6518     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6519       ParameterLists.push_back(DD->getTemplateParameterList(i));
6520
6521     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6522       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6523         ParameterLists.push_back(FTD->getTemplateParameters());
6524     }
6525   }
6526
6527   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6528     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6529       ParameterLists.push_back(TD->getTemplateParameterList(i));
6530
6531     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6532       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6533         ParameterLists.push_back(CTD->getTemplateParameters());
6534     }
6535   }
6536
6537   unsigned Count = 0;
6538   for (TemplateParameterList *Params : ParameterLists) {
6539     if (Params->size() > 0)
6540       // Ignore explicit specializations; they don't contribute to the template
6541       // depth.
6542       ++Count;
6543     for (NamedDecl *Param : *Params) {
6544       if (Param->getDeclName()) {
6545         S->AddDecl(Param);
6546         IdResolver.AddDecl(Param);
6547       }
6548     }
6549   }
6550
6551   return Count;
6552 }
6553
6554 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6555   if (!RecordD) return;
6556   AdjustDeclIfTemplate(RecordD);
6557   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6558   PushDeclContext(S, Record);
6559 }
6560
6561 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6562   if (!RecordD) return;
6563   PopDeclContext();
6564 }
6565
6566 /// This is used to implement the constant expression evaluation part of the
6567 /// attribute enable_if extension. There is nothing in standard C++ which would
6568 /// require reentering parameters.
6569 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6570   if (!Param)
6571     return;
6572
6573   S->AddDecl(Param);
6574   if (Param->getDeclName())
6575     IdResolver.AddDecl(Param);
6576 }
6577
6578 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6579 /// parsing a top-level (non-nested) C++ class, and we are now
6580 /// parsing those parts of the given Method declaration that could
6581 /// not be parsed earlier (C++ [class.mem]p2), such as default
6582 /// arguments. This action should enter the scope of the given
6583 /// Method declaration as if we had just parsed the qualified method
6584 /// name. However, it should not bring the parameters into scope;
6585 /// that will be performed by ActOnDelayedCXXMethodParameter.
6586 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6587 }
6588
6589 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6590 /// C++ method declaration. We're (re-)introducing the given
6591 /// function parameter into scope for use in parsing later parts of
6592 /// the method declaration. For example, we could see an
6593 /// ActOnParamDefaultArgument event for this parameter.
6594 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6595   if (!ParamD)
6596     return;
6597
6598   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6599
6600   // If this parameter has an unparsed default argument, clear it out
6601   // to make way for the parsed default argument.
6602   if (Param->hasUnparsedDefaultArg())
6603     Param->setDefaultArg(nullptr);
6604
6605   S->AddDecl(Param);
6606   if (Param->getDeclName())
6607     IdResolver.AddDecl(Param);
6608 }
6609
6610 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6611 /// processing the delayed method declaration for Method. The method
6612 /// declaration is now considered finished. There may be a separate
6613 /// ActOnStartOfFunctionDef action later (not necessarily
6614 /// immediately!) for this method, if it was also defined inside the
6615 /// class body.
6616 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6617   if (!MethodD)
6618     return;
6619
6620   AdjustDeclIfTemplate(MethodD);
6621
6622   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6623
6624   // Now that we have our default arguments, check the constructor
6625   // again. It could produce additional diagnostics or affect whether
6626   // the class has implicitly-declared destructors, among other
6627   // things.
6628   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6629     CheckConstructor(Constructor);
6630
6631   // Check the default arguments, which we may have added.
6632   if (!Method->isInvalidDecl())
6633     CheckCXXDefaultArguments(Method);
6634 }
6635
6636 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6637 /// the well-formedness of the constructor declarator @p D with type @p
6638 /// R. If there are any errors in the declarator, this routine will
6639 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6640 /// will be updated to reflect a well-formed type for the constructor and
6641 /// returned.
6642 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6643                                           StorageClass &SC) {
6644   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6645
6646   // C++ [class.ctor]p3:
6647   //   A constructor shall not be virtual (10.3) or static (9.4). A
6648   //   constructor can be invoked for a const, volatile or const
6649   //   volatile object. A constructor shall not be declared const,
6650   //   volatile, or const volatile (9.3.2).
6651   if (isVirtual) {
6652     if (!D.isInvalidType())
6653       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6654         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6655         << SourceRange(D.getIdentifierLoc());
6656     D.setInvalidType();
6657   }
6658   if (SC == SC_Static) {
6659     if (!D.isInvalidType())
6660       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6661         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6662         << SourceRange(D.getIdentifierLoc());
6663     D.setInvalidType();
6664     SC = SC_None;
6665   }
6666
6667   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6668     diagnoseIgnoredQualifiers(
6669         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6670         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6671         D.getDeclSpec().getRestrictSpecLoc(),
6672         D.getDeclSpec().getAtomicSpecLoc());
6673     D.setInvalidType();
6674   }
6675
6676   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6677   if (FTI.TypeQuals != 0) {
6678     if (FTI.TypeQuals & Qualifiers::Const)
6679       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6680         << "const" << SourceRange(D.getIdentifierLoc());
6681     if (FTI.TypeQuals & Qualifiers::Volatile)
6682       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6683         << "volatile" << SourceRange(D.getIdentifierLoc());
6684     if (FTI.TypeQuals & Qualifiers::Restrict)
6685       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6686         << "restrict" << SourceRange(D.getIdentifierLoc());
6687     D.setInvalidType();
6688   }
6689
6690   // C++0x [class.ctor]p4:
6691   //   A constructor shall not be declared with a ref-qualifier.
6692   if (FTI.hasRefQualifier()) {
6693     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6694       << FTI.RefQualifierIsLValueRef 
6695       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6696     D.setInvalidType();
6697   }
6698   
6699   // Rebuild the function type "R" without any type qualifiers (in
6700   // case any of the errors above fired) and with "void" as the
6701   // return type, since constructors don't have return types.
6702   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6703   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6704     return R;
6705
6706   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6707   EPI.TypeQuals = 0;
6708   EPI.RefQualifier = RQ_None;
6709
6710   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6711 }
6712
6713 /// CheckConstructor - Checks a fully-formed constructor for
6714 /// well-formedness, issuing any diagnostics required. Returns true if
6715 /// the constructor declarator is invalid.
6716 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6717   CXXRecordDecl *ClassDecl
6718     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6719   if (!ClassDecl)
6720     return Constructor->setInvalidDecl();
6721
6722   // C++ [class.copy]p3:
6723   //   A declaration of a constructor for a class X is ill-formed if
6724   //   its first parameter is of type (optionally cv-qualified) X and
6725   //   either there are no other parameters or else all other
6726   //   parameters have default arguments.
6727   if (!Constructor->isInvalidDecl() &&
6728       ((Constructor->getNumParams() == 1) ||
6729        (Constructor->getNumParams() > 1 &&
6730         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6731       Constructor->getTemplateSpecializationKind()
6732                                               != TSK_ImplicitInstantiation) {
6733     QualType ParamType = Constructor->getParamDecl(0)->getType();
6734     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6735     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6736       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6737       const char *ConstRef 
6738         = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 
6739                                                         : " const &";
6740       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6741         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6742
6743       // FIXME: Rather that making the constructor invalid, we should endeavor
6744       // to fix the type.
6745       Constructor->setInvalidDecl();
6746     }
6747   }
6748 }
6749
6750 /// CheckDestructor - Checks a fully-formed destructor definition for
6751 /// well-formedness, issuing any diagnostics required.  Returns true
6752 /// on error.
6753 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6754   CXXRecordDecl *RD = Destructor->getParent();
6755   
6756   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6757     SourceLocation Loc;
6758     
6759     if (!Destructor->isImplicit())
6760       Loc = Destructor->getLocation();
6761     else
6762       Loc = RD->getLocation();
6763     
6764     // If we have a virtual destructor, look up the deallocation function
6765     FunctionDecl *OperatorDelete = nullptr;
6766     DeclarationName Name = 
6767     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6768     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6769       return true;
6770     // If there's no class-specific operator delete, look up the global
6771     // non-array delete.
6772     if (!OperatorDelete)
6773       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6774
6775     MarkFunctionReferenced(Loc, OperatorDelete);
6776     
6777     Destructor->setOperatorDelete(OperatorDelete);
6778   }
6779   
6780   return false;
6781 }
6782
6783 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6784 /// the well-formednes of the destructor declarator @p D with type @p
6785 /// R. If there are any errors in the declarator, this routine will
6786 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6787 /// will be updated to reflect a well-formed type for the destructor and
6788 /// returned.
6789 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6790                                          StorageClass& SC) {
6791   // C++ [class.dtor]p1:
6792   //   [...] A typedef-name that names a class is a class-name
6793   //   (7.1.3); however, a typedef-name that names a class shall not
6794   //   be used as the identifier in the declarator for a destructor
6795   //   declaration.
6796   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6797   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6798     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6799       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6800   else if (const TemplateSpecializationType *TST =
6801              DeclaratorType->getAs<TemplateSpecializationType>())
6802     if (TST->isTypeAlias())
6803       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6804         << DeclaratorType << 1;
6805
6806   // C++ [class.dtor]p2:
6807   //   A destructor is used to destroy objects of its class type. A
6808   //   destructor takes no parameters, and no return type can be
6809   //   specified for it (not even void). The address of a destructor
6810   //   shall not be taken. A destructor shall not be static. A
6811   //   destructor can be invoked for a const, volatile or const
6812   //   volatile object. A destructor shall not be declared const,
6813   //   volatile or const volatile (9.3.2).
6814   if (SC == SC_Static) {
6815     if (!D.isInvalidType())
6816       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6817         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6818         << SourceRange(D.getIdentifierLoc())
6819         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6820     
6821     SC = SC_None;
6822   }
6823   if (!D.isInvalidType()) {
6824     // Destructors don't have return types, but the parser will
6825     // happily parse something like:
6826     //
6827     //   class X {
6828     //     float ~X();
6829     //   };
6830     //
6831     // The return type will be eliminated later.
6832     if (D.getDeclSpec().hasTypeSpecifier())
6833       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6834         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6835         << SourceRange(D.getIdentifierLoc());
6836     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6837       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6838                                 SourceLocation(),
6839                                 D.getDeclSpec().getConstSpecLoc(),
6840                                 D.getDeclSpec().getVolatileSpecLoc(),
6841                                 D.getDeclSpec().getRestrictSpecLoc(),
6842                                 D.getDeclSpec().getAtomicSpecLoc());
6843       D.setInvalidType();
6844     }
6845   }
6846
6847   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6848   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6849     if (FTI.TypeQuals & Qualifiers::Const)
6850       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6851         << "const" << SourceRange(D.getIdentifierLoc());
6852     if (FTI.TypeQuals & Qualifiers::Volatile)
6853       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6854         << "volatile" << SourceRange(D.getIdentifierLoc());
6855     if (FTI.TypeQuals & Qualifiers::Restrict)
6856       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6857         << "restrict" << SourceRange(D.getIdentifierLoc());
6858     D.setInvalidType();
6859   }
6860
6861   // C++0x [class.dtor]p2:
6862   //   A destructor shall not be declared with a ref-qualifier.
6863   if (FTI.hasRefQualifier()) {
6864     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6865       << FTI.RefQualifierIsLValueRef
6866       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6867     D.setInvalidType();
6868   }
6869   
6870   // Make sure we don't have any parameters.
6871   if (FTIHasNonVoidParameters(FTI)) {
6872     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6873
6874     // Delete the parameters.
6875     FTI.freeParams();
6876     D.setInvalidType();
6877   }
6878
6879   // Make sure the destructor isn't variadic.
6880   if (FTI.isVariadic) {
6881     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6882     D.setInvalidType();
6883   }
6884
6885   // Rebuild the function type "R" without any type qualifiers or
6886   // parameters (in case any of the errors above fired) and with
6887   // "void" as the return type, since destructors don't have return
6888   // types. 
6889   if (!D.isInvalidType())
6890     return R;
6891
6892   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6893   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6894   EPI.Variadic = false;
6895   EPI.TypeQuals = 0;
6896   EPI.RefQualifier = RQ_None;
6897   return Context.getFunctionType(Context.VoidTy, None, EPI);
6898 }
6899
6900 static void extendLeft(SourceRange &R, const SourceRange &Before) {
6901   if (Before.isInvalid())
6902     return;
6903   R.setBegin(Before.getBegin());
6904   if (R.getEnd().isInvalid())
6905     R.setEnd(Before.getEnd());
6906 }
6907
6908 static void extendRight(SourceRange &R, const SourceRange &After) {
6909   if (After.isInvalid())
6910     return;
6911   if (R.getBegin().isInvalid())
6912     R.setBegin(After.getBegin());
6913   R.setEnd(After.getEnd());
6914 }
6915
6916 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6917 /// well-formednes of the conversion function declarator @p D with
6918 /// type @p R. If there are any errors in the declarator, this routine
6919 /// will emit diagnostics and return true. Otherwise, it will return
6920 /// false. Either way, the type @p R will be updated to reflect a
6921 /// well-formed type for the conversion operator.
6922 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6923                                      StorageClass& SC) {
6924   // C++ [class.conv.fct]p1:
6925   //   Neither parameter types nor return type can be specified. The
6926   //   type of a conversion function (8.3.5) is "function taking no
6927   //   parameter returning conversion-type-id."
6928   if (SC == SC_Static) {
6929     if (!D.isInvalidType())
6930       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6931         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6932         << D.getName().getSourceRange();
6933     D.setInvalidType();
6934     SC = SC_None;
6935   }
6936
6937   TypeSourceInfo *ConvTSI = nullptr;
6938   QualType ConvType =
6939       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
6940
6941   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6942     // Conversion functions don't have return types, but the parser will
6943     // happily parse something like:
6944     //
6945     //   class X {
6946     //     float operator bool();
6947     //   };
6948     //
6949     // The return type will be changed later anyway.
6950     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6951       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6952       << SourceRange(D.getIdentifierLoc());
6953     D.setInvalidType();
6954   }
6955
6956   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6957
6958   // Make sure we don't have any parameters.
6959   if (Proto->getNumParams() > 0) {
6960     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6961
6962     // Delete the parameters.
6963     D.getFunctionTypeInfo().freeParams();
6964     D.setInvalidType();
6965   } else if (Proto->isVariadic()) {
6966     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6967     D.setInvalidType();
6968   }
6969
6970   // Diagnose "&operator bool()" and other such nonsense.  This
6971   // is actually a gcc extension which we don't support.
6972   if (Proto->getReturnType() != ConvType) {
6973     bool NeedsTypedef = false;
6974     SourceRange Before, After;
6975
6976     // Walk the chunks and extract information on them for our diagnostic.
6977     bool PastFunctionChunk = false;
6978     for (auto &Chunk : D.type_objects()) {
6979       switch (Chunk.Kind) {
6980       case DeclaratorChunk::Function:
6981         if (!PastFunctionChunk) {
6982           if (Chunk.Fun.HasTrailingReturnType) {
6983             TypeSourceInfo *TRT = nullptr;
6984             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6985             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6986           }
6987           PastFunctionChunk = true;
6988           break;
6989         }
6990         // Fall through.
6991       case DeclaratorChunk::Array:
6992         NeedsTypedef = true;
6993         extendRight(After, Chunk.getSourceRange());
6994         break;
6995
6996       case DeclaratorChunk::Pointer:
6997       case DeclaratorChunk::BlockPointer:
6998       case DeclaratorChunk::Reference:
6999       case DeclaratorChunk::MemberPointer:
7000         extendLeft(Before, Chunk.getSourceRange());
7001         break;
7002
7003       case DeclaratorChunk::Paren:
7004         extendLeft(Before, Chunk.Loc);
7005         extendRight(After, Chunk.EndLoc);
7006         break;
7007       }
7008     }
7009
7010     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7011                          After.isValid()  ? After.getBegin() :
7012                                             D.getIdentifierLoc();
7013     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7014     DB << Before << After;
7015
7016     if (!NeedsTypedef) {
7017       DB << /*don't need a typedef*/0;
7018
7019       // If we can provide a correct fix-it hint, do so.
7020       if (After.isInvalid() && ConvTSI) {
7021         SourceLocation InsertLoc =
7022             PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7023         DB << FixItHint::CreateInsertion(InsertLoc, " ")
7024            << FixItHint::CreateInsertionFromRange(
7025                   InsertLoc, CharSourceRange::getTokenRange(Before))
7026            << FixItHint::CreateRemoval(Before);
7027       }
7028     } else if (!Proto->getReturnType()->isDependentType()) {
7029       DB << /*typedef*/1 << Proto->getReturnType();
7030     } else if (getLangOpts().CPlusPlus11) {
7031       DB << /*alias template*/2 << Proto->getReturnType();
7032     } else {
7033       DB << /*might not be fixable*/3;
7034     }
7035
7036     // Recover by incorporating the other type chunks into the result type.
7037     // Note, this does *not* change the name of the function. This is compatible
7038     // with the GCC extension:
7039     //   struct S { &operator int(); } s;
7040     //   int &r = s.operator int(); // ok in GCC
7041     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
7042     ConvType = Proto->getReturnType();
7043   }
7044
7045   // C++ [class.conv.fct]p4:
7046   //   The conversion-type-id shall not represent a function type nor
7047   //   an array type.
7048   if (ConvType->isArrayType()) {
7049     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7050     ConvType = Context.getPointerType(ConvType);
7051     D.setInvalidType();
7052   } else if (ConvType->isFunctionType()) {
7053     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7054     ConvType = Context.getPointerType(ConvType);
7055     D.setInvalidType();
7056   }
7057
7058   // Rebuild the function type "R" without any parameters (in case any
7059   // of the errors above fired) and with the conversion type as the
7060   // return type.
7061   if (D.isInvalidType())
7062     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7063
7064   // C++0x explicit conversion operators.
7065   if (D.getDeclSpec().isExplicitSpecified())
7066     Diag(D.getDeclSpec().getExplicitSpecLoc(),
7067          getLangOpts().CPlusPlus11 ?
7068            diag::warn_cxx98_compat_explicit_conversion_functions :
7069            diag::ext_explicit_conversion_functions)
7070       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7071 }
7072
7073 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7074 /// the declaration of the given C++ conversion function. This routine
7075 /// is responsible for recording the conversion function in the C++
7076 /// class, if possible.
7077 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
7078   assert(Conversion && "Expected to receive a conversion function declaration");
7079
7080   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
7081
7082   // Make sure we aren't redeclaring the conversion function.
7083   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
7084
7085   // C++ [class.conv.fct]p1:
7086   //   [...] A conversion function is never used to convert a
7087   //   (possibly cv-qualified) object to the (possibly cv-qualified)
7088   //   same object type (or a reference to it), to a (possibly
7089   //   cv-qualified) base class of that type (or a reference to it),
7090   //   or to (possibly cv-qualified) void.
7091   // FIXME: Suppress this warning if the conversion function ends up being a
7092   // virtual function that overrides a virtual function in a base class.
7093   QualType ClassType
7094     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7095   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
7096     ConvType = ConvTypeRef->getPointeeType();
7097   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7098       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
7099     /* Suppress diagnostics for instantiations. */;
7100   else if (ConvType->isRecordType()) {
7101     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7102     if (ConvType == ClassType)
7103       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
7104         << ClassType;
7105     else if (IsDerivedFrom(ClassType, ConvType))
7106       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
7107         <<  ClassType << ConvType;
7108   } else if (ConvType->isVoidType()) {
7109     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
7110       << ClassType << ConvType;
7111   }
7112
7113   if (FunctionTemplateDecl *ConversionTemplate
7114                                 = Conversion->getDescribedFunctionTemplate())
7115     return ConversionTemplate;
7116   
7117   return Conversion;
7118 }
7119
7120 //===----------------------------------------------------------------------===//
7121 // Namespace Handling
7122 //===----------------------------------------------------------------------===//
7123
7124 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7125 /// reopened.
7126 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7127                                             SourceLocation Loc,
7128                                             IdentifierInfo *II, bool *IsInline,
7129                                             NamespaceDecl *PrevNS) {
7130   assert(*IsInline != PrevNS->isInline());
7131
7132   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7133   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7134   // inline namespaces, with the intention of bringing names into namespace std.
7135   //
7136   // We support this just well enough to get that case working; this is not
7137   // sufficient to support reopening namespaces as inline in general.
7138   if (*IsInline && II && II->getName().startswith("__atomic") &&
7139       S.getSourceManager().isInSystemHeader(Loc)) {
7140     // Mark all prior declarations of the namespace as inline.
7141     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7142          NS = NS->getPreviousDecl())
7143       NS->setInline(*IsInline);
7144     // Patch up the lookup table for the containing namespace. This isn't really
7145     // correct, but it's good enough for this particular case.
7146     for (auto *I : PrevNS->decls())
7147       if (auto *ND = dyn_cast<NamedDecl>(I))
7148         PrevNS->getParent()->makeDeclVisibleInContext(ND);
7149     return;
7150   }
7151
7152   if (PrevNS->isInline())
7153     // The user probably just forgot the 'inline', so suggest that it
7154     // be added back.
7155     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7156       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7157   else
7158     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
7159
7160   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7161   *IsInline = PrevNS->isInline();
7162 }
7163
7164 /// ActOnStartNamespaceDef - This is called at the start of a namespace
7165 /// definition.
7166 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
7167                                    SourceLocation InlineLoc,
7168                                    SourceLocation NamespaceLoc,
7169                                    SourceLocation IdentLoc,
7170                                    IdentifierInfo *II,
7171                                    SourceLocation LBrace,
7172                                    AttributeList *AttrList) {
7173   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7174   // For anonymous namespace, take the location of the left brace.
7175   SourceLocation Loc = II ? IdentLoc : LBrace;
7176   bool IsInline = InlineLoc.isValid();
7177   bool IsInvalid = false;
7178   bool IsStd = false;
7179   bool AddToKnown = false;
7180   Scope *DeclRegionScope = NamespcScope->getParent();
7181
7182   NamespaceDecl *PrevNS = nullptr;
7183   if (II) {
7184     // C++ [namespace.def]p2:
7185     //   The identifier in an original-namespace-definition shall not
7186     //   have been previously defined in the declarative region in
7187     //   which the original-namespace-definition appears. The
7188     //   identifier in an original-namespace-definition is the name of
7189     //   the namespace. Subsequently in that declarative region, it is
7190     //   treated as an original-namespace-name.
7191     //
7192     // Since namespace names are unique in their scope, and we don't
7193     // look through using directives, just look for any ordinary names.
7194     
7195     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 
7196     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 
7197     Decl::IDNS_Namespace;
7198     NamedDecl *PrevDecl = nullptr;
7199     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7200     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7201          ++I) {
7202       if ((*I)->getIdentifierNamespace() & IDNS) {
7203         PrevDecl = *I;
7204         break;
7205       }
7206     }
7207     
7208     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7209     
7210     if (PrevNS) {
7211       // This is an extended namespace definition.
7212       if (IsInline != PrevNS->isInline())
7213         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7214                                         &IsInline, PrevNS);
7215     } else if (PrevDecl) {
7216       // This is an invalid name redefinition.
7217       Diag(Loc, diag::err_redefinition_different_kind)
7218         << II;
7219       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7220       IsInvalid = true;
7221       // Continue on to push Namespc as current DeclContext and return it.
7222     } else if (II->isStr("std") &&
7223                CurContext->getRedeclContext()->isTranslationUnit()) {
7224       // This is the first "real" definition of the namespace "std", so update
7225       // our cache of the "std" namespace to point at this definition.
7226       PrevNS = getStdNamespace();
7227       IsStd = true;
7228       AddToKnown = !IsInline;
7229     } else {
7230       // We've seen this namespace for the first time.
7231       AddToKnown = !IsInline;
7232     }
7233   } else {
7234     // Anonymous namespaces.
7235     
7236     // Determine whether the parent already has an anonymous namespace.
7237     DeclContext *Parent = CurContext->getRedeclContext();
7238     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7239       PrevNS = TU->getAnonymousNamespace();
7240     } else {
7241       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
7242       PrevNS = ND->getAnonymousNamespace();
7243     }
7244
7245     if (PrevNS && IsInline != PrevNS->isInline())
7246       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7247                                       &IsInline, PrevNS);
7248   }
7249   
7250   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7251                                                  StartLoc, Loc, II, PrevNS);
7252   if (IsInvalid)
7253     Namespc->setInvalidDecl();
7254   
7255   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
7256
7257   // FIXME: Should we be merging attributes?
7258   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
7259     PushNamespaceVisibilityAttr(Attr, Loc);
7260
7261   if (IsStd)
7262     StdNamespace = Namespc;
7263   if (AddToKnown)
7264     KnownNamespaces[Namespc] = false;
7265   
7266   if (II) {
7267     PushOnScopeChains(Namespc, DeclRegionScope);
7268   } else {
7269     // Link the anonymous namespace into its parent.
7270     DeclContext *Parent = CurContext->getRedeclContext();
7271     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7272       TU->setAnonymousNamespace(Namespc);
7273     } else {
7274       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
7275     }
7276
7277     CurContext->addDecl(Namespc);
7278
7279     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
7280     //   behaves as if it were replaced by
7281     //     namespace unique { /* empty body */ }
7282     //     using namespace unique;
7283     //     namespace unique { namespace-body }
7284     //   where all occurrences of 'unique' in a translation unit are
7285     //   replaced by the same identifier and this identifier differs
7286     //   from all other identifiers in the entire program.
7287
7288     // We just create the namespace with an empty name and then add an
7289     // implicit using declaration, just like the standard suggests.
7290     //
7291     // CodeGen enforces the "universally unique" aspect by giving all
7292     // declarations semantically contained within an anonymous
7293     // namespace internal linkage.
7294
7295     if (!PrevNS) {
7296       UsingDirectiveDecl* UD
7297         = UsingDirectiveDecl::Create(Context, Parent,
7298                                      /* 'using' */ LBrace,
7299                                      /* 'namespace' */ SourceLocation(),
7300                                      /* qualifier */ NestedNameSpecifierLoc(),
7301                                      /* identifier */ SourceLocation(),
7302                                      Namespc,
7303                                      /* Ancestor */ Parent);
7304       UD->setImplicit();
7305       Parent->addDecl(UD);
7306     }
7307   }
7308
7309   ActOnDocumentableDecl(Namespc);
7310
7311   // Although we could have an invalid decl (i.e. the namespace name is a
7312   // redefinition), push it as current DeclContext and try to continue parsing.
7313   // FIXME: We should be able to push Namespc here, so that the each DeclContext
7314   // for the namespace has the declarations that showed up in that particular
7315   // namespace definition.
7316   PushDeclContext(NamespcScope, Namespc);
7317   return Namespc;
7318 }
7319
7320 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7321 /// is a namespace alias, returns the namespace it points to.
7322 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7323   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7324     return AD->getNamespace();
7325   return dyn_cast_or_null<NamespaceDecl>(D);
7326 }
7327
7328 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
7329 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
7330 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
7331   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7332   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
7333   Namespc->setRBraceLoc(RBrace);
7334   PopDeclContext();
7335   if (Namespc->hasAttr<VisibilityAttr>())
7336     PopPragmaVisibility(true, RBrace);
7337 }
7338
7339 CXXRecordDecl *Sema::getStdBadAlloc() const {
7340   return cast_or_null<CXXRecordDecl>(
7341                                   StdBadAlloc.get(Context.getExternalSource()));
7342 }
7343
7344 NamespaceDecl *Sema::getStdNamespace() const {
7345   return cast_or_null<NamespaceDecl>(
7346                                  StdNamespace.get(Context.getExternalSource()));
7347 }
7348
7349 /// \brief Retrieve the special "std" namespace, which may require us to 
7350 /// implicitly define the namespace.
7351 NamespaceDecl *Sema::getOrCreateStdNamespace() {
7352   if (!StdNamespace) {
7353     // The "std" namespace has not yet been defined, so build one implicitly.
7354     StdNamespace = NamespaceDecl::Create(Context, 
7355                                          Context.getTranslationUnitDecl(),
7356                                          /*Inline=*/false,
7357                                          SourceLocation(), SourceLocation(),
7358                                          &PP.getIdentifierTable().get("std"),
7359                                          /*PrevDecl=*/nullptr);
7360     getStdNamespace()->setImplicit(true);
7361   }
7362
7363   return getStdNamespace();
7364 }
7365
7366 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
7367   assert(getLangOpts().CPlusPlus &&
7368          "Looking for std::initializer_list outside of C++.");
7369
7370   // We're looking for implicit instantiations of
7371   // template <typename E> class std::initializer_list.
7372
7373   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7374     return false;
7375
7376   ClassTemplateDecl *Template = nullptr;
7377   const TemplateArgument *Arguments = nullptr;
7378
7379   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7380
7381     ClassTemplateSpecializationDecl *Specialization =
7382         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7383     if (!Specialization)
7384       return false;
7385
7386     Template = Specialization->getSpecializedTemplate();
7387     Arguments = Specialization->getTemplateArgs().data();
7388   } else if (const TemplateSpecializationType *TST =
7389                  Ty->getAs<TemplateSpecializationType>()) {
7390     Template = dyn_cast_or_null<ClassTemplateDecl>(
7391         TST->getTemplateName().getAsTemplateDecl());
7392     Arguments = TST->getArgs();
7393   }
7394   if (!Template)
7395     return false;
7396
7397   if (!StdInitializerList) {
7398     // Haven't recognized std::initializer_list yet, maybe this is it.
7399     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7400     if (TemplateClass->getIdentifier() !=
7401             &PP.getIdentifierTable().get("initializer_list") ||
7402         !getStdNamespace()->InEnclosingNamespaceSetOf(
7403             TemplateClass->getDeclContext()))
7404       return false;
7405     // This is a template called std::initializer_list, but is it the right
7406     // template?
7407     TemplateParameterList *Params = Template->getTemplateParameters();
7408     if (Params->getMinRequiredArguments() != 1)
7409       return false;
7410     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7411       return false;
7412
7413     // It's the right template.
7414     StdInitializerList = Template;
7415   }
7416
7417   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
7418     return false;
7419
7420   // This is an instance of std::initializer_list. Find the argument type.
7421   if (Element)
7422     *Element = Arguments[0].getAsType();
7423   return true;
7424 }
7425
7426 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7427   NamespaceDecl *Std = S.getStdNamespace();
7428   if (!Std) {
7429     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7430     return nullptr;
7431   }
7432
7433   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7434                       Loc, Sema::LookupOrdinaryName);
7435   if (!S.LookupQualifiedName(Result, Std)) {
7436     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7437     return nullptr;
7438   }
7439   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7440   if (!Template) {
7441     Result.suppressDiagnostics();
7442     // We found something weird. Complain about the first thing we found.
7443     NamedDecl *Found = *Result.begin();
7444     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7445     return nullptr;
7446   }
7447
7448   // We found some template called std::initializer_list. Now verify that it's
7449   // correct.
7450   TemplateParameterList *Params = Template->getTemplateParameters();
7451   if (Params->getMinRequiredArguments() != 1 ||
7452       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7453     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7454     return nullptr;
7455   }
7456
7457   return Template;
7458 }
7459
7460 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7461   if (!StdInitializerList) {
7462     StdInitializerList = LookupStdInitializerList(*this, Loc);
7463     if (!StdInitializerList)
7464       return QualType();
7465   }
7466
7467   TemplateArgumentListInfo Args(Loc, Loc);
7468   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7469                                        Context.getTrivialTypeSourceInfo(Element,
7470                                                                         Loc)));
7471   return Context.getCanonicalType(
7472       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7473 }
7474
7475 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7476   // C++ [dcl.init.list]p2:
7477   //   A constructor is an initializer-list constructor if its first parameter
7478   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
7479   //   std::initializer_list<E> for some type E, and either there are no other
7480   //   parameters or else all other parameters have default arguments.
7481   if (Ctor->getNumParams() < 1 ||
7482       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7483     return false;
7484
7485   QualType ArgType = Ctor->getParamDecl(0)->getType();
7486   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7487     ArgType = RT->getPointeeType().getUnqualifiedType();
7488
7489   return isStdInitializerList(ArgType, nullptr);
7490 }
7491
7492 /// \brief Determine whether a using statement is in a context where it will be
7493 /// apply in all contexts.
7494 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7495   switch (CurContext->getDeclKind()) {
7496     case Decl::TranslationUnit:
7497       return true;
7498     case Decl::LinkageSpec:
7499       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7500     default:
7501       return false;
7502   }
7503 }
7504
7505 namespace {
7506
7507 // Callback to only accept typo corrections that are namespaces.
7508 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7509 public:
7510   bool ValidateCandidate(const TypoCorrection &candidate) override {
7511     if (NamedDecl *ND = candidate.getCorrectionDecl())
7512       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7513     return false;
7514   }
7515 };
7516
7517 }
7518
7519 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7520                                        CXXScopeSpec &SS,
7521                                        SourceLocation IdentLoc,
7522                                        IdentifierInfo *Ident) {
7523   R.clear();
7524   if (TypoCorrection Corrected =
7525           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7526                         llvm::make_unique<NamespaceValidatorCCC>(),
7527                         Sema::CTK_ErrorRecovery)) {
7528     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7529       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7530       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7531                               Ident->getName().equals(CorrectedStr);
7532       S.diagnoseTypo(Corrected,
7533                      S.PDiag(diag::err_using_directive_member_suggest)
7534                        << Ident << DC << DroppedSpecifier << SS.getRange(),
7535                      S.PDiag(diag::note_namespace_defined_here));
7536     } else {
7537       S.diagnoseTypo(Corrected,
7538                      S.PDiag(diag::err_using_directive_suggest) << Ident,
7539                      S.PDiag(diag::note_namespace_defined_here));
7540     }
7541     R.addDecl(Corrected.getCorrectionDecl());
7542     return true;
7543   }
7544   return false;
7545 }
7546
7547 Decl *Sema::ActOnUsingDirective(Scope *S,
7548                                           SourceLocation UsingLoc,
7549                                           SourceLocation NamespcLoc,
7550                                           CXXScopeSpec &SS,
7551                                           SourceLocation IdentLoc,
7552                                           IdentifierInfo *NamespcName,
7553                                           AttributeList *AttrList) {
7554   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7555   assert(NamespcName && "Invalid NamespcName.");
7556   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7557
7558   // This can only happen along a recovery path.
7559   while (S->getFlags() & Scope::TemplateParamScope)
7560     S = S->getParent();
7561   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7562
7563   UsingDirectiveDecl *UDir = nullptr;
7564   NestedNameSpecifier *Qualifier = nullptr;
7565   if (SS.isSet())
7566     Qualifier = SS.getScopeRep();
7567   
7568   // Lookup namespace name.
7569   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7570   LookupParsedName(R, S, &SS);
7571   if (R.isAmbiguous())
7572     return nullptr;
7573
7574   if (R.empty()) {
7575     R.clear();
7576     // Allow "using namespace std;" or "using namespace ::std;" even if 
7577     // "std" hasn't been defined yet, for GCC compatibility.
7578     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7579         NamespcName->isStr("std")) {
7580       Diag(IdentLoc, diag::ext_using_undefined_std);
7581       R.addDecl(getOrCreateStdNamespace());
7582       R.resolveKind();
7583     } 
7584     // Otherwise, attempt typo correction.
7585     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7586   }
7587   
7588   if (!R.empty()) {
7589     NamedDecl *Named = R.getFoundDecl();
7590     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7591         && "expected namespace decl");
7592
7593     // The use of a nested name specifier may trigger deprecation warnings.
7594     DiagnoseUseOfDecl(Named, IdentLoc);
7595
7596     // C++ [namespace.udir]p1:
7597     //   A using-directive specifies that the names in the nominated
7598     //   namespace can be used in the scope in which the
7599     //   using-directive appears after the using-directive. During
7600     //   unqualified name lookup (3.4.1), the names appear as if they
7601     //   were declared in the nearest enclosing namespace which
7602     //   contains both the using-directive and the nominated
7603     //   namespace. [Note: in this context, "contains" means "contains
7604     //   directly or indirectly". ]
7605
7606     // Find enclosing context containing both using-directive and
7607     // nominated namespace.
7608     NamespaceDecl *NS = getNamespaceDecl(Named);
7609     DeclContext *CommonAncestor = cast<DeclContext>(NS);
7610     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7611       CommonAncestor = CommonAncestor->getParent();
7612
7613     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7614                                       SS.getWithLocInContext(Context),
7615                                       IdentLoc, Named, CommonAncestor);
7616
7617     if (IsUsingDirectiveInToplevelContext(CurContext) &&
7618         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7619       Diag(IdentLoc, diag::warn_using_directive_in_header);
7620     }
7621
7622     PushUsingDirective(S, UDir);
7623   } else {
7624     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7625   }
7626
7627   if (UDir)
7628     ProcessDeclAttributeList(S, UDir, AttrList);
7629
7630   return UDir;
7631 }
7632
7633 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7634   // If the scope has an associated entity and the using directive is at
7635   // namespace or translation unit scope, add the UsingDirectiveDecl into
7636   // its lookup structure so qualified name lookup can find it.
7637   DeclContext *Ctx = S->getEntity();
7638   if (Ctx && !Ctx->isFunctionOrMethod())
7639     Ctx->addDecl(UDir);
7640   else
7641     // Otherwise, it is at block scope. The using-directives will affect lookup
7642     // only to the end of the scope.
7643     S->PushUsingDirective(UDir);
7644 }
7645
7646
7647 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7648                                   AccessSpecifier AS,
7649                                   bool HasUsingKeyword,
7650                                   SourceLocation UsingLoc,
7651                                   CXXScopeSpec &SS,
7652                                   UnqualifiedId &Name,
7653                                   AttributeList *AttrList,
7654                                   bool HasTypenameKeyword,
7655                                   SourceLocation TypenameLoc) {
7656   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7657
7658   switch (Name.getKind()) {
7659   case UnqualifiedId::IK_ImplicitSelfParam:
7660   case UnqualifiedId::IK_Identifier:
7661   case UnqualifiedId::IK_OperatorFunctionId:
7662   case UnqualifiedId::IK_LiteralOperatorId:
7663   case UnqualifiedId::IK_ConversionFunctionId:
7664     break;
7665       
7666   case UnqualifiedId::IK_ConstructorName:
7667   case UnqualifiedId::IK_ConstructorTemplateId:
7668     // C++11 inheriting constructors.
7669     Diag(Name.getLocStart(),
7670          getLangOpts().CPlusPlus11 ?
7671            diag::warn_cxx98_compat_using_decl_constructor :
7672            diag::err_using_decl_constructor)
7673       << SS.getRange();
7674
7675     if (getLangOpts().CPlusPlus11) break;
7676
7677     return nullptr;
7678
7679   case UnqualifiedId::IK_DestructorName:
7680     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7681       << SS.getRange();
7682     return nullptr;
7683
7684   case UnqualifiedId::IK_TemplateId:
7685     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7686       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7687     return nullptr;
7688   }
7689
7690   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7691   DeclarationName TargetName = TargetNameInfo.getName();
7692   if (!TargetName)
7693     return nullptr;
7694
7695   // Warn about access declarations.
7696   if (!HasUsingKeyword) {
7697     Diag(Name.getLocStart(),
7698          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7699                                    : diag::warn_access_decl_deprecated)
7700       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7701   }
7702
7703   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7704       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7705     return nullptr;
7706
7707   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7708                                         TargetNameInfo, AttrList,
7709                                         /* IsInstantiation */ false,
7710                                         HasTypenameKeyword, TypenameLoc);
7711   if (UD)
7712     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7713
7714   return UD;
7715 }
7716
7717 /// \brief Determine whether a using declaration considers the given
7718 /// declarations as "equivalent", e.g., if they are redeclarations of
7719 /// the same entity or are both typedefs of the same type.
7720 static bool
7721 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7722   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7723     return true;
7724
7725   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7726     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7727       return Context.hasSameType(TD1->getUnderlyingType(),
7728                                  TD2->getUnderlyingType());
7729
7730   return false;
7731 }
7732
7733
7734 /// Determines whether to create a using shadow decl for a particular
7735 /// decl, given the set of decls existing prior to this using lookup.
7736 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7737                                 const LookupResult &Previous,
7738                                 UsingShadowDecl *&PrevShadow) {
7739   // Diagnose finding a decl which is not from a base class of the
7740   // current class.  We do this now because there are cases where this
7741   // function will silently decide not to build a shadow decl, which
7742   // will pre-empt further diagnostics.
7743   //
7744   // We don't need to do this in C++0x because we do the check once on
7745   // the qualifier.
7746   //
7747   // FIXME: diagnose the following if we care enough:
7748   //   struct A { int foo; };
7749   //   struct B : A { using A::foo; };
7750   //   template <class T> struct C : A {};
7751   //   template <class T> struct D : C<T> { using B::foo; } // <---
7752   // This is invalid (during instantiation) in C++03 because B::foo
7753   // resolves to the using decl in B, which is not a base class of D<T>.
7754   // We can't diagnose it immediately because C<T> is an unknown
7755   // specialization.  The UsingShadowDecl in D<T> then points directly
7756   // to A::foo, which will look well-formed when we instantiate.
7757   // The right solution is to not collapse the shadow-decl chain.
7758   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7759     DeclContext *OrigDC = Orig->getDeclContext();
7760
7761     // Handle enums and anonymous structs.
7762     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7763     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7764     while (OrigRec->isAnonymousStructOrUnion())
7765       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7766
7767     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7768       if (OrigDC == CurContext) {
7769         Diag(Using->getLocation(),
7770              diag::err_using_decl_nested_name_specifier_is_current_class)
7771           << Using->getQualifierLoc().getSourceRange();
7772         Diag(Orig->getLocation(), diag::note_using_decl_target);
7773         return true;
7774       }
7775
7776       Diag(Using->getQualifierLoc().getBeginLoc(),
7777            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7778         << Using->getQualifier()
7779         << cast<CXXRecordDecl>(CurContext)
7780         << Using->getQualifierLoc().getSourceRange();
7781       Diag(Orig->getLocation(), diag::note_using_decl_target);
7782       return true;
7783     }
7784   }
7785
7786   if (Previous.empty()) return false;
7787
7788   NamedDecl *Target = Orig;
7789   if (isa<UsingShadowDecl>(Target))
7790     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7791
7792   // If the target happens to be one of the previous declarations, we
7793   // don't have a conflict.
7794   // 
7795   // FIXME: but we might be increasing its access, in which case we
7796   // should redeclare it.
7797   NamedDecl *NonTag = nullptr, *Tag = nullptr;
7798   bool FoundEquivalentDecl = false;
7799   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7800          I != E; ++I) {
7801     NamedDecl *D = (*I)->getUnderlyingDecl();
7802     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7803       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7804         PrevShadow = Shadow;
7805       FoundEquivalentDecl = true;
7806     }
7807
7808     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7809   }
7810
7811   if (FoundEquivalentDecl)
7812     return false;
7813
7814   if (FunctionDecl *FD = Target->getAsFunction()) {
7815     NamedDecl *OldDecl = nullptr;
7816     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7817                           /*IsForUsingDecl*/ true)) {
7818     case Ovl_Overload:
7819       return false;
7820
7821     case Ovl_NonFunction:
7822       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7823       break;
7824
7825     // We found a decl with the exact signature.
7826     case Ovl_Match:
7827       // If we're in a record, we want to hide the target, so we
7828       // return true (without a diagnostic) to tell the caller not to
7829       // build a shadow decl.
7830       if (CurContext->isRecord())
7831         return true;
7832
7833       // If we're not in a record, this is an error.
7834       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7835       break;
7836     }
7837
7838     Diag(Target->getLocation(), diag::note_using_decl_target);
7839     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7840     return true;
7841   }
7842
7843   // Target is not a function.
7844
7845   if (isa<TagDecl>(Target)) {
7846     // No conflict between a tag and a non-tag.
7847     if (!Tag) return false;
7848
7849     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7850     Diag(Target->getLocation(), diag::note_using_decl_target);
7851     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7852     return true;
7853   }
7854
7855   // No conflict between a tag and a non-tag.
7856   if (!NonTag) return false;
7857
7858   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7859   Diag(Target->getLocation(), diag::note_using_decl_target);
7860   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7861   return true;
7862 }
7863
7864 /// Builds a shadow declaration corresponding to a 'using' declaration.
7865 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7866                                             UsingDecl *UD,
7867                                             NamedDecl *Orig,
7868                                             UsingShadowDecl *PrevDecl) {
7869
7870   // If we resolved to another shadow declaration, just coalesce them.
7871   NamedDecl *Target = Orig;
7872   if (isa<UsingShadowDecl>(Target)) {
7873     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7874     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7875   }
7876
7877   UsingShadowDecl *Shadow
7878     = UsingShadowDecl::Create(Context, CurContext,
7879                               UD->getLocation(), UD, Target);
7880   UD->addShadowDecl(Shadow);
7881
7882   Shadow->setAccess(UD->getAccess());
7883   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7884     Shadow->setInvalidDecl();
7885
7886   Shadow->setPreviousDecl(PrevDecl);
7887
7888   if (S)
7889     PushOnScopeChains(Shadow, S);
7890   else
7891     CurContext->addDecl(Shadow);
7892
7893
7894   return Shadow;
7895 }
7896
7897 /// Hides a using shadow declaration.  This is required by the current
7898 /// using-decl implementation when a resolvable using declaration in a
7899 /// class is followed by a declaration which would hide or override
7900 /// one or more of the using decl's targets; for example:
7901 ///
7902 ///   struct Base { void foo(int); };
7903 ///   struct Derived : Base {
7904 ///     using Base::foo;
7905 ///     void foo(int);
7906 ///   };
7907 ///
7908 /// The governing language is C++03 [namespace.udecl]p12:
7909 ///
7910 ///   When a using-declaration brings names from a base class into a
7911 ///   derived class scope, member functions in the derived class
7912 ///   override and/or hide member functions with the same name and
7913 ///   parameter types in a base class (rather than conflicting).
7914 ///
7915 /// There are two ways to implement this:
7916 ///   (1) optimistically create shadow decls when they're not hidden
7917 ///       by existing declarations, or
7918 ///   (2) don't create any shadow decls (or at least don't make them
7919 ///       visible) until we've fully parsed/instantiated the class.
7920 /// The problem with (1) is that we might have to retroactively remove
7921 /// a shadow decl, which requires several O(n) operations because the
7922 /// decl structures are (very reasonably) not designed for removal.
7923 /// (2) avoids this but is very fiddly and phase-dependent.
7924 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7925   if (Shadow->getDeclName().getNameKind() ==
7926         DeclarationName::CXXConversionFunctionName)
7927     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7928
7929   // Remove it from the DeclContext...
7930   Shadow->getDeclContext()->removeDecl(Shadow);
7931
7932   // ...and the scope, if applicable...
7933   if (S) {
7934     S->RemoveDecl(Shadow);
7935     IdResolver.RemoveDecl(Shadow);
7936   }
7937
7938   // ...and the using decl.
7939   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7940
7941   // TODO: complain somehow if Shadow was used.  It shouldn't
7942   // be possible for this to happen, because...?
7943 }
7944
7945 /// Find the base specifier for a base class with the given type.
7946 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7947                                                 QualType DesiredBase,
7948                                                 bool &AnyDependentBases) {
7949   // Check whether the named type is a direct base class.
7950   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7951   for (auto &Base : Derived->bases()) {
7952     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7953     if (CanonicalDesiredBase == BaseType)
7954       return &Base;
7955     if (BaseType->isDependentType())
7956       AnyDependentBases = true;
7957   }
7958   return nullptr;
7959 }
7960
7961 namespace {
7962 class UsingValidatorCCC : public CorrectionCandidateCallback {
7963 public:
7964   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7965                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7966       : HasTypenameKeyword(HasTypenameKeyword),
7967         IsInstantiation(IsInstantiation), OldNNS(NNS),
7968         RequireMemberOf(RequireMemberOf) {}
7969
7970   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7971     NamedDecl *ND = Candidate.getCorrectionDecl();
7972
7973     // Keywords are not valid here.
7974     if (!ND || isa<NamespaceDecl>(ND))
7975       return false;
7976
7977     // Completely unqualified names are invalid for a 'using' declaration.
7978     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7979       return false;
7980
7981     if (RequireMemberOf) {
7982       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7983       if (FoundRecord && FoundRecord->isInjectedClassName()) {
7984         // No-one ever wants a using-declaration to name an injected-class-name
7985         // of a base class, unless they're declaring an inheriting constructor.
7986         ASTContext &Ctx = ND->getASTContext();
7987         if (!Ctx.getLangOpts().CPlusPlus11)
7988           return false;
7989         QualType FoundType = Ctx.getRecordType(FoundRecord);
7990
7991         // Check that the injected-class-name is named as a member of its own
7992         // type; we don't want to suggest 'using Derived::Base;', since that
7993         // means something else.
7994         NestedNameSpecifier *Specifier =
7995             Candidate.WillReplaceSpecifier()
7996                 ? Candidate.getCorrectionSpecifier()
7997                 : OldNNS;
7998         if (!Specifier->getAsType() ||
7999             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8000           return false;
8001
8002         // Check that this inheriting constructor declaration actually names a
8003         // direct base class of the current class.
8004         bool AnyDependentBases = false;
8005         if (!findDirectBaseWithType(RequireMemberOf,
8006                                     Ctx.getRecordType(FoundRecord),
8007                                     AnyDependentBases) &&
8008             !AnyDependentBases)
8009           return false;
8010       } else {
8011         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8012         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8013           return false;
8014
8015         // FIXME: Check that the base class member is accessible?
8016       }
8017     }
8018
8019     if (isa<TypeDecl>(ND))
8020       return HasTypenameKeyword || !IsInstantiation;
8021
8022     return !HasTypenameKeyword;
8023   }
8024
8025 private:
8026   bool HasTypenameKeyword;
8027   bool IsInstantiation;
8028   NestedNameSpecifier *OldNNS;
8029   CXXRecordDecl *RequireMemberOf;
8030 };
8031 } // end anonymous namespace
8032
8033 /// Builds a using declaration.
8034 ///
8035 /// \param IsInstantiation - Whether this call arises from an
8036 ///   instantiation of an unresolved using declaration.  We treat
8037 ///   the lookup differently for these declarations.
8038 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8039                                        SourceLocation UsingLoc,
8040                                        CXXScopeSpec &SS,
8041                                        DeclarationNameInfo NameInfo,
8042                                        AttributeList *AttrList,
8043                                        bool IsInstantiation,
8044                                        bool HasTypenameKeyword,
8045                                        SourceLocation TypenameLoc) {
8046   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8047   SourceLocation IdentLoc = NameInfo.getLoc();
8048   assert(IdentLoc.isValid() && "Invalid TargetName location.");
8049
8050   // FIXME: We ignore attributes for now.
8051
8052   if (SS.isEmpty()) {
8053     Diag(IdentLoc, diag::err_using_requires_qualname);
8054     return nullptr;
8055   }
8056
8057   // Do the redeclaration lookup in the current scope.
8058   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
8059                         ForRedeclaration);
8060   Previous.setHideTags(false);
8061   if (S) {
8062     LookupName(Previous, S);
8063
8064     // It is really dumb that we have to do this.
8065     LookupResult::Filter F = Previous.makeFilter();
8066     while (F.hasNext()) {
8067       NamedDecl *D = F.next();
8068       if (!isDeclInScope(D, CurContext, S))
8069         F.erase();
8070       // If we found a local extern declaration that's not ordinarily visible,
8071       // and this declaration is being added to a non-block scope, ignore it.
8072       // We're only checking for scope conflicts here, not also for violations
8073       // of the linkage rules.
8074       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8075                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8076         F.erase();
8077     }
8078     F.done();
8079   } else {
8080     assert(IsInstantiation && "no scope in non-instantiation");
8081     assert(CurContext->isRecord() && "scope not record in instantiation");
8082     LookupQualifiedName(Previous, CurContext);
8083   }
8084
8085   // Check for invalid redeclarations.
8086   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8087                                   SS, IdentLoc, Previous))
8088     return nullptr;
8089
8090   // Check for bad qualifiers.
8091   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
8092     return nullptr;
8093
8094   DeclContext *LookupContext = computeDeclContext(SS);
8095   NamedDecl *D;
8096   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8097   if (!LookupContext) {
8098     if (HasTypenameKeyword) {
8099       // FIXME: not all declaration name kinds are legal here
8100       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8101                                               UsingLoc, TypenameLoc,
8102                                               QualifierLoc,
8103                                               IdentLoc, NameInfo.getName());
8104     } else {
8105       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 
8106                                            QualifierLoc, NameInfo);
8107     }
8108     D->setAccess(AS);
8109     CurContext->addDecl(D);
8110     return D;
8111   }
8112
8113   auto Build = [&](bool Invalid) {
8114     UsingDecl *UD =
8115         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8116                           HasTypenameKeyword);
8117     UD->setAccess(AS);
8118     CurContext->addDecl(UD);
8119     UD->setInvalidDecl(Invalid);
8120     return UD;
8121   };
8122   auto BuildInvalid = [&]{ return Build(true); };
8123   auto BuildValid = [&]{ return Build(false); };
8124
8125   if (RequireCompleteDeclContext(SS, LookupContext))
8126     return BuildInvalid();
8127
8128   // Look up the target name.
8129   LookupResult R(*this, NameInfo, LookupOrdinaryName);
8130
8131   // Unlike most lookups, we don't always want to hide tag
8132   // declarations: tag names are visible through the using declaration
8133   // even if hidden by ordinary names, *except* in a dependent context
8134   // where it's important for the sanity of two-phase lookup.
8135   if (!IsInstantiation)
8136     R.setHideTags(false);
8137
8138   // For the purposes of this lookup, we have a base object type
8139   // equal to that of the current context.
8140   if (CurContext->isRecord()) {
8141     R.setBaseObjectType(
8142                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8143   }
8144
8145   LookupQualifiedName(R, LookupContext);
8146
8147   // Try to correct typos if possible. If constructor name lookup finds no
8148   // results, that means the named class has no explicit constructors, and we
8149   // suppressed declaring implicit ones (probably because it's dependent or
8150   // invalid).
8151   if (R.empty() &&
8152       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
8153     if (TypoCorrection Corrected = CorrectTypo(
8154             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8155             llvm::make_unique<UsingValidatorCCC>(
8156                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8157                 dyn_cast<CXXRecordDecl>(CurContext)),
8158             CTK_ErrorRecovery)) {
8159       // We reject any correction for which ND would be NULL.
8160       NamedDecl *ND = Corrected.getCorrectionDecl();
8161
8162       // We reject candidates where DroppedSpecifier == true, hence the
8163       // literal '0' below.
8164       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8165                                 << NameInfo.getName() << LookupContext << 0
8166                                 << SS.getRange());
8167
8168       // If we corrected to an inheriting constructor, handle it as one.
8169       auto *RD = dyn_cast<CXXRecordDecl>(ND);
8170       if (RD && RD->isInjectedClassName()) {
8171         // Fix up the information we'll use to build the using declaration.
8172         if (Corrected.WillReplaceSpecifier()) {
8173           NestedNameSpecifierLocBuilder Builder;
8174           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8175                               QualifierLoc.getSourceRange());
8176           QualifierLoc = Builder.getWithLocInContext(Context);
8177         }
8178
8179         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8180             Context.getCanonicalType(Context.getRecordType(RD))));
8181         NameInfo.setNamedTypeInfo(nullptr);
8182         for (auto *Ctor : LookupConstructors(RD))
8183           R.addDecl(Ctor);
8184       } else {
8185         // FIXME: Pick up all the declarations if we found an overloaded function.
8186         R.addDecl(ND);
8187       }
8188     } else {
8189       Diag(IdentLoc, diag::err_no_member)
8190         << NameInfo.getName() << LookupContext << SS.getRange();
8191       return BuildInvalid();
8192     }
8193   }
8194
8195   if (R.isAmbiguous())
8196     return BuildInvalid();
8197
8198   if (HasTypenameKeyword) {
8199     // If we asked for a typename and got a non-type decl, error out.
8200     if (!R.getAsSingle<TypeDecl>()) {
8201       Diag(IdentLoc, diag::err_using_typename_non_type);
8202       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8203         Diag((*I)->getUnderlyingDecl()->getLocation(),
8204              diag::note_using_decl_target);
8205       return BuildInvalid();
8206     }
8207   } else {
8208     // If we asked for a non-typename and we got a type, error out,
8209     // but only if this is an instantiation of an unresolved using
8210     // decl.  Otherwise just silently find the type name.
8211     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
8212       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8213       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
8214       return BuildInvalid();
8215     }
8216   }
8217
8218   // C++0x N2914 [namespace.udecl]p6:
8219   // A using-declaration shall not name a namespace.
8220   if (R.getAsSingle<NamespaceDecl>()) {
8221     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8222       << SS.getRange();
8223     return BuildInvalid();
8224   }
8225
8226   UsingDecl *UD = BuildValid();
8227
8228   // The normal rules do not apply to inheriting constructor declarations.
8229   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8230     // Suppress access diagnostics; the access check is instead performed at the
8231     // point of use for an inheriting constructor.
8232     R.suppressDiagnostics();
8233     CheckInheritingConstructorUsingDecl(UD);
8234     return UD;
8235   }
8236
8237   // Otherwise, look up the target name.
8238
8239   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8240     UsingShadowDecl *PrevDecl = nullptr;
8241     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8242       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
8243   }
8244
8245   return UD;
8246 }
8247
8248 /// Additional checks for a using declaration referring to a constructor name.
8249 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
8250   assert(!UD->hasTypename() && "expecting a constructor name");
8251
8252   const Type *SourceType = UD->getQualifier()->getAsType();
8253   assert(SourceType &&
8254          "Using decl naming constructor doesn't have type in scope spec.");
8255   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8256
8257   // Check whether the named type is a direct base class.
8258   bool AnyDependentBases = false;
8259   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8260                                       AnyDependentBases);
8261   if (!Base && !AnyDependentBases) {
8262     Diag(UD->getUsingLoc(),
8263          diag::err_using_decl_constructor_not_in_direct_base)
8264       << UD->getNameInfo().getSourceRange()
8265       << QualType(SourceType, 0) << TargetClass;
8266     UD->setInvalidDecl();
8267     return true;
8268   }
8269
8270   if (Base)
8271     Base->setInheritConstructors();
8272
8273   return false;
8274 }
8275
8276 /// Checks that the given using declaration is not an invalid
8277 /// redeclaration.  Note that this is checking only for the using decl
8278 /// itself, not for any ill-formedness among the UsingShadowDecls.
8279 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
8280                                        bool HasTypenameKeyword,
8281                                        const CXXScopeSpec &SS,
8282                                        SourceLocation NameLoc,
8283                                        const LookupResult &Prev) {
8284   // C++03 [namespace.udecl]p8:
8285   // C++0x [namespace.udecl]p10:
8286   //   A using-declaration is a declaration and can therefore be used
8287   //   repeatedly where (and only where) multiple declarations are
8288   //   allowed.
8289   //
8290   // That's in non-member contexts.
8291   if (!CurContext->getRedeclContext()->isRecord())
8292     return false;
8293
8294   NestedNameSpecifier *Qual = SS.getScopeRep();
8295
8296   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8297     NamedDecl *D = *I;
8298
8299     bool DTypename;
8300     NestedNameSpecifier *DQual;
8301     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
8302       DTypename = UD->hasTypename();
8303       DQual = UD->getQualifier();
8304     } else if (UnresolvedUsingValueDecl *UD
8305                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8306       DTypename = false;
8307       DQual = UD->getQualifier();
8308     } else if (UnresolvedUsingTypenameDecl *UD
8309                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8310       DTypename = true;
8311       DQual = UD->getQualifier();
8312     } else continue;
8313
8314     // using decls differ if one says 'typename' and the other doesn't.
8315     // FIXME: non-dependent using decls?
8316     if (HasTypenameKeyword != DTypename) continue;
8317
8318     // using decls differ if they name different scopes (but note that
8319     // template instantiation can cause this check to trigger when it
8320     // didn't before instantiation).
8321     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8322         Context.getCanonicalNestedNameSpecifier(DQual))
8323       continue;
8324
8325     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
8326     Diag(D->getLocation(), diag::note_using_decl) << 1;
8327     return true;
8328   }
8329
8330   return false;
8331 }
8332
8333
8334 /// Checks that the given nested-name qualifier used in a using decl
8335 /// in the current context is appropriately related to the current
8336 /// scope.  If an error is found, diagnoses it and returns true.
8337 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8338                                    const CXXScopeSpec &SS,
8339                                    const DeclarationNameInfo &NameInfo,
8340                                    SourceLocation NameLoc) {
8341   DeclContext *NamedContext = computeDeclContext(SS);
8342
8343   if (!CurContext->isRecord()) {
8344     // C++03 [namespace.udecl]p3:
8345     // C++0x [namespace.udecl]p8:
8346     //   A using-declaration for a class member shall be a member-declaration.
8347
8348     // If we weren't able to compute a valid scope, it must be a
8349     // dependent class scope.
8350     if (!NamedContext || NamedContext->isRecord()) {
8351       auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
8352       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
8353         RD = nullptr;
8354
8355       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8356         << SS.getRange();
8357
8358       // If we have a complete, non-dependent source type, try to suggest a
8359       // way to get the same effect.
8360       if (!RD)
8361         return true;
8362
8363       // Find what this using-declaration was referring to.
8364       LookupResult R(*this, NameInfo, LookupOrdinaryName);
8365       R.setHideTags(false);
8366       R.suppressDiagnostics();
8367       LookupQualifiedName(R, RD);
8368
8369       if (R.getAsSingle<TypeDecl>()) {
8370         if (getLangOpts().CPlusPlus11) {
8371           // Convert 'using X::Y;' to 'using Y = X::Y;'.
8372           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8373             << 0 // alias declaration
8374             << FixItHint::CreateInsertion(SS.getBeginLoc(),
8375                                           NameInfo.getName().getAsString() +
8376                                               " = ");
8377         } else {
8378           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8379           SourceLocation InsertLoc =
8380               PP.getLocForEndOfToken(NameInfo.getLocEnd());
8381           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8382             << 1 // typedef declaration
8383             << FixItHint::CreateReplacement(UsingLoc, "typedef")
8384             << FixItHint::CreateInsertion(
8385                    InsertLoc, " " + NameInfo.getName().getAsString());
8386         }
8387       } else if (R.getAsSingle<VarDecl>()) {
8388         // Don't provide a fixit outside C++11 mode; we don't want to suggest
8389         // repeating the type of the static data member here.
8390         FixItHint FixIt;
8391         if (getLangOpts().CPlusPlus11) {
8392           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8393           FixIt = FixItHint::CreateReplacement(
8394               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8395         }
8396
8397         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8398           << 2 // reference declaration
8399           << FixIt;
8400       }
8401       return true;
8402     }
8403
8404     // Otherwise, everything is known to be fine.
8405     return false;
8406   }
8407
8408   // The current scope is a record.
8409
8410   // If the named context is dependent, we can't decide much.
8411   if (!NamedContext) {
8412     // FIXME: in C++0x, we can diagnose if we can prove that the
8413     // nested-name-specifier does not refer to a base class, which is
8414     // still possible in some cases.
8415
8416     // Otherwise we have to conservatively report that things might be
8417     // okay.
8418     return false;
8419   }
8420
8421   if (!NamedContext->isRecord()) {
8422     // Ideally this would point at the last name in the specifier,
8423     // but we don't have that level of source info.
8424     Diag(SS.getRange().getBegin(),
8425          diag::err_using_decl_nested_name_specifier_is_not_class)
8426       << SS.getScopeRep() << SS.getRange();
8427     return true;
8428   }
8429
8430   if (!NamedContext->isDependentContext() &&
8431       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8432     return true;
8433
8434   if (getLangOpts().CPlusPlus11) {
8435     // C++0x [namespace.udecl]p3:
8436     //   In a using-declaration used as a member-declaration, the
8437     //   nested-name-specifier shall name a base class of the class
8438     //   being defined.
8439
8440     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8441                                  cast<CXXRecordDecl>(NamedContext))) {
8442       if (CurContext == NamedContext) {
8443         Diag(NameLoc,
8444              diag::err_using_decl_nested_name_specifier_is_current_class)
8445           << SS.getRange();
8446         return true;
8447       }
8448
8449       Diag(SS.getRange().getBegin(),
8450            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8451         << SS.getScopeRep()
8452         << cast<CXXRecordDecl>(CurContext)
8453         << SS.getRange();
8454       return true;
8455     }
8456
8457     return false;
8458   }
8459
8460   // C++03 [namespace.udecl]p4:
8461   //   A using-declaration used as a member-declaration shall refer
8462   //   to a member of a base class of the class being defined [etc.].
8463
8464   // Salient point: SS doesn't have to name a base class as long as
8465   // lookup only finds members from base classes.  Therefore we can
8466   // diagnose here only if we can prove that that can't happen,
8467   // i.e. if the class hierarchies provably don't intersect.
8468
8469   // TODO: it would be nice if "definitely valid" results were cached
8470   // in the UsingDecl and UsingShadowDecl so that these checks didn't
8471   // need to be repeated.
8472
8473   struct UserData {
8474     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
8475
8476     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8477       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8478       Data->Bases.insert(Base);
8479       return true;
8480     }
8481
8482     bool hasDependentBases(const CXXRecordDecl *Class) {
8483       return !Class->forallBases(collect, this);
8484     }
8485
8486     /// Returns true if the base is dependent or is one of the
8487     /// accumulated base classes.
8488     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8489       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8490       return !Data->Bases.count(Base);
8491     }
8492
8493     bool mightShareBases(const CXXRecordDecl *Class) {
8494       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8495     }
8496   };
8497
8498   UserData Data;
8499
8500   // Returns false if we find a dependent base.
8501   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8502     return false;
8503
8504   // Returns false if the class has a dependent base or if it or one
8505   // of its bases is present in the base set of the current context.
8506   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8507     return false;
8508
8509   Diag(SS.getRange().getBegin(),
8510        diag::err_using_decl_nested_name_specifier_is_not_base_class)
8511     << SS.getScopeRep()
8512     << cast<CXXRecordDecl>(CurContext)
8513     << SS.getRange();
8514
8515   return true;
8516 }
8517
8518 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8519                                   AccessSpecifier AS,
8520                                   MultiTemplateParamsArg TemplateParamLists,
8521                                   SourceLocation UsingLoc,
8522                                   UnqualifiedId &Name,
8523                                   AttributeList *AttrList,
8524                                   TypeResult Type,
8525                                   Decl *DeclFromDeclSpec) {
8526   // Skip up to the relevant declaration scope.
8527   while (S->getFlags() & Scope::TemplateParamScope)
8528     S = S->getParent();
8529   assert((S->getFlags() & Scope::DeclScope) &&
8530          "got alias-declaration outside of declaration scope");
8531
8532   if (Type.isInvalid())
8533     return nullptr;
8534
8535   bool Invalid = false;
8536   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8537   TypeSourceInfo *TInfo = nullptr;
8538   GetTypeFromParser(Type.get(), &TInfo);
8539
8540   if (DiagnoseClassNameShadow(CurContext, NameInfo))
8541     return nullptr;
8542
8543   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8544                                       UPPC_DeclarationType)) {
8545     Invalid = true;
8546     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 
8547                                              TInfo->getTypeLoc().getBeginLoc());
8548   }
8549
8550   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8551   LookupName(Previous, S);
8552
8553   // Warn about shadowing the name of a template parameter.
8554   if (Previous.isSingleResult() &&
8555       Previous.getFoundDecl()->isTemplateParameter()) {
8556     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8557     Previous.clear();
8558   }
8559
8560   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8561          "name in alias declaration must be an identifier");
8562   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8563                                                Name.StartLocation,
8564                                                Name.Identifier, TInfo);
8565
8566   NewTD->setAccess(AS);
8567
8568   if (Invalid)
8569     NewTD->setInvalidDecl();
8570
8571   ProcessDeclAttributeList(S, NewTD, AttrList);
8572
8573   CheckTypedefForVariablyModifiedType(S, NewTD);
8574   Invalid |= NewTD->isInvalidDecl();
8575
8576   bool Redeclaration = false;
8577
8578   NamedDecl *NewND;
8579   if (TemplateParamLists.size()) {
8580     TypeAliasTemplateDecl *OldDecl = nullptr;
8581     TemplateParameterList *OldTemplateParams = nullptr;
8582
8583     if (TemplateParamLists.size() != 1) {
8584       Diag(UsingLoc, diag::err_alias_template_extra_headers)
8585         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8586          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8587     }
8588     TemplateParameterList *TemplateParams = TemplateParamLists[0];
8589
8590     // Only consider previous declarations in the same scope.
8591     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8592                          /*ExplicitInstantiationOrSpecialization*/false);
8593     if (!Previous.empty()) {
8594       Redeclaration = true;
8595
8596       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8597       if (!OldDecl && !Invalid) {
8598         Diag(UsingLoc, diag::err_redefinition_different_kind)
8599           << Name.Identifier;
8600
8601         NamedDecl *OldD = Previous.getRepresentativeDecl();
8602         if (OldD->getLocation().isValid())
8603           Diag(OldD->getLocation(), diag::note_previous_definition);
8604
8605         Invalid = true;
8606       }
8607
8608       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8609         if (TemplateParameterListsAreEqual(TemplateParams,
8610                                            OldDecl->getTemplateParameters(),
8611                                            /*Complain=*/true,
8612                                            TPL_TemplateMatch))
8613           OldTemplateParams = OldDecl->getTemplateParameters();
8614         else
8615           Invalid = true;
8616
8617         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8618         if (!Invalid &&
8619             !Context.hasSameType(OldTD->getUnderlyingType(),
8620                                  NewTD->getUnderlyingType())) {
8621           // FIXME: The C++0x standard does not clearly say this is ill-formed,
8622           // but we can't reasonably accept it.
8623           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8624             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8625           if (OldTD->getLocation().isValid())
8626             Diag(OldTD->getLocation(), diag::note_previous_definition);
8627           Invalid = true;
8628         }
8629       }
8630     }
8631
8632     // Merge any previous default template arguments into our parameters,
8633     // and check the parameter list.
8634     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8635                                    TPC_TypeAliasTemplate))
8636       return nullptr;
8637
8638     TypeAliasTemplateDecl *NewDecl =
8639       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8640                                     Name.Identifier, TemplateParams,
8641                                     NewTD);
8642     NewTD->setDescribedAliasTemplate(NewDecl);
8643
8644     NewDecl->setAccess(AS);
8645
8646     if (Invalid)
8647       NewDecl->setInvalidDecl();
8648     else if (OldDecl)
8649       NewDecl->setPreviousDecl(OldDecl);
8650
8651     NewND = NewDecl;
8652   } else {
8653     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8654       setTagNameForLinkagePurposes(TD, NewTD);
8655       handleTagNumbering(TD, S);
8656     }
8657     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8658     NewND = NewTD;
8659   }
8660
8661   if (!Redeclaration)
8662     PushOnScopeChains(NewND, S);
8663
8664   ActOnDocumentableDecl(NewND);
8665   return NewND;
8666 }
8667
8668 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8669                                    SourceLocation AliasLoc,
8670                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
8671                                    SourceLocation IdentLoc,
8672                                    IdentifierInfo *Ident) {
8673
8674   // Lookup the namespace name.
8675   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8676   LookupParsedName(R, S, &SS);
8677
8678   if (R.isAmbiguous())
8679     return nullptr;
8680
8681   if (R.empty()) {
8682     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8683       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8684       return nullptr;
8685     }
8686   }
8687   assert(!R.isAmbiguous() && !R.empty());
8688
8689   // Check if we have a previous declaration with the same name.
8690   NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8691                                          ForRedeclaration);
8692   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8693     PrevDecl = nullptr;
8694
8695   NamedDecl *ND = R.getFoundDecl();
8696
8697   if (PrevDecl) {
8698     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8699       // We already have an alias with the same name that points to the same
8700       // namespace; check that it matches.
8701       if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8702         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8703           << Alias;
8704         Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8705           << AD->getNamespace();
8706         return nullptr;
8707       }
8708     } else {
8709       unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8710                             ? diag::err_redefinition
8711                             : diag::err_redefinition_different_kind;
8712       Diag(AliasLoc, DiagID) << Alias;
8713       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8714       return nullptr;
8715     }
8716   }
8717
8718   // The use of a nested name specifier may trigger deprecation warnings.
8719   DiagnoseUseOfDecl(ND, IdentLoc);
8720
8721   NamespaceAliasDecl *AliasDecl =
8722     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8723                                Alias, SS.getWithLocInContext(Context),
8724                                IdentLoc, ND);
8725   if (PrevDecl)
8726     AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
8727
8728   PushOnScopeChains(AliasDecl, S);
8729   return AliasDecl;
8730 }
8731
8732 Sema::ImplicitExceptionSpecification
8733 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8734                                                CXXMethodDecl *MD) {
8735   CXXRecordDecl *ClassDecl = MD->getParent();
8736
8737   // C++ [except.spec]p14:
8738   //   An implicitly declared special member function (Clause 12) shall have an 
8739   //   exception-specification. [...]
8740   ImplicitExceptionSpecification ExceptSpec(*this);
8741   if (ClassDecl->isInvalidDecl())
8742     return ExceptSpec;
8743
8744   // Direct base-class constructors.
8745   for (const auto &B : ClassDecl->bases()) {
8746     if (B.isVirtual()) // Handled below.
8747       continue;
8748     
8749     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8750       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8751       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8752       // If this is a deleted function, add it anyway. This might be conformant
8753       // with the standard. This might not. I'm not sure. It might not matter.
8754       if (Constructor)
8755         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8756     }
8757   }
8758
8759   // Virtual base-class constructors.
8760   for (const auto &B : ClassDecl->vbases()) {
8761     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8762       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8763       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8764       // If this is a deleted function, add it anyway. This might be conformant
8765       // with the standard. This might not. I'm not sure. It might not matter.
8766       if (Constructor)
8767         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8768     }
8769   }
8770
8771   // Field constructors.
8772   for (const auto *F : ClassDecl->fields()) {
8773     if (F->hasInClassInitializer()) {
8774       if (Expr *E = F->getInClassInitializer())
8775         ExceptSpec.CalledExpr(E);
8776     } else if (const RecordType *RecordTy
8777               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8778       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8779       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8780       // If this is a deleted function, add it anyway. This might be conformant
8781       // with the standard. This might not. I'm not sure. It might not matter.
8782       // In particular, the problem is that this function never gets called. It
8783       // might just be ill-formed because this function attempts to refer to
8784       // a deleted function here.
8785       if (Constructor)
8786         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8787     }
8788   }
8789
8790   return ExceptSpec;
8791 }
8792
8793 Sema::ImplicitExceptionSpecification
8794 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8795   CXXRecordDecl *ClassDecl = CD->getParent();
8796
8797   // C++ [except.spec]p14:
8798   //   An inheriting constructor [...] shall have an exception-specification. [...]
8799   ImplicitExceptionSpecification ExceptSpec(*this);
8800   if (ClassDecl->isInvalidDecl())
8801     return ExceptSpec;
8802
8803   // Inherited constructor.
8804   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8805   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8806   // FIXME: Copying or moving the parameters could add extra exceptions to the
8807   // set, as could the default arguments for the inherited constructor. This
8808   // will be addressed when we implement the resolution of core issue 1351.
8809   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8810
8811   // Direct base-class constructors.
8812   for (const auto &B : ClassDecl->bases()) {
8813     if (B.isVirtual()) // Handled below.
8814       continue;
8815
8816     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8817       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8818       if (BaseClassDecl == InheritedDecl)
8819         continue;
8820       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8821       if (Constructor)
8822         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8823     }
8824   }
8825
8826   // Virtual base-class constructors.
8827   for (const auto &B : ClassDecl->vbases()) {
8828     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8829       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8830       if (BaseClassDecl == InheritedDecl)
8831         continue;
8832       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8833       if (Constructor)
8834         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8835     }
8836   }
8837
8838   // Field constructors.
8839   for (const auto *F : ClassDecl->fields()) {
8840     if (F->hasInClassInitializer()) {
8841       if (Expr *E = F->getInClassInitializer())
8842         ExceptSpec.CalledExpr(E);
8843     } else if (const RecordType *RecordTy
8844               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8845       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8846       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8847       if (Constructor)
8848         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8849     }
8850   }
8851
8852   return ExceptSpec;
8853 }
8854
8855 namespace {
8856 /// RAII object to register a special member as being currently declared.
8857 struct DeclaringSpecialMember {
8858   Sema &S;
8859   Sema::SpecialMemberDecl D;
8860   bool WasAlreadyBeingDeclared;
8861
8862   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8863     : S(S), D(RD, CSM) {
8864     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
8865     if (WasAlreadyBeingDeclared)
8866       // This almost never happens, but if it does, ensure that our cache
8867       // doesn't contain a stale result.
8868       S.SpecialMemberCache.clear();
8869
8870     // FIXME: Register a note to be produced if we encounter an error while
8871     // declaring the special member.
8872   }
8873   ~DeclaringSpecialMember() {
8874     if (!WasAlreadyBeingDeclared)
8875       S.SpecialMembersBeingDeclared.erase(D);
8876   }
8877
8878   /// \brief Are we already trying to declare this special member?
8879   bool isAlreadyBeingDeclared() const {
8880     return WasAlreadyBeingDeclared;
8881   }
8882 };
8883 }
8884
8885 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8886                                                      CXXRecordDecl *ClassDecl) {
8887   // C++ [class.ctor]p5:
8888   //   A default constructor for a class X is a constructor of class X
8889   //   that can be called without an argument. If there is no
8890   //   user-declared constructor for class X, a default constructor is
8891   //   implicitly declared. An implicitly-declared default constructor
8892   //   is an inline public member of its class.
8893   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8894          "Should not build implicit default constructor!");
8895
8896   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8897   if (DSM.isAlreadyBeingDeclared())
8898     return nullptr;
8899
8900   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8901                                                      CXXDefaultConstructor,
8902                                                      false);
8903
8904   // Create the actual constructor declaration.
8905   CanQualType ClassType
8906     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8907   SourceLocation ClassLoc = ClassDecl->getLocation();
8908   DeclarationName Name
8909     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8910   DeclarationNameInfo NameInfo(Name, ClassLoc);
8911   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8912       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8913       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8914       /*isImplicitlyDeclared=*/true, Constexpr);
8915   DefaultCon->setAccess(AS_public);
8916   DefaultCon->setDefaulted();
8917
8918   if (getLangOpts().CUDA) {
8919     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8920                                             DefaultCon,
8921                                             /* ConstRHS */ false,
8922                                             /* Diagnose */ false);
8923   }
8924
8925   // Build an exception specification pointing back at this constructor.
8926   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8927   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8928
8929   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8930   // constructors is easy to compute.
8931   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8932
8933   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8934     SetDeclDeleted(DefaultCon, ClassLoc);
8935
8936   // Note that we have declared this constructor.
8937   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8938
8939   if (Scope *S = getScopeForContext(ClassDecl))
8940     PushOnScopeChains(DefaultCon, S, false);
8941   ClassDecl->addDecl(DefaultCon);
8942
8943   return DefaultCon;
8944 }
8945
8946 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8947                                             CXXConstructorDecl *Constructor) {
8948   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8949           !Constructor->doesThisDeclarationHaveABody() &&
8950           !Constructor->isDeleted()) &&
8951     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8952
8953   CXXRecordDecl *ClassDecl = Constructor->getParent();
8954   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8955
8956   SynthesizedFunctionScope Scope(*this, Constructor);
8957   DiagnosticErrorTrap Trap(Diags);
8958   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8959       Trap.hasErrorOccurred()) {
8960     Diag(CurrentLocation, diag::note_member_synthesized_at) 
8961       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8962     Constructor->setInvalidDecl();
8963     return;
8964   }
8965
8966   // The exception specification is needed because we are defining the
8967   // function.
8968   ResolveExceptionSpec(CurrentLocation,
8969                        Constructor->getType()->castAs<FunctionProtoType>());
8970
8971   SourceLocation Loc = Constructor->getLocEnd().isValid()
8972                            ? Constructor->getLocEnd()
8973                            : Constructor->getLocation();
8974   Constructor->setBody(new (Context) CompoundStmt(Loc));
8975
8976   Constructor->markUsed(Context);
8977   MarkVTableUsed(CurrentLocation, ClassDecl);
8978
8979   if (ASTMutationListener *L = getASTMutationListener()) {
8980     L->CompletedImplicitDefinition(Constructor);
8981   }
8982
8983   DiagnoseUninitializedFields(*this, Constructor);
8984 }
8985
8986 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8987   // Perform any delayed checks on exception specifications.
8988   CheckDelayedMemberExceptionSpecs();
8989 }
8990
8991 namespace {
8992 /// Information on inheriting constructors to declare.
8993 class InheritingConstructorInfo {
8994 public:
8995   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8996       : SemaRef(SemaRef), Derived(Derived) {
8997     // Mark the constructors that we already have in the derived class.
8998     //
8999     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
9000     //   unless there is a user-declared constructor with the same signature in
9001     //   the class where the using-declaration appears.
9002     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
9003   }
9004
9005   void inheritAll(CXXRecordDecl *RD) {
9006     visitAll(RD, &InheritingConstructorInfo::inherit);
9007   }
9008
9009 private:
9010   /// Information about an inheriting constructor.
9011   struct InheritingConstructor {
9012     InheritingConstructor()
9013       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
9014
9015     /// If \c true, a constructor with this signature is already declared
9016     /// in the derived class.
9017     bool DeclaredInDerived;
9018
9019     /// The constructor which is inherited.
9020     const CXXConstructorDecl *BaseCtor;
9021
9022     /// The derived constructor we declared.
9023     CXXConstructorDecl *DerivedCtor;
9024   };
9025
9026   /// Inheriting constructors with a given canonical type. There can be at
9027   /// most one such non-template constructor, and any number of templated
9028   /// constructors.
9029   struct InheritingConstructorsForType {
9030     InheritingConstructor NonTemplate;
9031     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
9032         Templates;
9033
9034     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
9035       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
9036         TemplateParameterList *ParamList = FTD->getTemplateParameters();
9037         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
9038           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
9039                                                false, S.TPL_TemplateMatch))
9040             return Templates[I].second;
9041         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
9042         return Templates.back().second;
9043       }
9044
9045       return NonTemplate;
9046     }
9047   };
9048
9049   /// Get or create the inheriting constructor record for a constructor.
9050   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9051                                   QualType CtorType) {
9052     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9053         .getEntry(SemaRef, Ctor);
9054   }
9055
9056   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9057
9058   /// Process all constructors for a class.
9059   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
9060     for (const auto *Ctor : RD->ctors())
9061       (this->*Callback)(Ctor);
9062     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9063              I(RD->decls_begin()), E(RD->decls_end());
9064          I != E; ++I) {
9065       const FunctionDecl *FD = (*I)->getTemplatedDecl();
9066       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9067         (this->*Callback)(CD);
9068     }
9069   }
9070
9071   /// Note that a constructor (or constructor template) was declared in Derived.
9072   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9073     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9074   }
9075
9076   /// Inherit a single constructor.
9077   void inherit(const CXXConstructorDecl *Ctor) {
9078     const FunctionProtoType *CtorType =
9079         Ctor->getType()->castAs<FunctionProtoType>();
9080     ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
9081     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9082
9083     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9084
9085     // Core issue (no number yet): the ellipsis is always discarded.
9086     if (EPI.Variadic) {
9087       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9088       SemaRef.Diag(Ctor->getLocation(),
9089                    diag::note_using_decl_constructor_ellipsis);
9090       EPI.Variadic = false;
9091     }
9092
9093     // Declare a constructor for each number of parameters.
9094     //
9095     // C++11 [class.inhctor]p1:
9096     //   The candidate set of inherited constructors from the class X named in
9097     //   the using-declaration consists of [... modulo defects ...] for each
9098     //   constructor or constructor template of X, the set of constructors or
9099     //   constructor templates that results from omitting any ellipsis parameter
9100     //   specification and successively omitting parameters with a default
9101     //   argument from the end of the parameter-type-list
9102     unsigned MinParams = minParamsToInherit(Ctor);
9103     unsigned Params = Ctor->getNumParams();
9104     if (Params >= MinParams) {
9105       do
9106         declareCtor(UsingLoc, Ctor,
9107                     SemaRef.Context.getFunctionType(
9108                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
9109       while (Params > MinParams &&
9110              Ctor->getParamDecl(--Params)->hasDefaultArg());
9111     }
9112   }
9113
9114   /// Find the using-declaration which specified that we should inherit the
9115   /// constructors of \p Base.
9116   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9117     // No fancy lookup required; just look for the base constructor name
9118     // directly within the derived class.
9119     ASTContext &Context = SemaRef.Context;
9120     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9121         Context.getCanonicalType(Context.getRecordType(Base)));
9122     DeclContext::lookup_result Decls = Derived->lookup(Name);
9123     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9124   }
9125
9126   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9127     // C++11 [class.inhctor]p3:
9128     //   [F]or each constructor template in the candidate set of inherited
9129     //   constructors, a constructor template is implicitly declared
9130     if (Ctor->getDescribedFunctionTemplate())
9131       return 0;
9132
9133     //   For each non-template constructor in the candidate set of inherited
9134     //   constructors other than a constructor having no parameters or a
9135     //   copy/move constructor having a single parameter, a constructor is
9136     //   implicitly declared [...]
9137     if (Ctor->getNumParams() == 0)
9138       return 1;
9139     if (Ctor->isCopyOrMoveConstructor())
9140       return 2;
9141
9142     // Per discussion on core reflector, never inherit a constructor which
9143     // would become a default, copy, or move constructor of Derived either.
9144     const ParmVarDecl *PD = Ctor->getParamDecl(0);
9145     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9146     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9147   }
9148
9149   /// Declare a single inheriting constructor, inheriting the specified
9150   /// constructor, with the given type.
9151   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9152                    QualType DerivedType) {
9153     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9154
9155     // C++11 [class.inhctor]p3:
9156     //   ... a constructor is implicitly declared with the same constructor
9157     //   characteristics unless there is a user-declared constructor with
9158     //   the same signature in the class where the using-declaration appears
9159     if (Entry.DeclaredInDerived)
9160       return;
9161
9162     // C++11 [class.inhctor]p7:
9163     //   If two using-declarations declare inheriting constructors with the
9164     //   same signature, the program is ill-formed
9165     if (Entry.DerivedCtor) {
9166       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9167         // Only diagnose this once per constructor.
9168         if (Entry.DerivedCtor->isInvalidDecl())
9169           return;
9170         Entry.DerivedCtor->setInvalidDecl();
9171
9172         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9173         SemaRef.Diag(BaseCtor->getLocation(),
9174                      diag::note_using_decl_constructor_conflict_current_ctor);
9175         SemaRef.Diag(Entry.BaseCtor->getLocation(),
9176                      diag::note_using_decl_constructor_conflict_previous_ctor);
9177         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9178                      diag::note_using_decl_constructor_conflict_previous_using);
9179       } else {
9180         // Core issue (no number): if the same inheriting constructor is
9181         // produced by multiple base class constructors from the same base
9182         // class, the inheriting constructor is defined as deleted.
9183         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9184       }
9185
9186       return;
9187     }
9188
9189     ASTContext &Context = SemaRef.Context;
9190     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9191         Context.getCanonicalType(Context.getRecordType(Derived)));
9192     DeclarationNameInfo NameInfo(Name, UsingLoc);
9193
9194     TemplateParameterList *TemplateParams = nullptr;
9195     if (const FunctionTemplateDecl *FTD =
9196             BaseCtor->getDescribedFunctionTemplate()) {
9197       TemplateParams = FTD->getTemplateParameters();
9198       // We're reusing template parameters from a different DeclContext. This
9199       // is questionable at best, but works out because the template depth in
9200       // both places is guaranteed to be 0.
9201       // FIXME: Rebuild the template parameters in the new context, and
9202       // transform the function type to refer to them.
9203     }
9204
9205     // Build type source info pointing at the using-declaration. This is
9206     // required by template instantiation.
9207     TypeSourceInfo *TInfo =
9208         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9209     FunctionProtoTypeLoc ProtoLoc =
9210         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9211
9212     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9213         Context, Derived, UsingLoc, NameInfo, DerivedType,
9214         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9215         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9216
9217     // Build an unevaluated exception specification for this constructor.
9218     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9219     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9220     EPI.ExceptionSpec.Type = EST_Unevaluated;
9221     EPI.ExceptionSpec.SourceDecl = DerivedCtor;
9222     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
9223                                                  FPT->getParamTypes(), EPI));
9224
9225     // Build the parameter declarations.
9226     SmallVector<ParmVarDecl *, 16> ParamDecls;
9227     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
9228       TypeSourceInfo *TInfo =
9229           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
9230       ParmVarDecl *PD = ParmVarDecl::Create(
9231           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9232           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
9233       PD->setScopeInfo(0, I);
9234       PD->setImplicit();
9235       ParamDecls.push_back(PD);
9236       ProtoLoc.setParam(I, PD);
9237     }
9238
9239     // Set up the new constructor.
9240     DerivedCtor->setAccess(BaseCtor->getAccess());
9241     DerivedCtor->setParams(ParamDecls);
9242     DerivedCtor->setInheritedConstructor(BaseCtor);
9243     if (BaseCtor->isDeleted())
9244       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9245
9246     // If this is a constructor template, build the template declaration.
9247     if (TemplateParams) {
9248       FunctionTemplateDecl *DerivedTemplate =
9249           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9250                                        TemplateParams, DerivedCtor);
9251       DerivedTemplate->setAccess(BaseCtor->getAccess());
9252       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9253       Derived->addDecl(DerivedTemplate);
9254     } else {
9255       Derived->addDecl(DerivedCtor);
9256     }
9257
9258     Entry.BaseCtor = BaseCtor;
9259     Entry.DerivedCtor = DerivedCtor;
9260   }
9261
9262   Sema &SemaRef;
9263   CXXRecordDecl *Derived;
9264   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9265   MapType Map;
9266 };
9267 }
9268
9269 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9270   // Defer declaring the inheriting constructors until the class is
9271   // instantiated.
9272   if (ClassDecl->isDependentContext())
9273     return;
9274
9275   // Find base classes from which we might inherit constructors.
9276   SmallVector<CXXRecordDecl*, 4> InheritedBases;
9277   for (const auto &BaseIt : ClassDecl->bases())
9278     if (BaseIt.getInheritConstructors())
9279       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
9280
9281   // Go no further if we're not inheriting any constructors.
9282   if (InheritedBases.empty())
9283     return;
9284
9285   // Declare the inherited constructors.
9286   InheritingConstructorInfo ICI(*this, ClassDecl);
9287   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9288     ICI.inheritAll(InheritedBases[I]);
9289 }
9290
9291 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9292                                        CXXConstructorDecl *Constructor) {
9293   CXXRecordDecl *ClassDecl = Constructor->getParent();
9294   assert(Constructor->getInheritedConstructor() &&
9295          !Constructor->doesThisDeclarationHaveABody() &&
9296          !Constructor->isDeleted());
9297
9298   SynthesizedFunctionScope Scope(*this, Constructor);
9299   DiagnosticErrorTrap Trap(Diags);
9300   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9301       Trap.hasErrorOccurred()) {
9302     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9303       << Context.getTagDeclType(ClassDecl);
9304     Constructor->setInvalidDecl();
9305     return;
9306   }
9307
9308   SourceLocation Loc = Constructor->getLocation();
9309   Constructor->setBody(new (Context) CompoundStmt(Loc));
9310
9311   Constructor->markUsed(Context);
9312   MarkVTableUsed(CurrentLocation, ClassDecl);
9313
9314   if (ASTMutationListener *L = getASTMutationListener()) {
9315     L->CompletedImplicitDefinition(Constructor);
9316   }
9317 }
9318
9319
9320 Sema::ImplicitExceptionSpecification
9321 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9322   CXXRecordDecl *ClassDecl = MD->getParent();
9323
9324   // C++ [except.spec]p14: 
9325   //   An implicitly declared special member function (Clause 12) shall have 
9326   //   an exception-specification.
9327   ImplicitExceptionSpecification ExceptSpec(*this);
9328   if (ClassDecl->isInvalidDecl())
9329     return ExceptSpec;
9330
9331   // Direct base-class destructors.
9332   for (const auto &B : ClassDecl->bases()) {
9333     if (B.isVirtual()) // Handled below.
9334       continue;
9335     
9336     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9337       ExceptSpec.CalledDecl(B.getLocStart(),
9338                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9339   }
9340
9341   // Virtual base-class destructors.
9342   for (const auto &B : ClassDecl->vbases()) {
9343     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9344       ExceptSpec.CalledDecl(B.getLocStart(),
9345                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9346   }
9347
9348   // Field destructors.
9349   for (const auto *F : ClassDecl->fields()) {
9350     if (const RecordType *RecordTy
9351         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
9352       ExceptSpec.CalledDecl(F->getLocation(),
9353                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
9354   }
9355
9356   return ExceptSpec;
9357 }
9358
9359 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9360   // C++ [class.dtor]p2:
9361   //   If a class has no user-declared destructor, a destructor is
9362   //   declared implicitly. An implicitly-declared destructor is an
9363   //   inline public member of its class.
9364   assert(ClassDecl->needsImplicitDestructor());
9365
9366   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9367   if (DSM.isAlreadyBeingDeclared())
9368     return nullptr;
9369
9370   // Create the actual destructor declaration.
9371   CanQualType ClassType
9372     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9373   SourceLocation ClassLoc = ClassDecl->getLocation();
9374   DeclarationName Name
9375     = Context.DeclarationNames.getCXXDestructorName(ClassType);
9376   DeclarationNameInfo NameInfo(Name, ClassLoc);
9377   CXXDestructorDecl *Destructor
9378       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
9379                                   QualType(), nullptr, /*isInline=*/true,
9380                                   /*isImplicitlyDeclared=*/true);
9381   Destructor->setAccess(AS_public);
9382   Destructor->setDefaulted();
9383
9384   if (getLangOpts().CUDA) {
9385     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9386                                             Destructor,
9387                                             /* ConstRHS */ false,
9388                                             /* Diagnose */ false);
9389   }
9390
9391   // Build an exception specification pointing back at this destructor.
9392   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
9393   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9394
9395   AddOverriddenMethods(ClassDecl, Destructor);
9396
9397   // We don't need to use SpecialMemberIsTrivial here; triviality for
9398   // destructors is easy to compute.
9399   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9400
9401   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9402     SetDeclDeleted(Destructor, ClassLoc);
9403
9404   // Note that we have declared this destructor.
9405   ++ASTContext::NumImplicitDestructorsDeclared;
9406
9407   // Introduce this destructor into its scope.
9408   if (Scope *S = getScopeForContext(ClassDecl))
9409     PushOnScopeChains(Destructor, S, false);
9410   ClassDecl->addDecl(Destructor);
9411
9412   return Destructor;
9413 }
9414
9415 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
9416                                     CXXDestructorDecl *Destructor) {
9417   assert((Destructor->isDefaulted() &&
9418           !Destructor->doesThisDeclarationHaveABody() &&
9419           !Destructor->isDeleted()) &&
9420          "DefineImplicitDestructor - call it for implicit default dtor");
9421   CXXRecordDecl *ClassDecl = Destructor->getParent();
9422   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9423
9424   if (Destructor->isInvalidDecl())
9425     return;
9426
9427   SynthesizedFunctionScope Scope(*this, Destructor);
9428
9429   DiagnosticErrorTrap Trap(Diags);
9430   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9431                                          Destructor->getParent());
9432
9433   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9434     Diag(CurrentLocation, diag::note_member_synthesized_at) 
9435       << CXXDestructor << Context.getTagDeclType(ClassDecl);
9436
9437     Destructor->setInvalidDecl();
9438     return;
9439   }
9440
9441   // The exception specification is needed because we are defining the
9442   // function.
9443   ResolveExceptionSpec(CurrentLocation,
9444                        Destructor->getType()->castAs<FunctionProtoType>());
9445
9446   SourceLocation Loc = Destructor->getLocEnd().isValid()
9447                            ? Destructor->getLocEnd()
9448                            : Destructor->getLocation();
9449   Destructor->setBody(new (Context) CompoundStmt(Loc));
9450   Destructor->markUsed(Context);
9451   MarkVTableUsed(CurrentLocation, ClassDecl);
9452
9453   if (ASTMutationListener *L = getASTMutationListener()) {
9454     L->CompletedImplicitDefinition(Destructor);
9455   }
9456 }
9457
9458 /// \brief Perform any semantic analysis which needs to be delayed until all
9459 /// pending class member declarations have been parsed.
9460 void Sema::ActOnFinishCXXMemberDecls() {
9461   // If the context is an invalid C++ class, just suppress these checks.
9462   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9463     if (Record->isInvalidDecl()) {
9464       DelayedDefaultedMemberExceptionSpecs.clear();
9465       DelayedExceptionSpecChecks.clear();
9466       return;
9467     }
9468   }
9469 }
9470
9471 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9472   // Don't do anything for template patterns.
9473   if (Class->getDescribedClassTemplate())
9474     return;
9475
9476   for (Decl *Member : Class->decls()) {
9477     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9478     if (!CD) {
9479       // Recurse on nested classes.
9480       if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9481         getDefaultArgExprsForConstructors(S, NestedRD);
9482       continue;
9483     } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9484       continue;
9485     }
9486
9487     for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) {
9488       // Skip any default arguments that we've already instantiated.
9489       if (S.Context.getDefaultArgExprForConstructor(CD, I))
9490         continue;
9491
9492       Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9493                                                   CD->getParamDecl(I)).get();
9494       S.DiscardCleanupsInEvaluationContext();
9495       S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9496     }
9497   }
9498 }
9499
9500 void Sema::ActOnFinishCXXMemberDefaultArgs(Decl *D) {
9501   auto *RD = dyn_cast<CXXRecordDecl>(D);
9502
9503   // Default constructors that are annotated with __declspec(dllexport) which
9504   // have default arguments or don't use the standard calling convention are
9505   // wrapped with a thunk called the default constructor closure.
9506   if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9507     getDefaultArgExprsForConstructors(*this, RD);
9508 }
9509
9510 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9511                                          CXXDestructorDecl *Destructor) {
9512   assert(getLangOpts().CPlusPlus11 &&
9513          "adjusting dtor exception specs was introduced in c++11");
9514
9515   // C++11 [class.dtor]p3:
9516   //   A declaration of a destructor that does not have an exception-
9517   //   specification is implicitly considered to have the same exception-
9518   //   specification as an implicit declaration.
9519   const FunctionProtoType *DtorType = Destructor->getType()->
9520                                         getAs<FunctionProtoType>();
9521   if (DtorType->hasExceptionSpec())
9522     return;
9523
9524   // Replace the destructor's type, building off the existing one. Fortunately,
9525   // the only thing of interest in the destructor type is its extended info.
9526   // The return and arguments are fixed.
9527   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9528   EPI.ExceptionSpec.Type = EST_Unevaluated;
9529   EPI.ExceptionSpec.SourceDecl = Destructor;
9530   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9531
9532   // FIXME: If the destructor has a body that could throw, and the newly created
9533   // spec doesn't allow exceptions, we should emit a warning, because this
9534   // change in behavior can break conforming C++03 programs at runtime.
9535   // However, we don't have a body or an exception specification yet, so it
9536   // needs to be done somewhere else.
9537 }
9538
9539 namespace {
9540 /// \brief An abstract base class for all helper classes used in building the
9541 //  copy/move operators. These classes serve as factory functions and help us
9542 //  avoid using the same Expr* in the AST twice.
9543 class ExprBuilder {
9544   ExprBuilder(const ExprBuilder&) = delete;
9545   ExprBuilder &operator=(const ExprBuilder&) = delete;
9546
9547 protected:
9548   static Expr *assertNotNull(Expr *E) {
9549     assert(E && "Expression construction must not fail.");
9550     return E;
9551   }
9552
9553 public:
9554   ExprBuilder() {}
9555   virtual ~ExprBuilder() {}
9556
9557   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9558 };
9559
9560 class RefBuilder: public ExprBuilder {
9561   VarDecl *Var;
9562   QualType VarType;
9563
9564 public:
9565   Expr *build(Sema &S, SourceLocation Loc) const override {
9566     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9567   }
9568
9569   RefBuilder(VarDecl *Var, QualType VarType)
9570       : Var(Var), VarType(VarType) {}
9571 };
9572
9573 class ThisBuilder: public ExprBuilder {
9574 public:
9575   Expr *build(Sema &S, SourceLocation Loc) const override {
9576     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9577   }
9578 };
9579
9580 class CastBuilder: public ExprBuilder {
9581   const ExprBuilder &Builder;
9582   QualType Type;
9583   ExprValueKind Kind;
9584   const CXXCastPath &Path;
9585
9586 public:
9587   Expr *build(Sema &S, SourceLocation Loc) const override {
9588     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9589                                              CK_UncheckedDerivedToBase, Kind,
9590                                              &Path).get());
9591   }
9592
9593   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9594               const CXXCastPath &Path)
9595       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9596 };
9597
9598 class DerefBuilder: public ExprBuilder {
9599   const ExprBuilder &Builder;
9600
9601 public:
9602   Expr *build(Sema &S, SourceLocation Loc) const override {
9603     return assertNotNull(
9604         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9605   }
9606
9607   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9608 };
9609
9610 class MemberBuilder: public ExprBuilder {
9611   const ExprBuilder &Builder;
9612   QualType Type;
9613   CXXScopeSpec SS;
9614   bool IsArrow;
9615   LookupResult &MemberLookup;
9616
9617 public:
9618   Expr *build(Sema &S, SourceLocation Loc) const override {
9619     return assertNotNull(S.BuildMemberReferenceExpr(
9620         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9621         nullptr, MemberLookup, nullptr).get());
9622   }
9623
9624   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9625                 LookupResult &MemberLookup)
9626       : Builder(Builder), Type(Type), IsArrow(IsArrow),
9627         MemberLookup(MemberLookup) {}
9628 };
9629
9630 class MoveCastBuilder: public ExprBuilder {
9631   const ExprBuilder &Builder;
9632
9633 public:
9634   Expr *build(Sema &S, SourceLocation Loc) const override {
9635     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9636   }
9637
9638   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9639 };
9640
9641 class LvalueConvBuilder: public ExprBuilder {
9642   const ExprBuilder &Builder;
9643
9644 public:
9645   Expr *build(Sema &S, SourceLocation Loc) const override {
9646     return assertNotNull(
9647         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9648   }
9649
9650   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9651 };
9652
9653 class SubscriptBuilder: public ExprBuilder {
9654   const ExprBuilder &Base;
9655   const ExprBuilder &Index;
9656
9657 public:
9658   Expr *build(Sema &S, SourceLocation Loc) const override {
9659     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9660         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9661   }
9662
9663   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9664       : Base(Base), Index(Index) {}
9665 };
9666
9667 } // end anonymous namespace
9668
9669 /// When generating a defaulted copy or move assignment operator, if a field
9670 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9671 /// do so. This optimization only applies for arrays of scalars, and for arrays
9672 /// of class type where the selected copy/move-assignment operator is trivial.
9673 static StmtResult
9674 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9675                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
9676   // Compute the size of the memory buffer to be copied.
9677   QualType SizeType = S.Context.getSizeType();
9678   llvm::APInt Size(S.Context.getTypeSize(SizeType),
9679                    S.Context.getTypeSizeInChars(T).getQuantity());
9680
9681   // Take the address of the field references for "from" and "to". We
9682   // directly construct UnaryOperators here because semantic analysis
9683   // does not permit us to take the address of an xvalue.
9684   Expr *From = FromB.build(S, Loc);
9685   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9686                          S.Context.getPointerType(From->getType()),
9687                          VK_RValue, OK_Ordinary, Loc);
9688   Expr *To = ToB.build(S, Loc);
9689   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9690                        S.Context.getPointerType(To->getType()),
9691                        VK_RValue, OK_Ordinary, Loc);
9692
9693   const Type *E = T->getBaseElementTypeUnsafe();
9694   bool NeedsCollectableMemCpy =
9695     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9696
9697   // Create a reference to the __builtin_objc_memmove_collectable function
9698   StringRef MemCpyName = NeedsCollectableMemCpy ?
9699     "__builtin_objc_memmove_collectable" :
9700     "__builtin_memcpy";
9701   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9702                  Sema::LookupOrdinaryName);
9703   S.LookupName(R, S.TUScope, true);
9704
9705   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9706   if (!MemCpy)
9707     // Something went horribly wrong earlier, and we will have complained
9708     // about it.
9709     return StmtError();
9710
9711   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9712                                             VK_RValue, Loc, nullptr);
9713   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9714
9715   Expr *CallArgs[] = {
9716     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9717   };
9718   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9719                                     Loc, CallArgs, Loc);
9720
9721   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9722   return Call.getAs<Stmt>();
9723 }
9724
9725 /// \brief Builds a statement that copies/moves the given entity from \p From to
9726 /// \c To.
9727 ///
9728 /// This routine is used to copy/move the members of a class with an
9729 /// implicitly-declared copy/move assignment operator. When the entities being
9730 /// copied are arrays, this routine builds for loops to copy them.
9731 ///
9732 /// \param S The Sema object used for type-checking.
9733 ///
9734 /// \param Loc The location where the implicit copy/move is being generated.
9735 ///
9736 /// \param T The type of the expressions being copied/moved. Both expressions
9737 /// must have this type.
9738 ///
9739 /// \param To The expression we are copying/moving to.
9740 ///
9741 /// \param From The expression we are copying/moving from.
9742 ///
9743 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9744 /// Otherwise, it's a non-static member subobject.
9745 ///
9746 /// \param Copying Whether we're copying or moving.
9747 ///
9748 /// \param Depth Internal parameter recording the depth of the recursion.
9749 ///
9750 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9751 /// if a memcpy should be used instead.
9752 static StmtResult
9753 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9754                                  const ExprBuilder &To, const ExprBuilder &From,
9755                                  bool CopyingBaseSubobject, bool Copying,
9756                                  unsigned Depth = 0) {
9757   // C++11 [class.copy]p28:
9758   //   Each subobject is assigned in the manner appropriate to its type:
9759   //
9760   //     - if the subobject is of class type, as if by a call to operator= with
9761   //       the subobject as the object expression and the corresponding
9762   //       subobject of x as a single function argument (as if by explicit
9763   //       qualification; that is, ignoring any possible virtual overriding
9764   //       functions in more derived classes);
9765   //
9766   // C++03 [class.copy]p13:
9767   //     - if the subobject is of class type, the copy assignment operator for
9768   //       the class is used (as if by explicit qualification; that is,
9769   //       ignoring any possible virtual overriding functions in more derived
9770   //       classes);
9771   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9772     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9773
9774     // Look for operator=.
9775     DeclarationName Name
9776       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9777     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9778     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9779
9780     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9781     // operator.
9782     if (!S.getLangOpts().CPlusPlus11) {
9783       LookupResult::Filter F = OpLookup.makeFilter();
9784       while (F.hasNext()) {
9785         NamedDecl *D = F.next();
9786         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9787           if (Method->isCopyAssignmentOperator() ||
9788               (!Copying && Method->isMoveAssignmentOperator()))
9789             continue;
9790
9791         F.erase();
9792       }
9793       F.done();
9794     }
9795
9796     // Suppress the protected check (C++ [class.protected]) for each of the
9797     // assignment operators we found. This strange dance is required when
9798     // we're assigning via a base classes's copy-assignment operator. To
9799     // ensure that we're getting the right base class subobject (without
9800     // ambiguities), we need to cast "this" to that subobject type; to
9801     // ensure that we don't go through the virtual call mechanism, we need
9802     // to qualify the operator= name with the base class (see below). However,
9803     // this means that if the base class has a protected copy assignment
9804     // operator, the protected member access check will fail. So, we
9805     // rewrite "protected" access to "public" access in this case, since we
9806     // know by construction that we're calling from a derived class.
9807     if (CopyingBaseSubobject) {
9808       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9809            L != LEnd; ++L) {
9810         if (L.getAccess() == AS_protected)
9811           L.setAccess(AS_public);
9812       }
9813     }
9814
9815     // Create the nested-name-specifier that will be used to qualify the
9816     // reference to operator=; this is required to suppress the virtual
9817     // call mechanism.
9818     CXXScopeSpec SS;
9819     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9820     SS.MakeTrivial(S.Context,
9821                    NestedNameSpecifier::Create(S.Context, nullptr, false,
9822                                                CanonicalT),
9823                    Loc);
9824
9825     // Create the reference to operator=.
9826     ExprResult OpEqualRef
9827       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9828                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9829                                    /*FirstQualifierInScope=*/nullptr,
9830                                    OpLookup,
9831                                    /*TemplateArgs=*/nullptr,
9832                                    /*SuppressQualifierCheck=*/true);
9833     if (OpEqualRef.isInvalid())
9834       return StmtError();
9835
9836     // Build the call to the assignment operator.
9837
9838     Expr *FromInst = From.build(S, Loc);
9839     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9840                                                   OpEqualRef.getAs<Expr>(),
9841                                                   Loc, FromInst, Loc);
9842     if (Call.isInvalid())
9843       return StmtError();
9844
9845     // If we built a call to a trivial 'operator=' while copying an array,
9846     // bail out. We'll replace the whole shebang with a memcpy.
9847     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9848     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9849       return StmtResult((Stmt*)nullptr);
9850
9851     // Convert to an expression-statement, and clean up any produced
9852     // temporaries.
9853     return S.ActOnExprStmt(Call);
9854   }
9855
9856   //     - if the subobject is of scalar type, the built-in assignment
9857   //       operator is used.
9858   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9859   if (!ArrayTy) {
9860     ExprResult Assignment = S.CreateBuiltinBinOp(
9861         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9862     if (Assignment.isInvalid())
9863       return StmtError();
9864     return S.ActOnExprStmt(Assignment);
9865   }
9866
9867   //     - if the subobject is an array, each element is assigned, in the
9868   //       manner appropriate to the element type;
9869
9870   // Construct a loop over the array bounds, e.g.,
9871   //
9872   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9873   //
9874   // that will copy each of the array elements. 
9875   QualType SizeType = S.Context.getSizeType();
9876
9877   // Create the iteration variable.
9878   IdentifierInfo *IterationVarName = nullptr;
9879   {
9880     SmallString<8> Str;
9881     llvm::raw_svector_ostream OS(Str);
9882     OS << "__i" << Depth;
9883     IterationVarName = &S.Context.Idents.get(OS.str());
9884   }
9885   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9886                                           IterationVarName, SizeType,
9887                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9888                                           SC_None);
9889
9890   // Initialize the iteration variable to zero.
9891   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9892   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9893
9894   // Creates a reference to the iteration variable.
9895   RefBuilder IterationVarRef(IterationVar, SizeType);
9896   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9897
9898   // Create the DeclStmt that holds the iteration variable.
9899   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9900
9901   // Subscript the "from" and "to" expressions with the iteration variable.
9902   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9903   MoveCastBuilder FromIndexMove(FromIndexCopy);
9904   const ExprBuilder *FromIndex;
9905   if (Copying)
9906     FromIndex = &FromIndexCopy;
9907   else
9908     FromIndex = &FromIndexMove;
9909
9910   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9911
9912   // Build the copy/move for an individual element of the array.
9913   StmtResult Copy =
9914     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9915                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9916                                      Copying, Depth + 1);
9917   // Bail out if copying fails or if we determined that we should use memcpy.
9918   if (Copy.isInvalid() || !Copy.get())
9919     return Copy;
9920
9921   // Create the comparison against the array bound.
9922   llvm::APInt Upper
9923     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9924   Expr *Comparison
9925     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9926                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9927                                      BO_NE, S.Context.BoolTy,
9928                                      VK_RValue, OK_Ordinary, Loc, false);
9929
9930   // Create the pre-increment of the iteration variable.
9931   Expr *Increment
9932     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9933                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9934
9935   // Construct the loop that copies all elements of this array.
9936   return S.ActOnForStmt(Loc, Loc, InitStmt, 
9937                         S.MakeFullExpr(Comparison),
9938                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
9939                         Loc, Copy.get());
9940 }
9941
9942 static StmtResult
9943 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9944                       const ExprBuilder &To, const ExprBuilder &From,
9945                       bool CopyingBaseSubobject, bool Copying) {
9946   // Maybe we should use a memcpy?
9947   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9948       T.isTriviallyCopyableType(S.Context))
9949     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9950
9951   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9952                                                      CopyingBaseSubobject,
9953                                                      Copying, 0));
9954
9955   // If we ended up picking a trivial assignment operator for an array of a
9956   // non-trivially-copyable class type, just emit a memcpy.
9957   if (!Result.isInvalid() && !Result.get())
9958     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9959
9960   return Result;
9961 }
9962
9963 Sema::ImplicitExceptionSpecification
9964 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9965   CXXRecordDecl *ClassDecl = MD->getParent();
9966
9967   ImplicitExceptionSpecification ExceptSpec(*this);
9968   if (ClassDecl->isInvalidDecl())
9969     return ExceptSpec;
9970
9971   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9972   assert(T->getNumParams() == 1 && "not a copy assignment op");
9973   unsigned ArgQuals =
9974       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9975
9976   // C++ [except.spec]p14:
9977   //   An implicitly declared special member function (Clause 12) shall have an
9978   //   exception-specification. [...]
9979
9980   // It is unspecified whether or not an implicit copy assignment operator
9981   // attempts to deduplicate calls to assignment operators of virtual bases are
9982   // made. As such, this exception specification is effectively unspecified.
9983   // Based on a similar decision made for constness in C++0x, we're erring on
9984   // the side of assuming such calls to be made regardless of whether they
9985   // actually happen.
9986   for (const auto &Base : ClassDecl->bases()) {
9987     if (Base.isVirtual())
9988       continue;
9989
9990     CXXRecordDecl *BaseClassDecl
9991       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9992     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9993                                                             ArgQuals, false, 0))
9994       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9995   }
9996
9997   for (const auto &Base : ClassDecl->vbases()) {
9998     CXXRecordDecl *BaseClassDecl
9999       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10000     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10001                                                             ArgQuals, false, 0))
10002       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10003   }
10004
10005   for (const auto *Field : ClassDecl->fields()) {
10006     QualType FieldType = Context.getBaseElementType(Field->getType());
10007     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10008       if (CXXMethodDecl *CopyAssign =
10009           LookupCopyingAssignment(FieldClassDecl,
10010                                   ArgQuals | FieldType.getCVRQualifiers(),
10011                                   false, 0))
10012         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
10013     }
10014   }
10015
10016   return ExceptSpec;
10017 }
10018
10019 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10020   // Note: The following rules are largely analoguous to the copy
10021   // constructor rules. Note that virtual bases are not taken into account
10022   // for determining the argument type of the operator. Note also that
10023   // operators taking an object instead of a reference are allowed.
10024   assert(ClassDecl->needsImplicitCopyAssignment());
10025
10026   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10027   if (DSM.isAlreadyBeingDeclared())
10028     return nullptr;
10029
10030   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10031   QualType RetType = Context.getLValueReferenceType(ArgType);
10032   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10033   if (Const)
10034     ArgType = ArgType.withConst();
10035   ArgType = Context.getLValueReferenceType(ArgType);
10036
10037   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10038                                                      CXXCopyAssignment,
10039                                                      Const);
10040
10041   //   An implicitly-declared copy assignment operator is an inline public
10042   //   member of its class.
10043   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10044   SourceLocation ClassLoc = ClassDecl->getLocation();
10045   DeclarationNameInfo NameInfo(Name, ClassLoc);
10046   CXXMethodDecl *CopyAssignment =
10047       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10048                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10049                             /*isInline=*/true, Constexpr, SourceLocation());
10050   CopyAssignment->setAccess(AS_public);
10051   CopyAssignment->setDefaulted();
10052   CopyAssignment->setImplicit();
10053
10054   if (getLangOpts().CUDA) {
10055     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10056                                             CopyAssignment,
10057                                             /* ConstRHS */ Const,
10058                                             /* Diagnose */ false);
10059   }
10060
10061   // Build an exception specification pointing back at this member.
10062   FunctionProtoType::ExtProtoInfo EPI =
10063       getImplicitMethodEPI(*this, CopyAssignment);
10064   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10065
10066   // Add the parameter to the operator.
10067   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
10068                                                ClassLoc, ClassLoc,
10069                                                /*Id=*/nullptr, ArgType,
10070                                                /*TInfo=*/nullptr, SC_None,
10071                                                nullptr);
10072   CopyAssignment->setParams(FromParam);
10073
10074   AddOverriddenMethods(ClassDecl, CopyAssignment);
10075
10076   CopyAssignment->setTrivial(
10077     ClassDecl->needsOverloadResolutionForCopyAssignment()
10078       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10079       : ClassDecl->hasTrivialCopyAssignment());
10080
10081   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10082     SetDeclDeleted(CopyAssignment, ClassLoc);
10083
10084   // Note that we have added this copy-assignment operator.
10085   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10086
10087   if (Scope *S = getScopeForContext(ClassDecl))
10088     PushOnScopeChains(CopyAssignment, S, false);
10089   ClassDecl->addDecl(CopyAssignment);
10090
10091   return CopyAssignment;
10092 }
10093
10094 /// Diagnose an implicit copy operation for a class which is odr-used, but
10095 /// which is deprecated because the class has a user-declared copy constructor,
10096 /// copy assignment operator, or destructor.
10097 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10098                                             SourceLocation UseLoc) {
10099   assert(CopyOp->isImplicit());
10100
10101   CXXRecordDecl *RD = CopyOp->getParent();
10102   CXXMethodDecl *UserDeclaredOperation = nullptr;
10103
10104   // In Microsoft mode, assignment operations don't affect constructors and
10105   // vice versa.
10106   if (RD->hasUserDeclaredDestructor()) {
10107     UserDeclaredOperation = RD->getDestructor();
10108   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10109              RD->hasUserDeclaredCopyConstructor() &&
10110              !S.getLangOpts().MSVCCompat) {
10111     // Find any user-declared copy constructor.
10112     for (auto *I : RD->ctors()) {
10113       if (I->isCopyConstructor()) {
10114         UserDeclaredOperation = I;
10115         break;
10116       }
10117     }
10118     assert(UserDeclaredOperation);
10119   } else if (isa<CXXConstructorDecl>(CopyOp) &&
10120              RD->hasUserDeclaredCopyAssignment() &&
10121              !S.getLangOpts().MSVCCompat) {
10122     // Find any user-declared move assignment operator.
10123     for (auto *I : RD->methods()) {
10124       if (I->isCopyAssignmentOperator()) {
10125         UserDeclaredOperation = I;
10126         break;
10127       }
10128     }
10129     assert(UserDeclaredOperation);
10130   }
10131
10132   if (UserDeclaredOperation) {
10133     S.Diag(UserDeclaredOperation->getLocation(),
10134          diag::warn_deprecated_copy_operation)
10135       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10136       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10137     S.Diag(UseLoc, diag::note_member_synthesized_at)
10138       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10139                                           : Sema::CXXCopyAssignment)
10140       << RD;
10141   }
10142 }
10143
10144 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10145                                         CXXMethodDecl *CopyAssignOperator) {
10146   assert((CopyAssignOperator->isDefaulted() && 
10147           CopyAssignOperator->isOverloadedOperator() &&
10148           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
10149           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10150           !CopyAssignOperator->isDeleted()) &&
10151          "DefineImplicitCopyAssignment called for wrong function");
10152
10153   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10154
10155   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10156     CopyAssignOperator->setInvalidDecl();
10157     return;
10158   }
10159
10160   // C++11 [class.copy]p18:
10161   //   The [definition of an implicitly declared copy assignment operator] is
10162   //   deprecated if the class has a user-declared copy constructor or a
10163   //   user-declared destructor.
10164   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10165     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10166
10167   CopyAssignOperator->markUsed(Context);
10168
10169   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
10170   DiagnosticErrorTrap Trap(Diags);
10171
10172   // C++0x [class.copy]p30:
10173   //   The implicitly-defined or explicitly-defaulted copy assignment operator
10174   //   for a non-union class X performs memberwise copy assignment of its 
10175   //   subobjects. The direct base classes of X are assigned first, in the 
10176   //   order of their declaration in the base-specifier-list, and then the 
10177   //   immediate non-static data members of X are assigned, in the order in 
10178   //   which they were declared in the class definition.
10179   
10180   // The statements that form the synthesized function body.
10181   SmallVector<Stmt*, 8> Statements;
10182   
10183   // The parameter for the "other" object, which we are copying from.
10184   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10185   Qualifiers OtherQuals = Other->getType().getQualifiers();
10186   QualType OtherRefType = Other->getType();
10187   if (const LValueReferenceType *OtherRef
10188                                 = OtherRefType->getAs<LValueReferenceType>()) {
10189     OtherRefType = OtherRef->getPointeeType();
10190     OtherQuals = OtherRefType.getQualifiers();
10191   }
10192   
10193   // Our location for everything implicitly-generated.
10194   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10195                            ? CopyAssignOperator->getLocEnd()
10196                            : CopyAssignOperator->getLocation();
10197
10198   // Builds a DeclRefExpr for the "other" object.
10199   RefBuilder OtherRef(Other, OtherRefType);
10200
10201   // Builds the "this" pointer.
10202   ThisBuilder This;
10203   
10204   // Assign base classes.
10205   bool Invalid = false;
10206   for (auto &Base : ClassDecl->bases()) {
10207     // Form the assignment:
10208     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
10209     QualType BaseType = Base.getType().getUnqualifiedType();
10210     if (!BaseType->isRecordType()) {
10211       Invalid = true;
10212       continue;
10213     }
10214
10215     CXXCastPath BasePath;
10216     BasePath.push_back(&Base);
10217
10218     // Construct the "from" expression, which is an implicit cast to the
10219     // appropriately-qualified base type.
10220     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10221                      VK_LValue, BasePath);
10222
10223     // Dereference "this".
10224     DerefBuilder DerefThis(This);
10225     CastBuilder To(DerefThis,
10226                    Context.getCVRQualifiedType(
10227                        BaseType, CopyAssignOperator->getTypeQualifiers()),
10228                    VK_LValue, BasePath);
10229
10230     // Build the copy.
10231     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
10232                                             To, From,
10233                                             /*CopyingBaseSubobject=*/true,
10234                                             /*Copying=*/true);
10235     if (Copy.isInvalid()) {
10236       Diag(CurrentLocation, diag::note_member_synthesized_at) 
10237         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10238       CopyAssignOperator->setInvalidDecl();
10239       return;
10240     }
10241     
10242     // Success! Record the copy.
10243     Statements.push_back(Copy.getAs<Expr>());
10244   }
10245   
10246   // Assign non-static members.
10247   for (auto *Field : ClassDecl->fields()) {
10248     // FIXME: We should form some kind of AST representation for the implied
10249     // memcpy in a union copy operation.
10250     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10251       continue;
10252
10253     if (Field->isInvalidDecl()) {
10254       Invalid = true;
10255       continue;
10256     }
10257
10258     // Check for members of reference type; we can't copy those.
10259     if (Field->getType()->isReferenceType()) {
10260       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10261         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10262       Diag(Field->getLocation(), diag::note_declared_at);
10263       Diag(CurrentLocation, diag::note_member_synthesized_at) 
10264         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10265       Invalid = true;
10266       continue;
10267     }
10268     
10269     // Check for members of const-qualified, non-class type.
10270     QualType BaseType = Context.getBaseElementType(Field->getType());
10271     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10272       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10273         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10274       Diag(Field->getLocation(), diag::note_declared_at);
10275       Diag(CurrentLocation, diag::note_member_synthesized_at) 
10276         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10277       Invalid = true;      
10278       continue;
10279     }
10280
10281     // Suppress assigning zero-width bitfields.
10282     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10283       continue;
10284     
10285     QualType FieldType = Field->getType().getNonReferenceType();
10286     if (FieldType->isIncompleteArrayType()) {
10287       assert(ClassDecl->hasFlexibleArrayMember() && 
10288              "Incomplete array type is not valid");
10289       continue;
10290     }
10291     
10292     // Build references to the field in the object we're copying from and to.
10293     CXXScopeSpec SS; // Intentionally empty
10294     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10295                               LookupMemberName);
10296     MemberLookup.addDecl(Field);
10297     MemberLookup.resolveKind();
10298
10299     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10300
10301     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
10302
10303     // Build the copy of this field.
10304     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
10305                                             To, From,
10306                                             /*CopyingBaseSubobject=*/false,
10307                                             /*Copying=*/true);
10308     if (Copy.isInvalid()) {
10309       Diag(CurrentLocation, diag::note_member_synthesized_at) 
10310         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10311       CopyAssignOperator->setInvalidDecl();
10312       return;
10313     }
10314     
10315     // Success! Record the copy.
10316     Statements.push_back(Copy.getAs<Stmt>());
10317   }
10318
10319   if (!Invalid) {
10320     // Add a "return *this;"
10321     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10322     
10323     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10324     if (Return.isInvalid())
10325       Invalid = true;
10326     else {
10327       Statements.push_back(Return.getAs<Stmt>());
10328
10329       if (Trap.hasErrorOccurred()) {
10330         Diag(CurrentLocation, diag::note_member_synthesized_at) 
10331           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10332         Invalid = true;
10333       }
10334     }
10335   }
10336
10337   // The exception specification is needed because we are defining the
10338   // function.
10339   ResolveExceptionSpec(CurrentLocation,
10340                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10341
10342   if (Invalid) {
10343     CopyAssignOperator->setInvalidDecl();
10344     return;
10345   }
10346
10347   StmtResult Body;
10348   {
10349     CompoundScopeRAII CompoundScope(*this);
10350     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10351                              /*isStmtExpr=*/false);
10352     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10353   }
10354   CopyAssignOperator->setBody(Body.getAs<Stmt>());
10355
10356   if (ASTMutationListener *L = getASTMutationListener()) {
10357     L->CompletedImplicitDefinition(CopyAssignOperator);
10358   }
10359 }
10360
10361 Sema::ImplicitExceptionSpecification
10362 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10363   CXXRecordDecl *ClassDecl = MD->getParent();
10364
10365   ImplicitExceptionSpecification ExceptSpec(*this);
10366   if (ClassDecl->isInvalidDecl())
10367     return ExceptSpec;
10368
10369   // C++0x [except.spec]p14:
10370   //   An implicitly declared special member function (Clause 12) shall have an 
10371   //   exception-specification. [...]
10372
10373   // It is unspecified whether or not an implicit move assignment operator
10374   // attempts to deduplicate calls to assignment operators of virtual bases are
10375   // made. As such, this exception specification is effectively unspecified.
10376   // Based on a similar decision made for constness in C++0x, we're erring on
10377   // the side of assuming such calls to be made regardless of whether they
10378   // actually happen.
10379   // Note that a move constructor is not implicitly declared when there are
10380   // virtual bases, but it can still be user-declared and explicitly defaulted.
10381   for (const auto &Base : ClassDecl->bases()) {
10382     if (Base.isVirtual())
10383       continue;
10384
10385     CXXRecordDecl *BaseClassDecl
10386       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10387     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10388                                                            0, false, 0))
10389       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10390   }
10391
10392   for (const auto &Base : ClassDecl->vbases()) {
10393     CXXRecordDecl *BaseClassDecl
10394       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10395     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10396                                                            0, false, 0))
10397       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10398   }
10399
10400   for (const auto *Field : ClassDecl->fields()) {
10401     QualType FieldType = Context.getBaseElementType(Field->getType());
10402     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10403       if (CXXMethodDecl *MoveAssign =
10404               LookupMovingAssignment(FieldClassDecl,
10405                                      FieldType.getCVRQualifiers(),
10406                                      false, 0))
10407         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10408     }
10409   }
10410
10411   return ExceptSpec;
10412 }
10413
10414 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
10415   assert(ClassDecl->needsImplicitMoveAssignment());
10416
10417   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10418   if (DSM.isAlreadyBeingDeclared())
10419     return nullptr;
10420
10421   // Note: The following rules are largely analoguous to the move
10422   // constructor rules.
10423
10424   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10425   QualType RetType = Context.getLValueReferenceType(ArgType);
10426   ArgType = Context.getRValueReferenceType(ArgType);
10427
10428   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10429                                                      CXXMoveAssignment,
10430                                                      false);
10431
10432   //   An implicitly-declared move assignment operator is an inline public
10433   //   member of its class.
10434   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10435   SourceLocation ClassLoc = ClassDecl->getLocation();
10436   DeclarationNameInfo NameInfo(Name, ClassLoc);
10437   CXXMethodDecl *MoveAssignment =
10438       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10439                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10440                             /*isInline=*/true, Constexpr, SourceLocation());
10441   MoveAssignment->setAccess(AS_public);
10442   MoveAssignment->setDefaulted();
10443   MoveAssignment->setImplicit();
10444
10445   if (getLangOpts().CUDA) {
10446     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10447                                             MoveAssignment,
10448                                             /* ConstRHS */ false,
10449                                             /* Diagnose */ false);
10450   }
10451
10452   // Build an exception specification pointing back at this member.
10453   FunctionProtoType::ExtProtoInfo EPI =
10454       getImplicitMethodEPI(*this, MoveAssignment);
10455   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10456
10457   // Add the parameter to the operator.
10458   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10459                                                ClassLoc, ClassLoc,
10460                                                /*Id=*/nullptr, ArgType,
10461                                                /*TInfo=*/nullptr, SC_None,
10462                                                nullptr);
10463   MoveAssignment->setParams(FromParam);
10464
10465   AddOverriddenMethods(ClassDecl, MoveAssignment);
10466
10467   MoveAssignment->setTrivial(
10468     ClassDecl->needsOverloadResolutionForMoveAssignment()
10469       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10470       : ClassDecl->hasTrivialMoveAssignment());
10471
10472   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10473     ClassDecl->setImplicitMoveAssignmentIsDeleted();
10474     SetDeclDeleted(MoveAssignment, ClassLoc);
10475   }
10476
10477   // Note that we have added this copy-assignment operator.
10478   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10479
10480   if (Scope *S = getScopeForContext(ClassDecl))
10481     PushOnScopeChains(MoveAssignment, S, false);
10482   ClassDecl->addDecl(MoveAssignment);
10483
10484   return MoveAssignment;
10485 }
10486
10487 /// Check if we're implicitly defining a move assignment operator for a class
10488 /// with virtual bases. Such a move assignment might move-assign the virtual
10489 /// base multiple times.
10490 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10491                                                SourceLocation CurrentLocation) {
10492   assert(!Class->isDependentContext() && "should not define dependent move");
10493
10494   // Only a virtual base could get implicitly move-assigned multiple times.
10495   // Only a non-trivial move assignment can observe this. We only want to
10496   // diagnose if we implicitly define an assignment operator that assigns
10497   // two base classes, both of which move-assign the same virtual base.
10498   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10499       Class->getNumBases() < 2)
10500     return;
10501
10502   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10503   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10504   VBaseMap VBases;
10505
10506   for (auto &BI : Class->bases()) {
10507     Worklist.push_back(&BI);
10508     while (!Worklist.empty()) {
10509       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10510       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10511
10512       // If the base has no non-trivial move assignment operators,
10513       // we don't care about moves from it.
10514       if (!Base->hasNonTrivialMoveAssignment())
10515         continue;
10516
10517       // If there's nothing virtual here, skip it.
10518       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10519         continue;
10520
10521       // If we're not actually going to call a move assignment for this base,
10522       // or the selected move assignment is trivial, skip it.
10523       Sema::SpecialMemberOverloadResult *SMOR =
10524         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10525                               /*ConstArg*/false, /*VolatileArg*/false,
10526                               /*RValueThis*/true, /*ConstThis*/false,
10527                               /*VolatileThis*/false);
10528       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10529           !SMOR->getMethod()->isMoveAssignmentOperator())
10530         continue;
10531
10532       if (BaseSpec->isVirtual()) {
10533         // We're going to move-assign this virtual base, and its move
10534         // assignment operator is not trivial. If this can happen for
10535         // multiple distinct direct bases of Class, diagnose it. (If it
10536         // only happens in one base, we'll diagnose it when synthesizing
10537         // that base class's move assignment operator.)
10538         CXXBaseSpecifier *&Existing =
10539             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10540                 .first->second;
10541         if (Existing && Existing != &BI) {
10542           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10543             << Class << Base;
10544           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10545             << (Base->getCanonicalDecl() ==
10546                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10547             << Base << Existing->getType() << Existing->getSourceRange();
10548           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10549             << (Base->getCanonicalDecl() ==
10550                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10551             << Base << BI.getType() << BaseSpec->getSourceRange();
10552
10553           // Only diagnose each vbase once.
10554           Existing = nullptr;
10555         }
10556       } else {
10557         // Only walk over bases that have defaulted move assignment operators.
10558         // We assume that any user-provided move assignment operator handles
10559         // the multiple-moves-of-vbase case itself somehow.
10560         if (!SMOR->getMethod()->isDefaulted())
10561           continue;
10562
10563         // We're going to move the base classes of Base. Add them to the list.
10564         for (auto &BI : Base->bases())
10565           Worklist.push_back(&BI);
10566       }
10567     }
10568   }
10569 }
10570
10571 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10572                                         CXXMethodDecl *MoveAssignOperator) {
10573   assert((MoveAssignOperator->isDefaulted() && 
10574           MoveAssignOperator->isOverloadedOperator() &&
10575           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10576           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10577           !MoveAssignOperator->isDeleted()) &&
10578          "DefineImplicitMoveAssignment called for wrong function");
10579
10580   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10581
10582   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10583     MoveAssignOperator->setInvalidDecl();
10584     return;
10585   }
10586   
10587   MoveAssignOperator->markUsed(Context);
10588
10589   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10590   DiagnosticErrorTrap Trap(Diags);
10591
10592   // C++0x [class.copy]p28:
10593   //   The implicitly-defined or move assignment operator for a non-union class
10594   //   X performs memberwise move assignment of its subobjects. The direct base
10595   //   classes of X are assigned first, in the order of their declaration in the
10596   //   base-specifier-list, and then the immediate non-static data members of X
10597   //   are assigned, in the order in which they were declared in the class
10598   //   definition.
10599
10600   // Issue a warning if our implicit move assignment operator will move
10601   // from a virtual base more than once.
10602   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10603
10604   // The statements that form the synthesized function body.
10605   SmallVector<Stmt*, 8> Statements;
10606
10607   // The parameter for the "other" object, which we are move from.
10608   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10609   QualType OtherRefType = Other->getType()->
10610       getAs<RValueReferenceType>()->getPointeeType();
10611   assert(!OtherRefType.getQualifiers() &&
10612          "Bad argument type of defaulted move assignment");
10613
10614   // Our location for everything implicitly-generated.
10615   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10616                            ? MoveAssignOperator->getLocEnd()
10617                            : MoveAssignOperator->getLocation();
10618
10619   // Builds a reference to the "other" object.
10620   RefBuilder OtherRef(Other, OtherRefType);
10621   // Cast to rvalue.
10622   MoveCastBuilder MoveOther(OtherRef);
10623
10624   // Builds the "this" pointer.
10625   ThisBuilder This;
10626
10627   // Assign base classes.
10628   bool Invalid = false;
10629   for (auto &Base : ClassDecl->bases()) {
10630     // C++11 [class.copy]p28:
10631     //   It is unspecified whether subobjects representing virtual base classes
10632     //   are assigned more than once by the implicitly-defined copy assignment
10633     //   operator.
10634     // FIXME: Do not assign to a vbase that will be assigned by some other base
10635     // class. For a move-assignment, this can result in the vbase being moved
10636     // multiple times.
10637
10638     // Form the assignment:
10639     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10640     QualType BaseType = Base.getType().getUnqualifiedType();
10641     if (!BaseType->isRecordType()) {
10642       Invalid = true;
10643       continue;
10644     }
10645
10646     CXXCastPath BasePath;
10647     BasePath.push_back(&Base);
10648
10649     // Construct the "from" expression, which is an implicit cast to the
10650     // appropriately-qualified base type.
10651     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10652
10653     // Dereference "this".
10654     DerefBuilder DerefThis(This);
10655
10656     // Implicitly cast "this" to the appropriately-qualified base type.
10657     CastBuilder To(DerefThis,
10658                    Context.getCVRQualifiedType(
10659                        BaseType, MoveAssignOperator->getTypeQualifiers()),
10660                    VK_LValue, BasePath);
10661
10662     // Build the move.
10663     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10664                                             To, From,
10665                                             /*CopyingBaseSubobject=*/true,
10666                                             /*Copying=*/false);
10667     if (Move.isInvalid()) {
10668       Diag(CurrentLocation, diag::note_member_synthesized_at) 
10669         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10670       MoveAssignOperator->setInvalidDecl();
10671       return;
10672     }
10673
10674     // Success! Record the move.
10675     Statements.push_back(Move.getAs<Expr>());
10676   }
10677
10678   // Assign non-static members.
10679   for (auto *Field : ClassDecl->fields()) {
10680     // FIXME: We should form some kind of AST representation for the implied
10681     // memcpy in a union copy operation.
10682     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10683       continue;
10684
10685     if (Field->isInvalidDecl()) {
10686       Invalid = true;
10687       continue;
10688     }
10689
10690     // Check for members of reference type; we can't move those.
10691     if (Field->getType()->isReferenceType()) {
10692       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10693         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10694       Diag(Field->getLocation(), diag::note_declared_at);
10695       Diag(CurrentLocation, diag::note_member_synthesized_at) 
10696         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10697       Invalid = true;
10698       continue;
10699     }
10700
10701     // Check for members of const-qualified, non-class type.
10702     QualType BaseType = Context.getBaseElementType(Field->getType());
10703     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10704       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10705         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10706       Diag(Field->getLocation(), diag::note_declared_at);
10707       Diag(CurrentLocation, diag::note_member_synthesized_at) 
10708         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10709       Invalid = true;      
10710       continue;
10711     }
10712
10713     // Suppress assigning zero-width bitfields.
10714     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10715       continue;
10716     
10717     QualType FieldType = Field->getType().getNonReferenceType();
10718     if (FieldType->isIncompleteArrayType()) {
10719       assert(ClassDecl->hasFlexibleArrayMember() && 
10720              "Incomplete array type is not valid");
10721       continue;
10722     }
10723     
10724     // Build references to the field in the object we're copying from and to.
10725     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10726                               LookupMemberName);
10727     MemberLookup.addDecl(Field);
10728     MemberLookup.resolveKind();
10729     MemberBuilder From(MoveOther, OtherRefType,
10730                        /*IsArrow=*/false, MemberLookup);
10731     MemberBuilder To(This, getCurrentThisType(),
10732                      /*IsArrow=*/true, MemberLookup);
10733
10734     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10735         "Member reference with rvalue base must be rvalue except for reference "
10736         "members, which aren't allowed for move assignment.");
10737
10738     // Build the move of this field.
10739     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10740                                             To, From,
10741                                             /*CopyingBaseSubobject=*/false,
10742                                             /*Copying=*/false);
10743     if (Move.isInvalid()) {
10744       Diag(CurrentLocation, diag::note_member_synthesized_at) 
10745         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10746       MoveAssignOperator->setInvalidDecl();
10747       return;
10748     }
10749
10750     // Success! Record the copy.
10751     Statements.push_back(Move.getAs<Stmt>());
10752   }
10753
10754   if (!Invalid) {
10755     // Add a "return *this;"
10756     ExprResult ThisObj =
10757         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10758
10759     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10760     if (Return.isInvalid())
10761       Invalid = true;
10762     else {
10763       Statements.push_back(Return.getAs<Stmt>());
10764
10765       if (Trap.hasErrorOccurred()) {
10766         Diag(CurrentLocation, diag::note_member_synthesized_at) 
10767           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10768         Invalid = true;
10769       }
10770     }
10771   }
10772
10773   // The exception specification is needed because we are defining the
10774   // function.
10775   ResolveExceptionSpec(CurrentLocation,
10776                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10777
10778   if (Invalid) {
10779     MoveAssignOperator->setInvalidDecl();
10780     return;
10781   }
10782
10783   StmtResult Body;
10784   {
10785     CompoundScopeRAII CompoundScope(*this);
10786     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10787                              /*isStmtExpr=*/false);
10788     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10789   }
10790   MoveAssignOperator->setBody(Body.getAs<Stmt>());
10791
10792   if (ASTMutationListener *L = getASTMutationListener()) {
10793     L->CompletedImplicitDefinition(MoveAssignOperator);
10794   }
10795 }
10796
10797 Sema::ImplicitExceptionSpecification
10798 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10799   CXXRecordDecl *ClassDecl = MD->getParent();
10800
10801   ImplicitExceptionSpecification ExceptSpec(*this);
10802   if (ClassDecl->isInvalidDecl())
10803     return ExceptSpec;
10804
10805   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10806   assert(T->getNumParams() >= 1 && "not a copy ctor");
10807   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10808
10809   // C++ [except.spec]p14:
10810   //   An implicitly declared special member function (Clause 12) shall have an 
10811   //   exception-specification. [...]
10812   for (const auto &Base : ClassDecl->bases()) {
10813     // Virtual bases are handled below.
10814     if (Base.isVirtual())
10815       continue;
10816     
10817     CXXRecordDecl *BaseClassDecl
10818       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10819     if (CXXConstructorDecl *CopyConstructor =
10820           LookupCopyingConstructor(BaseClassDecl, Quals))
10821       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10822   }
10823   for (const auto &Base : ClassDecl->vbases()) {
10824     CXXRecordDecl *BaseClassDecl
10825       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10826     if (CXXConstructorDecl *CopyConstructor =
10827           LookupCopyingConstructor(BaseClassDecl, Quals))
10828       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10829   }
10830   for (const auto *Field : ClassDecl->fields()) {
10831     QualType FieldType = Context.getBaseElementType(Field->getType());
10832     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10833       if (CXXConstructorDecl *CopyConstructor =
10834               LookupCopyingConstructor(FieldClassDecl,
10835                                        Quals | FieldType.getCVRQualifiers()))
10836       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10837     }
10838   }
10839
10840   return ExceptSpec;
10841 }
10842
10843 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10844                                                     CXXRecordDecl *ClassDecl) {
10845   // C++ [class.copy]p4:
10846   //   If the class definition does not explicitly declare a copy
10847   //   constructor, one is declared implicitly.
10848   assert(ClassDecl->needsImplicitCopyConstructor());
10849
10850   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10851   if (DSM.isAlreadyBeingDeclared())
10852     return nullptr;
10853
10854   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10855   QualType ArgType = ClassType;
10856   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10857   if (Const)
10858     ArgType = ArgType.withConst();
10859   ArgType = Context.getLValueReferenceType(ArgType);
10860
10861   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10862                                                      CXXCopyConstructor,
10863                                                      Const);
10864
10865   DeclarationName Name
10866     = Context.DeclarationNames.getCXXConstructorName(
10867                                            Context.getCanonicalType(ClassType));
10868   SourceLocation ClassLoc = ClassDecl->getLocation();
10869   DeclarationNameInfo NameInfo(Name, ClassLoc);
10870
10871   //   An implicitly-declared copy constructor is an inline public
10872   //   member of its class.
10873   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10874       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10875       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10876       Constexpr);
10877   CopyConstructor->setAccess(AS_public);
10878   CopyConstructor->setDefaulted();
10879
10880   if (getLangOpts().CUDA) {
10881     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10882                                             CopyConstructor,
10883                                             /* ConstRHS */ Const,
10884                                             /* Diagnose */ false);
10885   }
10886
10887   // Build an exception specification pointing back at this member.
10888   FunctionProtoType::ExtProtoInfo EPI =
10889       getImplicitMethodEPI(*this, CopyConstructor);
10890   CopyConstructor->setType(
10891       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10892
10893   // Add the parameter to the constructor.
10894   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10895                                                ClassLoc, ClassLoc,
10896                                                /*IdentifierInfo=*/nullptr,
10897                                                ArgType, /*TInfo=*/nullptr,
10898                                                SC_None, nullptr);
10899   CopyConstructor->setParams(FromParam);
10900
10901   CopyConstructor->setTrivial(
10902     ClassDecl->needsOverloadResolutionForCopyConstructor()
10903       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10904       : ClassDecl->hasTrivialCopyConstructor());
10905
10906   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10907     SetDeclDeleted(CopyConstructor, ClassLoc);
10908
10909   // Note that we have declared this constructor.
10910   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10911
10912   if (Scope *S = getScopeForContext(ClassDecl))
10913     PushOnScopeChains(CopyConstructor, S, false);
10914   ClassDecl->addDecl(CopyConstructor);
10915
10916   return CopyConstructor;
10917 }
10918
10919 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10920                                    CXXConstructorDecl *CopyConstructor) {
10921   assert((CopyConstructor->isDefaulted() &&
10922           CopyConstructor->isCopyConstructor() &&
10923           !CopyConstructor->doesThisDeclarationHaveABody() &&
10924           !CopyConstructor->isDeleted()) &&
10925          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10926
10927   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10928   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10929
10930   // C++11 [class.copy]p7:
10931   //   The [definition of an implicitly declared copy constructor] is
10932   //   deprecated if the class has a user-declared copy assignment operator
10933   //   or a user-declared destructor.
10934   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10935     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10936
10937   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10938   DiagnosticErrorTrap Trap(Diags);
10939
10940   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10941       Trap.hasErrorOccurred()) {
10942     Diag(CurrentLocation, diag::note_member_synthesized_at) 
10943       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10944     CopyConstructor->setInvalidDecl();
10945   }  else {
10946     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10947                              ? CopyConstructor->getLocEnd()
10948                              : CopyConstructor->getLocation();
10949     Sema::CompoundScopeRAII CompoundScope(*this);
10950     CopyConstructor->setBody(
10951         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10952   }
10953
10954   // The exception specification is needed because we are defining the
10955   // function.
10956   ResolveExceptionSpec(CurrentLocation,
10957                        CopyConstructor->getType()->castAs<FunctionProtoType>());
10958
10959   CopyConstructor->markUsed(Context);
10960   MarkVTableUsed(CurrentLocation, ClassDecl);
10961
10962   if (ASTMutationListener *L = getASTMutationListener()) {
10963     L->CompletedImplicitDefinition(CopyConstructor);
10964   }
10965 }
10966
10967 Sema::ImplicitExceptionSpecification
10968 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10969   CXXRecordDecl *ClassDecl = MD->getParent();
10970
10971   // C++ [except.spec]p14:
10972   //   An implicitly declared special member function (Clause 12) shall have an 
10973   //   exception-specification. [...]
10974   ImplicitExceptionSpecification ExceptSpec(*this);
10975   if (ClassDecl->isInvalidDecl())
10976     return ExceptSpec;
10977
10978   // Direct base-class constructors.
10979   for (const auto &B : ClassDecl->bases()) {
10980     if (B.isVirtual()) // Handled below.
10981       continue;
10982     
10983     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10984       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10985       CXXConstructorDecl *Constructor =
10986           LookupMovingConstructor(BaseClassDecl, 0);
10987       // If this is a deleted function, add it anyway. This might be conformant
10988       // with the standard. This might not. I'm not sure. It might not matter.
10989       if (Constructor)
10990         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10991     }
10992   }
10993
10994   // Virtual base-class constructors.
10995   for (const auto &B : ClassDecl->vbases()) {
10996     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10997       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10998       CXXConstructorDecl *Constructor =
10999           LookupMovingConstructor(BaseClassDecl, 0);
11000       // If this is a deleted function, add it anyway. This might be conformant
11001       // with the standard. This might not. I'm not sure. It might not matter.
11002       if (Constructor)
11003         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11004     }
11005   }
11006
11007   // Field constructors.
11008   for (const auto *F : ClassDecl->fields()) {
11009     QualType FieldType = Context.getBaseElementType(F->getType());
11010     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11011       CXXConstructorDecl *Constructor =
11012           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
11013       // If this is a deleted function, add it anyway. This might be conformant
11014       // with the standard. This might not. I'm not sure. It might not matter.
11015       // In particular, the problem is that this function never gets called. It
11016       // might just be ill-formed because this function attempts to refer to
11017       // a deleted function here.
11018       if (Constructor)
11019         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
11020     }
11021   }
11022
11023   return ExceptSpec;
11024 }
11025
11026 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11027                                                     CXXRecordDecl *ClassDecl) {
11028   assert(ClassDecl->needsImplicitMoveConstructor());
11029
11030   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11031   if (DSM.isAlreadyBeingDeclared())
11032     return nullptr;
11033
11034   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11035   QualType ArgType = Context.getRValueReferenceType(ClassType);
11036
11037   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11038                                                      CXXMoveConstructor,
11039                                                      false);
11040
11041   DeclarationName Name
11042     = Context.DeclarationNames.getCXXConstructorName(
11043                                            Context.getCanonicalType(ClassType));
11044   SourceLocation ClassLoc = ClassDecl->getLocation();
11045   DeclarationNameInfo NameInfo(Name, ClassLoc);
11046
11047   // C++11 [class.copy]p11:
11048   //   An implicitly-declared copy/move constructor is an inline public
11049   //   member of its class.
11050   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
11051       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11052       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11053       Constexpr);
11054   MoveConstructor->setAccess(AS_public);
11055   MoveConstructor->setDefaulted();
11056
11057   if (getLangOpts().CUDA) {
11058     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11059                                             MoveConstructor,
11060                                             /* ConstRHS */ false,
11061                                             /* Diagnose */ false);
11062   }
11063
11064   // Build an exception specification pointing back at this member.
11065   FunctionProtoType::ExtProtoInfo EPI =
11066       getImplicitMethodEPI(*this, MoveConstructor);
11067   MoveConstructor->setType(
11068       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11069
11070   // Add the parameter to the constructor.
11071   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11072                                                ClassLoc, ClassLoc,
11073                                                /*IdentifierInfo=*/nullptr,
11074                                                ArgType, /*TInfo=*/nullptr,
11075                                                SC_None, nullptr);
11076   MoveConstructor->setParams(FromParam);
11077
11078   MoveConstructor->setTrivial(
11079     ClassDecl->needsOverloadResolutionForMoveConstructor()
11080       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11081       : ClassDecl->hasTrivialMoveConstructor());
11082
11083   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
11084     ClassDecl->setImplicitMoveConstructorIsDeleted();
11085     SetDeclDeleted(MoveConstructor, ClassLoc);
11086   }
11087
11088   // Note that we have declared this constructor.
11089   ++ASTContext::NumImplicitMoveConstructorsDeclared;
11090
11091   if (Scope *S = getScopeForContext(ClassDecl))
11092     PushOnScopeChains(MoveConstructor, S, false);
11093   ClassDecl->addDecl(MoveConstructor);
11094
11095   return MoveConstructor;
11096 }
11097
11098 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11099                                    CXXConstructorDecl *MoveConstructor) {
11100   assert((MoveConstructor->isDefaulted() &&
11101           MoveConstructor->isMoveConstructor() &&
11102           !MoveConstructor->doesThisDeclarationHaveABody() &&
11103           !MoveConstructor->isDeleted()) &&
11104          "DefineImplicitMoveConstructor - call it for implicit move ctor");
11105
11106   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11107   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11108
11109   SynthesizedFunctionScope Scope(*this, MoveConstructor);
11110   DiagnosticErrorTrap Trap(Diags);
11111
11112   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
11113       Trap.hasErrorOccurred()) {
11114     Diag(CurrentLocation, diag::note_member_synthesized_at) 
11115       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11116     MoveConstructor->setInvalidDecl();
11117   }  else {
11118     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11119                              ? MoveConstructor->getLocEnd()
11120                              : MoveConstructor->getLocation();
11121     Sema::CompoundScopeRAII CompoundScope(*this);
11122     MoveConstructor->setBody(ActOnCompoundStmt(
11123         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
11124   }
11125
11126   // The exception specification is needed because we are defining the
11127   // function.
11128   ResolveExceptionSpec(CurrentLocation,
11129                        MoveConstructor->getType()->castAs<FunctionProtoType>());
11130
11131   MoveConstructor->markUsed(Context);
11132   MarkVTableUsed(CurrentLocation, ClassDecl);
11133
11134   if (ASTMutationListener *L = getASTMutationListener()) {
11135     L->CompletedImplicitDefinition(MoveConstructor);
11136   }
11137 }
11138
11139 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
11140   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
11141 }
11142
11143 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
11144                             SourceLocation CurrentLocation,
11145                             CXXConversionDecl *Conv) {
11146   CXXRecordDecl *Lambda = Conv->getParent();
11147   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11148   // If we are defining a specialization of a conversion to function-ptr
11149   // cache the deduced template arguments for this specialization
11150   // so that we can use them to retrieve the corresponding call-operator
11151   // and static-invoker. 
11152   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11153
11154   // Retrieve the corresponding call-operator specialization.
11155   if (Lambda->isGenericLambda()) {
11156     assert(Conv->isFunctionTemplateSpecialization());
11157     FunctionTemplateDecl *CallOpTemplate = 
11158         CallOp->getDescribedFunctionTemplate();
11159     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
11160     void *InsertPos = nullptr;
11161     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
11162                                                 DeducedTemplateArgs->asArray(),
11163                                                 InsertPos);
11164     assert(CallOpSpec && 
11165           "Conversion operator must have a corresponding call operator");
11166     CallOp = cast<CXXMethodDecl>(CallOpSpec);
11167   }
11168   // Mark the call operator referenced (and add to pending instantiations
11169   // if necessary).
11170   // For both the conversion and static-invoker template specializations
11171   // we construct their body's in this function, so no need to add them
11172   // to the PendingInstantiations.
11173   MarkFunctionReferenced(CurrentLocation, CallOp);
11174
11175   SynthesizedFunctionScope Scope(*this, Conv);
11176   DiagnosticErrorTrap Trap(Diags);
11177    
11178   // Retrieve the static invoker...
11179   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11180   // ... and get the corresponding specialization for a generic lambda.
11181   if (Lambda->isGenericLambda()) {
11182     assert(DeducedTemplateArgs && 
11183       "Must have deduced template arguments from Conversion Operator");
11184     FunctionTemplateDecl *InvokeTemplate = 
11185                           Invoker->getDescribedFunctionTemplate();
11186     void *InsertPos = nullptr;
11187     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
11188                                                 DeducedTemplateArgs->asArray(),
11189                                                 InsertPos);
11190     assert(InvokeSpec && 
11191       "Must have a corresponding static invoker specialization");
11192     Invoker = cast<CXXMethodDecl>(InvokeSpec);
11193   }
11194   // Construct the body of the conversion function { return __invoke; }.
11195   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
11196                                         VK_LValue, Conv->getLocation()).get();
11197    assert(FunctionRef && "Can't refer to __invoke function?");
11198    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
11199    Conv->setBody(new (Context) CompoundStmt(Context, Return,
11200                                             Conv->getLocation(),
11201                                             Conv->getLocation()));
11202
11203   Conv->markUsed(Context);
11204   Conv->setReferenced();
11205   
11206   // Fill in the __invoke function with a dummy implementation. IR generation
11207   // will fill in the actual details.
11208   Invoker->markUsed(Context);
11209   Invoker->setReferenced();
11210   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11211    
11212   if (ASTMutationListener *L = getASTMutationListener()) {
11213     L->CompletedImplicitDefinition(Conv);
11214     L->CompletedImplicitDefinition(Invoker);
11215    }
11216 }
11217
11218
11219
11220 void Sema::DefineImplicitLambdaToBlockPointerConversion(
11221        SourceLocation CurrentLocation,
11222        CXXConversionDecl *Conv) 
11223 {
11224   assert(!Conv->getParent()->isGenericLambda());
11225
11226   Conv->markUsed(Context);
11227   
11228   SynthesizedFunctionScope Scope(*this, Conv);
11229   DiagnosticErrorTrap Trap(Diags);
11230   
11231   // Copy-initialize the lambda object as needed to capture it.
11232   Expr *This = ActOnCXXThis(CurrentLocation).get();
11233   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
11234   
11235   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11236                                                         Conv->getLocation(),
11237                                                         Conv, DerefThis);
11238
11239   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11240   // behavior.  Note that only the general conversion function does this
11241   // (since it's unusable otherwise); in the case where we inline the
11242   // block literal, it has block literal lifetime semantics.
11243   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
11244     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11245                                           CK_CopyAndAutoreleaseBlockObject,
11246                                           BuildBlock.get(), nullptr, VK_RValue);
11247
11248   if (BuildBlock.isInvalid()) {
11249     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11250     Conv->setInvalidDecl();
11251     return;
11252   }
11253
11254   // Create the return statement that returns the block from the conversion
11255   // function.
11256   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
11257   if (Return.isInvalid()) {
11258     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11259     Conv->setInvalidDecl();
11260     return;
11261   }
11262
11263   // Set the body of the conversion function.
11264   Stmt *ReturnS = Return.get();
11265   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
11266                                            Conv->getLocation(), 
11267                                            Conv->getLocation()));
11268   
11269   // We're done; notify the mutation listener, if any.
11270   if (ASTMutationListener *L = getASTMutationListener()) {
11271     L->CompletedImplicitDefinition(Conv);
11272   }
11273 }
11274
11275 /// \brief Determine whether the given list arguments contains exactly one 
11276 /// "real" (non-default) argument.
11277 static bool hasOneRealArgument(MultiExprArg Args) {
11278   switch (Args.size()) {
11279   case 0:
11280     return false;
11281     
11282   default:
11283     if (!Args[1]->isDefaultArgument())
11284       return false;
11285     
11286     // fall through
11287   case 1:
11288     return !Args[0]->isDefaultArgument();
11289   }
11290   
11291   return false;
11292 }
11293
11294 ExprResult
11295 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11296                             CXXConstructorDecl *Constructor,
11297                             MultiExprArg ExprArgs,
11298                             bool HadMultipleCandidates,
11299                             bool IsListInitialization,
11300                             bool IsStdInitListInitialization,
11301                             bool RequiresZeroInit,
11302                             unsigned ConstructKind,
11303                             SourceRange ParenRange) {
11304   bool Elidable = false;
11305
11306   // C++0x [class.copy]p34:
11307   //   When certain criteria are met, an implementation is allowed to
11308   //   omit the copy/move construction of a class object, even if the
11309   //   copy/move constructor and/or destructor for the object have
11310   //   side effects. [...]
11311   //     - when a temporary class object that has not been bound to a
11312   //       reference (12.2) would be copied/moved to a class object
11313   //       with the same cv-unqualified type, the copy/move operation
11314   //       can be omitted by constructing the temporary object
11315   //       directly into the target of the omitted copy/move
11316   if (ConstructKind == CXXConstructExpr::CK_Complete &&
11317       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
11318     Expr *SubExpr = ExprArgs[0];
11319     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
11320   }
11321
11322   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
11323                                Elidable, ExprArgs, HadMultipleCandidates,
11324                                IsListInitialization,
11325                                IsStdInitListInitialization, RequiresZeroInit,
11326                                ConstructKind, ParenRange);
11327 }
11328
11329 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
11330 /// including handling of its default argument expressions.
11331 ExprResult
11332 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11333                             CXXConstructorDecl *Constructor, bool Elidable,
11334                             MultiExprArg ExprArgs,
11335                             bool HadMultipleCandidates,
11336                             bool IsListInitialization,
11337                             bool IsStdInitListInitialization,
11338                             bool RequiresZeroInit,
11339                             unsigned ConstructKind,
11340                             SourceRange ParenRange) {
11341   MarkFunctionReferenced(ConstructLoc, Constructor);
11342   return CXXConstructExpr::Create(
11343       Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
11344       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11345       RequiresZeroInit,
11346       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11347       ParenRange);
11348 }
11349
11350 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11351   assert(Field->hasInClassInitializer());
11352
11353   // If we already have the in-class initializer nothing needs to be done.
11354   if (Field->getInClassInitializer())
11355     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11356
11357   // Maybe we haven't instantiated the in-class initializer. Go check the
11358   // pattern FieldDecl to see if it has one.
11359   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11360
11361   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11362     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11363     DeclContext::lookup_result Lookup =
11364         ClassPattern->lookup(Field->getDeclName());
11365     assert(Lookup.size() == 1);
11366     FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11367     if (InstantiateInClassInitializer(Loc, Field, Pattern,
11368                                       getTemplateInstantiationArgs(Field)))
11369       return ExprError();
11370     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11371   }
11372
11373   // DR1351:
11374   //   If the brace-or-equal-initializer of a non-static data member
11375   //   invokes a defaulted default constructor of its class or of an
11376   //   enclosing class in a potentially evaluated subexpression, the
11377   //   program is ill-formed.
11378   //
11379   // This resolution is unworkable: the exception specification of the
11380   // default constructor can be needed in an unevaluated context, in
11381   // particular, in the operand of a noexcept-expression, and we can be
11382   // unable to compute an exception specification for an enclosed class.
11383   //
11384   // Any attempt to resolve the exception specification of a defaulted default
11385   // constructor before the initializer is lexically complete will ultimately
11386   // come here at which point we can diagnose it.
11387   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11388   if (OutermostClass == ParentRD) {
11389     Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11390         << ParentRD << Field;
11391   } else {
11392     Diag(Field->getLocEnd(),
11393          diag::err_in_class_initializer_not_yet_parsed_outer_class)
11394         << ParentRD << OutermostClass << Field;
11395   }
11396
11397   return ExprError();
11398 }
11399
11400 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
11401   if (VD->isInvalidDecl()) return;
11402
11403   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11404   if (ClassDecl->isInvalidDecl()) return;
11405   if (ClassDecl->hasIrrelevantDestructor()) return;
11406   if (ClassDecl->isDependentContext()) return;
11407
11408   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11409   MarkFunctionReferenced(VD->getLocation(), Destructor);
11410   CheckDestructorAccess(VD->getLocation(), Destructor,
11411                         PDiag(diag::err_access_dtor_var)
11412                         << VD->getDeclName()
11413                         << VD->getType());
11414   DiagnoseUseOfDecl(Destructor, VD->getLocation());
11415
11416   if (Destructor->isTrivial()) return;
11417   if (!VD->hasGlobalStorage()) return;
11418
11419   // Emit warning for non-trivial dtor in global scope (a real global,
11420   // class-static, function-static).
11421   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11422
11423   // TODO: this should be re-enabled for static locals by !CXAAtExit
11424   if (!VD->isStaticLocal())
11425     Diag(VD->getLocation(), diag::warn_global_destructor);
11426 }
11427
11428 /// \brief Given a constructor and the set of arguments provided for the
11429 /// constructor, convert the arguments and add any required default arguments
11430 /// to form a proper call to this constructor.
11431 ///
11432 /// \returns true if an error occurred, false otherwise.
11433 bool 
11434 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11435                               MultiExprArg ArgsPtr,
11436                               SourceLocation Loc,
11437                               SmallVectorImpl<Expr*> &ConvertedArgs,
11438                               bool AllowExplicit,
11439                               bool IsListInitialization) {
11440   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11441   unsigned NumArgs = ArgsPtr.size();
11442   Expr **Args = ArgsPtr.data();
11443
11444   const FunctionProtoType *Proto 
11445     = Constructor->getType()->getAs<FunctionProtoType>();
11446   assert(Proto && "Constructor without a prototype?");
11447   unsigned NumParams = Proto->getNumParams();
11448
11449   // If too few arguments are available, we'll fill in the rest with defaults.
11450   if (NumArgs < NumParams)
11451     ConvertedArgs.reserve(NumParams);
11452   else
11453     ConvertedArgs.reserve(NumArgs);
11454
11455   VariadicCallType CallType = 
11456     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
11457   SmallVector<Expr *, 8> AllArgs;
11458   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11459                                         Proto, 0,
11460                                         llvm::makeArrayRef(Args, NumArgs),
11461                                         AllArgs,
11462                                         CallType, AllowExplicit,
11463                                         IsListInitialization);
11464   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11465
11466   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11467
11468   CheckConstructorCall(Constructor,
11469                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11470                        Proto, Loc);
11471
11472   return Invalid;
11473 }
11474
11475 static inline bool
11476 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 
11477                                        const FunctionDecl *FnDecl) {
11478   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11479   if (isa<NamespaceDecl>(DC)) {
11480     return SemaRef.Diag(FnDecl->getLocation(), 
11481                         diag::err_operator_new_delete_declared_in_namespace)
11482       << FnDecl->getDeclName();
11483   }
11484   
11485   if (isa<TranslationUnitDecl>(DC) && 
11486       FnDecl->getStorageClass() == SC_Static) {
11487     return SemaRef.Diag(FnDecl->getLocation(),
11488                         diag::err_operator_new_delete_declared_static)
11489       << FnDecl->getDeclName();
11490   }
11491   
11492   return false;
11493 }
11494
11495 static inline bool
11496 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11497                             CanQualType ExpectedResultType,
11498                             CanQualType ExpectedFirstParamType,
11499                             unsigned DependentParamTypeDiag,
11500                             unsigned InvalidParamTypeDiag) {
11501   QualType ResultType =
11502       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11503
11504   // Check that the result type is not dependent.
11505   if (ResultType->isDependentType())
11506     return SemaRef.Diag(FnDecl->getLocation(),
11507                         diag::err_operator_new_delete_dependent_result_type)
11508     << FnDecl->getDeclName() << ExpectedResultType;
11509
11510   // Check that the result type is what we expect.
11511   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11512     return SemaRef.Diag(FnDecl->getLocation(),
11513                         diag::err_operator_new_delete_invalid_result_type) 
11514     << FnDecl->getDeclName() << ExpectedResultType;
11515   
11516   // A function template must have at least 2 parameters.
11517   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11518     return SemaRef.Diag(FnDecl->getLocation(),
11519                       diag::err_operator_new_delete_template_too_few_parameters)
11520         << FnDecl->getDeclName();
11521   
11522   // The function decl must have at least 1 parameter.
11523   if (FnDecl->getNumParams() == 0)
11524     return SemaRef.Diag(FnDecl->getLocation(),
11525                         diag::err_operator_new_delete_too_few_parameters)
11526       << FnDecl->getDeclName();
11527  
11528   // Check the first parameter type is not dependent.
11529   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11530   if (FirstParamType->isDependentType())
11531     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11532       << FnDecl->getDeclName() << ExpectedFirstParamType;
11533
11534   // Check that the first parameter type is what we expect.
11535   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 
11536       ExpectedFirstParamType)
11537     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11538     << FnDecl->getDeclName() << ExpectedFirstParamType;
11539   
11540   return false;
11541 }
11542
11543 static bool
11544 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
11545   // C++ [basic.stc.dynamic.allocation]p1:
11546   //   A program is ill-formed if an allocation function is declared in a
11547   //   namespace scope other than global scope or declared static in global 
11548   //   scope.
11549   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11550     return true;
11551
11552   CanQualType SizeTy = 
11553     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11554
11555   // C++ [basic.stc.dynamic.allocation]p1:
11556   //  The return type shall be void*. The first parameter shall have type 
11557   //  std::size_t.
11558   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 
11559                                   SizeTy,
11560                                   diag::err_operator_new_dependent_param_type,
11561                                   diag::err_operator_new_param_type))
11562     return true;
11563
11564   // C++ [basic.stc.dynamic.allocation]p1:
11565   //  The first parameter shall not have an associated default argument.
11566   if (FnDecl->getParamDecl(0)->hasDefaultArg())
11567     return SemaRef.Diag(FnDecl->getLocation(),
11568                         diag::err_operator_new_default_arg)
11569       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11570
11571   return false;
11572 }
11573
11574 static bool
11575 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11576   // C++ [basic.stc.dynamic.deallocation]p1:
11577   //   A program is ill-formed if deallocation functions are declared in a
11578   //   namespace scope other than global scope or declared static in global 
11579   //   scope.
11580   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11581     return true;
11582
11583   // C++ [basic.stc.dynamic.deallocation]p2:
11584   //   Each deallocation function shall return void and its first parameter 
11585   //   shall be void*.
11586   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 
11587                                   SemaRef.Context.VoidPtrTy,
11588                                  diag::err_operator_delete_dependent_param_type,
11589                                  diag::err_operator_delete_param_type))
11590     return true;
11591
11592   return false;
11593 }
11594
11595 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11596 /// of this overloaded operator is well-formed. If so, returns false;
11597 /// otherwise, emits appropriate diagnostics and returns true.
11598 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11599   assert(FnDecl && FnDecl->isOverloadedOperator() &&
11600          "Expected an overloaded operator declaration");
11601
11602   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11603
11604   // C++ [over.oper]p5:
11605   //   The allocation and deallocation functions, operator new,
11606   //   operator new[], operator delete and operator delete[], are
11607   //   described completely in 3.7.3. The attributes and restrictions
11608   //   found in the rest of this subclause do not apply to them unless
11609   //   explicitly stated in 3.7.3.
11610   if (Op == OO_Delete || Op == OO_Array_Delete)
11611     return CheckOperatorDeleteDeclaration(*this, FnDecl);
11612   
11613   if (Op == OO_New || Op == OO_Array_New)
11614     return CheckOperatorNewDeclaration(*this, FnDecl);
11615
11616   // C++ [over.oper]p6:
11617   //   An operator function shall either be a non-static member
11618   //   function or be a non-member function and have at least one
11619   //   parameter whose type is a class, a reference to a class, an
11620   //   enumeration, or a reference to an enumeration.
11621   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11622     if (MethodDecl->isStatic())
11623       return Diag(FnDecl->getLocation(),
11624                   diag::err_operator_overload_static) << FnDecl->getDeclName();
11625   } else {
11626     bool ClassOrEnumParam = false;
11627     for (auto Param : FnDecl->params()) {
11628       QualType ParamType = Param->getType().getNonReferenceType();
11629       if (ParamType->isDependentType() || ParamType->isRecordType() ||
11630           ParamType->isEnumeralType()) {
11631         ClassOrEnumParam = true;
11632         break;
11633       }
11634     }
11635
11636     if (!ClassOrEnumParam)
11637       return Diag(FnDecl->getLocation(),
11638                   diag::err_operator_overload_needs_class_or_enum)
11639         << FnDecl->getDeclName();
11640   }
11641
11642   // C++ [over.oper]p8:
11643   //   An operator function cannot have default arguments (8.3.6),
11644   //   except where explicitly stated below.
11645   //
11646   // Only the function-call operator allows default arguments
11647   // (C++ [over.call]p1).
11648   if (Op != OO_Call) {
11649     for (auto Param : FnDecl->params()) {
11650       if (Param->hasDefaultArg())
11651         return Diag(Param->getLocation(),
11652                     diag::err_operator_overload_default_arg)
11653           << FnDecl->getDeclName() << Param->getDefaultArgRange();
11654     }
11655   }
11656
11657   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11658     { false, false, false }
11659 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11660     , { Unary, Binary, MemberOnly }
11661 #include "clang/Basic/OperatorKinds.def"
11662   };
11663
11664   bool CanBeUnaryOperator = OperatorUses[Op][0];
11665   bool CanBeBinaryOperator = OperatorUses[Op][1];
11666   bool MustBeMemberOperator = OperatorUses[Op][2];
11667
11668   // C++ [over.oper]p8:
11669   //   [...] Operator functions cannot have more or fewer parameters
11670   //   than the number required for the corresponding operator, as
11671   //   described in the rest of this subclause.
11672   unsigned NumParams = FnDecl->getNumParams()
11673                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11674   if (Op != OO_Call &&
11675       ((NumParams == 1 && !CanBeUnaryOperator) ||
11676        (NumParams == 2 && !CanBeBinaryOperator) ||
11677        (NumParams < 1) || (NumParams > 2))) {
11678     // We have the wrong number of parameters.
11679     unsigned ErrorKind;
11680     if (CanBeUnaryOperator && CanBeBinaryOperator) {
11681       ErrorKind = 2;  // 2 -> unary or binary.
11682     } else if (CanBeUnaryOperator) {
11683       ErrorKind = 0;  // 0 -> unary
11684     } else {
11685       assert(CanBeBinaryOperator &&
11686              "All non-call overloaded operators are unary or binary!");
11687       ErrorKind = 1;  // 1 -> binary
11688     }
11689
11690     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11691       << FnDecl->getDeclName() << NumParams << ErrorKind;
11692   }
11693
11694   // Overloaded operators other than operator() cannot be variadic.
11695   if (Op != OO_Call &&
11696       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11697     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11698       << FnDecl->getDeclName();
11699   }
11700
11701   // Some operators must be non-static member functions.
11702   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11703     return Diag(FnDecl->getLocation(),
11704                 diag::err_operator_overload_must_be_member)
11705       << FnDecl->getDeclName();
11706   }
11707
11708   // C++ [over.inc]p1:
11709   //   The user-defined function called operator++ implements the
11710   //   prefix and postfix ++ operator. If this function is a member
11711   //   function with no parameters, or a non-member function with one
11712   //   parameter of class or enumeration type, it defines the prefix
11713   //   increment operator ++ for objects of that type. If the function
11714   //   is a member function with one parameter (which shall be of type
11715   //   int) or a non-member function with two parameters (the second
11716   //   of which shall be of type int), it defines the postfix
11717   //   increment operator ++ for objects of that type.
11718   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11719     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11720     QualType ParamType = LastParam->getType();
11721
11722     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11723         !ParamType->isDependentType())
11724       return Diag(LastParam->getLocation(),
11725                   diag::err_operator_overload_post_incdec_must_be_int)
11726         << LastParam->getType() << (Op == OO_MinusMinus);
11727   }
11728
11729   return false;
11730 }
11731
11732 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11733 /// of this literal operator function is well-formed. If so, returns
11734 /// false; otherwise, emits appropriate diagnostics and returns true.
11735 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11736   if (isa<CXXMethodDecl>(FnDecl)) {
11737     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11738       << FnDecl->getDeclName();
11739     return true;
11740   }
11741
11742   if (FnDecl->isExternC()) {
11743     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11744     return true;
11745   }
11746
11747   bool Valid = false;
11748
11749   // This might be the definition of a literal operator template.
11750   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11751   // This might be a specialization of a literal operator template.
11752   if (!TpDecl)
11753     TpDecl = FnDecl->getPrimaryTemplate();
11754
11755   // template <char...> type operator "" name() and
11756   // template <class T, T...> type operator "" name() are the only valid
11757   // template signatures, and the only valid signatures with no parameters.
11758   if (TpDecl) {
11759     if (FnDecl->param_size() == 0) {
11760       // Must have one or two template parameters
11761       TemplateParameterList *Params = TpDecl->getTemplateParameters();
11762       if (Params->size() == 1) {
11763         NonTypeTemplateParmDecl *PmDecl =
11764           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11765
11766         // The template parameter must be a char parameter pack.
11767         if (PmDecl && PmDecl->isTemplateParameterPack() &&
11768             Context.hasSameType(PmDecl->getType(), Context.CharTy))
11769           Valid = true;
11770       } else if (Params->size() == 2) {
11771         TemplateTypeParmDecl *PmType =
11772           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11773         NonTypeTemplateParmDecl *PmArgs =
11774           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11775
11776         // The second template parameter must be a parameter pack with the
11777         // first template parameter as its type.
11778         if (PmType && PmArgs &&
11779             !PmType->isTemplateParameterPack() &&
11780             PmArgs->isTemplateParameterPack()) {
11781           const TemplateTypeParmType *TArgs =
11782             PmArgs->getType()->getAs<TemplateTypeParmType>();
11783           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11784               TArgs->getIndex() == PmType->getIndex()) {
11785             Valid = true;
11786             if (ActiveTemplateInstantiations.empty())
11787               Diag(FnDecl->getLocation(),
11788                    diag::ext_string_literal_operator_template);
11789           }
11790         }
11791       }
11792     }
11793   } else if (FnDecl->param_size()) {
11794     // Check the first parameter
11795     FunctionDecl::param_iterator Param = FnDecl->param_begin();
11796
11797     QualType T = (*Param)->getType().getUnqualifiedType();
11798
11799     // unsigned long long int, long double, and any character type are allowed
11800     // as the only parameters.
11801     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11802         Context.hasSameType(T, Context.LongDoubleTy) ||
11803         Context.hasSameType(T, Context.CharTy) ||
11804         Context.hasSameType(T, Context.WideCharTy) ||
11805         Context.hasSameType(T, Context.Char16Ty) ||
11806         Context.hasSameType(T, Context.Char32Ty)) {
11807       if (++Param == FnDecl->param_end())
11808         Valid = true;
11809       goto FinishedParams;
11810     }
11811
11812     // Otherwise it must be a pointer to const; let's strip those qualifiers.
11813     const PointerType *PT = T->getAs<PointerType>();
11814     if (!PT)
11815       goto FinishedParams;
11816     T = PT->getPointeeType();
11817     if (!T.isConstQualified() || T.isVolatileQualified())
11818       goto FinishedParams;
11819     T = T.getUnqualifiedType();
11820
11821     // Move on to the second parameter;
11822     ++Param;
11823
11824     // If there is no second parameter, the first must be a const char *
11825     if (Param == FnDecl->param_end()) {
11826       if (Context.hasSameType(T, Context.CharTy))
11827         Valid = true;
11828       goto FinishedParams;
11829     }
11830
11831     // const char *, const wchar_t*, const char16_t*, and const char32_t*
11832     // are allowed as the first parameter to a two-parameter function
11833     if (!(Context.hasSameType(T, Context.CharTy) ||
11834           Context.hasSameType(T, Context.WideCharTy) ||
11835           Context.hasSameType(T, Context.Char16Ty) ||
11836           Context.hasSameType(T, Context.Char32Ty)))
11837       goto FinishedParams;
11838
11839     // The second and final parameter must be an std::size_t
11840     T = (*Param)->getType().getUnqualifiedType();
11841     if (Context.hasSameType(T, Context.getSizeType()) &&
11842         ++Param == FnDecl->param_end())
11843       Valid = true;
11844   }
11845
11846   // FIXME: This diagnostic is absolutely terrible.
11847 FinishedParams:
11848   if (!Valid) {
11849     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11850       << FnDecl->getDeclName();
11851     return true;
11852   }
11853
11854   // A parameter-declaration-clause containing a default argument is not
11855   // equivalent to any of the permitted forms.
11856   for (auto Param : FnDecl->params()) {
11857     if (Param->hasDefaultArg()) {
11858       Diag(Param->getDefaultArgRange().getBegin(),
11859            diag::err_literal_operator_default_argument)
11860         << Param->getDefaultArgRange();
11861       break;
11862     }
11863   }
11864
11865   StringRef LiteralName
11866     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11867   if (LiteralName[0] != '_') {
11868     // C++11 [usrlit.suffix]p1:
11869     //   Literal suffix identifiers that do not start with an underscore
11870     //   are reserved for future standardization.
11871     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11872       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11873   }
11874
11875   return false;
11876 }
11877
11878 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11879 /// linkage specification, including the language and (if present)
11880 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11881 /// language string literal. LBraceLoc, if valid, provides the location of
11882 /// the '{' brace. Otherwise, this linkage specification does not
11883 /// have any braces.
11884 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11885                                            Expr *LangStr,
11886                                            SourceLocation LBraceLoc) {
11887   StringLiteral *Lit = cast<StringLiteral>(LangStr);
11888   if (!Lit->isAscii()) {
11889     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11890       << LangStr->getSourceRange();
11891     return nullptr;
11892   }
11893
11894   StringRef Lang = Lit->getString();
11895   LinkageSpecDecl::LanguageIDs Language;
11896   if (Lang == "C")
11897     Language = LinkageSpecDecl::lang_c;
11898   else if (Lang == "C++")
11899     Language = LinkageSpecDecl::lang_cxx;
11900   else {
11901     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11902       << LangStr->getSourceRange();
11903     return nullptr;
11904   }
11905
11906   // FIXME: Add all the various semantics of linkage specifications
11907
11908   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11909                                                LangStr->getExprLoc(), Language,
11910                                                LBraceLoc.isValid());
11911   CurContext->addDecl(D);
11912   PushDeclContext(S, D);
11913   return D;
11914 }
11915
11916 /// ActOnFinishLinkageSpecification - Complete the definition of
11917 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11918 /// valid, it's the position of the closing '}' brace in a linkage
11919 /// specification that uses braces.
11920 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11921                                             Decl *LinkageSpec,
11922                                             SourceLocation RBraceLoc) {
11923   if (RBraceLoc.isValid()) {
11924     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11925     LSDecl->setRBraceLoc(RBraceLoc);
11926   }
11927   PopDeclContext();
11928   return LinkageSpec;
11929 }
11930
11931 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11932                                   AttributeList *AttrList,
11933                                   SourceLocation SemiLoc) {
11934   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11935   // Attribute declarations appertain to empty declaration so we handle
11936   // them here.
11937   if (AttrList)
11938     ProcessDeclAttributeList(S, ED, AttrList);
11939
11940   CurContext->addDecl(ED);
11941   return ED;
11942 }
11943
11944 /// \brief Perform semantic analysis for the variable declaration that
11945 /// occurs within a C++ catch clause, returning the newly-created
11946 /// variable.
11947 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11948                                          TypeSourceInfo *TInfo,
11949                                          SourceLocation StartLoc,
11950                                          SourceLocation Loc,
11951                                          IdentifierInfo *Name) {
11952   bool Invalid = false;
11953   QualType ExDeclType = TInfo->getType();
11954   
11955   // Arrays and functions decay.
11956   if (ExDeclType->isArrayType())
11957     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11958   else if (ExDeclType->isFunctionType())
11959     ExDeclType = Context.getPointerType(ExDeclType);
11960
11961   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11962   // The exception-declaration shall not denote a pointer or reference to an
11963   // incomplete type, other than [cv] void*.
11964   // N2844 forbids rvalue references.
11965   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11966     Diag(Loc, diag::err_catch_rvalue_ref);
11967     Invalid = true;
11968   }
11969
11970   QualType BaseType = ExDeclType;
11971   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11972   unsigned DK = diag::err_catch_incomplete;
11973   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11974     BaseType = Ptr->getPointeeType();
11975     Mode = 1;
11976     DK = diag::err_catch_incomplete_ptr;
11977   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11978     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11979     BaseType = Ref->getPointeeType();
11980     Mode = 2;
11981     DK = diag::err_catch_incomplete_ref;
11982   }
11983   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11984       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11985     Invalid = true;
11986
11987   if (!Invalid && !ExDeclType->isDependentType() &&
11988       RequireNonAbstractType(Loc, ExDeclType,
11989                              diag::err_abstract_type_in_decl,
11990                              AbstractVariableType))
11991     Invalid = true;
11992
11993   // Only the non-fragile NeXT runtime currently supports C++ catches
11994   // of ObjC types, and no runtime supports catching ObjC types by value.
11995   if (!Invalid && getLangOpts().ObjC1) {
11996     QualType T = ExDeclType;
11997     if (const ReferenceType *RT = T->getAs<ReferenceType>())
11998       T = RT->getPointeeType();
11999
12000     if (T->isObjCObjectType()) {
12001       Diag(Loc, diag::err_objc_object_catch);
12002       Invalid = true;
12003     } else if (T->isObjCObjectPointerType()) {
12004       // FIXME: should this be a test for macosx-fragile specifically?
12005       if (getLangOpts().ObjCRuntime.isFragile())
12006         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
12007     }
12008   }
12009
12010   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
12011                                     ExDeclType, TInfo, SC_None);
12012   ExDecl->setExceptionVariable(true);
12013   
12014   // In ARC, infer 'retaining' for variables of retainable type.
12015   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
12016     Invalid = true;
12017
12018   if (!Invalid && !ExDeclType->isDependentType()) {
12019     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
12020       // Insulate this from anything else we might currently be parsing.
12021       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
12022
12023       // C++ [except.handle]p16:
12024       //   The object declared in an exception-declaration or, if the
12025       //   exception-declaration does not specify a name, a temporary (12.2) is
12026       //   copy-initialized (8.5) from the exception object. [...]
12027       //   The object is destroyed when the handler exits, after the destruction
12028       //   of any automatic objects initialized within the handler.
12029       //
12030       // We just pretend to initialize the object with itself, then make sure
12031       // it can be destroyed later.
12032       QualType initType = Context.getExceptionObjectType(ExDeclType);
12033
12034       InitializedEntity entity =
12035         InitializedEntity::InitializeVariable(ExDecl);
12036       InitializationKind initKind =
12037         InitializationKind::CreateCopy(Loc, SourceLocation());
12038
12039       Expr *opaqueValue =
12040         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
12041       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
12042       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
12043       if (result.isInvalid())
12044         Invalid = true;
12045       else {
12046         // If the constructor used was non-trivial, set this as the
12047         // "initializer".
12048         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
12049         if (!construct->getConstructor()->isTrivial()) {
12050           Expr *init = MaybeCreateExprWithCleanups(construct);
12051           ExDecl->setInit(init);
12052         }
12053         
12054         // And make sure it's destructable.
12055         FinalizeVarWithDestructor(ExDecl, recordType);
12056       }
12057     }
12058   }
12059   
12060   if (Invalid)
12061     ExDecl->setInvalidDecl();
12062
12063   return ExDecl;
12064 }
12065
12066 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12067 /// handler.
12068 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
12069   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12070   bool Invalid = D.isInvalidType();
12071
12072   // Check for unexpanded parameter packs.
12073   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12074                                       UPPC_ExceptionType)) {
12075     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 
12076                                              D.getIdentifierLoc());
12077     Invalid = true;
12078   }
12079
12080   IdentifierInfo *II = D.getIdentifier();
12081   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
12082                                              LookupOrdinaryName,
12083                                              ForRedeclaration)) {
12084     // The scope should be freshly made just for us. There is just no way
12085     // it contains any previous declaration, except for function parameters in
12086     // a function-try-block's catch statement.
12087     assert(!S->isDeclScope(PrevDecl));
12088     if (isDeclInScope(PrevDecl, CurContext, S)) {
12089       Diag(D.getIdentifierLoc(), diag::err_redefinition)
12090         << D.getIdentifier();
12091       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12092       Invalid = true;
12093     } else if (PrevDecl->isTemplateParameter())
12094       // Maybe we will complain about the shadowed template parameter.
12095       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12096   }
12097
12098   if (D.getCXXScopeSpec().isSet() && !Invalid) {
12099     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12100       << D.getCXXScopeSpec().getRange();
12101     Invalid = true;
12102   }
12103
12104   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
12105                                               D.getLocStart(),
12106                                               D.getIdentifierLoc(),
12107                                               D.getIdentifier());
12108   if (Invalid)
12109     ExDecl->setInvalidDecl();
12110
12111   // Add the exception declaration into this scope.
12112   if (II)
12113     PushOnScopeChains(ExDecl, S);
12114   else
12115     CurContext->addDecl(ExDecl);
12116
12117   ProcessDeclAttributes(S, ExDecl, D);
12118   return ExDecl;
12119 }
12120
12121 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12122                                          Expr *AssertExpr,
12123                                          Expr *AssertMessageExpr,
12124                                          SourceLocation RParenLoc) {
12125   StringLiteral *AssertMessage =
12126       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
12127
12128   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
12129     return nullptr;
12130
12131   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12132                                       AssertMessage, RParenLoc, false);
12133 }
12134
12135 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12136                                          Expr *AssertExpr,
12137                                          StringLiteral *AssertMessage,
12138                                          SourceLocation RParenLoc,
12139                                          bool Failed) {
12140   assert(AssertExpr != nullptr && "Expected non-null condition");
12141   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12142       !Failed) {
12143     // In a static_assert-declaration, the constant-expression shall be a
12144     // constant expression that can be contextually converted to bool.
12145     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12146     if (Converted.isInvalid())
12147       Failed = true;
12148
12149     llvm::APSInt Cond;
12150     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
12151           diag::err_static_assert_expression_is_not_constant,
12152           /*AllowFold=*/false).isInvalid())
12153       Failed = true;
12154
12155     if (!Failed && !Cond) {
12156       SmallString<256> MsgBuffer;
12157       llvm::raw_svector_ostream Msg(MsgBuffer);
12158       if (AssertMessage)
12159         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
12160       Diag(StaticAssertLoc, diag::err_static_assert_failed)
12161         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
12162       Failed = true;
12163     }
12164   }
12165
12166   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
12167                                         AssertExpr, AssertMessage, RParenLoc,
12168                                         Failed);
12169
12170   CurContext->addDecl(Decl);
12171   return Decl;
12172 }
12173
12174 /// \brief Perform semantic analysis of the given friend type declaration.
12175 ///
12176 /// \returns A friend declaration that.
12177 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
12178                                       SourceLocation FriendLoc,
12179                                       TypeSourceInfo *TSInfo) {
12180   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12181   
12182   QualType T = TSInfo->getType();
12183   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
12184   
12185   // C++03 [class.friend]p2:
12186   //   An elaborated-type-specifier shall be used in a friend declaration
12187   //   for a class.*
12188   //
12189   //   * The class-key of the elaborated-type-specifier is required.
12190   if (!ActiveTemplateInstantiations.empty()) {
12191     // Do not complain about the form of friend template types during
12192     // template instantiation; we will already have complained when the
12193     // template was declared.
12194   } else {
12195     if (!T->isElaboratedTypeSpecifier()) {
12196       // If we evaluated the type to a record type, suggest putting
12197       // a tag in front.
12198       if (const RecordType *RT = T->getAs<RecordType>()) {
12199         RecordDecl *RD = RT->getDecl();
12200
12201         SmallString<16> InsertionText(" ");
12202         InsertionText += RD->getKindName();
12203
12204         Diag(TypeRange.getBegin(),
12205              getLangOpts().CPlusPlus11 ?
12206                diag::warn_cxx98_compat_unelaborated_friend_type :
12207                diag::ext_unelaborated_friend_type)
12208           << (unsigned) RD->getTagKind()
12209           << T
12210           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12211                                         InsertionText);
12212       } else {
12213         Diag(FriendLoc,
12214              getLangOpts().CPlusPlus11 ?
12215                diag::warn_cxx98_compat_nonclass_type_friend :
12216                diag::ext_nonclass_type_friend)
12217           << T
12218           << TypeRange;
12219       }
12220     } else if (T->getAs<EnumType>()) {
12221       Diag(FriendLoc,
12222            getLangOpts().CPlusPlus11 ?
12223              diag::warn_cxx98_compat_enum_friend :
12224              diag::ext_enum_friend)
12225         << T
12226         << TypeRange;
12227     }
12228   
12229     // C++11 [class.friend]p3:
12230     //   A friend declaration that does not declare a function shall have one
12231     //   of the following forms:
12232     //     friend elaborated-type-specifier ;
12233     //     friend simple-type-specifier ;
12234     //     friend typename-specifier ;
12235     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12236       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12237   }
12238
12239   //   If the type specifier in a friend declaration designates a (possibly
12240   //   cv-qualified) class type, that class is declared as a friend; otherwise,
12241   //   the friend declaration is ignored.
12242   return FriendDecl::Create(Context, CurContext,
12243                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
12244                             FriendLoc);
12245 }
12246
12247 /// Handle a friend tag declaration where the scope specifier was
12248 /// templated.
12249 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12250                                     unsigned TagSpec, SourceLocation TagLoc,
12251                                     CXXScopeSpec &SS,
12252                                     IdentifierInfo *Name,
12253                                     SourceLocation NameLoc,
12254                                     AttributeList *Attr,
12255                                     MultiTemplateParamsArg TempParamLists) {
12256   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12257
12258   bool isExplicitSpecialization = false;
12259   bool Invalid = false;
12260
12261   if (TemplateParameterList *TemplateParams =
12262           MatchTemplateParametersToScopeSpecifier(
12263               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
12264               isExplicitSpecialization, Invalid)) {
12265     if (TemplateParams->size() > 0) {
12266       // This is a declaration of a class template.
12267       if (Invalid)
12268         return nullptr;
12269
12270       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12271                                 NameLoc, Attr, TemplateParams, AS_public,
12272                                 /*ModulePrivateLoc=*/SourceLocation(),
12273                                 FriendLoc, TempParamLists.size() - 1,
12274                                 TempParamLists.data()).get();
12275     } else {
12276       // The "template<>" header is extraneous.
12277       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12278         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12279       isExplicitSpecialization = true;
12280     }
12281   }
12282
12283   if (Invalid) return nullptr;
12284
12285   bool isAllExplicitSpecializations = true;
12286   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
12287     if (TempParamLists[I]->size()) {
12288       isAllExplicitSpecializations = false;
12289       break;
12290     }
12291   }
12292
12293   // FIXME: don't ignore attributes.
12294
12295   // If it's explicit specializations all the way down, just forget
12296   // about the template header and build an appropriate non-templated
12297   // friend.  TODO: for source fidelity, remember the headers.
12298   if (isAllExplicitSpecializations) {
12299     if (SS.isEmpty()) {
12300       bool Owned = false;
12301       bool IsDependent = false;
12302       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
12303                       Attr, AS_public,
12304                       /*ModulePrivateLoc=*/SourceLocation(),
12305                       MultiTemplateParamsArg(), Owned, IsDependent,
12306                       /*ScopedEnumKWLoc=*/SourceLocation(),
12307                       /*ScopedEnumUsesClassTag=*/false,
12308                       /*UnderlyingType=*/TypeResult(),
12309                       /*IsTypeSpecifier=*/false);
12310     }
12311
12312     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12313     ElaboratedTypeKeyword Keyword
12314       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12315     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
12316                                    *Name, NameLoc);
12317     if (T.isNull())
12318       return nullptr;
12319
12320     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12321     if (isa<DependentNameType>(T)) {
12322       DependentNameTypeLoc TL =
12323           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12324       TL.setElaboratedKeywordLoc(TagLoc);
12325       TL.setQualifierLoc(QualifierLoc);
12326       TL.setNameLoc(NameLoc);
12327     } else {
12328       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
12329       TL.setElaboratedKeywordLoc(TagLoc);
12330       TL.setQualifierLoc(QualifierLoc);
12331       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
12332     }
12333
12334     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12335                                             TSI, FriendLoc, TempParamLists);
12336     Friend->setAccess(AS_public);
12337     CurContext->addDecl(Friend);
12338     return Friend;
12339   }
12340   
12341   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12342   
12343
12344
12345   // Handle the case of a templated-scope friend class.  e.g.
12346   //   template <class T> class A<T>::B;
12347   // FIXME: we don't support these right now.
12348   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12349     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
12350   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12351   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12352   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12353   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12354   TL.setElaboratedKeywordLoc(TagLoc);
12355   TL.setQualifierLoc(SS.getWithLocInContext(Context));
12356   TL.setNameLoc(NameLoc);
12357
12358   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12359                                           TSI, FriendLoc, TempParamLists);
12360   Friend->setAccess(AS_public);
12361   Friend->setUnsupportedFriend(true);
12362   CurContext->addDecl(Friend);
12363   return Friend;
12364 }
12365
12366
12367 /// Handle a friend type declaration.  This works in tandem with
12368 /// ActOnTag.
12369 ///
12370 /// Notes on friend class templates:
12371 ///
12372 /// We generally treat friend class declarations as if they were
12373 /// declaring a class.  So, for example, the elaborated type specifier
12374 /// in a friend declaration is required to obey the restrictions of a
12375 /// class-head (i.e. no typedefs in the scope chain), template
12376 /// parameters are required to match up with simple template-ids, &c.
12377 /// However, unlike when declaring a template specialization, it's
12378 /// okay to refer to a template specialization without an empty
12379 /// template parameter declaration, e.g.
12380 ///   friend class A<T>::B<unsigned>;
12381 /// We permit this as a special case; if there are any template
12382 /// parameters present at all, require proper matching, i.e.
12383 ///   template <> template \<class T> friend class A<int>::B;
12384 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
12385                                 MultiTemplateParamsArg TempParams) {
12386   SourceLocation Loc = DS.getLocStart();
12387
12388   assert(DS.isFriendSpecified());
12389   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12390
12391   // Try to convert the decl specifier to a type.  This works for
12392   // friend templates because ActOnTag never produces a ClassTemplateDecl
12393   // for a TUK_Friend.
12394   Declarator TheDeclarator(DS, Declarator::MemberContext);
12395   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12396   QualType T = TSI->getType();
12397   if (TheDeclarator.isInvalidType())
12398     return nullptr;
12399
12400   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
12401     return nullptr;
12402
12403   // This is definitely an error in C++98.  It's probably meant to
12404   // be forbidden in C++0x, too, but the specification is just
12405   // poorly written.
12406   //
12407   // The problem is with declarations like the following:
12408   //   template <T> friend A<T>::foo;
12409   // where deciding whether a class C is a friend or not now hinges
12410   // on whether there exists an instantiation of A that causes
12411   // 'foo' to equal C.  There are restrictions on class-heads
12412   // (which we declare (by fiat) elaborated friend declarations to
12413   // be) that makes this tractable.
12414   //
12415   // FIXME: handle "template <> friend class A<T>;", which
12416   // is possibly well-formed?  Who even knows?
12417   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12418     Diag(Loc, diag::err_tagless_friend_type_template)
12419       << DS.getSourceRange();
12420     return nullptr;
12421   }
12422   
12423   // C++98 [class.friend]p1: A friend of a class is a function
12424   //   or class that is not a member of the class . . .
12425   // This is fixed in DR77, which just barely didn't make the C++03
12426   // deadline.  It's also a very silly restriction that seriously
12427   // affects inner classes and which nobody else seems to implement;
12428   // thus we never diagnose it, not even in -pedantic.
12429   //
12430   // But note that we could warn about it: it's always useless to
12431   // friend one of your own members (it's not, however, worthless to
12432   // friend a member of an arbitrary specialization of your template).
12433
12434   Decl *D;
12435   if (unsigned NumTempParamLists = TempParams.size())
12436     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
12437                                    NumTempParamLists,
12438                                    TempParams.data(),
12439                                    TSI,
12440                                    DS.getFriendSpecLoc());
12441   else
12442     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12443   
12444   if (!D)
12445     return nullptr;
12446
12447   D->setAccess(AS_public);
12448   CurContext->addDecl(D);
12449
12450   return D;
12451 }
12452
12453 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12454                                         MultiTemplateParamsArg TemplateParams) {
12455   const DeclSpec &DS = D.getDeclSpec();
12456
12457   assert(DS.isFriendSpecified());
12458   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12459
12460   SourceLocation Loc = D.getIdentifierLoc();
12461   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12462
12463   // C++ [class.friend]p1
12464   //   A friend of a class is a function or class....
12465   // Note that this sees through typedefs, which is intended.
12466   // It *doesn't* see through dependent types, which is correct
12467   // according to [temp.arg.type]p3:
12468   //   If a declaration acquires a function type through a
12469   //   type dependent on a template-parameter and this causes
12470   //   a declaration that does not use the syntactic form of a
12471   //   function declarator to have a function type, the program
12472   //   is ill-formed.
12473   if (!TInfo->getType()->isFunctionType()) {
12474     Diag(Loc, diag::err_unexpected_friend);
12475
12476     // It might be worthwhile to try to recover by creating an
12477     // appropriate declaration.
12478     return nullptr;
12479   }
12480
12481   // C++ [namespace.memdef]p3
12482   //  - If a friend declaration in a non-local class first declares a
12483   //    class or function, the friend class or function is a member
12484   //    of the innermost enclosing namespace.
12485   //  - The name of the friend is not found by simple name lookup
12486   //    until a matching declaration is provided in that namespace
12487   //    scope (either before or after the class declaration granting
12488   //    friendship).
12489   //  - If a friend function is called, its name may be found by the
12490   //    name lookup that considers functions from namespaces and
12491   //    classes associated with the types of the function arguments.
12492   //  - When looking for a prior declaration of a class or a function
12493   //    declared as a friend, scopes outside the innermost enclosing
12494   //    namespace scope are not considered.
12495
12496   CXXScopeSpec &SS = D.getCXXScopeSpec();
12497   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12498   DeclarationName Name = NameInfo.getName();
12499   assert(Name);
12500
12501   // Check for unexpanded parameter packs.
12502   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12503       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12504       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
12505     return nullptr;
12506
12507   // The context we found the declaration in, or in which we should
12508   // create the declaration.
12509   DeclContext *DC;
12510   Scope *DCScope = S;
12511   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12512                         ForRedeclaration);
12513
12514   // There are five cases here.
12515   //   - There's no scope specifier and we're in a local class. Only look
12516   //     for functions declared in the immediately-enclosing block scope.
12517   // We recover from invalid scope qualifiers as if they just weren't there.
12518   FunctionDecl *FunctionContainingLocalClass = nullptr;
12519   if ((SS.isInvalid() || !SS.isSet()) &&
12520       (FunctionContainingLocalClass =
12521            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12522     // C++11 [class.friend]p11:
12523     //   If a friend declaration appears in a local class and the name
12524     //   specified is an unqualified name, a prior declaration is
12525     //   looked up without considering scopes that are outside the
12526     //   innermost enclosing non-class scope. For a friend function
12527     //   declaration, if there is no prior declaration, the program is
12528     //   ill-formed.
12529
12530     // Find the innermost enclosing non-class scope. This is the block
12531     // scope containing the local class definition (or for a nested class,
12532     // the outer local class).
12533     DCScope = S->getFnParent();
12534
12535     // Look up the function name in the scope.
12536     Previous.clear(LookupLocalFriendName);
12537     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12538
12539     if (!Previous.empty()) {
12540       // All possible previous declarations must have the same context:
12541       // either they were declared at block scope or they are members of
12542       // one of the enclosing local classes.
12543       DC = Previous.getRepresentativeDecl()->getDeclContext();
12544     } else {
12545       // This is ill-formed, but provide the context that we would have
12546       // declared the function in, if we were permitted to, for error recovery.
12547       DC = FunctionContainingLocalClass;
12548     }
12549     adjustContextForLocalExternDecl(DC);
12550
12551     // C++ [class.friend]p6:
12552     //   A function can be defined in a friend declaration of a class if and
12553     //   only if the class is a non-local class (9.8), the function name is
12554     //   unqualified, and the function has namespace scope.
12555     if (D.isFunctionDefinition()) {
12556       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12557     }
12558
12559   //   - There's no scope specifier, in which case we just go to the
12560   //     appropriate scope and look for a function or function template
12561   //     there as appropriate.
12562   } else if (SS.isInvalid() || !SS.isSet()) {
12563     // C++11 [namespace.memdef]p3:
12564     //   If the name in a friend declaration is neither qualified nor
12565     //   a template-id and the declaration is a function or an
12566     //   elaborated-type-specifier, the lookup to determine whether
12567     //   the entity has been previously declared shall not consider
12568     //   any scopes outside the innermost enclosing namespace.
12569     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12570
12571     // Find the appropriate context according to the above.
12572     DC = CurContext;
12573
12574     // Skip class contexts.  If someone can cite chapter and verse
12575     // for this behavior, that would be nice --- it's what GCC and
12576     // EDG do, and it seems like a reasonable intent, but the spec
12577     // really only says that checks for unqualified existing
12578     // declarations should stop at the nearest enclosing namespace,
12579     // not that they should only consider the nearest enclosing
12580     // namespace.
12581     while (DC->isRecord())
12582       DC = DC->getParent();
12583
12584     DeclContext *LookupDC = DC;
12585     while (LookupDC->isTransparentContext())
12586       LookupDC = LookupDC->getParent();
12587
12588     while (true) {
12589       LookupQualifiedName(Previous, LookupDC);
12590
12591       if (!Previous.empty()) {
12592         DC = LookupDC;
12593         break;
12594       }
12595
12596       if (isTemplateId) {
12597         if (isa<TranslationUnitDecl>(LookupDC)) break;
12598       } else {
12599         if (LookupDC->isFileContext()) break;
12600       }
12601       LookupDC = LookupDC->getParent();
12602     }
12603
12604     DCScope = getScopeForDeclContext(S, DC);
12605
12606   //   - There's a non-dependent scope specifier, in which case we
12607   //     compute it and do a previous lookup there for a function
12608   //     or function template.
12609   } else if (!SS.getScopeRep()->isDependent()) {
12610     DC = computeDeclContext(SS);
12611     if (!DC) return nullptr;
12612
12613     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12614
12615     LookupQualifiedName(Previous, DC);
12616
12617     // Ignore things found implicitly in the wrong scope.
12618     // TODO: better diagnostics for this case.  Suggesting the right
12619     // qualified scope would be nice...
12620     LookupResult::Filter F = Previous.makeFilter();
12621     while (F.hasNext()) {
12622       NamedDecl *D = F.next();
12623       if (!DC->InEnclosingNamespaceSetOf(
12624               D->getDeclContext()->getRedeclContext()))
12625         F.erase();
12626     }
12627     F.done();
12628
12629     if (Previous.empty()) {
12630       D.setInvalidType();
12631       Diag(Loc, diag::err_qualified_friend_not_found)
12632           << Name << TInfo->getType();
12633       return nullptr;
12634     }
12635
12636     // C++ [class.friend]p1: A friend of a class is a function or
12637     //   class that is not a member of the class . . .
12638     if (DC->Equals(CurContext))
12639       Diag(DS.getFriendSpecLoc(),
12640            getLangOpts().CPlusPlus11 ?
12641              diag::warn_cxx98_compat_friend_is_member :
12642              diag::err_friend_is_member);
12643     
12644     if (D.isFunctionDefinition()) {
12645       // C++ [class.friend]p6:
12646       //   A function can be defined in a friend declaration of a class if and 
12647       //   only if the class is a non-local class (9.8), the function name is
12648       //   unqualified, and the function has namespace scope.
12649       SemaDiagnosticBuilder DB
12650         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12651       
12652       DB << SS.getScopeRep();
12653       if (DC->isFileContext())
12654         DB << FixItHint::CreateRemoval(SS.getRange());
12655       SS.clear();
12656     }
12657
12658   //   - There's a scope specifier that does not match any template
12659   //     parameter lists, in which case we use some arbitrary context,
12660   //     create a method or method template, and wait for instantiation.
12661   //   - There's a scope specifier that does match some template
12662   //     parameter lists, which we don't handle right now.
12663   } else {
12664     if (D.isFunctionDefinition()) {
12665       // C++ [class.friend]p6:
12666       //   A function can be defined in a friend declaration of a class if and 
12667       //   only if the class is a non-local class (9.8), the function name is
12668       //   unqualified, and the function has namespace scope.
12669       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12670         << SS.getScopeRep();
12671     }
12672     
12673     DC = CurContext;
12674     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12675   }
12676   
12677   if (!DC->isRecord()) {
12678     // This implies that it has to be an operator or function.
12679     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12680         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12681         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
12682       Diag(Loc, diag::err_introducing_special_friend) <<
12683         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12684          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
12685       return nullptr;
12686     }
12687   }
12688
12689   // FIXME: This is an egregious hack to cope with cases where the scope stack
12690   // does not contain the declaration context, i.e., in an out-of-line 
12691   // definition of a class.
12692   Scope FakeDCScope(S, Scope::DeclScope, Diags);
12693   if (!DCScope) {
12694     FakeDCScope.setEntity(DC);
12695     DCScope = &FakeDCScope;
12696   }
12697
12698   bool AddToScope = true;
12699   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12700                                           TemplateParams, AddToScope);
12701   if (!ND) return nullptr;
12702
12703   assert(ND->getLexicalDeclContext() == CurContext);
12704
12705   // If we performed typo correction, we might have added a scope specifier
12706   // and changed the decl context.
12707   DC = ND->getDeclContext();
12708
12709   // Add the function declaration to the appropriate lookup tables,
12710   // adjusting the redeclarations list as necessary.  We don't
12711   // want to do this yet if the friending class is dependent.
12712   //
12713   // Also update the scope-based lookup if the target context's
12714   // lookup context is in lexical scope.
12715   if (!CurContext->isDependentContext()) {
12716     DC = DC->getRedeclContext();
12717     DC->makeDeclVisibleInContext(ND);
12718     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12719       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12720   }
12721
12722   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12723                                        D.getIdentifierLoc(), ND,
12724                                        DS.getFriendSpecLoc());
12725   FrD->setAccess(AS_public);
12726   CurContext->addDecl(FrD);
12727
12728   if (ND->isInvalidDecl()) {
12729     FrD->setInvalidDecl();
12730   } else {
12731     if (DC->isRecord()) CheckFriendAccess(ND);
12732
12733     FunctionDecl *FD;
12734     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12735       FD = FTD->getTemplatedDecl();
12736     else
12737       FD = cast<FunctionDecl>(ND);
12738
12739     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12740     // default argument expression, that declaration shall be a definition
12741     // and shall be the only declaration of the function or function
12742     // template in the translation unit.
12743     if (functionDeclHasDefaultArgument(FD)) {
12744       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12745         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12746         Diag(OldFD->getLocation(), diag::note_previous_declaration);
12747       } else if (!D.isFunctionDefinition())
12748         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12749     }
12750
12751     // Mark templated-scope function declarations as unsupported.
12752     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12753       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12754         << SS.getScopeRep() << SS.getRange()
12755         << cast<CXXRecordDecl>(CurContext);
12756       FrD->setUnsupportedFriend(true);
12757     }
12758   }
12759
12760   return ND;
12761 }
12762
12763 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12764   AdjustDeclIfTemplate(Dcl);
12765
12766   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12767   if (!Fn) {
12768     Diag(DelLoc, diag::err_deleted_non_function);
12769     return;
12770   }
12771
12772   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12773     // Don't consider the implicit declaration we generate for explicit
12774     // specializations. FIXME: Do not generate these implicit declarations.
12775     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12776          Prev->getPreviousDecl()) &&
12777         !Prev->isDefined()) {
12778       Diag(DelLoc, diag::err_deleted_decl_not_first);
12779       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12780            Prev->isImplicit() ? diag::note_previous_implicit_declaration
12781                               : diag::note_previous_declaration);
12782     }
12783     // If the declaration wasn't the first, we delete the function anyway for
12784     // recovery.
12785     Fn = Fn->getCanonicalDecl();
12786   }
12787
12788   // dllimport/dllexport cannot be deleted.
12789   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12790     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12791     Fn->setInvalidDecl();
12792   }
12793
12794   if (Fn->isDeleted())
12795     return;
12796
12797   // See if we're deleting a function which is already known to override a
12798   // non-deleted virtual function.
12799   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12800     bool IssuedDiagnostic = false;
12801     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12802                                         E = MD->end_overridden_methods();
12803          I != E; ++I) {
12804       if (!(*MD->begin_overridden_methods())->isDeleted()) {
12805         if (!IssuedDiagnostic) {
12806           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12807           IssuedDiagnostic = true;
12808         }
12809         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12810       }
12811     }
12812   }
12813
12814   // C++11 [basic.start.main]p3:
12815   //   A program that defines main as deleted [...] is ill-formed.
12816   if (Fn->isMain())
12817     Diag(DelLoc, diag::err_deleted_main);
12818
12819   Fn->setDeletedAsWritten();
12820 }
12821
12822 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12823   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12824
12825   if (MD) {
12826     if (MD->getParent()->isDependentType()) {
12827       MD->setDefaulted();
12828       MD->setExplicitlyDefaulted();
12829       return;
12830     }
12831
12832     CXXSpecialMember Member = getSpecialMember(MD);
12833     if (Member == CXXInvalid) {
12834       if (!MD->isInvalidDecl())
12835         Diag(DefaultLoc, diag::err_default_special_members);
12836       return;
12837     }
12838
12839     MD->setDefaulted();
12840     MD->setExplicitlyDefaulted();
12841
12842     // If this definition appears within the record, do the checking when
12843     // the record is complete.
12844     const FunctionDecl *Primary = MD;
12845     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12846       // Find the uninstantiated declaration that actually had the '= default'
12847       // on it.
12848       Pattern->isDefined(Primary);
12849
12850     // If the method was defaulted on its first declaration, we will have
12851     // already performed the checking in CheckCompletedCXXClass. Such a
12852     // declaration doesn't trigger an implicit definition.
12853     if (Primary == Primary->getCanonicalDecl())
12854       return;
12855
12856     CheckExplicitlyDefaultedSpecialMember(MD);
12857
12858     if (MD->isInvalidDecl())
12859       return;
12860
12861     switch (Member) {
12862     case CXXDefaultConstructor:
12863       DefineImplicitDefaultConstructor(DefaultLoc,
12864                                        cast<CXXConstructorDecl>(MD));
12865       break;
12866     case CXXCopyConstructor:
12867       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12868       break;
12869     case CXXCopyAssignment:
12870       DefineImplicitCopyAssignment(DefaultLoc, MD);
12871       break;
12872     case CXXDestructor:
12873       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12874       break;
12875     case CXXMoveConstructor:
12876       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12877       break;
12878     case CXXMoveAssignment:
12879       DefineImplicitMoveAssignment(DefaultLoc, MD);
12880       break;
12881     case CXXInvalid:
12882       llvm_unreachable("Invalid special member.");
12883     }
12884   } else {
12885     Diag(DefaultLoc, diag::err_default_special_members);
12886   }
12887 }
12888
12889 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12890   for (Stmt *SubStmt : S->children()) {
12891     if (!SubStmt)
12892       continue;
12893     if (isa<ReturnStmt>(SubStmt))
12894       Self.Diag(SubStmt->getLocStart(),
12895            diag::err_return_in_constructor_handler);
12896     if (!isa<Expr>(SubStmt))
12897       SearchForReturnInStmt(Self, SubStmt);
12898   }
12899 }
12900
12901 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12902   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12903     CXXCatchStmt *Handler = TryBlock->getHandler(I);
12904     SearchForReturnInStmt(*this, Handler);
12905   }
12906 }
12907
12908 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12909                                              const CXXMethodDecl *Old) {
12910   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12911   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12912
12913   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12914
12915   // If the calling conventions match, everything is fine
12916   if (NewCC == OldCC)
12917     return false;
12918
12919   // If the calling conventions mismatch because the new function is static,
12920   // suppress the calling convention mismatch error; the error about static
12921   // function override (err_static_overrides_virtual from
12922   // Sema::CheckFunctionDeclaration) is more clear.
12923   if (New->getStorageClass() == SC_Static)
12924     return false;
12925
12926   Diag(New->getLocation(),
12927        diag::err_conflicting_overriding_cc_attributes)
12928     << New->getDeclName() << New->getType() << Old->getType();
12929   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12930   return true;
12931 }
12932
12933 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12934                                              const CXXMethodDecl *Old) {
12935   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12936   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12937
12938   if (Context.hasSameType(NewTy, OldTy) ||
12939       NewTy->isDependentType() || OldTy->isDependentType())
12940     return false;
12941
12942   // Check if the return types are covariant
12943   QualType NewClassTy, OldClassTy;
12944
12945   /// Both types must be pointers or references to classes.
12946   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12947     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12948       NewClassTy = NewPT->getPointeeType();
12949       OldClassTy = OldPT->getPointeeType();
12950     }
12951   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12952     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12953       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12954         NewClassTy = NewRT->getPointeeType();
12955         OldClassTy = OldRT->getPointeeType();
12956       }
12957     }
12958   }
12959
12960   // The return types aren't either both pointers or references to a class type.
12961   if (NewClassTy.isNull()) {
12962     Diag(New->getLocation(),
12963          diag::err_different_return_type_for_overriding_virtual_function)
12964         << New->getDeclName() << NewTy << OldTy
12965         << New->getReturnTypeSourceRange();
12966     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12967         << Old->getReturnTypeSourceRange();
12968
12969     return true;
12970   }
12971
12972   // C++ [class.virtual]p6:
12973   //   If the return type of D::f differs from the return type of B::f, the 
12974   //   class type in the return type of D::f shall be complete at the point of
12975   //   declaration of D::f or shall be the class type D.
12976   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12977     if (!RT->isBeingDefined() &&
12978         RequireCompleteType(New->getLocation(), NewClassTy, 
12979                             diag::err_covariant_return_incomplete,
12980                             New->getDeclName()))
12981     return true;
12982   }
12983
12984   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12985     // Check if the new class derives from the old class.
12986     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12987       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12988           << New->getDeclName() << NewTy << OldTy
12989           << New->getReturnTypeSourceRange();
12990       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12991           << Old->getReturnTypeSourceRange();
12992       return true;
12993     }
12994
12995     // Check if we the conversion from derived to base is valid.
12996     if (CheckDerivedToBaseConversion(
12997             NewClassTy, OldClassTy,
12998             diag::err_covariant_return_inaccessible_base,
12999             diag::err_covariant_return_ambiguous_derived_to_base_conv,
13000             New->getLocation(), New->getReturnTypeSourceRange(),
13001             New->getDeclName(), nullptr)) {
13002       // FIXME: this note won't trigger for delayed access control
13003       // diagnostics, and it's impossible to get an undelayed error
13004       // here from access control during the original parse because
13005       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
13006       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13007           << Old->getReturnTypeSourceRange();
13008       return true;
13009     }
13010   }
13011
13012   // The qualifiers of the return types must be the same.
13013   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
13014     Diag(New->getLocation(),
13015          diag::err_covariant_return_type_different_qualifications)
13016         << New->getDeclName() << NewTy << OldTy
13017         << New->getReturnTypeSourceRange();
13018     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13019         << Old->getReturnTypeSourceRange();
13020     return true;
13021   };
13022
13023
13024   // The new class type must have the same or less qualifiers as the old type.
13025   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
13026     Diag(New->getLocation(),
13027          diag::err_covariant_return_type_class_type_more_qualified)
13028         << New->getDeclName() << NewTy << OldTy
13029         << New->getReturnTypeSourceRange();
13030     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13031         << Old->getReturnTypeSourceRange();
13032     return true;
13033   };
13034
13035   return false;
13036 }
13037
13038 /// \brief Mark the given method pure.
13039 ///
13040 /// \param Method the method to be marked pure.
13041 ///
13042 /// \param InitRange the source range that covers the "0" initializer.
13043 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
13044   SourceLocation EndLoc = InitRange.getEnd();
13045   if (EndLoc.isValid())
13046     Method->setRangeEnd(EndLoc);
13047
13048   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13049     Method->setPure();
13050     return false;
13051   }
13052
13053   if (!Method->isInvalidDecl())
13054     Diag(Method->getLocation(), diag::err_non_virtual_pure)
13055       << Method->getDeclName() << InitRange;
13056   return true;
13057 }
13058
13059 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
13060   if (D->getFriendObjectKind())
13061     Diag(D->getLocation(), diag::err_pure_friend);
13062   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
13063     CheckPureMethod(M, ZeroLoc);
13064   else
13065     Diag(D->getLocation(), diag::err_illegal_initializer);
13066 }
13067
13068 /// \brief Determine whether the given declaration is a static data member.
13069 static bool isStaticDataMember(const Decl *D) {
13070   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13071     return Var->isStaticDataMember();
13072
13073   return false;
13074 }
13075
13076 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13077 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
13078 /// is a fresh scope pushed for just this purpose.
13079 ///
13080 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13081 /// static data member of class X, names should be looked up in the scope of
13082 /// class X.
13083 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
13084   // If there is no declaration, there was an error parsing it.
13085   if (!D || D->isInvalidDecl())
13086     return;
13087
13088   // We will always have a nested name specifier here, but this declaration
13089   // might not be out of line if the specifier names the current namespace:
13090   //   extern int n;
13091   //   int ::n = 0;
13092   if (D->isOutOfLine())
13093     EnterDeclaratorContext(S, D->getDeclContext());
13094
13095   // If we are parsing the initializer for a static data member, push a
13096   // new expression evaluation context that is associated with this static
13097   // data member.
13098   if (isStaticDataMember(D))
13099     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
13100 }
13101
13102 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
13103 /// initializer for the out-of-line declaration 'D'.
13104 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
13105   // If there is no declaration, there was an error parsing it.
13106   if (!D || D->isInvalidDecl())
13107     return;
13108
13109   if (isStaticDataMember(D))
13110     PopExpressionEvaluationContext();
13111
13112   if (D->isOutOfLine())
13113     ExitDeclaratorContext(S);
13114 }
13115
13116 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13117 /// C++ if/switch/while/for statement.
13118 /// e.g: "if (int x = f()) {...}"
13119 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
13120   // C++ 6.4p2:
13121   // The declarator shall not specify a function or an array.
13122   // The type-specifier-seq shall not contain typedef and shall not declare a
13123   // new class or enumeration.
13124   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13125          "Parser allowed 'typedef' as storage class of condition decl.");
13126
13127   Decl *Dcl = ActOnDeclarator(S, D);
13128   if (!Dcl)
13129     return true;
13130
13131   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13132     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
13133       << D.getSourceRange();
13134     return true;
13135   }
13136
13137   return Dcl;
13138 }
13139
13140 void Sema::LoadExternalVTableUses() {
13141   if (!ExternalSource)
13142     return;
13143   
13144   SmallVector<ExternalVTableUse, 4> VTables;
13145   ExternalSource->ReadUsedVTables(VTables);
13146   SmallVector<VTableUse, 4> NewUses;
13147   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13148     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13149       = VTablesUsed.find(VTables[I].Record);
13150     // Even if a definition wasn't required before, it may be required now.
13151     if (Pos != VTablesUsed.end()) {
13152       if (!Pos->second && VTables[I].DefinitionRequired)
13153         Pos->second = true;
13154       continue;
13155     }
13156     
13157     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13158     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13159   }
13160   
13161   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13162 }
13163
13164 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13165                           bool DefinitionRequired) {
13166   // Ignore any vtable uses in unevaluated operands or for classes that do
13167   // not have a vtable.
13168   if (!Class->isDynamicClass() || Class->isDependentContext() ||
13169       CurContext->isDependentContext() || isUnevaluatedContext())
13170     return;
13171
13172   // Try to insert this class into the map.
13173   LoadExternalVTableUses();
13174   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13175   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13176     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13177   if (!Pos.second) {
13178     // If we already had an entry, check to see if we are promoting this vtable
13179     // to require a definition. If so, we need to reappend to the VTableUses
13180     // list, since we may have already processed the first entry.
13181     if (DefinitionRequired && !Pos.first->second) {
13182       Pos.first->second = true;
13183     } else {
13184       // Otherwise, we can early exit.
13185       return;
13186     }
13187   } else {
13188     // The Microsoft ABI requires that we perform the destructor body
13189     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13190     // the deleting destructor is emitted with the vtable, not with the
13191     // destructor definition as in the Itanium ABI.
13192     // If it has a definition, we do the check at that point instead.
13193     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13194         Class->hasUserDeclaredDestructor() &&
13195         !Class->getDestructor()->isDefined() &&
13196         !Class->getDestructor()->isDeleted()) {
13197       CXXDestructorDecl *DD = Class->getDestructor();
13198       ContextRAII SavedContext(*this, DD);
13199       CheckDestructor(DD);
13200     }
13201   }
13202
13203   // Local classes need to have their virtual members marked
13204   // immediately. For all other classes, we mark their virtual members
13205   // at the end of the translation unit.
13206   if (Class->isLocalClass())
13207     MarkVirtualMembersReferenced(Loc, Class);
13208   else
13209     VTableUses.push_back(std::make_pair(Class, Loc));
13210 }
13211
13212 bool Sema::DefineUsedVTables() {
13213   LoadExternalVTableUses();
13214   if (VTableUses.empty())
13215     return false;
13216
13217   // Note: The VTableUses vector could grow as a result of marking
13218   // the members of a class as "used", so we check the size each
13219   // time through the loop and prefer indices (which are stable) to
13220   // iterators (which are not).
13221   bool DefinedAnything = false;
13222   for (unsigned I = 0; I != VTableUses.size(); ++I) {
13223     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
13224     if (!Class)
13225       continue;
13226
13227     SourceLocation Loc = VTableUses[I].second;
13228
13229     bool DefineVTable = true;
13230
13231     // If this class has a key function, but that key function is
13232     // defined in another translation unit, we don't need to emit the
13233     // vtable even though we're using it.
13234     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
13235     if (KeyFunction && !KeyFunction->hasBody()) {
13236       // The key function is in another translation unit.
13237       DefineVTable = false;
13238       TemplateSpecializationKind TSK =
13239           KeyFunction->getTemplateSpecializationKind();
13240       assert(TSK != TSK_ExplicitInstantiationDefinition &&
13241              TSK != TSK_ImplicitInstantiation &&
13242              "Instantiations don't have key functions");
13243       (void)TSK;
13244     } else if (!KeyFunction) {
13245       // If we have a class with no key function that is the subject
13246       // of an explicit instantiation declaration, suppress the
13247       // vtable; it will live with the explicit instantiation
13248       // definition.
13249       bool IsExplicitInstantiationDeclaration
13250         = Class->getTemplateSpecializationKind()
13251                                       == TSK_ExplicitInstantiationDeclaration;
13252       for (auto R : Class->redecls()) {
13253         TemplateSpecializationKind TSK
13254           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
13255         if (TSK == TSK_ExplicitInstantiationDeclaration)
13256           IsExplicitInstantiationDeclaration = true;
13257         else if (TSK == TSK_ExplicitInstantiationDefinition) {
13258           IsExplicitInstantiationDeclaration = false;
13259           break;
13260         }
13261       }
13262
13263       if (IsExplicitInstantiationDeclaration)
13264         DefineVTable = false;
13265     }
13266
13267     // The exception specifications for all virtual members may be needed even
13268     // if we are not providing an authoritative form of the vtable in this TU.
13269     // We may choose to emit it available_externally anyway.
13270     if (!DefineVTable) {
13271       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13272       continue;
13273     }
13274
13275     // Mark all of the virtual members of this class as referenced, so
13276     // that we can build a vtable. Then, tell the AST consumer that a
13277     // vtable for this class is required.
13278     DefinedAnything = true;
13279     MarkVirtualMembersReferenced(Loc, Class);
13280     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13281     if (VTablesUsed[Canonical])
13282       Consumer.HandleVTable(Class);
13283
13284     // Optionally warn if we're emitting a weak vtable.
13285     if (Class->isExternallyVisible() &&
13286         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
13287       const FunctionDecl *KeyFunctionDef = nullptr;
13288       if (!KeyFunction || 
13289           (KeyFunction->hasBody(KeyFunctionDef) && 
13290            KeyFunctionDef->isInlined()))
13291         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13292              TSK_ExplicitInstantiationDefinition 
13293              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 
13294           << Class;
13295     }
13296   }
13297   VTableUses.clear();
13298
13299   return DefinedAnything;
13300 }
13301
13302 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13303                                                  const CXXRecordDecl *RD) {
13304   for (const auto *I : RD->methods())
13305     if (I->isVirtual() && !I->isPure())
13306       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
13307 }
13308
13309 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13310                                         const CXXRecordDecl *RD) {
13311   // Mark all functions which will appear in RD's vtable as used.
13312   CXXFinalOverriderMap FinalOverriders;
13313   RD->getFinalOverriders(FinalOverriders);
13314   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13315                                             E = FinalOverriders.end();
13316        I != E; ++I) {
13317     for (OverridingMethods::const_iterator OI = I->second.begin(),
13318                                            OE = I->second.end();
13319          OI != OE; ++OI) {
13320       assert(OI->second.size() > 0 && "no final overrider");
13321       CXXMethodDecl *Overrider = OI->second.front().Method;
13322
13323       // C++ [basic.def.odr]p2:
13324       //   [...] A virtual member function is used if it is not pure. [...]
13325       if (!Overrider->isPure())
13326         MarkFunctionReferenced(Loc, Overrider);
13327     }
13328   }
13329
13330   // Only classes that have virtual bases need a VTT.
13331   if (RD->getNumVBases() == 0)
13332     return;
13333
13334   for (const auto &I : RD->bases()) {
13335     const CXXRecordDecl *Base =
13336         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
13337     if (Base->getNumVBases() == 0)
13338       continue;
13339     MarkVirtualMembersReferenced(Loc, Base);
13340   }
13341 }
13342
13343 /// SetIvarInitializers - This routine builds initialization ASTs for the
13344 /// Objective-C implementation whose ivars need be initialized.
13345 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
13346   if (!getLangOpts().CPlusPlus)
13347     return;
13348   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
13349     SmallVector<ObjCIvarDecl*, 8> ivars;
13350     CollectIvarsToConstructOrDestruct(OID, ivars);
13351     if (ivars.empty())
13352       return;
13353     SmallVector<CXXCtorInitializer*, 32> AllToInit;
13354     for (unsigned i = 0; i < ivars.size(); i++) {
13355       FieldDecl *Field = ivars[i];
13356       if (Field->isInvalidDecl())
13357         continue;
13358       
13359       CXXCtorInitializer *Member;
13360       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13361       InitializationKind InitKind = 
13362         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
13363
13364       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13365       ExprResult MemberInit =
13366         InitSeq.Perform(*this, InitEntity, InitKind, None);
13367       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
13368       // Note, MemberInit could actually come back empty if no initialization 
13369       // is required (e.g., because it would call a trivial default constructor)
13370       if (!MemberInit.get() || MemberInit.isInvalid())
13371         continue;
13372
13373       Member =
13374         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13375                                          SourceLocation(),
13376                                          MemberInit.getAs<Expr>(),
13377                                          SourceLocation());
13378       AllToInit.push_back(Member);
13379       
13380       // Be sure that the destructor is accessible and is marked as referenced.
13381       if (const RecordType *RecordTy =
13382               Context.getBaseElementType(Field->getType())
13383                   ->getAs<RecordType>()) {
13384         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
13385         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
13386           MarkFunctionReferenced(Field->getLocation(), Destructor);
13387           CheckDestructorAccess(Field->getLocation(), Destructor,
13388                             PDiag(diag::err_access_dtor_ivar)
13389                               << Context.getBaseElementType(Field->getType()));
13390         }
13391       }      
13392     }
13393     ObjCImplementation->setIvarInitializers(Context, 
13394                                             AllToInit.data(), AllToInit.size());
13395   }
13396 }
13397
13398 static
13399 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13400                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13401                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13402                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13403                            Sema &S) {
13404   if (Ctor->isInvalidDecl())
13405     return;
13406
13407   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13408
13409   // Target may not be determinable yet, for instance if this is a dependent
13410   // call in an uninstantiated template.
13411   if (Target) {
13412     const FunctionDecl *FNTarget = nullptr;
13413     (void)Target->hasBody(FNTarget);
13414     Target = const_cast<CXXConstructorDecl*>(
13415       cast_or_null<CXXConstructorDecl>(FNTarget));
13416   }
13417
13418   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13419                      // Avoid dereferencing a null pointer here.
13420                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13421
13422   if (!Current.insert(Canonical).second)
13423     return;
13424
13425   // We know that beyond here, we aren't chaining into a cycle.
13426   if (!Target || !Target->isDelegatingConstructor() ||
13427       Target->isInvalidDecl() || Valid.count(TCanonical)) {
13428     Valid.insert(Current.begin(), Current.end());
13429     Current.clear();
13430   // We've hit a cycle.
13431   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13432              Current.count(TCanonical)) {
13433     // If we haven't diagnosed this cycle yet, do so now.
13434     if (!Invalid.count(TCanonical)) {
13435       S.Diag((*Ctor->init_begin())->getSourceLocation(),
13436              diag::warn_delegating_ctor_cycle)
13437         << Ctor;
13438
13439       // Don't add a note for a function delegating directly to itself.
13440       if (TCanonical != Canonical)
13441         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13442
13443       CXXConstructorDecl *C = Target;
13444       while (C->getCanonicalDecl() != Canonical) {
13445         const FunctionDecl *FNTarget = nullptr;
13446         (void)C->getTargetConstructor()->hasBody(FNTarget);
13447         assert(FNTarget && "Ctor cycle through bodiless function");
13448
13449         C = const_cast<CXXConstructorDecl*>(
13450           cast<CXXConstructorDecl>(FNTarget));
13451         S.Diag(C->getLocation(), diag::note_which_delegates_to);
13452       }
13453     }
13454
13455     Invalid.insert(Current.begin(), Current.end());
13456     Current.clear();
13457   } else {
13458     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13459   }
13460 }
13461    
13462
13463 void Sema::CheckDelegatingCtorCycles() {
13464   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13465
13466   for (DelegatingCtorDeclsType::iterator
13467          I = DelegatingCtorDecls.begin(ExternalSource),
13468          E = DelegatingCtorDecls.end();
13469        I != E; ++I)
13470     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13471
13472   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13473                                                          CE = Invalid.end();
13474        CI != CE; ++CI)
13475     (*CI)->setInvalidDecl();
13476 }
13477
13478 namespace {
13479   /// \brief AST visitor that finds references to the 'this' expression.
13480   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13481     Sema &S;
13482     
13483   public:
13484     explicit FindCXXThisExpr(Sema &S) : S(S) { }
13485     
13486     bool VisitCXXThisExpr(CXXThisExpr *E) {
13487       S.Diag(E->getLocation(), diag::err_this_static_member_func)
13488         << E->isImplicit();
13489       return false;
13490     }
13491   };
13492 }
13493
13494 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13495   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13496   if (!TSInfo)
13497     return false;
13498   
13499   TypeLoc TL = TSInfo->getTypeLoc();
13500   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13501   if (!ProtoTL)
13502     return false;
13503   
13504   // C++11 [expr.prim.general]p3:
13505   //   [The expression this] shall not appear before the optional 
13506   //   cv-qualifier-seq and it shall not appear within the declaration of a 
13507   //   static member function (although its type and value category are defined
13508   //   within a static member function as they are within a non-static member
13509   //   function). [ Note: this is because declaration matching does not occur
13510   //  until the complete declarator is known. - end note ]
13511   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13512   FindCXXThisExpr Finder(*this);
13513   
13514   // If the return type came after the cv-qualifier-seq, check it now.
13515   if (Proto->hasTrailingReturn() &&
13516       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13517     return true;
13518
13519   // Check the exception specification.
13520   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13521     return true;
13522   
13523   return checkThisInStaticMemberFunctionAttributes(Method);
13524 }
13525
13526 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13527   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13528   if (!TSInfo)
13529     return false;
13530   
13531   TypeLoc TL = TSInfo->getTypeLoc();
13532   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13533   if (!ProtoTL)
13534     return false;
13535   
13536   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13537   FindCXXThisExpr Finder(*this);
13538
13539   switch (Proto->getExceptionSpecType()) {
13540   case EST_Unparsed:
13541   case EST_Uninstantiated:
13542   case EST_Unevaluated:
13543   case EST_BasicNoexcept:
13544   case EST_DynamicNone:
13545   case EST_MSAny:
13546   case EST_None:
13547     break;
13548     
13549   case EST_ComputedNoexcept:
13550     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13551       return true;
13552     
13553   case EST_Dynamic:
13554     for (const auto &E : Proto->exceptions()) {
13555       if (!Finder.TraverseType(E))
13556         return true;
13557     }
13558     break;
13559   }
13560
13561   return false;
13562 }
13563
13564 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13565   FindCXXThisExpr Finder(*this);
13566
13567   // Check attributes.
13568   for (const auto *A : Method->attrs()) {
13569     // FIXME: This should be emitted by tblgen.
13570     Expr *Arg = nullptr;
13571     ArrayRef<Expr *> Args;
13572     if (const auto *G = dyn_cast<GuardedByAttr>(A))
13573       Arg = G->getArg();
13574     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13575       Arg = G->getArg();
13576     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13577       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13578     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13579       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13580     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13581       Arg = ETLF->getSuccessValue();
13582       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13583     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13584       Arg = STLF->getSuccessValue();
13585       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13586     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13587       Arg = LR->getArg();
13588     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13589       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13590     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13591       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13592     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13593       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13594     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13595       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13596     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13597       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13598
13599     if (Arg && !Finder.TraverseStmt(Arg))
13600       return true;
13601     
13602     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13603       if (!Finder.TraverseStmt(Args[I]))
13604         return true;
13605     }
13606   }
13607   
13608   return false;
13609 }
13610
13611 void Sema::checkExceptionSpecification(
13612     bool IsTopLevel, ExceptionSpecificationType EST,
13613     ArrayRef<ParsedType> DynamicExceptions,
13614     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13615     SmallVectorImpl<QualType> &Exceptions,
13616     FunctionProtoType::ExceptionSpecInfo &ESI) {
13617   Exceptions.clear();
13618   ESI.Type = EST;
13619   if (EST == EST_Dynamic) {
13620     Exceptions.reserve(DynamicExceptions.size());
13621     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13622       // FIXME: Preserve type source info.
13623       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13624
13625       if (IsTopLevel) {
13626         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13627         collectUnexpandedParameterPacks(ET, Unexpanded);
13628         if (!Unexpanded.empty()) {
13629           DiagnoseUnexpandedParameterPacks(
13630               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13631               Unexpanded);
13632           continue;
13633         }
13634       }
13635
13636       // Check that the type is valid for an exception spec, and
13637       // drop it if not.
13638       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13639         Exceptions.push_back(ET);
13640     }
13641     ESI.Exceptions = Exceptions;
13642     return;
13643   }
13644
13645   if (EST == EST_ComputedNoexcept) {
13646     // If an error occurred, there's no expression here.
13647     if (NoexceptExpr) {
13648       assert((NoexceptExpr->isTypeDependent() ||
13649               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13650               Context.BoolTy) &&
13651              "Parser should have made sure that the expression is boolean");
13652       if (IsTopLevel && NoexceptExpr &&
13653           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13654         ESI.Type = EST_BasicNoexcept;
13655         return;
13656       }
13657
13658       if (!NoexceptExpr->isValueDependent())
13659         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13660                          diag::err_noexcept_needs_constant_expression,
13661                          /*AllowFold*/ false).get();
13662       ESI.NoexceptExpr = NoexceptExpr;
13663     }
13664     return;
13665   }
13666 }
13667
13668 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13669              ExceptionSpecificationType EST,
13670              SourceRange SpecificationRange,
13671              ArrayRef<ParsedType> DynamicExceptions,
13672              ArrayRef<SourceRange> DynamicExceptionRanges,
13673              Expr *NoexceptExpr) {
13674   if (!MethodD)
13675     return;
13676
13677   // Dig out the method we're referring to.
13678   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13679     MethodD = FunTmpl->getTemplatedDecl();
13680
13681   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13682   if (!Method)
13683     return;
13684
13685   // Check the exception specification.
13686   llvm::SmallVector<QualType, 4> Exceptions;
13687   FunctionProtoType::ExceptionSpecInfo ESI;
13688   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13689                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
13690                               ESI);
13691
13692   // Update the exception specification on the function type.
13693   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13694
13695   if (Method->isStatic())
13696     checkThisInStaticMemberFunctionExceptionSpec(Method);
13697
13698   if (Method->isVirtual()) {
13699     // Check overrides, which we previously had to delay.
13700     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13701                                      OEnd = Method->end_overridden_methods();
13702          O != OEnd; ++O)
13703       CheckOverridingFunctionExceptionSpec(Method, *O);
13704   }
13705 }
13706
13707 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13708 ///
13709 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13710                                        SourceLocation DeclStart,
13711                                        Declarator &D, Expr *BitWidth,
13712                                        InClassInitStyle InitStyle,
13713                                        AccessSpecifier AS,
13714                                        AttributeList *MSPropertyAttr) {
13715   IdentifierInfo *II = D.getIdentifier();
13716   if (!II) {
13717     Diag(DeclStart, diag::err_anonymous_property);
13718     return nullptr;
13719   }
13720   SourceLocation Loc = D.getIdentifierLoc();
13721
13722   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13723   QualType T = TInfo->getType();
13724   if (getLangOpts().CPlusPlus) {
13725     CheckExtraCXXDefaultArguments(D);
13726
13727     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13728                                         UPPC_DataMemberType)) {
13729       D.setInvalidType();
13730       T = Context.IntTy;
13731       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13732     }
13733   }
13734
13735   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13736
13737   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13738     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13739          diag::err_invalid_thread)
13740       << DeclSpec::getSpecifierName(TSCS);
13741
13742   // Check to see if this name was declared as a member previously
13743   NamedDecl *PrevDecl = nullptr;
13744   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13745   LookupName(Previous, S);
13746   switch (Previous.getResultKind()) {
13747   case LookupResult::Found:
13748   case LookupResult::FoundUnresolvedValue:
13749     PrevDecl = Previous.getAsSingle<NamedDecl>();
13750     break;
13751
13752   case LookupResult::FoundOverloaded:
13753     PrevDecl = Previous.getRepresentativeDecl();
13754     break;
13755
13756   case LookupResult::NotFound:
13757   case LookupResult::NotFoundInCurrentInstantiation:
13758   case LookupResult::Ambiguous:
13759     break;
13760   }
13761
13762   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13763     // Maybe we will complain about the shadowed template parameter.
13764     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13765     // Just pretend that we didn't see the previous declaration.
13766     PrevDecl = nullptr;
13767   }
13768
13769   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13770     PrevDecl = nullptr;
13771
13772   SourceLocation TSSL = D.getLocStart();
13773   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13774   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13775       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13776   ProcessDeclAttributes(TUScope, NewPD, D);
13777   NewPD->setAccess(AS);
13778
13779   if (NewPD->isInvalidDecl())
13780     Record->setInvalidDecl();
13781
13782   if (D.getDeclSpec().isModulePrivateSpecified())
13783     NewPD->setModulePrivate();
13784
13785   if (NewPD->isInvalidDecl() && PrevDecl) {
13786     // Don't introduce NewFD into scope; there's already something
13787     // with the same name in the same scope.
13788   } else if (II) {
13789     PushOnScopeChains(NewPD, S);
13790   } else
13791     Record->addDecl(NewPD);
13792
13793   return NewPD;
13794 }