]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp
Merge lldb trunk r300422 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaDecl.cpp
1 //===--- SemaDecl.cpp - Semantic Analysis for 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 declarations.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50
51 using namespace clang;
52 using namespace sema;
53
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62
63 namespace {
64
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68                        bool AllowTemplates=false)
69       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowTemplates(AllowTemplates) {
71     WantExpressionKeywords = false;
72     WantCXXNamedCasts = false;
73     WantRemainingKeywords = false;
74   }
75
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79       bool AllowedTemplate = AllowTemplates && getAsTypeTemplateDecl(ND);
80       return (IsType || AllowedTemplate) &&
81              (AllowInvalidDecl || !ND->isInvalidDecl());
82     }
83     return !WantClassName && candidate.isKeyword();
84   }
85
86  private:
87   bool AllowInvalidDecl;
88   bool WantClassName;
89   bool AllowTemplates;
90 };
91
92 } // end anonymous namespace
93
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96   switch (Kind) {
97   // FIXME: Take into account the current language when deciding whether a
98   // token kind is a valid type specifier
99   case tok::kw_short:
100   case tok::kw_long:
101   case tok::kw___int64:
102   case tok::kw___int128:
103   case tok::kw_signed:
104   case tok::kw_unsigned:
105   case tok::kw_void:
106   case tok::kw_char:
107   case tok::kw_int:
108   case tok::kw_half:
109   case tok::kw_float:
110   case tok::kw_double:
111   case tok::kw___float128:
112   case tok::kw_wchar_t:
113   case tok::kw_bool:
114   case tok::kw___underlying_type:
115   case tok::kw___auto_type:
116     return true;
117
118   case tok::annot_typename:
119   case tok::kw_char16_t:
120   case tok::kw_char32_t:
121   case tok::kw_typeof:
122   case tok::annot_decltype:
123   case tok::kw_decltype:
124     return getLangOpts().CPlusPlus;
125
126   default:
127     break;
128   }
129
130   return false;
131 }
132
133 namespace {
134 enum class UnqualifiedTypeNameLookupResult {
135   NotFound,
136   FoundNonType,
137   FoundType
138 };
139 } // end anonymous namespace
140
141 /// \brief Tries to perform unqualified lookup of the type decls in bases for
142 /// dependent class.
143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
144 /// type decl, \a FoundType if only type decls are found.
145 static UnqualifiedTypeNameLookupResult
146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
147                                 SourceLocation NameLoc,
148                                 const CXXRecordDecl *RD) {
149   if (!RD->hasDefinition())
150     return UnqualifiedTypeNameLookupResult::NotFound;
151   // Look for type decls in base classes.
152   UnqualifiedTypeNameLookupResult FoundTypeDecl =
153       UnqualifiedTypeNameLookupResult::NotFound;
154   for (const auto &Base : RD->bases()) {
155     const CXXRecordDecl *BaseRD = nullptr;
156     if (auto *BaseTT = Base.getType()->getAs<TagType>())
157       BaseRD = BaseTT->getAsCXXRecordDecl();
158     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
159       // Look for type decls in dependent base classes that have known primary
160       // templates.
161       if (!TST || !TST->isDependentType())
162         continue;
163       auto *TD = TST->getTemplateName().getAsTemplateDecl();
164       if (!TD)
165         continue;
166       if (auto *BasePrimaryTemplate =
167           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
168         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
169           BaseRD = BasePrimaryTemplate;
170         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
171           if (const ClassTemplatePartialSpecializationDecl *PS =
172                   CTD->findPartialSpecialization(Base.getType()))
173             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
174               BaseRD = PS;
175         }
176       }
177     }
178     if (BaseRD) {
179       for (NamedDecl *ND : BaseRD->lookup(&II)) {
180         if (!isa<TypeDecl>(ND))
181           return UnqualifiedTypeNameLookupResult::FoundNonType;
182         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183       }
184       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
185         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
186         case UnqualifiedTypeNameLookupResult::FoundNonType:
187           return UnqualifiedTypeNameLookupResult::FoundNonType;
188         case UnqualifiedTypeNameLookupResult::FoundType:
189           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
190           break;
191         case UnqualifiedTypeNameLookupResult::NotFound:
192           break;
193         }
194       }
195     }
196   }
197
198   return FoundTypeDecl;
199 }
200
201 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
202                                                       const IdentifierInfo &II,
203                                                       SourceLocation NameLoc) {
204   // Lookup in the parent class template context, if any.
205   const CXXRecordDecl *RD = nullptr;
206   UnqualifiedTypeNameLookupResult FoundTypeDecl =
207       UnqualifiedTypeNameLookupResult::NotFound;
208   for (DeclContext *DC = S.CurContext;
209        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
210        DC = DC->getParent()) {
211     // Look for type decls in dependent base classes that have known primary
212     // templates.
213     RD = dyn_cast<CXXRecordDecl>(DC);
214     if (RD && RD->getDescribedClassTemplate())
215       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
216   }
217   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
218     return nullptr;
219
220   // We found some types in dependent base classes.  Recover as if the user
221   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
222   // lookup during template instantiation.
223   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
224
225   ASTContext &Context = S.Context;
226   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
227                                           cast<Type>(Context.getRecordType(RD)));
228   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
229
230   CXXScopeSpec SS;
231   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
232
233   TypeLocBuilder Builder;
234   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
235   DepTL.setNameLoc(NameLoc);
236   DepTL.setElaboratedKeywordLoc(SourceLocation());
237   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
238   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
239 }
240
241 /// \brief If the identifier refers to a type name within this scope,
242 /// return the declaration of that type.
243 ///
244 /// This routine performs ordinary name lookup of the identifier II
245 /// within the given scope, with optional C++ scope specifier SS, to
246 /// determine whether the name refers to a type. If so, returns an
247 /// opaque pointer (actually a QualType) corresponding to that
248 /// type. Otherwise, returns NULL.
249 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
250                              Scope *S, CXXScopeSpec *SS,
251                              bool isClassName, bool HasTrailingDot,
252                              ParsedType ObjectTypePtr,
253                              bool IsCtorOrDtorName,
254                              bool WantNontrivialTypeSourceInfo,
255                              bool IsClassTemplateDeductionContext,
256                              IdentifierInfo **CorrectedII) {
257   // FIXME: Consider allowing this outside C++1z mode as an extension.
258   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
259                               getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
260                               !isClassName && !HasTrailingDot;
261
262   // Determine where we will perform name lookup.
263   DeclContext *LookupCtx = nullptr;
264   if (ObjectTypePtr) {
265     QualType ObjectType = ObjectTypePtr.get();
266     if (ObjectType->isRecordType())
267       LookupCtx = computeDeclContext(ObjectType);
268   } else if (SS && SS->isNotEmpty()) {
269     LookupCtx = computeDeclContext(*SS, false);
270
271     if (!LookupCtx) {
272       if (isDependentScopeSpecifier(*SS)) {
273         // C++ [temp.res]p3:
274         //   A qualified-id that refers to a type and in which the
275         //   nested-name-specifier depends on a template-parameter (14.6.2)
276         //   shall be prefixed by the keyword typename to indicate that the
277         //   qualified-id denotes a type, forming an
278         //   elaborated-type-specifier (7.1.5.3).
279         //
280         // We therefore do not perform any name lookup if the result would
281         // refer to a member of an unknown specialization.
282         if (!isClassName && !IsCtorOrDtorName)
283           return nullptr;
284
285         // We know from the grammar that this name refers to a type,
286         // so build a dependent node to describe the type.
287         if (WantNontrivialTypeSourceInfo)
288           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
289
290         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
291         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
292                                        II, NameLoc);
293         return ParsedType::make(T);
294       }
295
296       return nullptr;
297     }
298
299     if (!LookupCtx->isDependentContext() &&
300         RequireCompleteDeclContext(*SS, LookupCtx))
301       return nullptr;
302   }
303
304   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
305   // lookup for class-names.
306   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
307                                       LookupOrdinaryName;
308   LookupResult Result(*this, &II, NameLoc, Kind);
309   if (LookupCtx) {
310     // Perform "qualified" name lookup into the declaration context we
311     // computed, which is either the type of the base of a member access
312     // expression or the declaration context associated with a prior
313     // nested-name-specifier.
314     LookupQualifiedName(Result, LookupCtx);
315
316     if (ObjectTypePtr && Result.empty()) {
317       // C++ [basic.lookup.classref]p3:
318       //   If the unqualified-id is ~type-name, the type-name is looked up
319       //   in the context of the entire postfix-expression. If the type T of
320       //   the object expression is of a class type C, the type-name is also
321       //   looked up in the scope of class C. At least one of the lookups shall
322       //   find a name that refers to (possibly cv-qualified) T.
323       LookupName(Result, S);
324     }
325   } else {
326     // Perform unqualified name lookup.
327     LookupName(Result, S);
328
329     // For unqualified lookup in a class template in MSVC mode, look into
330     // dependent base classes where the primary class template is known.
331     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
332       if (ParsedType TypeInBase =
333               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
334         return TypeInBase;
335     }
336   }
337
338   NamedDecl *IIDecl = nullptr;
339   switch (Result.getResultKind()) {
340   case LookupResult::NotFound:
341   case LookupResult::NotFoundInCurrentInstantiation:
342     if (CorrectedII) {
343       TypoCorrection Correction =
344           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
345                       llvm::make_unique<TypeNameValidatorCCC>(
346                           true, isClassName, AllowDeducedTemplate),
347                       CTK_ErrorRecovery);
348       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
349       TemplateTy Template;
350       bool MemberOfUnknownSpecialization;
351       UnqualifiedId TemplateName;
352       TemplateName.setIdentifier(NewII, NameLoc);
353       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
354       CXXScopeSpec NewSS, *NewSSPtr = SS;
355       if (SS && NNS) {
356         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
357         NewSSPtr = &NewSS;
358       }
359       if (Correction && (NNS || NewII != &II) &&
360           // Ignore a correction to a template type as the to-be-corrected
361           // identifier is not a template (typo correction for template names
362           // is handled elsewhere).
363           !(getLangOpts().CPlusPlus && NewSSPtr &&
364             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
365                            Template, MemberOfUnknownSpecialization))) {
366         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
367                                     isClassName, HasTrailingDot, ObjectTypePtr,
368                                     IsCtorOrDtorName,
369                                     WantNontrivialTypeSourceInfo,
370                                     IsClassTemplateDeductionContext);
371         if (Ty) {
372           diagnoseTypo(Correction,
373                        PDiag(diag::err_unknown_type_or_class_name_suggest)
374                          << Result.getLookupName() << isClassName);
375           if (SS && NNS)
376             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
377           *CorrectedII = NewII;
378           return Ty;
379         }
380       }
381     }
382     // If typo correction failed or was not performed, fall through
383   case LookupResult::FoundOverloaded:
384   case LookupResult::FoundUnresolvedValue:
385     Result.suppressDiagnostics();
386     return nullptr;
387
388   case LookupResult::Ambiguous:
389     // Recover from type-hiding ambiguities by hiding the type.  We'll
390     // do the lookup again when looking for an object, and we can
391     // diagnose the error then.  If we don't do this, then the error
392     // about hiding the type will be immediately followed by an error
393     // that only makes sense if the identifier was treated like a type.
394     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
395       Result.suppressDiagnostics();
396       return nullptr;
397     }
398
399     // Look to see if we have a type anywhere in the list of results.
400     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
401          Res != ResEnd; ++Res) {
402       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
403           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
404         if (!IIDecl ||
405             (*Res)->getLocation().getRawEncoding() <
406               IIDecl->getLocation().getRawEncoding())
407           IIDecl = *Res;
408       }
409     }
410
411     if (!IIDecl) {
412       // None of the entities we found is a type, so there is no way
413       // to even assume that the result is a type. In this case, don't
414       // complain about the ambiguity. The parser will either try to
415       // perform this lookup again (e.g., as an object name), which
416       // will produce the ambiguity, or will complain that it expected
417       // a type name.
418       Result.suppressDiagnostics();
419       return nullptr;
420     }
421
422     // We found a type within the ambiguous lookup; diagnose the
423     // ambiguity and then return that type. This might be the right
424     // answer, or it might not be, but it suppresses any attempt to
425     // perform the name lookup again.
426     break;
427
428   case LookupResult::Found:
429     IIDecl = Result.getFoundDecl();
430     break;
431   }
432
433   assert(IIDecl && "Didn't find decl");
434
435   QualType T;
436   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
437     // C++ [class.qual]p2: A lookup that would find the injected-class-name
438     // instead names the constructors of the class, except when naming a class.
439     // This is ill-formed when we're not actually forming a ctor or dtor name.
440     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
441     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
442     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
443         FoundRD->isInjectedClassName() &&
444         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
445       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
446           << &II << /*Type*/1;
447
448     DiagnoseUseOfDecl(IIDecl, NameLoc);
449
450     T = Context.getTypeDeclType(TD);
451     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
452   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
453     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
454     if (!HasTrailingDot)
455       T = Context.getObjCInterfaceType(IDecl);
456   } else if (AllowDeducedTemplate) {
457     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
458       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
459                                                        QualType(), false);
460   }
461
462   if (T.isNull()) {
463     // If it's not plausibly a type, suppress diagnostics.
464     Result.suppressDiagnostics();
465     return nullptr;
466   }
467
468   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
469   // constructor or destructor name (in such a case, the scope specifier
470   // will be attached to the enclosing Expr or Decl node).
471   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
472       !isa<ObjCInterfaceDecl>(IIDecl)) {
473     if (WantNontrivialTypeSourceInfo) {
474       // Construct a type with type-source information.
475       TypeLocBuilder Builder;
476       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
477
478       T = getElaboratedType(ETK_None, *SS, T);
479       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
480       ElabTL.setElaboratedKeywordLoc(SourceLocation());
481       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
482       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
483     } else {
484       T = getElaboratedType(ETK_None, *SS, T);
485     }
486   }
487
488   return ParsedType::make(T);
489 }
490
491 // Builds a fake NNS for the given decl context.
492 static NestedNameSpecifier *
493 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
494   for (;; DC = DC->getLookupParent()) {
495     DC = DC->getPrimaryContext();
496     auto *ND = dyn_cast<NamespaceDecl>(DC);
497     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
498       return NestedNameSpecifier::Create(Context, nullptr, ND);
499     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
500       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
501                                          RD->getTypeForDecl());
502     else if (isa<TranslationUnitDecl>(DC))
503       return NestedNameSpecifier::GlobalSpecifier(Context);
504   }
505   llvm_unreachable("something isn't in TU scope?");
506 }
507
508 /// Find the parent class with dependent bases of the innermost enclosing method
509 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
510 /// up allowing unqualified dependent type names at class-level, which MSVC
511 /// correctly rejects.
512 static const CXXRecordDecl *
513 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
514   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
515     DC = DC->getPrimaryContext();
516     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
517       if (MD->getParent()->hasAnyDependentBases())
518         return MD->getParent();
519   }
520   return nullptr;
521 }
522
523 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
524                                           SourceLocation NameLoc,
525                                           bool IsTemplateTypeArg) {
526   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
527
528   NestedNameSpecifier *NNS = nullptr;
529   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
530     // If we weren't able to parse a default template argument, delay lookup
531     // until instantiation time by making a non-dependent DependentTypeName. We
532     // pretend we saw a NestedNameSpecifier referring to the current scope, and
533     // lookup is retried.
534     // FIXME: This hurts our diagnostic quality, since we get errors like "no
535     // type named 'Foo' in 'current_namespace'" when the user didn't write any
536     // name specifiers.
537     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
538     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
539   } else if (const CXXRecordDecl *RD =
540                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
541     // Build a DependentNameType that will perform lookup into RD at
542     // instantiation time.
543     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
544                                       RD->getTypeForDecl());
545
546     // Diagnose that this identifier was undeclared, and retry the lookup during
547     // template instantiation.
548     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
549                                                                       << RD;
550   } else {
551     // This is not a situation that we should recover from.
552     return ParsedType();
553   }
554
555   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
556
557   // Build type location information.  We synthesized the qualifier, so we have
558   // to build a fake NestedNameSpecifierLoc.
559   NestedNameSpecifierLocBuilder NNSLocBuilder;
560   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
561   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
562
563   TypeLocBuilder Builder;
564   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
565   DepTL.setNameLoc(NameLoc);
566   DepTL.setElaboratedKeywordLoc(SourceLocation());
567   DepTL.setQualifierLoc(QualifierLoc);
568   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
569 }
570
571 /// isTagName() - This method is called *for error recovery purposes only*
572 /// to determine if the specified name is a valid tag name ("struct foo").  If
573 /// so, this returns the TST for the tag corresponding to it (TST_enum,
574 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
575 /// cases in C where the user forgot to specify the tag.
576 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
577   // Do a tag name lookup in this scope.
578   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
579   LookupName(R, S, false);
580   R.suppressDiagnostics();
581   if (R.getResultKind() == LookupResult::Found)
582     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
583       switch (TD->getTagKind()) {
584       case TTK_Struct: return DeclSpec::TST_struct;
585       case TTK_Interface: return DeclSpec::TST_interface;
586       case TTK_Union:  return DeclSpec::TST_union;
587       case TTK_Class:  return DeclSpec::TST_class;
588       case TTK_Enum:   return DeclSpec::TST_enum;
589       }
590     }
591
592   return DeclSpec::TST_unspecified;
593 }
594
595 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
596 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
597 /// then downgrade the missing typename error to a warning.
598 /// This is needed for MSVC compatibility; Example:
599 /// @code
600 /// template<class T> class A {
601 /// public:
602 ///   typedef int TYPE;
603 /// };
604 /// template<class T> class B : public A<T> {
605 /// public:
606 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
607 /// };
608 /// @endcode
609 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
610   if (CurContext->isRecord()) {
611     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
612       return true;
613
614     const Type *Ty = SS->getScopeRep()->getAsType();
615
616     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
617     for (const auto &Base : RD->bases())
618       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
619         return true;
620     return S->isFunctionPrototypeScope();
621   }
622   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
623 }
624
625 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
626                                    SourceLocation IILoc,
627                                    Scope *S,
628                                    CXXScopeSpec *SS,
629                                    ParsedType &SuggestedType,
630                                    bool AllowClassTemplates) {
631   // We don't have anything to suggest (yet).
632   SuggestedType = nullptr;
633
634   // There may have been a typo in the name of the type. Look up typo
635   // results, in case we have something that we can suggest.
636   if (TypoCorrection Corrected =
637           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
638                       llvm::make_unique<TypeNameValidatorCCC>(
639                           false, false, AllowClassTemplates),
640                       CTK_ErrorRecovery)) {
641     if (Corrected.isKeyword()) {
642       // We corrected to a keyword.
643       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
644       II = Corrected.getCorrectionAsIdentifierInfo();
645     } else {
646       // We found a similarly-named type or interface; suggest that.
647       if (!SS || !SS->isSet()) {
648         diagnoseTypo(Corrected,
649                      PDiag(diag::err_unknown_typename_suggest) << II);
650       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
651         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
652         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
653                                 II->getName().equals(CorrectedStr);
654         diagnoseTypo(Corrected,
655                      PDiag(diag::err_unknown_nested_typename_suggest)
656                        << II << DC << DroppedSpecifier << SS->getRange());
657       } else {
658         llvm_unreachable("could not have corrected a typo here");
659       }
660
661       CXXScopeSpec tmpSS;
662       if (Corrected.getCorrectionSpecifier())
663         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
664                           SourceRange(IILoc));
665       // FIXME: Support class template argument deduction here.
666       SuggestedType =
667           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
668                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
669                       /*IsCtorOrDtorName=*/false,
670                       /*NonTrivialTypeSourceInfo=*/true);
671     }
672     return;
673   }
674
675   if (getLangOpts().CPlusPlus) {
676     // See if II is a class template that the user forgot to pass arguments to.
677     UnqualifiedId Name;
678     Name.setIdentifier(II, IILoc);
679     CXXScopeSpec EmptySS;
680     TemplateTy TemplateResult;
681     bool MemberOfUnknownSpecialization;
682     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
683                        Name, nullptr, true, TemplateResult,
684                        MemberOfUnknownSpecialization) == TNK_Type_template) {
685       TemplateName TplName = TemplateResult.get();
686       Diag(IILoc, diag::err_template_missing_args)
687         << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
688       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
689         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
690           << TplDecl->getTemplateParameters()->getSourceRange();
691       }
692       return;
693     }
694   }
695
696   // FIXME: Should we move the logic that tries to recover from a missing tag
697   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
698
699   if (!SS || (!SS->isSet() && !SS->isInvalid()))
700     Diag(IILoc, diag::err_unknown_typename) << II;
701   else if (DeclContext *DC = computeDeclContext(*SS, false))
702     Diag(IILoc, diag::err_typename_nested_not_found)
703       << II << DC << SS->getRange();
704   else if (isDependentScopeSpecifier(*SS)) {
705     unsigned DiagID = diag::err_typename_missing;
706     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
707       DiagID = diag::ext_typename_missing;
708
709     Diag(SS->getRange().getBegin(), DiagID)
710       << SS->getScopeRep() << II->getName()
711       << SourceRange(SS->getRange().getBegin(), IILoc)
712       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
713     SuggestedType = ActOnTypenameType(S, SourceLocation(),
714                                       *SS, *II, IILoc).get();
715   } else {
716     assert(SS && SS->isInvalid() &&
717            "Invalid scope specifier has already been diagnosed");
718   }
719 }
720
721 /// \brief Determine whether the given result set contains either a type name
722 /// or
723 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
724   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
725                        NextToken.is(tok::less);
726
727   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
728     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
729       return true;
730
731     if (CheckTemplate && isa<TemplateDecl>(*I))
732       return true;
733   }
734
735   return false;
736 }
737
738 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
739                                     Scope *S, CXXScopeSpec &SS,
740                                     IdentifierInfo *&Name,
741                                     SourceLocation NameLoc) {
742   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
743   SemaRef.LookupParsedName(R, S, &SS);
744   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
745     StringRef FixItTagName;
746     switch (Tag->getTagKind()) {
747       case TTK_Class:
748         FixItTagName = "class ";
749         break;
750
751       case TTK_Enum:
752         FixItTagName = "enum ";
753         break;
754
755       case TTK_Struct:
756         FixItTagName = "struct ";
757         break;
758
759       case TTK_Interface:
760         FixItTagName = "__interface ";
761         break;
762
763       case TTK_Union:
764         FixItTagName = "union ";
765         break;
766     }
767
768     StringRef TagName = FixItTagName.drop_back();
769     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
770       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
771       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
772
773     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
774          I != IEnd; ++I)
775       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
776         << Name << TagName;
777
778     // Replace lookup results with just the tag decl.
779     Result.clear(Sema::LookupTagName);
780     SemaRef.LookupParsedName(Result, S, &SS);
781     return true;
782   }
783
784   return false;
785 }
786
787 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
788 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
789                                   QualType T, SourceLocation NameLoc) {
790   ASTContext &Context = S.Context;
791
792   TypeLocBuilder Builder;
793   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
794
795   T = S.getElaboratedType(ETK_None, SS, T);
796   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
797   ElabTL.setElaboratedKeywordLoc(SourceLocation());
798   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
799   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
800 }
801
802 Sema::NameClassification
803 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
804                    SourceLocation NameLoc, const Token &NextToken,
805                    bool IsAddressOfOperand,
806                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
807   DeclarationNameInfo NameInfo(Name, NameLoc);
808   ObjCMethodDecl *CurMethod = getCurMethodDecl();
809
810   if (NextToken.is(tok::coloncolon)) {
811     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
812     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
813   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
814              isCurrentClassName(*Name, S, &SS)) {
815     // Per [class.qual]p2, this names the constructors of SS, not the
816     // injected-class-name. We don't have a classification for that.
817     // There's not much point caching this result, since the parser
818     // will reject it later.
819     return NameClassification::Unknown();
820   }
821
822   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
823   LookupParsedName(Result, S, &SS, !CurMethod);
824
825   // For unqualified lookup in a class template in MSVC mode, look into
826   // dependent base classes where the primary class template is known.
827   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
828     if (ParsedType TypeInBase =
829             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
830       return TypeInBase;
831   }
832
833   // Perform lookup for Objective-C instance variables (including automatically
834   // synthesized instance variables), if we're in an Objective-C method.
835   // FIXME: This lookup really, really needs to be folded in to the normal
836   // unqualified lookup mechanism.
837   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
838     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
839     if (E.get() || E.isInvalid())
840       return E;
841   }
842
843   bool SecondTry = false;
844   bool IsFilteredTemplateName = false;
845
846 Corrected:
847   switch (Result.getResultKind()) {
848   case LookupResult::NotFound:
849     // If an unqualified-id is followed by a '(', then we have a function
850     // call.
851     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
852       // In C++, this is an ADL-only call.
853       // FIXME: Reference?
854       if (getLangOpts().CPlusPlus)
855         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
856
857       // C90 6.3.2.2:
858       //   If the expression that precedes the parenthesized argument list in a
859       //   function call consists solely of an identifier, and if no
860       //   declaration is visible for this identifier, the identifier is
861       //   implicitly declared exactly as if, in the innermost block containing
862       //   the function call, the declaration
863       //
864       //     extern int identifier ();
865       //
866       //   appeared.
867       //
868       // We also allow this in C99 as an extension.
869       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
870         Result.addDecl(D);
871         Result.resolveKind();
872         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
873       }
874     }
875
876     // In C, we first see whether there is a tag type by the same name, in
877     // which case it's likely that the user just forgot to write "enum",
878     // "struct", or "union".
879     if (!getLangOpts().CPlusPlus && !SecondTry &&
880         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
881       break;
882     }
883
884     // Perform typo correction to determine if there is another name that is
885     // close to this name.
886     if (!SecondTry && CCC) {
887       SecondTry = true;
888       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
889                                                  Result.getLookupKind(), S,
890                                                  &SS, std::move(CCC),
891                                                  CTK_ErrorRecovery)) {
892         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
893         unsigned QualifiedDiag = diag::err_no_member_suggest;
894
895         NamedDecl *FirstDecl = Corrected.getFoundDecl();
896         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
897         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
898             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
899           UnqualifiedDiag = diag::err_no_template_suggest;
900           QualifiedDiag = diag::err_no_member_template_suggest;
901         } else if (UnderlyingFirstDecl &&
902                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
903                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
904                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
905           UnqualifiedDiag = diag::err_unknown_typename_suggest;
906           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
907         }
908
909         if (SS.isEmpty()) {
910           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
911         } else {// FIXME: is this even reachable? Test it.
912           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
913           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
914                                   Name->getName().equals(CorrectedStr);
915           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
916                                     << Name << computeDeclContext(SS, false)
917                                     << DroppedSpecifier << SS.getRange());
918         }
919
920         // Update the name, so that the caller has the new name.
921         Name = Corrected.getCorrectionAsIdentifierInfo();
922
923         // Typo correction corrected to a keyword.
924         if (Corrected.isKeyword())
925           return Name;
926
927         // Also update the LookupResult...
928         // FIXME: This should probably go away at some point
929         Result.clear();
930         Result.setLookupName(Corrected.getCorrection());
931         if (FirstDecl)
932           Result.addDecl(FirstDecl);
933
934         // If we found an Objective-C instance variable, let
935         // LookupInObjCMethod build the appropriate expression to
936         // reference the ivar.
937         // FIXME: This is a gross hack.
938         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
939           Result.clear();
940           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
941           return E;
942         }
943
944         goto Corrected;
945       }
946     }
947
948     // We failed to correct; just fall through and let the parser deal with it.
949     Result.suppressDiagnostics();
950     return NameClassification::Unknown();
951
952   case LookupResult::NotFoundInCurrentInstantiation: {
953     // We performed name lookup into the current instantiation, and there were
954     // dependent bases, so we treat this result the same way as any other
955     // dependent nested-name-specifier.
956
957     // C++ [temp.res]p2:
958     //   A name used in a template declaration or definition and that is
959     //   dependent on a template-parameter is assumed not to name a type
960     //   unless the applicable name lookup finds a type name or the name is
961     //   qualified by the keyword typename.
962     //
963     // FIXME: If the next token is '<', we might want to ask the parser to
964     // perform some heroics to see if we actually have a
965     // template-argument-list, which would indicate a missing 'template'
966     // keyword here.
967     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
968                                       NameInfo, IsAddressOfOperand,
969                                       /*TemplateArgs=*/nullptr);
970   }
971
972   case LookupResult::Found:
973   case LookupResult::FoundOverloaded:
974   case LookupResult::FoundUnresolvedValue:
975     break;
976
977   case LookupResult::Ambiguous:
978     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
979         hasAnyAcceptableTemplateNames(Result)) {
980       // C++ [temp.local]p3:
981       //   A lookup that finds an injected-class-name (10.2) can result in an
982       //   ambiguity in certain cases (for example, if it is found in more than
983       //   one base class). If all of the injected-class-names that are found
984       //   refer to specializations of the same class template, and if the name
985       //   is followed by a template-argument-list, the reference refers to the
986       //   class template itself and not a specialization thereof, and is not
987       //   ambiguous.
988       //
989       // This filtering can make an ambiguous result into an unambiguous one,
990       // so try again after filtering out template names.
991       FilterAcceptableTemplateNames(Result);
992       if (!Result.isAmbiguous()) {
993         IsFilteredTemplateName = true;
994         break;
995       }
996     }
997
998     // Diagnose the ambiguity and return an error.
999     return NameClassification::Error();
1000   }
1001
1002   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1003       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1004     // C++ [temp.names]p3:
1005     //   After name lookup (3.4) finds that a name is a template-name or that
1006     //   an operator-function-id or a literal- operator-id refers to a set of
1007     //   overloaded functions any member of which is a function template if
1008     //   this is followed by a <, the < is always taken as the delimiter of a
1009     //   template-argument-list and never as the less-than operator.
1010     if (!IsFilteredTemplateName)
1011       FilterAcceptableTemplateNames(Result);
1012
1013     if (!Result.empty()) {
1014       bool IsFunctionTemplate;
1015       bool IsVarTemplate;
1016       TemplateName Template;
1017       if (Result.end() - Result.begin() > 1) {
1018         IsFunctionTemplate = true;
1019         Template = Context.getOverloadedTemplateName(Result.begin(),
1020                                                      Result.end());
1021       } else {
1022         TemplateDecl *TD
1023           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1024         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1025         IsVarTemplate = isa<VarTemplateDecl>(TD);
1026
1027         if (SS.isSet() && !SS.isInvalid())
1028           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1029                                                     /*TemplateKeyword=*/false,
1030                                                       TD);
1031         else
1032           Template = TemplateName(TD);
1033       }
1034
1035       if (IsFunctionTemplate) {
1036         // Function templates always go through overload resolution, at which
1037         // point we'll perform the various checks (e.g., accessibility) we need
1038         // to based on which function we selected.
1039         Result.suppressDiagnostics();
1040
1041         return NameClassification::FunctionTemplate(Template);
1042       }
1043
1044       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1045                            : NameClassification::TypeTemplate(Template);
1046     }
1047   }
1048
1049   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1050   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1051     DiagnoseUseOfDecl(Type, NameLoc);
1052     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1053     QualType T = Context.getTypeDeclType(Type);
1054     if (SS.isNotEmpty())
1055       return buildNestedType(*this, SS, T, NameLoc);
1056     return ParsedType::make(T);
1057   }
1058
1059   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1060   if (!Class) {
1061     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1062     if (ObjCCompatibleAliasDecl *Alias =
1063             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1064       Class = Alias->getClassInterface();
1065   }
1066
1067   if (Class) {
1068     DiagnoseUseOfDecl(Class, NameLoc);
1069
1070     if (NextToken.is(tok::period)) {
1071       // Interface. <something> is parsed as a property reference expression.
1072       // Just return "unknown" as a fall-through for now.
1073       Result.suppressDiagnostics();
1074       return NameClassification::Unknown();
1075     }
1076
1077     QualType T = Context.getObjCInterfaceType(Class);
1078     return ParsedType::make(T);
1079   }
1080
1081   // We can have a type template here if we're classifying a template argument.
1082   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1083       !isa<VarTemplateDecl>(FirstDecl))
1084     return NameClassification::TypeTemplate(
1085         TemplateName(cast<TemplateDecl>(FirstDecl)));
1086
1087   // Check for a tag type hidden by a non-type decl in a few cases where it
1088   // seems likely a type is wanted instead of the non-type that was found.
1089   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1090   if ((NextToken.is(tok::identifier) ||
1091        (NextIsOp &&
1092         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1093       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1094     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1095     DiagnoseUseOfDecl(Type, NameLoc);
1096     QualType T = Context.getTypeDeclType(Type);
1097     if (SS.isNotEmpty())
1098       return buildNestedType(*this, SS, T, NameLoc);
1099     return ParsedType::make(T);
1100   }
1101
1102   if (FirstDecl->isCXXClassMember())
1103     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1104                                            nullptr, S);
1105
1106   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1107   return BuildDeclarationNameExpr(SS, Result, ADL);
1108 }
1109
1110 Sema::TemplateNameKindForDiagnostics
1111 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1112   auto *TD = Name.getAsTemplateDecl();
1113   if (!TD)
1114     return TemplateNameKindForDiagnostics::DependentTemplate;
1115   if (isa<ClassTemplateDecl>(TD))
1116     return TemplateNameKindForDiagnostics::ClassTemplate;
1117   if (isa<FunctionTemplateDecl>(TD))
1118     return TemplateNameKindForDiagnostics::FunctionTemplate;
1119   if (isa<VarTemplateDecl>(TD))
1120     return TemplateNameKindForDiagnostics::VarTemplate;
1121   if (isa<TypeAliasTemplateDecl>(TD))
1122     return TemplateNameKindForDiagnostics::AliasTemplate;
1123   if (isa<TemplateTemplateParmDecl>(TD))
1124     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1125   return TemplateNameKindForDiagnostics::DependentTemplate;
1126 }
1127
1128 // Determines the context to return to after temporarily entering a
1129 // context.  This depends in an unnecessarily complicated way on the
1130 // exact ordering of callbacks from the parser.
1131 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1132
1133   // Functions defined inline within classes aren't parsed until we've
1134   // finished parsing the top-level class, so the top-level class is
1135   // the context we'll need to return to.
1136   // A Lambda call operator whose parent is a class must not be treated
1137   // as an inline member function.  A Lambda can be used legally
1138   // either as an in-class member initializer or a default argument.  These
1139   // are parsed once the class has been marked complete and so the containing
1140   // context would be the nested class (when the lambda is defined in one);
1141   // If the class is not complete, then the lambda is being used in an
1142   // ill-formed fashion (such as to specify the width of a bit-field, or
1143   // in an array-bound) - in which case we still want to return the
1144   // lexically containing DC (which could be a nested class).
1145   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1146     DC = DC->getLexicalParent();
1147
1148     // A function not defined within a class will always return to its
1149     // lexical context.
1150     if (!isa<CXXRecordDecl>(DC))
1151       return DC;
1152
1153     // A C++ inline method/friend is parsed *after* the topmost class
1154     // it was declared in is fully parsed ("complete");  the topmost
1155     // class is the context we need to return to.
1156     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1157       DC = RD;
1158
1159     // Return the declaration context of the topmost class the inline method is
1160     // declared in.
1161     return DC;
1162   }
1163
1164   return DC->getLexicalParent();
1165 }
1166
1167 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1168   assert(getContainingDC(DC) == CurContext &&
1169       "The next DeclContext should be lexically contained in the current one.");
1170   CurContext = DC;
1171   S->setEntity(DC);
1172 }
1173
1174 void Sema::PopDeclContext() {
1175   assert(CurContext && "DeclContext imbalance!");
1176
1177   CurContext = getContainingDC(CurContext);
1178   assert(CurContext && "Popped translation unit!");
1179 }
1180
1181 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1182                                                                     Decl *D) {
1183   // Unlike PushDeclContext, the context to which we return is not necessarily
1184   // the containing DC of TD, because the new context will be some pre-existing
1185   // TagDecl definition instead of a fresh one.
1186   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1187   CurContext = cast<TagDecl>(D)->getDefinition();
1188   assert(CurContext && "skipping definition of undefined tag");
1189   // Start lookups from the parent of the current context; we don't want to look
1190   // into the pre-existing complete definition.
1191   S->setEntity(CurContext->getLookupParent());
1192   return Result;
1193 }
1194
1195 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1196   CurContext = static_cast<decltype(CurContext)>(Context);
1197 }
1198
1199 /// EnterDeclaratorContext - Used when we must lookup names in the context
1200 /// of a declarator's nested name specifier.
1201 ///
1202 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1203   // C++0x [basic.lookup.unqual]p13:
1204   //   A name used in the definition of a static data member of class
1205   //   X (after the qualified-id of the static member) is looked up as
1206   //   if the name was used in a member function of X.
1207   // C++0x [basic.lookup.unqual]p14:
1208   //   If a variable member of a namespace is defined outside of the
1209   //   scope of its namespace then any name used in the definition of
1210   //   the variable member (after the declarator-id) is looked up as
1211   //   if the definition of the variable member occurred in its
1212   //   namespace.
1213   // Both of these imply that we should push a scope whose context
1214   // is the semantic context of the declaration.  We can't use
1215   // PushDeclContext here because that context is not necessarily
1216   // lexically contained in the current context.  Fortunately,
1217   // the containing scope should have the appropriate information.
1218
1219   assert(!S->getEntity() && "scope already has entity");
1220
1221 #ifndef NDEBUG
1222   Scope *Ancestor = S->getParent();
1223   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1224   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1225 #endif
1226
1227   CurContext = DC;
1228   S->setEntity(DC);
1229 }
1230
1231 void Sema::ExitDeclaratorContext(Scope *S) {
1232   assert(S->getEntity() == CurContext && "Context imbalance!");
1233
1234   // Switch back to the lexical context.  The safety of this is
1235   // enforced by an assert in EnterDeclaratorContext.
1236   Scope *Ancestor = S->getParent();
1237   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1238   CurContext = Ancestor->getEntity();
1239
1240   // We don't need to do anything with the scope, which is going to
1241   // disappear.
1242 }
1243
1244 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1245   // We assume that the caller has already called
1246   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1247   FunctionDecl *FD = D->getAsFunction();
1248   if (!FD)
1249     return;
1250
1251   // Same implementation as PushDeclContext, but enters the context
1252   // from the lexical parent, rather than the top-level class.
1253   assert(CurContext == FD->getLexicalParent() &&
1254     "The next DeclContext should be lexically contained in the current one.");
1255   CurContext = FD;
1256   S->setEntity(CurContext);
1257
1258   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1259     ParmVarDecl *Param = FD->getParamDecl(P);
1260     // If the parameter has an identifier, then add it to the scope
1261     if (Param->getIdentifier()) {
1262       S->AddDecl(Param);
1263       IdResolver.AddDecl(Param);
1264     }
1265   }
1266 }
1267
1268 void Sema::ActOnExitFunctionContext() {
1269   // Same implementation as PopDeclContext, but returns to the lexical parent,
1270   // rather than the top-level class.
1271   assert(CurContext && "DeclContext imbalance!");
1272   CurContext = CurContext->getLexicalParent();
1273   assert(CurContext && "Popped translation unit!");
1274 }
1275
1276 /// \brief Determine whether we allow overloading of the function
1277 /// PrevDecl with another declaration.
1278 ///
1279 /// This routine determines whether overloading is possible, not
1280 /// whether some new function is actually an overload. It will return
1281 /// true in C++ (where we can always provide overloads) or, as an
1282 /// extension, in C when the previous function is already an
1283 /// overloaded function declaration or has the "overloadable"
1284 /// attribute.
1285 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1286                                        ASTContext &Context) {
1287   if (Context.getLangOpts().CPlusPlus)
1288     return true;
1289
1290   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1291     return true;
1292
1293   return (Previous.getResultKind() == LookupResult::Found
1294           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1295 }
1296
1297 /// Add this decl to the scope shadowed decl chains.
1298 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1299   // Move up the scope chain until we find the nearest enclosing
1300   // non-transparent context. The declaration will be introduced into this
1301   // scope.
1302   while (S->getEntity() && S->getEntity()->isTransparentContext())
1303     S = S->getParent();
1304
1305   // Add scoped declarations into their context, so that they can be
1306   // found later. Declarations without a context won't be inserted
1307   // into any context.
1308   if (AddToContext)
1309     CurContext->addDecl(D);
1310
1311   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1312   // are function-local declarations.
1313   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1314       !D->getDeclContext()->getRedeclContext()->Equals(
1315         D->getLexicalDeclContext()->getRedeclContext()) &&
1316       !D->getLexicalDeclContext()->isFunctionOrMethod())
1317     return;
1318
1319   // Template instantiations should also not be pushed into scope.
1320   if (isa<FunctionDecl>(D) &&
1321       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1322     return;
1323
1324   // If this replaces anything in the current scope,
1325   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1326                                IEnd = IdResolver.end();
1327   for (; I != IEnd; ++I) {
1328     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1329       S->RemoveDecl(*I);
1330       IdResolver.RemoveDecl(*I);
1331
1332       // Should only need to replace one decl.
1333       break;
1334     }
1335   }
1336
1337   S->AddDecl(D);
1338
1339   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1340     // Implicitly-generated labels may end up getting generated in an order that
1341     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1342     // the label at the appropriate place in the identifier chain.
1343     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1344       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1345       if (IDC == CurContext) {
1346         if (!S->isDeclScope(*I))
1347           continue;
1348       } else if (IDC->Encloses(CurContext))
1349         break;
1350     }
1351
1352     IdResolver.InsertDeclAfter(I, D);
1353   } else {
1354     IdResolver.AddDecl(D);
1355   }
1356 }
1357
1358 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1359   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1360     TUScope->AddDecl(D);
1361 }
1362
1363 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1364                          bool AllowInlineNamespace) {
1365   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1366 }
1367
1368 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1369   DeclContext *TargetDC = DC->getPrimaryContext();
1370   do {
1371     if (DeclContext *ScopeDC = S->getEntity())
1372       if (ScopeDC->getPrimaryContext() == TargetDC)
1373         return S;
1374   } while ((S = S->getParent()));
1375
1376   return nullptr;
1377 }
1378
1379 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1380                                             DeclContext*,
1381                                             ASTContext&);
1382
1383 /// Filters out lookup results that don't fall within the given scope
1384 /// as determined by isDeclInScope.
1385 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1386                                 bool ConsiderLinkage,
1387                                 bool AllowInlineNamespace) {
1388   LookupResult::Filter F = R.makeFilter();
1389   while (F.hasNext()) {
1390     NamedDecl *D = F.next();
1391
1392     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1393       continue;
1394
1395     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1396       continue;
1397
1398     F.erase();
1399   }
1400
1401   F.done();
1402 }
1403
1404 static bool isUsingDecl(NamedDecl *D) {
1405   return isa<UsingShadowDecl>(D) ||
1406          isa<UnresolvedUsingTypenameDecl>(D) ||
1407          isa<UnresolvedUsingValueDecl>(D);
1408 }
1409
1410 /// Removes using shadow declarations from the lookup results.
1411 static void RemoveUsingDecls(LookupResult &R) {
1412   LookupResult::Filter F = R.makeFilter();
1413   while (F.hasNext())
1414     if (isUsingDecl(F.next()))
1415       F.erase();
1416
1417   F.done();
1418 }
1419
1420 /// \brief Check for this common pattern:
1421 /// @code
1422 /// class S {
1423 ///   S(const S&); // DO NOT IMPLEMENT
1424 ///   void operator=(const S&); // DO NOT IMPLEMENT
1425 /// };
1426 /// @endcode
1427 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1428   // FIXME: Should check for private access too but access is set after we get
1429   // the decl here.
1430   if (D->doesThisDeclarationHaveABody())
1431     return false;
1432
1433   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1434     return CD->isCopyConstructor();
1435   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1436     return Method->isCopyAssignmentOperator();
1437   return false;
1438 }
1439
1440 // We need this to handle
1441 //
1442 // typedef struct {
1443 //   void *foo() { return 0; }
1444 // } A;
1445 //
1446 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1447 // for example. If 'A', foo will have external linkage. If we have '*A',
1448 // foo will have no linkage. Since we can't know until we get to the end
1449 // of the typedef, this function finds out if D might have non-external linkage.
1450 // Callers should verify at the end of the TU if it D has external linkage or
1451 // not.
1452 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1453   const DeclContext *DC = D->getDeclContext();
1454   while (!DC->isTranslationUnit()) {
1455     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1456       if (!RD->hasNameForLinkage())
1457         return true;
1458     }
1459     DC = DC->getParent();
1460   }
1461
1462   return !D->isExternallyVisible();
1463 }
1464
1465 // FIXME: This needs to be refactored; some other isInMainFile users want
1466 // these semantics.
1467 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1468   if (S.TUKind != TU_Complete)
1469     return false;
1470   return S.SourceMgr.isInMainFile(Loc);
1471 }
1472
1473 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1474   assert(D);
1475
1476   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1477     return false;
1478
1479   // Ignore all entities declared within templates, and out-of-line definitions
1480   // of members of class templates.
1481   if (D->getDeclContext()->isDependentContext() ||
1482       D->getLexicalDeclContext()->isDependentContext())
1483     return false;
1484
1485   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1486     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1487       return false;
1488
1489     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1490       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1491         return false;
1492     } else {
1493       // 'static inline' functions are defined in headers; don't warn.
1494       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1495         return false;
1496     }
1497
1498     if (FD->doesThisDeclarationHaveABody() &&
1499         Context.DeclMustBeEmitted(FD))
1500       return false;
1501   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1502     // Constants and utility variables are defined in headers with internal
1503     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1504     // like "inline".)
1505     if (!isMainFileLoc(*this, VD->getLocation()))
1506       return false;
1507
1508     if (Context.DeclMustBeEmitted(VD))
1509       return false;
1510
1511     if (VD->isStaticDataMember() &&
1512         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1513       return false;
1514
1515     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1516       return false;
1517   } else {
1518     return false;
1519   }
1520
1521   // Only warn for unused decls internal to the translation unit.
1522   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1523   // for inline functions defined in the main source file, for instance.
1524   return mightHaveNonExternalLinkage(D);
1525 }
1526
1527 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1528   if (!D)
1529     return;
1530
1531   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1532     const FunctionDecl *First = FD->getFirstDecl();
1533     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1534       return; // First should already be in the vector.
1535   }
1536
1537   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1538     const VarDecl *First = VD->getFirstDecl();
1539     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1540       return; // First should already be in the vector.
1541   }
1542
1543   if (ShouldWarnIfUnusedFileScopedDecl(D))
1544     UnusedFileScopedDecls.push_back(D);
1545 }
1546
1547 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1548   if (D->isInvalidDecl())
1549     return false;
1550
1551   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1552       D->hasAttr<ObjCPreciseLifetimeAttr>())
1553     return false;
1554
1555   if (isa<LabelDecl>(D))
1556     return true;
1557
1558   // Except for labels, we only care about unused decls that are local to
1559   // functions.
1560   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1561   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1562     // For dependent types, the diagnostic is deferred.
1563     WithinFunction =
1564         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1565   if (!WithinFunction)
1566     return false;
1567
1568   if (isa<TypedefNameDecl>(D))
1569     return true;
1570
1571   // White-list anything that isn't a local variable.
1572   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1573     return false;
1574
1575   // Types of valid local variables should be complete, so this should succeed.
1576   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1577
1578     // White-list anything with an __attribute__((unused)) type.
1579     const auto *Ty = VD->getType().getTypePtr();
1580
1581     // Only look at the outermost level of typedef.
1582     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1583       if (TT->getDecl()->hasAttr<UnusedAttr>())
1584         return false;
1585     }
1586
1587     // If we failed to complete the type for some reason, or if the type is
1588     // dependent, don't diagnose the variable.
1589     if (Ty->isIncompleteType() || Ty->isDependentType())
1590       return false;
1591
1592     // Look at the element type to ensure that the warning behaviour is
1593     // consistent for both scalars and arrays.
1594     Ty = Ty->getBaseElementTypeUnsafe();
1595
1596     if (const TagType *TT = Ty->getAs<TagType>()) {
1597       const TagDecl *Tag = TT->getDecl();
1598       if (Tag->hasAttr<UnusedAttr>())
1599         return false;
1600
1601       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1602         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1603           return false;
1604
1605         if (const Expr *Init = VD->getInit()) {
1606           if (const ExprWithCleanups *Cleanups =
1607                   dyn_cast<ExprWithCleanups>(Init))
1608             Init = Cleanups->getSubExpr();
1609           const CXXConstructExpr *Construct =
1610             dyn_cast<CXXConstructExpr>(Init);
1611           if (Construct && !Construct->isElidable()) {
1612             CXXConstructorDecl *CD = Construct->getConstructor();
1613             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1614               return false;
1615           }
1616         }
1617       }
1618     }
1619
1620     // TODO: __attribute__((unused)) templates?
1621   }
1622
1623   return true;
1624 }
1625
1626 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1627                                      FixItHint &Hint) {
1628   if (isa<LabelDecl>(D)) {
1629     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1630                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1631     if (AfterColon.isInvalid())
1632       return;
1633     Hint = FixItHint::CreateRemoval(CharSourceRange::
1634                                     getCharRange(D->getLocStart(), AfterColon));
1635   }
1636 }
1637
1638 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1639   if (D->getTypeForDecl()->isDependentType())
1640     return;
1641
1642   for (auto *TmpD : D->decls()) {
1643     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1644       DiagnoseUnusedDecl(T);
1645     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1646       DiagnoseUnusedNestedTypedefs(R);
1647   }
1648 }
1649
1650 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1651 /// unless they are marked attr(unused).
1652 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1653   if (!ShouldDiagnoseUnusedDecl(D))
1654     return;
1655
1656   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1657     // typedefs can be referenced later on, so the diagnostics are emitted
1658     // at end-of-translation-unit.
1659     UnusedLocalTypedefNameCandidates.insert(TD);
1660     return;
1661   }
1662
1663   FixItHint Hint;
1664   GenerateFixForUnusedDecl(D, Context, Hint);
1665
1666   unsigned DiagID;
1667   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1668     DiagID = diag::warn_unused_exception_param;
1669   else if (isa<LabelDecl>(D))
1670     DiagID = diag::warn_unused_label;
1671   else
1672     DiagID = diag::warn_unused_variable;
1673
1674   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1675 }
1676
1677 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1678   // Verify that we have no forward references left.  If so, there was a goto
1679   // or address of a label taken, but no definition of it.  Label fwd
1680   // definitions are indicated with a null substmt which is also not a resolved
1681   // MS inline assembly label name.
1682   bool Diagnose = false;
1683   if (L->isMSAsmLabel())
1684     Diagnose = !L->isResolvedMSAsmLabel();
1685   else
1686     Diagnose = L->getStmt() == nullptr;
1687   if (Diagnose)
1688     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1689 }
1690
1691 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1692   S->mergeNRVOIntoParent();
1693
1694   if (S->decl_empty()) return;
1695   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1696          "Scope shouldn't contain decls!");
1697
1698   for (auto *TmpD : S->decls()) {
1699     assert(TmpD && "This decl didn't get pushed??");
1700
1701     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1702     NamedDecl *D = cast<NamedDecl>(TmpD);
1703
1704     if (!D->getDeclName()) continue;
1705
1706     // Diagnose unused variables in this scope.
1707     if (!S->hasUnrecoverableErrorOccurred()) {
1708       DiagnoseUnusedDecl(D);
1709       if (const auto *RD = dyn_cast<RecordDecl>(D))
1710         DiagnoseUnusedNestedTypedefs(RD);
1711     }
1712
1713     // If this was a forward reference to a label, verify it was defined.
1714     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1715       CheckPoppedLabel(LD, *this);
1716
1717     // Remove this name from our lexical scope, and warn on it if we haven't
1718     // already.
1719     IdResolver.RemoveDecl(D);
1720     auto ShadowI = ShadowingDecls.find(D);
1721     if (ShadowI != ShadowingDecls.end()) {
1722       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1723         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1724             << D << FD << FD->getParent();
1725         Diag(FD->getLocation(), diag::note_previous_declaration);
1726       }
1727       ShadowingDecls.erase(ShadowI);
1728     }
1729   }
1730 }
1731
1732 /// \brief Look for an Objective-C class in the translation unit.
1733 ///
1734 /// \param Id The name of the Objective-C class we're looking for. If
1735 /// typo-correction fixes this name, the Id will be updated
1736 /// to the fixed name.
1737 ///
1738 /// \param IdLoc The location of the name in the translation unit.
1739 ///
1740 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1741 /// if there is no class with the given name.
1742 ///
1743 /// \returns The declaration of the named Objective-C class, or NULL if the
1744 /// class could not be found.
1745 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1746                                               SourceLocation IdLoc,
1747                                               bool DoTypoCorrection) {
1748   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1749   // creation from this context.
1750   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1751
1752   if (!IDecl && DoTypoCorrection) {
1753     // Perform typo correction at the given location, but only if we
1754     // find an Objective-C class name.
1755     if (TypoCorrection C = CorrectTypo(
1756             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1757             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1758             CTK_ErrorRecovery)) {
1759       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1760       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1761       Id = IDecl->getIdentifier();
1762     }
1763   }
1764   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1765   // This routine must always return a class definition, if any.
1766   if (Def && Def->getDefinition())
1767       Def = Def->getDefinition();
1768   return Def;
1769 }
1770
1771 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1772 /// from S, where a non-field would be declared. This routine copes
1773 /// with the difference between C and C++ scoping rules in structs and
1774 /// unions. For example, the following code is well-formed in C but
1775 /// ill-formed in C++:
1776 /// @code
1777 /// struct S6 {
1778 ///   enum { BAR } e;
1779 /// };
1780 ///
1781 /// void test_S6() {
1782 ///   struct S6 a;
1783 ///   a.e = BAR;
1784 /// }
1785 /// @endcode
1786 /// For the declaration of BAR, this routine will return a different
1787 /// scope. The scope S will be the scope of the unnamed enumeration
1788 /// within S6. In C++, this routine will return the scope associated
1789 /// with S6, because the enumeration's scope is a transparent
1790 /// context but structures can contain non-field names. In C, this
1791 /// routine will return the translation unit scope, since the
1792 /// enumeration's scope is a transparent context and structures cannot
1793 /// contain non-field names.
1794 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1795   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1796          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1797          (S->isClassScope() && !getLangOpts().CPlusPlus))
1798     S = S->getParent();
1799   return S;
1800 }
1801
1802 /// \brief Looks up the declaration of "struct objc_super" and
1803 /// saves it for later use in building builtin declaration of
1804 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1805 /// pre-existing declaration exists no action takes place.
1806 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1807                                         IdentifierInfo *II) {
1808   if (!II->isStr("objc_msgSendSuper"))
1809     return;
1810   ASTContext &Context = ThisSema.Context;
1811
1812   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1813                       SourceLocation(), Sema::LookupTagName);
1814   ThisSema.LookupName(Result, S);
1815   if (Result.getResultKind() == LookupResult::Found)
1816     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1817       Context.setObjCSuperType(Context.getTagDeclType(TD));
1818 }
1819
1820 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1821   switch (Error) {
1822   case ASTContext::GE_None:
1823     return "";
1824   case ASTContext::GE_Missing_stdio:
1825     return "stdio.h";
1826   case ASTContext::GE_Missing_setjmp:
1827     return "setjmp.h";
1828   case ASTContext::GE_Missing_ucontext:
1829     return "ucontext.h";
1830   }
1831   llvm_unreachable("unhandled error kind");
1832 }
1833
1834 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1835 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1836 /// if we're creating this built-in in anticipation of redeclaring the
1837 /// built-in.
1838 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1839                                      Scope *S, bool ForRedeclaration,
1840                                      SourceLocation Loc) {
1841   LookupPredefedObjCSuperType(*this, S, II);
1842
1843   ASTContext::GetBuiltinTypeError Error;
1844   QualType R = Context.GetBuiltinType(ID, Error);
1845   if (Error) {
1846     if (ForRedeclaration)
1847       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1848           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1849     return nullptr;
1850   }
1851
1852   if (!ForRedeclaration &&
1853       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1854        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1855     Diag(Loc, diag::ext_implicit_lib_function_decl)
1856         << Context.BuiltinInfo.getName(ID) << R;
1857     if (Context.BuiltinInfo.getHeaderName(ID) &&
1858         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1859       Diag(Loc, diag::note_include_header_or_declare)
1860           << Context.BuiltinInfo.getHeaderName(ID)
1861           << Context.BuiltinInfo.getName(ID);
1862   }
1863
1864   if (R.isNull())
1865     return nullptr;
1866
1867   DeclContext *Parent = Context.getTranslationUnitDecl();
1868   if (getLangOpts().CPlusPlus) {
1869     LinkageSpecDecl *CLinkageDecl =
1870         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1871                                 LinkageSpecDecl::lang_c, false);
1872     CLinkageDecl->setImplicit();
1873     Parent->addDecl(CLinkageDecl);
1874     Parent = CLinkageDecl;
1875   }
1876
1877   FunctionDecl *New = FunctionDecl::Create(Context,
1878                                            Parent,
1879                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1880                                            SC_Extern,
1881                                            false,
1882                                            R->isFunctionProtoType());
1883   New->setImplicit();
1884
1885   // Create Decl objects for each parameter, adding them to the
1886   // FunctionDecl.
1887   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1888     SmallVector<ParmVarDecl*, 16> Params;
1889     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1890       ParmVarDecl *parm =
1891           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1892                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1893                               SC_None, nullptr);
1894       parm->setScopeInfo(0, i);
1895       Params.push_back(parm);
1896     }
1897     New->setParams(Params);
1898   }
1899
1900   AddKnownFunctionAttributes(New);
1901   RegisterLocallyScopedExternCDecl(New, S);
1902
1903   // TUScope is the translation-unit scope to insert this function into.
1904   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1905   // relate Scopes to DeclContexts, and probably eliminate CurContext
1906   // entirely, but we're not there yet.
1907   DeclContext *SavedContext = CurContext;
1908   CurContext = Parent;
1909   PushOnScopeChains(New, TUScope);
1910   CurContext = SavedContext;
1911   return New;
1912 }
1913
1914 /// Typedef declarations don't have linkage, but they still denote the same
1915 /// entity if their types are the same.
1916 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1917 /// isSameEntity.
1918 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1919                                                      TypedefNameDecl *Decl,
1920                                                      LookupResult &Previous) {
1921   // This is only interesting when modules are enabled.
1922   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1923     return;
1924
1925   // Empty sets are uninteresting.
1926   if (Previous.empty())
1927     return;
1928
1929   LookupResult::Filter Filter = Previous.makeFilter();
1930   while (Filter.hasNext()) {
1931     NamedDecl *Old = Filter.next();
1932
1933     // Non-hidden declarations are never ignored.
1934     if (S.isVisible(Old))
1935       continue;
1936
1937     // Declarations of the same entity are not ignored, even if they have
1938     // different linkages.
1939     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1940       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1941                                 Decl->getUnderlyingType()))
1942         continue;
1943
1944       // If both declarations give a tag declaration a typedef name for linkage
1945       // purposes, then they declare the same entity.
1946       if (S.getLangOpts().CPlusPlus &&
1947           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1948           Decl->getAnonDeclWithTypedefName())
1949         continue;
1950     }
1951
1952     Filter.erase();
1953   }
1954
1955   Filter.done();
1956 }
1957
1958 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1959   QualType OldType;
1960   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1961     OldType = OldTypedef->getUnderlyingType();
1962   else
1963     OldType = Context.getTypeDeclType(Old);
1964   QualType NewType = New->getUnderlyingType();
1965
1966   if (NewType->isVariablyModifiedType()) {
1967     // Must not redefine a typedef with a variably-modified type.
1968     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1969     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1970       << Kind << NewType;
1971     if (Old->getLocation().isValid())
1972       Diag(Old->getLocation(), diag::note_previous_definition);
1973     New->setInvalidDecl();
1974     return true;
1975   }
1976
1977   if (OldType != NewType &&
1978       !OldType->isDependentType() &&
1979       !NewType->isDependentType() &&
1980       !Context.hasSameType(OldType, NewType)) {
1981     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1982     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1983       << Kind << NewType << OldType;
1984     if (Old->getLocation().isValid())
1985       Diag(Old->getLocation(), diag::note_previous_definition);
1986     New->setInvalidDecl();
1987     return true;
1988   }
1989   return false;
1990 }
1991
1992 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1993 /// same name and scope as a previous declaration 'Old'.  Figure out
1994 /// how to resolve this situation, merging decls or emitting
1995 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1996 ///
1997 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1998                                 LookupResult &OldDecls) {
1999   // If the new decl is known invalid already, don't bother doing any
2000   // merging checks.
2001   if (New->isInvalidDecl()) return;
2002
2003   // Allow multiple definitions for ObjC built-in typedefs.
2004   // FIXME: Verify the underlying types are equivalent!
2005   if (getLangOpts().ObjC1) {
2006     const IdentifierInfo *TypeID = New->getIdentifier();
2007     switch (TypeID->getLength()) {
2008     default: break;
2009     case 2:
2010       {
2011         if (!TypeID->isStr("id"))
2012           break;
2013         QualType T = New->getUnderlyingType();
2014         if (!T->isPointerType())
2015           break;
2016         if (!T->isVoidPointerType()) {
2017           QualType PT = T->getAs<PointerType>()->getPointeeType();
2018           if (!PT->isStructureType())
2019             break;
2020         }
2021         Context.setObjCIdRedefinitionType(T);
2022         // Install the built-in type for 'id', ignoring the current definition.
2023         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2024         return;
2025       }
2026     case 5:
2027       if (!TypeID->isStr("Class"))
2028         break;
2029       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2030       // Install the built-in type for 'Class', ignoring the current definition.
2031       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2032       return;
2033     case 3:
2034       if (!TypeID->isStr("SEL"))
2035         break;
2036       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2037       // Install the built-in type for 'SEL', ignoring the current definition.
2038       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2039       return;
2040     }
2041     // Fall through - the typedef name was not a builtin type.
2042   }
2043
2044   // Verify the old decl was also a type.
2045   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2046   if (!Old) {
2047     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2048       << New->getDeclName();
2049
2050     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2051     if (OldD->getLocation().isValid())
2052       Diag(OldD->getLocation(), diag::note_previous_definition);
2053
2054     return New->setInvalidDecl();
2055   }
2056
2057   // If the old declaration is invalid, just give up here.
2058   if (Old->isInvalidDecl())
2059     return New->setInvalidDecl();
2060
2061   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2062     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2063     auto *NewTag = New->getAnonDeclWithTypedefName();
2064     NamedDecl *Hidden = nullptr;
2065     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2066         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2067         !hasVisibleDefinition(OldTag, &Hidden)) {
2068       // There is a definition of this tag, but it is not visible. Use it
2069       // instead of our tag.
2070       New->setTypeForDecl(OldTD->getTypeForDecl());
2071       if (OldTD->isModed())
2072         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2073                                     OldTD->getUnderlyingType());
2074       else
2075         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2076
2077       // Make the old tag definition visible.
2078       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2079
2080       // If this was an unscoped enumeration, yank all of its enumerators
2081       // out of the scope.
2082       if (isa<EnumDecl>(NewTag)) {
2083         Scope *EnumScope = getNonFieldDeclScope(S);
2084         for (auto *D : NewTag->decls()) {
2085           auto *ED = cast<EnumConstantDecl>(D);
2086           assert(EnumScope->isDeclScope(ED));
2087           EnumScope->RemoveDecl(ED);
2088           IdResolver.RemoveDecl(ED);
2089           ED->getLexicalDeclContext()->removeDecl(ED);
2090         }
2091       }
2092     }
2093   }
2094
2095   // If the typedef types are not identical, reject them in all languages and
2096   // with any extensions enabled.
2097   if (isIncompatibleTypedef(Old, New))
2098     return;
2099
2100   // The types match.  Link up the redeclaration chain and merge attributes if
2101   // the old declaration was a typedef.
2102   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2103     New->setPreviousDecl(Typedef);
2104     mergeDeclAttributes(New, Old);
2105   }
2106
2107   if (getLangOpts().MicrosoftExt)
2108     return;
2109
2110   if (getLangOpts().CPlusPlus) {
2111     // C++ [dcl.typedef]p2:
2112     //   In a given non-class scope, a typedef specifier can be used to
2113     //   redefine the name of any type declared in that scope to refer
2114     //   to the type to which it already refers.
2115     if (!isa<CXXRecordDecl>(CurContext))
2116       return;
2117
2118     // C++0x [dcl.typedef]p4:
2119     //   In a given class scope, a typedef specifier can be used to redefine
2120     //   any class-name declared in that scope that is not also a typedef-name
2121     //   to refer to the type to which it already refers.
2122     //
2123     // This wording came in via DR424, which was a correction to the
2124     // wording in DR56, which accidentally banned code like:
2125     //
2126     //   struct S {
2127     //     typedef struct A { } A;
2128     //   };
2129     //
2130     // in the C++03 standard. We implement the C++0x semantics, which
2131     // allow the above but disallow
2132     //
2133     //   struct S {
2134     //     typedef int I;
2135     //     typedef int I;
2136     //   };
2137     //
2138     // since that was the intent of DR56.
2139     if (!isa<TypedefNameDecl>(Old))
2140       return;
2141
2142     Diag(New->getLocation(), diag::err_redefinition)
2143       << New->getDeclName();
2144     Diag(Old->getLocation(), diag::note_previous_definition);
2145     return New->setInvalidDecl();
2146   }
2147
2148   // Modules always permit redefinition of typedefs, as does C11.
2149   if (getLangOpts().Modules || getLangOpts().C11)
2150     return;
2151
2152   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2153   // is normally mapped to an error, but can be controlled with
2154   // -Wtypedef-redefinition.  If either the original or the redefinition is
2155   // in a system header, don't emit this for compatibility with GCC.
2156   if (getDiagnostics().getSuppressSystemWarnings() &&
2157       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2158       (Old->isImplicit() ||
2159        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2160        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2161     return;
2162
2163   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2164     << New->getDeclName();
2165   Diag(Old->getLocation(), diag::note_previous_definition);
2166 }
2167
2168 /// DeclhasAttr - returns true if decl Declaration already has the target
2169 /// attribute.
2170 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2171   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2172   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2173   for (const auto *i : D->attrs())
2174     if (i->getKind() == A->getKind()) {
2175       if (Ann) {
2176         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2177           return true;
2178         continue;
2179       }
2180       // FIXME: Don't hardcode this check
2181       if (OA && isa<OwnershipAttr>(i))
2182         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2183       return true;
2184     }
2185
2186   return false;
2187 }
2188
2189 static bool isAttributeTargetADefinition(Decl *D) {
2190   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2191     return VD->isThisDeclarationADefinition();
2192   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2193     return TD->isCompleteDefinition() || TD->isBeingDefined();
2194   return true;
2195 }
2196
2197 /// Merge alignment attributes from \p Old to \p New, taking into account the
2198 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2199 ///
2200 /// \return \c true if any attributes were added to \p New.
2201 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2202   // Look for alignas attributes on Old, and pick out whichever attribute
2203   // specifies the strictest alignment requirement.
2204   AlignedAttr *OldAlignasAttr = nullptr;
2205   AlignedAttr *OldStrictestAlignAttr = nullptr;
2206   unsigned OldAlign = 0;
2207   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2208     // FIXME: We have no way of representing inherited dependent alignments
2209     // in a case like:
2210     //   template<int A, int B> struct alignas(A) X;
2211     //   template<int A, int B> struct alignas(B) X {};
2212     // For now, we just ignore any alignas attributes which are not on the
2213     // definition in such a case.
2214     if (I->isAlignmentDependent())
2215       return false;
2216
2217     if (I->isAlignas())
2218       OldAlignasAttr = I;
2219
2220     unsigned Align = I->getAlignment(S.Context);
2221     if (Align > OldAlign) {
2222       OldAlign = Align;
2223       OldStrictestAlignAttr = I;
2224     }
2225   }
2226
2227   // Look for alignas attributes on New.
2228   AlignedAttr *NewAlignasAttr = nullptr;
2229   unsigned NewAlign = 0;
2230   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2231     if (I->isAlignmentDependent())
2232       return false;
2233
2234     if (I->isAlignas())
2235       NewAlignasAttr = I;
2236
2237     unsigned Align = I->getAlignment(S.Context);
2238     if (Align > NewAlign)
2239       NewAlign = Align;
2240   }
2241
2242   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2243     // Both declarations have 'alignas' attributes. We require them to match.
2244     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2245     // fall short. (If two declarations both have alignas, they must both match
2246     // every definition, and so must match each other if there is a definition.)
2247
2248     // If either declaration only contains 'alignas(0)' specifiers, then it
2249     // specifies the natural alignment for the type.
2250     if (OldAlign == 0 || NewAlign == 0) {
2251       QualType Ty;
2252       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2253         Ty = VD->getType();
2254       else
2255         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2256
2257       if (OldAlign == 0)
2258         OldAlign = S.Context.getTypeAlign(Ty);
2259       if (NewAlign == 0)
2260         NewAlign = S.Context.getTypeAlign(Ty);
2261     }
2262
2263     if (OldAlign != NewAlign) {
2264       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2265         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2266         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2267       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2268     }
2269   }
2270
2271   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2272     // C++11 [dcl.align]p6:
2273     //   if any declaration of an entity has an alignment-specifier,
2274     //   every defining declaration of that entity shall specify an
2275     //   equivalent alignment.
2276     // C11 6.7.5/7:
2277     //   If the definition of an object does not have an alignment
2278     //   specifier, any other declaration of that object shall also
2279     //   have no alignment specifier.
2280     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2281       << OldAlignasAttr;
2282     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2283       << OldAlignasAttr;
2284   }
2285
2286   bool AnyAdded = false;
2287
2288   // Ensure we have an attribute representing the strictest alignment.
2289   if (OldAlign > NewAlign) {
2290     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2291     Clone->setInherited(true);
2292     New->addAttr(Clone);
2293     AnyAdded = true;
2294   }
2295
2296   // Ensure we have an alignas attribute if the old declaration had one.
2297   if (OldAlignasAttr && !NewAlignasAttr &&
2298       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2299     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2300     Clone->setInherited(true);
2301     New->addAttr(Clone);
2302     AnyAdded = true;
2303   }
2304
2305   return AnyAdded;
2306 }
2307
2308 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2309                                const InheritableAttr *Attr,
2310                                Sema::AvailabilityMergeKind AMK) {
2311   // This function copies an attribute Attr from a previous declaration to the
2312   // new declaration D if the new declaration doesn't itself have that attribute
2313   // yet or if that attribute allows duplicates.
2314   // If you're adding a new attribute that requires logic different from
2315   // "use explicit attribute on decl if present, else use attribute from
2316   // previous decl", for example if the attribute needs to be consistent
2317   // between redeclarations, you need to call a custom merge function here.
2318   InheritableAttr *NewAttr = nullptr;
2319   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2320   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2321     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2322                                       AA->isImplicit(), AA->getIntroduced(),
2323                                       AA->getDeprecated(),
2324                                       AA->getObsoleted(), AA->getUnavailable(),
2325                                       AA->getMessage(), AA->getStrict(),
2326                                       AA->getReplacement(), AMK,
2327                                       AttrSpellingListIndex);
2328   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2329     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2330                                     AttrSpellingListIndex);
2331   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2332     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2333                                         AttrSpellingListIndex);
2334   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2335     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2336                                    AttrSpellingListIndex);
2337   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2338     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2339                                    AttrSpellingListIndex);
2340   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2341     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2342                                 FA->getFormatIdx(), FA->getFirstArg(),
2343                                 AttrSpellingListIndex);
2344   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2345     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2346                                  AttrSpellingListIndex);
2347   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2348     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2349                                        AttrSpellingListIndex,
2350                                        IA->getSemanticSpelling());
2351   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2352     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2353                                       &S.Context.Idents.get(AA->getSpelling()),
2354                                       AttrSpellingListIndex);
2355   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2356            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2357             isa<CUDAGlobalAttr>(Attr))) {
2358     // CUDA target attributes are part of function signature for
2359     // overloading purposes and must not be merged.
2360     return false;
2361   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2362     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2363   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2364     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2365   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2366     NewAttr = S.mergeInternalLinkageAttr(
2367         D, InternalLinkageA->getRange(),
2368         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2369         AttrSpellingListIndex);
2370   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2371     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2372                                 &S.Context.Idents.get(CommonA->getSpelling()),
2373                                 AttrSpellingListIndex);
2374   else if (isa<AlignedAttr>(Attr))
2375     // AlignedAttrs are handled separately, because we need to handle all
2376     // such attributes on a declaration at the same time.
2377     NewAttr = nullptr;
2378   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2379            (AMK == Sema::AMK_Override ||
2380             AMK == Sema::AMK_ProtocolImplementation))
2381     NewAttr = nullptr;
2382   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2383     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2384                               UA->getGuid());
2385   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2386     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2387
2388   if (NewAttr) {
2389     NewAttr->setInherited(true);
2390     D->addAttr(NewAttr);
2391     if (isa<MSInheritanceAttr>(NewAttr))
2392       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2393     return true;
2394   }
2395
2396   return false;
2397 }
2398
2399 static const Decl *getDefinition(const Decl *D) {
2400   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2401     return TD->getDefinition();
2402   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2403     const VarDecl *Def = VD->getDefinition();
2404     if (Def)
2405       return Def;
2406     return VD->getActingDefinition();
2407   }
2408   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2409     return FD->getDefinition();
2410   return nullptr;
2411 }
2412
2413 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2414   for (const auto *Attribute : D->attrs())
2415     if (Attribute->getKind() == Kind)
2416       return true;
2417   return false;
2418 }
2419
2420 /// checkNewAttributesAfterDef - If we already have a definition, check that
2421 /// there are no new attributes in this declaration.
2422 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2423   if (!New->hasAttrs())
2424     return;
2425
2426   const Decl *Def = getDefinition(Old);
2427   if (!Def || Def == New)
2428     return;
2429
2430   AttrVec &NewAttributes = New->getAttrs();
2431   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2432     const Attr *NewAttribute = NewAttributes[I];
2433
2434     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2435       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2436         Sema::SkipBodyInfo SkipBody;
2437         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2438
2439         // If we're skipping this definition, drop the "alias" attribute.
2440         if (SkipBody.ShouldSkip) {
2441           NewAttributes.erase(NewAttributes.begin() + I);
2442           --E;
2443           continue;
2444         }
2445       } else {
2446         VarDecl *VD = cast<VarDecl>(New);
2447         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2448                                 VarDecl::TentativeDefinition
2449                             ? diag::err_alias_after_tentative
2450                             : diag::err_redefinition;
2451         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2452         S.Diag(Def->getLocation(), diag::note_previous_definition);
2453         VD->setInvalidDecl();
2454       }
2455       ++I;
2456       continue;
2457     }
2458
2459     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2460       // Tentative definitions are only interesting for the alias check above.
2461       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2462         ++I;
2463         continue;
2464       }
2465     }
2466
2467     if (hasAttribute(Def, NewAttribute->getKind())) {
2468       ++I;
2469       continue; // regular attr merging will take care of validating this.
2470     }
2471
2472     if (isa<C11NoReturnAttr>(NewAttribute)) {
2473       // C's _Noreturn is allowed to be added to a function after it is defined.
2474       ++I;
2475       continue;
2476     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2477       if (AA->isAlignas()) {
2478         // C++11 [dcl.align]p6:
2479         //   if any declaration of an entity has an alignment-specifier,
2480         //   every defining declaration of that entity shall specify an
2481         //   equivalent alignment.
2482         // C11 6.7.5/7:
2483         //   If the definition of an object does not have an alignment
2484         //   specifier, any other declaration of that object shall also
2485         //   have no alignment specifier.
2486         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2487           << AA;
2488         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2489           << AA;
2490         NewAttributes.erase(NewAttributes.begin() + I);
2491         --E;
2492         continue;
2493       }
2494     }
2495
2496     S.Diag(NewAttribute->getLocation(),
2497            diag::warn_attribute_precede_definition);
2498     S.Diag(Def->getLocation(), diag::note_previous_definition);
2499     NewAttributes.erase(NewAttributes.begin() + I);
2500     --E;
2501   }
2502 }
2503
2504 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2505 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2506                                AvailabilityMergeKind AMK) {
2507   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2508     UsedAttr *NewAttr = OldAttr->clone(Context);
2509     NewAttr->setInherited(true);
2510     New->addAttr(NewAttr);
2511   }
2512
2513   if (!Old->hasAttrs() && !New->hasAttrs())
2514     return;
2515
2516   // Attributes declared post-definition are currently ignored.
2517   checkNewAttributesAfterDef(*this, New, Old);
2518
2519   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2520     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2521       if (OldA->getLabel() != NewA->getLabel()) {
2522         // This redeclaration changes __asm__ label.
2523         Diag(New->getLocation(), diag::err_different_asm_label);
2524         Diag(OldA->getLocation(), diag::note_previous_declaration);
2525       }
2526     } else if (Old->isUsed()) {
2527       // This redeclaration adds an __asm__ label to a declaration that has
2528       // already been ODR-used.
2529       Diag(New->getLocation(), diag::err_late_asm_label_name)
2530         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2531     }
2532   }
2533
2534   // Re-declaration cannot add abi_tag's.
2535   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2536     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2537       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2538         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2539                       NewTag) == OldAbiTagAttr->tags_end()) {
2540           Diag(NewAbiTagAttr->getLocation(),
2541                diag::err_new_abi_tag_on_redeclaration)
2542               << NewTag;
2543           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2544         }
2545       }
2546     } else {
2547       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2548       Diag(Old->getLocation(), diag::note_previous_declaration);
2549     }
2550   }
2551
2552   if (!Old->hasAttrs())
2553     return;
2554
2555   bool foundAny = New->hasAttrs();
2556
2557   // Ensure that any moving of objects within the allocated map is done before
2558   // we process them.
2559   if (!foundAny) New->setAttrs(AttrVec());
2560
2561   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2562     // Ignore deprecated/unavailable/availability attributes if requested.
2563     AvailabilityMergeKind LocalAMK = AMK_None;
2564     if (isa<DeprecatedAttr>(I) ||
2565         isa<UnavailableAttr>(I) ||
2566         isa<AvailabilityAttr>(I)) {
2567       switch (AMK) {
2568       case AMK_None:
2569         continue;
2570
2571       case AMK_Redeclaration:
2572       case AMK_Override:
2573       case AMK_ProtocolImplementation:
2574         LocalAMK = AMK;
2575         break;
2576       }
2577     }
2578
2579     // Already handled.
2580     if (isa<UsedAttr>(I))
2581       continue;
2582
2583     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2584       foundAny = true;
2585   }
2586
2587   if (mergeAlignedAttrs(*this, New, Old))
2588     foundAny = true;
2589
2590   if (!foundAny) New->dropAttrs();
2591 }
2592
2593 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2594 /// to the new one.
2595 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2596                                      const ParmVarDecl *oldDecl,
2597                                      Sema &S) {
2598   // C++11 [dcl.attr.depend]p2:
2599   //   The first declaration of a function shall specify the
2600   //   carries_dependency attribute for its declarator-id if any declaration
2601   //   of the function specifies the carries_dependency attribute.
2602   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2603   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2604     S.Diag(CDA->getLocation(),
2605            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2606     // Find the first declaration of the parameter.
2607     // FIXME: Should we build redeclaration chains for function parameters?
2608     const FunctionDecl *FirstFD =
2609       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2610     const ParmVarDecl *FirstVD =
2611       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2612     S.Diag(FirstVD->getLocation(),
2613            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2614   }
2615
2616   if (!oldDecl->hasAttrs())
2617     return;
2618
2619   bool foundAny = newDecl->hasAttrs();
2620
2621   // Ensure that any moving of objects within the allocated map is
2622   // done before we process them.
2623   if (!foundAny) newDecl->setAttrs(AttrVec());
2624
2625   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2626     if (!DeclHasAttr(newDecl, I)) {
2627       InheritableAttr *newAttr =
2628         cast<InheritableParamAttr>(I->clone(S.Context));
2629       newAttr->setInherited(true);
2630       newDecl->addAttr(newAttr);
2631       foundAny = true;
2632     }
2633   }
2634
2635   if (!foundAny) newDecl->dropAttrs();
2636 }
2637
2638 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2639                                 const ParmVarDecl *OldParam,
2640                                 Sema &S) {
2641   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2642     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2643       if (*Oldnullability != *Newnullability) {
2644         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2645           << DiagNullabilityKind(
2646                *Newnullability,
2647                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2648                 != 0))
2649           << DiagNullabilityKind(
2650                *Oldnullability,
2651                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2652                 != 0));
2653         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2654       }
2655     } else {
2656       QualType NewT = NewParam->getType();
2657       NewT = S.Context.getAttributedType(
2658                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2659                          NewT, NewT);
2660       NewParam->setType(NewT);
2661     }
2662   }
2663 }
2664
2665 namespace {
2666
2667 /// Used in MergeFunctionDecl to keep track of function parameters in
2668 /// C.
2669 struct GNUCompatibleParamWarning {
2670   ParmVarDecl *OldParm;
2671   ParmVarDecl *NewParm;
2672   QualType PromotedType;
2673 };
2674
2675 } // end anonymous namespace
2676
2677 /// getSpecialMember - get the special member enum for a method.
2678 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2679   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2680     if (Ctor->isDefaultConstructor())
2681       return Sema::CXXDefaultConstructor;
2682
2683     if (Ctor->isCopyConstructor())
2684       return Sema::CXXCopyConstructor;
2685
2686     if (Ctor->isMoveConstructor())
2687       return Sema::CXXMoveConstructor;
2688   } else if (isa<CXXDestructorDecl>(MD)) {
2689     return Sema::CXXDestructor;
2690   } else if (MD->isCopyAssignmentOperator()) {
2691     return Sema::CXXCopyAssignment;
2692   } else if (MD->isMoveAssignmentOperator()) {
2693     return Sema::CXXMoveAssignment;
2694   }
2695
2696   return Sema::CXXInvalid;
2697 }
2698
2699 // Determine whether the previous declaration was a definition, implicit
2700 // declaration, or a declaration.
2701 template <typename T>
2702 static std::pair<diag::kind, SourceLocation>
2703 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2704   diag::kind PrevDiag;
2705   SourceLocation OldLocation = Old->getLocation();
2706   if (Old->isThisDeclarationADefinition())
2707     PrevDiag = diag::note_previous_definition;
2708   else if (Old->isImplicit()) {
2709     PrevDiag = diag::note_previous_implicit_declaration;
2710     if (OldLocation.isInvalid())
2711       OldLocation = New->getLocation();
2712   } else
2713     PrevDiag = diag::note_previous_declaration;
2714   return std::make_pair(PrevDiag, OldLocation);
2715 }
2716
2717 /// canRedefineFunction - checks if a function can be redefined. Currently,
2718 /// only extern inline functions can be redefined, and even then only in
2719 /// GNU89 mode.
2720 static bool canRedefineFunction(const FunctionDecl *FD,
2721                                 const LangOptions& LangOpts) {
2722   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2723           !LangOpts.CPlusPlus &&
2724           FD->isInlineSpecified() &&
2725           FD->getStorageClass() == SC_Extern);
2726 }
2727
2728 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2729   const AttributedType *AT = T->getAs<AttributedType>();
2730   while (AT && !AT->isCallingConv())
2731     AT = AT->getModifiedType()->getAs<AttributedType>();
2732   return AT;
2733 }
2734
2735 template <typename T>
2736 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2737   const DeclContext *DC = Old->getDeclContext();
2738   if (DC->isRecord())
2739     return false;
2740
2741   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2742   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2743     return true;
2744   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2745     return true;
2746   return false;
2747 }
2748
2749 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2750 static bool isExternC(VarTemplateDecl *) { return false; }
2751
2752 /// \brief Check whether a redeclaration of an entity introduced by a
2753 /// using-declaration is valid, given that we know it's not an overload
2754 /// (nor a hidden tag declaration).
2755 template<typename ExpectedDecl>
2756 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2757                                    ExpectedDecl *New) {
2758   // C++11 [basic.scope.declarative]p4:
2759   //   Given a set of declarations in a single declarative region, each of
2760   //   which specifies the same unqualified name,
2761   //   -- they shall all refer to the same entity, or all refer to functions
2762   //      and function templates; or
2763   //   -- exactly one declaration shall declare a class name or enumeration
2764   //      name that is not a typedef name and the other declarations shall all
2765   //      refer to the same variable or enumerator, or all refer to functions
2766   //      and function templates; in this case the class name or enumeration
2767   //      name is hidden (3.3.10).
2768
2769   // C++11 [namespace.udecl]p14:
2770   //   If a function declaration in namespace scope or block scope has the
2771   //   same name and the same parameter-type-list as a function introduced
2772   //   by a using-declaration, and the declarations do not declare the same
2773   //   function, the program is ill-formed.
2774
2775   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2776   if (Old &&
2777       !Old->getDeclContext()->getRedeclContext()->Equals(
2778           New->getDeclContext()->getRedeclContext()) &&
2779       !(isExternC(Old) && isExternC(New)))
2780     Old = nullptr;
2781
2782   if (!Old) {
2783     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2784     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2785     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2786     return true;
2787   }
2788   return false;
2789 }
2790
2791 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2792                                             const FunctionDecl *B) {
2793   assert(A->getNumParams() == B->getNumParams());
2794
2795   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2796     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2797     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2798     if (AttrA == AttrB)
2799       return true;
2800     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2801   };
2802
2803   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2804 }
2805
2806 /// MergeFunctionDecl - We just parsed a function 'New' from
2807 /// declarator D which has the same name and scope as a previous
2808 /// declaration 'Old'.  Figure out how to resolve this situation,
2809 /// merging decls or emitting diagnostics as appropriate.
2810 ///
2811 /// In C++, New and Old must be declarations that are not
2812 /// overloaded. Use IsOverload to determine whether New and Old are
2813 /// overloaded, and to select the Old declaration that New should be
2814 /// merged with.
2815 ///
2816 /// Returns true if there was an error, false otherwise.
2817 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2818                              Scope *S, bool MergeTypeWithOld) {
2819   // Verify the old decl was also a function.
2820   FunctionDecl *Old = OldD->getAsFunction();
2821   if (!Old) {
2822     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2823       if (New->getFriendObjectKind()) {
2824         Diag(New->getLocation(), diag::err_using_decl_friend);
2825         Diag(Shadow->getTargetDecl()->getLocation(),
2826              diag::note_using_decl_target);
2827         Diag(Shadow->getUsingDecl()->getLocation(),
2828              diag::note_using_decl) << 0;
2829         return true;
2830       }
2831
2832       // Check whether the two declarations might declare the same function.
2833       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2834         return true;
2835       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2836     } else {
2837       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2838         << New->getDeclName();
2839       Diag(OldD->getLocation(), diag::note_previous_definition);
2840       return true;
2841     }
2842   }
2843
2844   // If the old declaration is invalid, just give up here.
2845   if (Old->isInvalidDecl())
2846     return true;
2847
2848   diag::kind PrevDiag;
2849   SourceLocation OldLocation;
2850   std::tie(PrevDiag, OldLocation) =
2851       getNoteDiagForInvalidRedeclaration(Old, New);
2852
2853   // Don't complain about this if we're in GNU89 mode and the old function
2854   // is an extern inline function.
2855   // Don't complain about specializations. They are not supposed to have
2856   // storage classes.
2857   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2858       New->getStorageClass() == SC_Static &&
2859       Old->hasExternalFormalLinkage() &&
2860       !New->getTemplateSpecializationInfo() &&
2861       !canRedefineFunction(Old, getLangOpts())) {
2862     if (getLangOpts().MicrosoftExt) {
2863       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2864       Diag(OldLocation, PrevDiag);
2865     } else {
2866       Diag(New->getLocation(), diag::err_static_non_static) << New;
2867       Diag(OldLocation, PrevDiag);
2868       return true;
2869     }
2870   }
2871
2872   if (New->hasAttr<InternalLinkageAttr>() &&
2873       !Old->hasAttr<InternalLinkageAttr>()) {
2874     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2875         << New->getDeclName();
2876     Diag(Old->getLocation(), diag::note_previous_definition);
2877     New->dropAttr<InternalLinkageAttr>();
2878   }
2879
2880   // If a function is first declared with a calling convention, but is later
2881   // declared or defined without one, all following decls assume the calling
2882   // convention of the first.
2883   //
2884   // It's OK if a function is first declared without a calling convention,
2885   // but is later declared or defined with the default calling convention.
2886   //
2887   // To test if either decl has an explicit calling convention, we look for
2888   // AttributedType sugar nodes on the type as written.  If they are missing or
2889   // were canonicalized away, we assume the calling convention was implicit.
2890   //
2891   // Note also that we DO NOT return at this point, because we still have
2892   // other tests to run.
2893   QualType OldQType = Context.getCanonicalType(Old->getType());
2894   QualType NewQType = Context.getCanonicalType(New->getType());
2895   const FunctionType *OldType = cast<FunctionType>(OldQType);
2896   const FunctionType *NewType = cast<FunctionType>(NewQType);
2897   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2898   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2899   bool RequiresAdjustment = false;
2900
2901   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2902     FunctionDecl *First = Old->getFirstDecl();
2903     const FunctionType *FT =
2904         First->getType().getCanonicalType()->castAs<FunctionType>();
2905     FunctionType::ExtInfo FI = FT->getExtInfo();
2906     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2907     if (!NewCCExplicit) {
2908       // Inherit the CC from the previous declaration if it was specified
2909       // there but not here.
2910       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2911       RequiresAdjustment = true;
2912     } else {
2913       // Calling conventions aren't compatible, so complain.
2914       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2915       Diag(New->getLocation(), diag::err_cconv_change)
2916         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2917         << !FirstCCExplicit
2918         << (!FirstCCExplicit ? "" :
2919             FunctionType::getNameForCallConv(FI.getCC()));
2920
2921       // Put the note on the first decl, since it is the one that matters.
2922       Diag(First->getLocation(), diag::note_previous_declaration);
2923       return true;
2924     }
2925   }
2926
2927   // FIXME: diagnose the other way around?
2928   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2929     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2930     RequiresAdjustment = true;
2931   }
2932
2933   // Merge regparm attribute.
2934   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2935       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2936     if (NewTypeInfo.getHasRegParm()) {
2937       Diag(New->getLocation(), diag::err_regparm_mismatch)
2938         << NewType->getRegParmType()
2939         << OldType->getRegParmType();
2940       Diag(OldLocation, diag::note_previous_declaration);
2941       return true;
2942     }
2943
2944     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2945     RequiresAdjustment = true;
2946   }
2947
2948   // Merge ns_returns_retained attribute.
2949   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2950     if (NewTypeInfo.getProducesResult()) {
2951       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2952       Diag(OldLocation, diag::note_previous_declaration);
2953       return true;
2954     }
2955
2956     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2957     RequiresAdjustment = true;
2958   }
2959
2960   if (RequiresAdjustment) {
2961     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2962     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2963     New->setType(QualType(AdjustedType, 0));
2964     NewQType = Context.getCanonicalType(New->getType());
2965     NewType = cast<FunctionType>(NewQType);
2966   }
2967
2968   // If this redeclaration makes the function inline, we may need to add it to
2969   // UndefinedButUsed.
2970   if (!Old->isInlined() && New->isInlined() &&
2971       !New->hasAttr<GNUInlineAttr>() &&
2972       !getLangOpts().GNUInline &&
2973       Old->isUsed(false) &&
2974       !Old->isDefined() && !New->isThisDeclarationADefinition())
2975     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2976                                            SourceLocation()));
2977
2978   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2979   // about it.
2980   if (New->hasAttr<GNUInlineAttr>() &&
2981       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2982     UndefinedButUsed.erase(Old->getCanonicalDecl());
2983   }
2984
2985   // If pass_object_size params don't match up perfectly, this isn't a valid
2986   // redeclaration.
2987   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2988       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2989     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2990         << New->getDeclName();
2991     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2992     return true;
2993   }
2994
2995   if (getLangOpts().CPlusPlus) {
2996     // C++1z [over.load]p2
2997     //   Certain function declarations cannot be overloaded:
2998     //     -- Function declarations that differ only in the return type,
2999     //        the exception specification, or both cannot be overloaded.
3000
3001     // Check the exception specifications match. This may recompute the type of
3002     // both Old and New if it resolved exception specifications, so grab the
3003     // types again after this. Because this updates the type, we do this before
3004     // any of the other checks below, which may update the "de facto" NewQType
3005     // but do not necessarily update the type of New.
3006     if (CheckEquivalentExceptionSpec(Old, New))
3007       return true;
3008     OldQType = Context.getCanonicalType(Old->getType());
3009     NewQType = Context.getCanonicalType(New->getType());
3010
3011     // Go back to the type source info to compare the declared return types,
3012     // per C++1y [dcl.type.auto]p13:
3013     //   Redeclarations or specializations of a function or function template
3014     //   with a declared return type that uses a placeholder type shall also
3015     //   use that placeholder, not a deduced type.
3016     QualType OldDeclaredReturnType =
3017         (Old->getTypeSourceInfo()
3018              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3019              : OldType)->getReturnType();
3020     QualType NewDeclaredReturnType =
3021         (New->getTypeSourceInfo()
3022              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3023              : NewType)->getReturnType();
3024     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3025         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3026           New->isLocalExternDecl())) {
3027       QualType ResQT;
3028       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3029           OldDeclaredReturnType->isObjCObjectPointerType())
3030         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3031       if (ResQT.isNull()) {
3032         if (New->isCXXClassMember() && New->isOutOfLine())
3033           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3034               << New << New->getReturnTypeSourceRange();
3035         else
3036           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3037               << New->getReturnTypeSourceRange();
3038         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3039                                     << Old->getReturnTypeSourceRange();
3040         return true;
3041       }
3042       else
3043         NewQType = ResQT;
3044     }
3045
3046     QualType OldReturnType = OldType->getReturnType();
3047     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3048     if (OldReturnType != NewReturnType) {
3049       // If this function has a deduced return type and has already been
3050       // defined, copy the deduced value from the old declaration.
3051       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3052       if (OldAT && OldAT->isDeduced()) {
3053         New->setType(
3054             SubstAutoType(New->getType(),
3055                           OldAT->isDependentType() ? Context.DependentTy
3056                                                    : OldAT->getDeducedType()));
3057         NewQType = Context.getCanonicalType(
3058             SubstAutoType(NewQType,
3059                           OldAT->isDependentType() ? Context.DependentTy
3060                                                    : OldAT->getDeducedType()));
3061       }
3062     }
3063
3064     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3065     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3066     if (OldMethod && NewMethod) {
3067       // Preserve triviality.
3068       NewMethod->setTrivial(OldMethod->isTrivial());
3069
3070       // MSVC allows explicit template specialization at class scope:
3071       // 2 CXXMethodDecls referring to the same function will be injected.
3072       // We don't want a redeclaration error.
3073       bool IsClassScopeExplicitSpecialization =
3074                               OldMethod->isFunctionTemplateSpecialization() &&
3075                               NewMethod->isFunctionTemplateSpecialization();
3076       bool isFriend = NewMethod->getFriendObjectKind();
3077
3078       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3079           !IsClassScopeExplicitSpecialization) {
3080         //    -- Member function declarations with the same name and the
3081         //       same parameter types cannot be overloaded if any of them
3082         //       is a static member function declaration.
3083         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3084           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3085           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3086           return true;
3087         }
3088
3089         // C++ [class.mem]p1:
3090         //   [...] A member shall not be declared twice in the
3091         //   member-specification, except that a nested class or member
3092         //   class template can be declared and then later defined.
3093         if (!inTemplateInstantiation()) {
3094           unsigned NewDiag;
3095           if (isa<CXXConstructorDecl>(OldMethod))
3096             NewDiag = diag::err_constructor_redeclared;
3097           else if (isa<CXXDestructorDecl>(NewMethod))
3098             NewDiag = diag::err_destructor_redeclared;
3099           else if (isa<CXXConversionDecl>(NewMethod))
3100             NewDiag = diag::err_conv_function_redeclared;
3101           else
3102             NewDiag = diag::err_member_redeclared;
3103
3104           Diag(New->getLocation(), NewDiag);
3105         } else {
3106           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3107             << New << New->getType();
3108         }
3109         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3110         return true;
3111
3112       // Complain if this is an explicit declaration of a special
3113       // member that was initially declared implicitly.
3114       //
3115       // As an exception, it's okay to befriend such methods in order
3116       // to permit the implicit constructor/destructor/operator calls.
3117       } else if (OldMethod->isImplicit()) {
3118         if (isFriend) {
3119           NewMethod->setImplicit();
3120         } else {
3121           Diag(NewMethod->getLocation(),
3122                diag::err_definition_of_implicitly_declared_member)
3123             << New << getSpecialMember(OldMethod);
3124           return true;
3125         }
3126       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3127         Diag(NewMethod->getLocation(),
3128              diag::err_definition_of_explicitly_defaulted_member)
3129           << getSpecialMember(OldMethod);
3130         return true;
3131       }
3132     }
3133
3134     // C++11 [dcl.attr.noreturn]p1:
3135     //   The first declaration of a function shall specify the noreturn
3136     //   attribute if any declaration of that function specifies the noreturn
3137     //   attribute.
3138     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3139     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3140       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3141       Diag(Old->getFirstDecl()->getLocation(),
3142            diag::note_noreturn_missing_first_decl);
3143     }
3144
3145     // C++11 [dcl.attr.depend]p2:
3146     //   The first declaration of a function shall specify the
3147     //   carries_dependency attribute for its declarator-id if any declaration
3148     //   of the function specifies the carries_dependency attribute.
3149     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3150     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3151       Diag(CDA->getLocation(),
3152            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3153       Diag(Old->getFirstDecl()->getLocation(),
3154            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3155     }
3156
3157     // (C++98 8.3.5p3):
3158     //   All declarations for a function shall agree exactly in both the
3159     //   return type and the parameter-type-list.
3160     // We also want to respect all the extended bits except noreturn.
3161
3162     // noreturn should now match unless the old type info didn't have it.
3163     QualType OldQTypeForComparison = OldQType;
3164     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3165       auto *OldType = OldQType->castAs<FunctionProtoType>();
3166       const FunctionType *OldTypeForComparison
3167         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3168       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3169       assert(OldQTypeForComparison.isCanonical());
3170     }
3171
3172     if (haveIncompatibleLanguageLinkages(Old, New)) {
3173       // As a special case, retain the language linkage from previous
3174       // declarations of a friend function as an extension.
3175       //
3176       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3177       // and is useful because there's otherwise no way to specify language
3178       // linkage within class scope.
3179       //
3180       // Check cautiously as the friend object kind isn't yet complete.
3181       if (New->getFriendObjectKind() != Decl::FOK_None) {
3182         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3183         Diag(OldLocation, PrevDiag);
3184       } else {
3185         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3186         Diag(OldLocation, PrevDiag);
3187         return true;
3188       }
3189     }
3190
3191     if (OldQTypeForComparison == NewQType)
3192       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3193
3194     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3195         New->isLocalExternDecl()) {
3196       // It's OK if we couldn't merge types for a local function declaraton
3197       // if either the old or new type is dependent. We'll merge the types
3198       // when we instantiate the function.
3199       return false;
3200     }
3201
3202     // Fall through for conflicting redeclarations and redefinitions.
3203   }
3204
3205   // C: Function types need to be compatible, not identical. This handles
3206   // duplicate function decls like "void f(int); void f(enum X);" properly.
3207   if (!getLangOpts().CPlusPlus &&
3208       Context.typesAreCompatible(OldQType, NewQType)) {
3209     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3210     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3211     const FunctionProtoType *OldProto = nullptr;
3212     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3213         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3214       // The old declaration provided a function prototype, but the
3215       // new declaration does not. Merge in the prototype.
3216       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3217       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3218       NewQType =
3219           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3220                                   OldProto->getExtProtoInfo());
3221       New->setType(NewQType);
3222       New->setHasInheritedPrototype();
3223
3224       // Synthesize parameters with the same types.
3225       SmallVector<ParmVarDecl*, 16> Params;
3226       for (const auto &ParamType : OldProto->param_types()) {
3227         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3228                                                  SourceLocation(), nullptr,
3229                                                  ParamType, /*TInfo=*/nullptr,
3230                                                  SC_None, nullptr);
3231         Param->setScopeInfo(0, Params.size());
3232         Param->setImplicit();
3233         Params.push_back(Param);
3234       }
3235
3236       New->setParams(Params);
3237     }
3238
3239     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3240   }
3241
3242   // GNU C permits a K&R definition to follow a prototype declaration
3243   // if the declared types of the parameters in the K&R definition
3244   // match the types in the prototype declaration, even when the
3245   // promoted types of the parameters from the K&R definition differ
3246   // from the types in the prototype. GCC then keeps the types from
3247   // the prototype.
3248   //
3249   // If a variadic prototype is followed by a non-variadic K&R definition,
3250   // the K&R definition becomes variadic.  This is sort of an edge case, but
3251   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3252   // C99 6.9.1p8.
3253   if (!getLangOpts().CPlusPlus &&
3254       Old->hasPrototype() && !New->hasPrototype() &&
3255       New->getType()->getAs<FunctionProtoType>() &&
3256       Old->getNumParams() == New->getNumParams()) {
3257     SmallVector<QualType, 16> ArgTypes;
3258     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3259     const FunctionProtoType *OldProto
3260       = Old->getType()->getAs<FunctionProtoType>();
3261     const FunctionProtoType *NewProto
3262       = New->getType()->getAs<FunctionProtoType>();
3263
3264     // Determine whether this is the GNU C extension.
3265     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3266                                                NewProto->getReturnType());
3267     bool LooseCompatible = !MergedReturn.isNull();
3268     for (unsigned Idx = 0, End = Old->getNumParams();
3269          LooseCompatible && Idx != End; ++Idx) {
3270       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3271       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3272       if (Context.typesAreCompatible(OldParm->getType(),
3273                                      NewProto->getParamType(Idx))) {
3274         ArgTypes.push_back(NewParm->getType());
3275       } else if (Context.typesAreCompatible(OldParm->getType(),
3276                                             NewParm->getType(),
3277                                             /*CompareUnqualified=*/true)) {
3278         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3279                                            NewProto->getParamType(Idx) };
3280         Warnings.push_back(Warn);
3281         ArgTypes.push_back(NewParm->getType());
3282       } else
3283         LooseCompatible = false;
3284     }
3285
3286     if (LooseCompatible) {
3287       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3288         Diag(Warnings[Warn].NewParm->getLocation(),
3289              diag::ext_param_promoted_not_compatible_with_prototype)
3290           << Warnings[Warn].PromotedType
3291           << Warnings[Warn].OldParm->getType();
3292         if (Warnings[Warn].OldParm->getLocation().isValid())
3293           Diag(Warnings[Warn].OldParm->getLocation(),
3294                diag::note_previous_declaration);
3295       }
3296
3297       if (MergeTypeWithOld)
3298         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3299                                              OldProto->getExtProtoInfo()));
3300       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3301     }
3302
3303     // Fall through to diagnose conflicting types.
3304   }
3305
3306   // A function that has already been declared has been redeclared or
3307   // defined with a different type; show an appropriate diagnostic.
3308
3309   // If the previous declaration was an implicitly-generated builtin
3310   // declaration, then at the very least we should use a specialized note.
3311   unsigned BuiltinID;
3312   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3313     // If it's actually a library-defined builtin function like 'malloc'
3314     // or 'printf', just warn about the incompatible redeclaration.
3315     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3316       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3317       Diag(OldLocation, diag::note_previous_builtin_declaration)
3318         << Old << Old->getType();
3319
3320       // If this is a global redeclaration, just forget hereafter
3321       // about the "builtin-ness" of the function.
3322       //
3323       // Doing this for local extern declarations is problematic.  If
3324       // the builtin declaration remains visible, a second invalid
3325       // local declaration will produce a hard error; if it doesn't
3326       // remain visible, a single bogus local redeclaration (which is
3327       // actually only a warning) could break all the downstream code.
3328       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3329         New->getIdentifier()->revertBuiltin();
3330
3331       return false;
3332     }
3333
3334     PrevDiag = diag::note_previous_builtin_declaration;
3335   }
3336
3337   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3338   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3339   return true;
3340 }
3341
3342 /// \brief Completes the merge of two function declarations that are
3343 /// known to be compatible.
3344 ///
3345 /// This routine handles the merging of attributes and other
3346 /// properties of function declarations from the old declaration to
3347 /// the new declaration, once we know that New is in fact a
3348 /// redeclaration of Old.
3349 ///
3350 /// \returns false
3351 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3352                                         Scope *S, bool MergeTypeWithOld) {
3353   // Merge the attributes
3354   mergeDeclAttributes(New, Old);
3355
3356   // Merge "pure" flag.
3357   if (Old->isPure())
3358     New->setPure();
3359
3360   // Merge "used" flag.
3361   if (Old->getMostRecentDecl()->isUsed(false))
3362     New->setIsUsed();
3363
3364   // Merge attributes from the parameters.  These can mismatch with K&R
3365   // declarations.
3366   if (New->getNumParams() == Old->getNumParams())
3367       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3368         ParmVarDecl *NewParam = New->getParamDecl(i);
3369         ParmVarDecl *OldParam = Old->getParamDecl(i);
3370         mergeParamDeclAttributes(NewParam, OldParam, *this);
3371         mergeParamDeclTypes(NewParam, OldParam, *this);
3372       }
3373
3374   if (getLangOpts().CPlusPlus)
3375     return MergeCXXFunctionDecl(New, Old, S);
3376
3377   // Merge the function types so the we get the composite types for the return
3378   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3379   // was visible.
3380   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3381   if (!Merged.isNull() && MergeTypeWithOld)
3382     New->setType(Merged);
3383
3384   return false;
3385 }
3386
3387 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3388                                 ObjCMethodDecl *oldMethod) {
3389   // Merge the attributes, including deprecated/unavailable
3390   AvailabilityMergeKind MergeKind =
3391     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3392       ? AMK_ProtocolImplementation
3393       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3394                                                        : AMK_Override;
3395
3396   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3397
3398   // Merge attributes from the parameters.
3399   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3400                                        oe = oldMethod->param_end();
3401   for (ObjCMethodDecl::param_iterator
3402          ni = newMethod->param_begin(), ne = newMethod->param_end();
3403        ni != ne && oi != oe; ++ni, ++oi)
3404     mergeParamDeclAttributes(*ni, *oi, *this);
3405
3406   CheckObjCMethodOverride(newMethod, oldMethod);
3407 }
3408
3409 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3410   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3411
3412   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3413          ? diag::err_redefinition_different_type
3414          : diag::err_redeclaration_different_type)
3415     << New->getDeclName() << New->getType() << Old->getType();
3416
3417   diag::kind PrevDiag;
3418   SourceLocation OldLocation;
3419   std::tie(PrevDiag, OldLocation)
3420     = getNoteDiagForInvalidRedeclaration(Old, New);
3421   S.Diag(OldLocation, PrevDiag);
3422   New->setInvalidDecl();
3423 }
3424
3425 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3426 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3427 /// emitting diagnostics as appropriate.
3428 ///
3429 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3430 /// to here in AddInitializerToDecl. We can't check them before the initializer
3431 /// is attached.
3432 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3433                              bool MergeTypeWithOld) {
3434   if (New->isInvalidDecl() || Old->isInvalidDecl())
3435     return;
3436
3437   QualType MergedT;
3438   if (getLangOpts().CPlusPlus) {
3439     if (New->getType()->isUndeducedType()) {
3440       // We don't know what the new type is until the initializer is attached.
3441       return;
3442     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3443       // These could still be something that needs exception specs checked.
3444       return MergeVarDeclExceptionSpecs(New, Old);
3445     }
3446     // C++ [basic.link]p10:
3447     //   [...] the types specified by all declarations referring to a given
3448     //   object or function shall be identical, except that declarations for an
3449     //   array object can specify array types that differ by the presence or
3450     //   absence of a major array bound (8.3.4).
3451     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3452       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3453       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3454
3455       // We are merging a variable declaration New into Old. If it has an array
3456       // bound, and that bound differs from Old's bound, we should diagnose the
3457       // mismatch.
3458       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3459         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3460              PrevVD = PrevVD->getPreviousDecl()) {
3461           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3462           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3463             continue;
3464
3465           if (!Context.hasSameType(NewArray, PrevVDTy))
3466             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3467         }
3468       }
3469
3470       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3471         if (Context.hasSameType(OldArray->getElementType(),
3472                                 NewArray->getElementType()))
3473           MergedT = New->getType();
3474       }
3475       // FIXME: Check visibility. New is hidden but has a complete type. If New
3476       // has no array bound, it should not inherit one from Old, if Old is not
3477       // visible.
3478       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3479         if (Context.hasSameType(OldArray->getElementType(),
3480                                 NewArray->getElementType()))
3481           MergedT = Old->getType();
3482       }
3483     }
3484     else if (New->getType()->isObjCObjectPointerType() &&
3485                Old->getType()->isObjCObjectPointerType()) {
3486       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3487                                               Old->getType());
3488     }
3489   } else {
3490     // C 6.2.7p2:
3491     //   All declarations that refer to the same object or function shall have
3492     //   compatible type.
3493     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3494   }
3495   if (MergedT.isNull()) {
3496     // It's OK if we couldn't merge types if either type is dependent, for a
3497     // block-scope variable. In other cases (static data members of class
3498     // templates, variable templates, ...), we require the types to be
3499     // equivalent.
3500     // FIXME: The C++ standard doesn't say anything about this.
3501     if ((New->getType()->isDependentType() ||
3502          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3503       // If the old type was dependent, we can't merge with it, so the new type
3504       // becomes dependent for now. We'll reproduce the original type when we
3505       // instantiate the TypeSourceInfo for the variable.
3506       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3507         New->setType(Context.DependentTy);
3508       return;
3509     }
3510     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3511   }
3512
3513   // Don't actually update the type on the new declaration if the old
3514   // declaration was an extern declaration in a different scope.
3515   if (MergeTypeWithOld)
3516     New->setType(MergedT);
3517 }
3518
3519 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3520                                   LookupResult &Previous) {
3521   // C11 6.2.7p4:
3522   //   For an identifier with internal or external linkage declared
3523   //   in a scope in which a prior declaration of that identifier is
3524   //   visible, if the prior declaration specifies internal or
3525   //   external linkage, the type of the identifier at the later
3526   //   declaration becomes the composite type.
3527   //
3528   // If the variable isn't visible, we do not merge with its type.
3529   if (Previous.isShadowed())
3530     return false;
3531
3532   if (S.getLangOpts().CPlusPlus) {
3533     // C++11 [dcl.array]p3:
3534     //   If there is a preceding declaration of the entity in the same
3535     //   scope in which the bound was specified, an omitted array bound
3536     //   is taken to be the same as in that earlier declaration.
3537     return NewVD->isPreviousDeclInSameBlockScope() ||
3538            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3539             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3540   } else {
3541     // If the old declaration was function-local, don't merge with its
3542     // type unless we're in the same function.
3543     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3544            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3545   }
3546 }
3547
3548 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3549 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3550 /// situation, merging decls or emitting diagnostics as appropriate.
3551 ///
3552 /// Tentative definition rules (C99 6.9.2p2) are checked by
3553 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3554 /// definitions here, since the initializer hasn't been attached.
3555 ///
3556 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3557   // If the new decl is already invalid, don't do any other checking.
3558   if (New->isInvalidDecl())
3559     return;
3560
3561   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3562     return;
3563
3564   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3565
3566   // Verify the old decl was also a variable or variable template.
3567   VarDecl *Old = nullptr;
3568   VarTemplateDecl *OldTemplate = nullptr;
3569   if (Previous.isSingleResult()) {
3570     if (NewTemplate) {
3571       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3572       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3573
3574       if (auto *Shadow =
3575               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3576         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3577           return New->setInvalidDecl();
3578     } else {
3579       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3580
3581       if (auto *Shadow =
3582               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3583         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3584           return New->setInvalidDecl();
3585     }
3586   }
3587   if (!Old) {
3588     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3589       << New->getDeclName();
3590     Diag(Previous.getRepresentativeDecl()->getLocation(),
3591          diag::note_previous_definition);
3592     return New->setInvalidDecl();
3593   }
3594
3595   // Ensure the template parameters are compatible.
3596   if (NewTemplate &&
3597       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3598                                       OldTemplate->getTemplateParameters(),
3599                                       /*Complain=*/true, TPL_TemplateMatch))
3600     return New->setInvalidDecl();
3601
3602   // C++ [class.mem]p1:
3603   //   A member shall not be declared twice in the member-specification [...]
3604   //
3605   // Here, we need only consider static data members.
3606   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3607     Diag(New->getLocation(), diag::err_duplicate_member)
3608       << New->getIdentifier();
3609     Diag(Old->getLocation(), diag::note_previous_declaration);
3610     New->setInvalidDecl();
3611   }
3612
3613   mergeDeclAttributes(New, Old);
3614   // Warn if an already-declared variable is made a weak_import in a subsequent
3615   // declaration
3616   if (New->hasAttr<WeakImportAttr>() &&
3617       Old->getStorageClass() == SC_None &&
3618       !Old->hasAttr<WeakImportAttr>()) {
3619     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3620     Diag(Old->getLocation(), diag::note_previous_definition);
3621     // Remove weak_import attribute on new declaration.
3622     New->dropAttr<WeakImportAttr>();
3623   }
3624
3625   if (New->hasAttr<InternalLinkageAttr>() &&
3626       !Old->hasAttr<InternalLinkageAttr>()) {
3627     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3628         << New->getDeclName();
3629     Diag(Old->getLocation(), diag::note_previous_definition);
3630     New->dropAttr<InternalLinkageAttr>();
3631   }
3632
3633   // Merge the types.
3634   VarDecl *MostRecent = Old->getMostRecentDecl();
3635   if (MostRecent != Old) {
3636     MergeVarDeclTypes(New, MostRecent,
3637                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3638     if (New->isInvalidDecl())
3639       return;
3640   }
3641
3642   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3643   if (New->isInvalidDecl())
3644     return;
3645
3646   diag::kind PrevDiag;
3647   SourceLocation OldLocation;
3648   std::tie(PrevDiag, OldLocation) =
3649       getNoteDiagForInvalidRedeclaration(Old, New);
3650
3651   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3652   if (New->getStorageClass() == SC_Static &&
3653       !New->isStaticDataMember() &&
3654       Old->hasExternalFormalLinkage()) {
3655     if (getLangOpts().MicrosoftExt) {
3656       Diag(New->getLocation(), diag::ext_static_non_static)
3657           << New->getDeclName();
3658       Diag(OldLocation, PrevDiag);
3659     } else {
3660       Diag(New->getLocation(), diag::err_static_non_static)
3661           << New->getDeclName();
3662       Diag(OldLocation, PrevDiag);
3663       return New->setInvalidDecl();
3664     }
3665   }
3666   // C99 6.2.2p4:
3667   //   For an identifier declared with the storage-class specifier
3668   //   extern in a scope in which a prior declaration of that
3669   //   identifier is visible,23) if the prior declaration specifies
3670   //   internal or external linkage, the linkage of the identifier at
3671   //   the later declaration is the same as the linkage specified at
3672   //   the prior declaration. If no prior declaration is visible, or
3673   //   if the prior declaration specifies no linkage, then the
3674   //   identifier has external linkage.
3675   if (New->hasExternalStorage() && Old->hasLinkage())
3676     /* Okay */;
3677   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3678            !New->isStaticDataMember() &&
3679            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3680     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3681     Diag(OldLocation, PrevDiag);
3682     return New->setInvalidDecl();
3683   }
3684
3685   // Check if extern is followed by non-extern and vice-versa.
3686   if (New->hasExternalStorage() &&
3687       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3688     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3689     Diag(OldLocation, PrevDiag);
3690     return New->setInvalidDecl();
3691   }
3692   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3693       !New->hasExternalStorage()) {
3694     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3695     Diag(OldLocation, PrevDiag);
3696     return New->setInvalidDecl();
3697   }
3698
3699   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3700
3701   // FIXME: The test for external storage here seems wrong? We still
3702   // need to check for mismatches.
3703   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3704       // Don't complain about out-of-line definitions of static members.
3705       !(Old->getLexicalDeclContext()->isRecord() &&
3706         !New->getLexicalDeclContext()->isRecord())) {
3707     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3708     Diag(OldLocation, PrevDiag);
3709     return New->setInvalidDecl();
3710   }
3711
3712   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3713     if (VarDecl *Def = Old->getDefinition()) {
3714       // C++1z [dcl.fcn.spec]p4:
3715       //   If the definition of a variable appears in a translation unit before
3716       //   its first declaration as inline, the program is ill-formed.
3717       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3718       Diag(Def->getLocation(), diag::note_previous_definition);
3719     }
3720   }
3721
3722   // If this redeclaration makes the function inline, we may need to add it to
3723   // UndefinedButUsed.
3724   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3725       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3726     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3727                                            SourceLocation()));
3728
3729   if (New->getTLSKind() != Old->getTLSKind()) {
3730     if (!Old->getTLSKind()) {
3731       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3732       Diag(OldLocation, PrevDiag);
3733     } else if (!New->getTLSKind()) {
3734       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3735       Diag(OldLocation, PrevDiag);
3736     } else {
3737       // Do not allow redeclaration to change the variable between requiring
3738       // static and dynamic initialization.
3739       // FIXME: GCC allows this, but uses the TLS keyword on the first
3740       // declaration to determine the kind. Do we need to be compatible here?
3741       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3742         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3743       Diag(OldLocation, PrevDiag);
3744     }
3745   }
3746
3747   // C++ doesn't have tentative definitions, so go right ahead and check here.
3748   if (getLangOpts().CPlusPlus &&
3749       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3750     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3751         Old->getCanonicalDecl()->isConstexpr()) {
3752       // This definition won't be a definition any more once it's been merged.
3753       Diag(New->getLocation(),
3754            diag::warn_deprecated_redundant_constexpr_static_def);
3755     } else if (VarDecl *Def = Old->getDefinition()) {
3756       if (checkVarDeclRedefinition(Def, New))
3757         return;
3758     }
3759   }
3760
3761   if (haveIncompatibleLanguageLinkages(Old, New)) {
3762     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3763     Diag(OldLocation, PrevDiag);
3764     New->setInvalidDecl();
3765     return;
3766   }
3767
3768   // Merge "used" flag.
3769   if (Old->getMostRecentDecl()->isUsed(false))
3770     New->setIsUsed();
3771
3772   // Keep a chain of previous declarations.
3773   New->setPreviousDecl(Old);
3774   if (NewTemplate)
3775     NewTemplate->setPreviousDecl(OldTemplate);
3776
3777   // Inherit access appropriately.
3778   New->setAccess(Old->getAccess());
3779   if (NewTemplate)
3780     NewTemplate->setAccess(New->getAccess());
3781
3782   if (Old->isInline())
3783     New->setImplicitlyInline();
3784 }
3785
3786 /// We've just determined that \p Old and \p New both appear to be definitions
3787 /// of the same variable. Either diagnose or fix the problem.
3788 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3789   if (!hasVisibleDefinition(Old) &&
3790       (New->getFormalLinkage() == InternalLinkage ||
3791        New->isInline() ||
3792        New->getDescribedVarTemplate() ||
3793        New->getNumTemplateParameterLists() ||
3794        New->getDeclContext()->isDependentContext())) {
3795     // The previous definition is hidden, and multiple definitions are
3796     // permitted (in separate TUs). Demote this to a declaration.
3797     New->demoteThisDefinitionToDeclaration();
3798
3799     // Make the canonical definition visible.
3800     if (auto *OldTD = Old->getDescribedVarTemplate())
3801       makeMergedDefinitionVisible(OldTD, New->getLocation());
3802     makeMergedDefinitionVisible(Old, New->getLocation());
3803     return false;
3804   } else {
3805     Diag(New->getLocation(), diag::err_redefinition) << New;
3806     Diag(Old->getLocation(), diag::note_previous_definition);
3807     New->setInvalidDecl();
3808     return true;
3809   }
3810 }
3811
3812 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3813 /// no declarator (e.g. "struct foo;") is parsed.
3814 Decl *
3815 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3816                                  RecordDecl *&AnonRecord) {
3817   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3818                                     AnonRecord);
3819 }
3820
3821 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3822 // disambiguate entities defined in different scopes.
3823 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3824 // compatibility.
3825 // We will pick our mangling number depending on which version of MSVC is being
3826 // targeted.
3827 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3828   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3829              ? S->getMSCurManglingNumber()
3830              : S->getMSLastManglingNumber();
3831 }
3832
3833 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3834   if (!Context.getLangOpts().CPlusPlus)
3835     return;
3836
3837   if (isa<CXXRecordDecl>(Tag->getParent())) {
3838     // If this tag is the direct child of a class, number it if
3839     // it is anonymous.
3840     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3841       return;
3842     MangleNumberingContext &MCtx =
3843         Context.getManglingNumberContext(Tag->getParent());
3844     Context.setManglingNumber(
3845         Tag, MCtx.getManglingNumber(
3846                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3847     return;
3848   }
3849
3850   // If this tag isn't a direct child of a class, number it if it is local.
3851   Decl *ManglingContextDecl;
3852   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3853           Tag->getDeclContext(), ManglingContextDecl)) {
3854     Context.setManglingNumber(
3855         Tag, MCtx->getManglingNumber(
3856                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3857   }
3858 }
3859
3860 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3861                                         TypedefNameDecl *NewTD) {
3862   if (TagFromDeclSpec->isInvalidDecl())
3863     return;
3864
3865   // Do nothing if the tag already has a name for linkage purposes.
3866   if (TagFromDeclSpec->hasNameForLinkage())
3867     return;
3868
3869   // A well-formed anonymous tag must always be a TUK_Definition.
3870   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3871
3872   // The type must match the tag exactly;  no qualifiers allowed.
3873   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3874                            Context.getTagDeclType(TagFromDeclSpec))) {
3875     if (getLangOpts().CPlusPlus)
3876       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3877     return;
3878   }
3879
3880   // If we've already computed linkage for the anonymous tag, then
3881   // adding a typedef name for the anonymous decl can change that
3882   // linkage, which might be a serious problem.  Diagnose this as
3883   // unsupported and ignore the typedef name.  TODO: we should
3884   // pursue this as a language defect and establish a formal rule
3885   // for how to handle it.
3886   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3887     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3888
3889     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3890     tagLoc = getLocForEndOfToken(tagLoc);
3891
3892     llvm::SmallString<40> textToInsert;
3893     textToInsert += ' ';
3894     textToInsert += NewTD->getIdentifier()->getName();
3895     Diag(tagLoc, diag::note_typedef_changes_linkage)
3896         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3897     return;
3898   }
3899
3900   // Otherwise, set this is the anon-decl typedef for the tag.
3901   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3902 }
3903
3904 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3905   switch (T) {
3906   case DeclSpec::TST_class:
3907     return 0;
3908   case DeclSpec::TST_struct:
3909     return 1;
3910   case DeclSpec::TST_interface:
3911     return 2;
3912   case DeclSpec::TST_union:
3913     return 3;
3914   case DeclSpec::TST_enum:
3915     return 4;
3916   default:
3917     llvm_unreachable("unexpected type specifier");
3918   }
3919 }
3920
3921 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3922 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3923 /// parameters to cope with template friend declarations.
3924 Decl *
3925 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3926                                  MultiTemplateParamsArg TemplateParams,
3927                                  bool IsExplicitInstantiation,
3928                                  RecordDecl *&AnonRecord) {
3929   Decl *TagD = nullptr;
3930   TagDecl *Tag = nullptr;
3931   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3932       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3933       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3934       DS.getTypeSpecType() == DeclSpec::TST_union ||
3935       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3936     TagD = DS.getRepAsDecl();
3937
3938     if (!TagD) // We probably had an error
3939       return nullptr;
3940
3941     // Note that the above type specs guarantee that the
3942     // type rep is a Decl, whereas in many of the others
3943     // it's a Type.
3944     if (isa<TagDecl>(TagD))
3945       Tag = cast<TagDecl>(TagD);
3946     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3947       Tag = CTD->getTemplatedDecl();
3948   }
3949
3950   if (Tag) {
3951     handleTagNumbering(Tag, S);
3952     Tag->setFreeStanding();
3953     if (Tag->isInvalidDecl())
3954       return Tag;
3955   }
3956
3957   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3958     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3959     // or incomplete types shall not be restrict-qualified."
3960     if (TypeQuals & DeclSpec::TQ_restrict)
3961       Diag(DS.getRestrictSpecLoc(),
3962            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3963            << DS.getSourceRange();
3964   }
3965
3966   if (DS.isInlineSpecified())
3967     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3968         << getLangOpts().CPlusPlus1z;
3969
3970   if (DS.isConstexprSpecified()) {
3971     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3972     // and definitions of functions and variables.
3973     if (Tag)
3974       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3975           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3976     else
3977       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3978     // Don't emit warnings after this error.
3979     return TagD;
3980   }
3981
3982   if (DS.isConceptSpecified()) {
3983     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3984     // either a function concept and its definition or a variable concept and
3985     // its initializer.
3986     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3987     return TagD;
3988   }
3989
3990   DiagnoseFunctionSpecifiers(DS);
3991
3992   if (DS.isFriendSpecified()) {
3993     // If we're dealing with a decl but not a TagDecl, assume that
3994     // whatever routines created it handled the friendship aspect.
3995     if (TagD && !Tag)
3996       return nullptr;
3997     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3998   }
3999
4000   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4001   bool IsExplicitSpecialization =
4002     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4003   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4004       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4005       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4006     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4007     // nested-name-specifier unless it is an explicit instantiation
4008     // or an explicit specialization.
4009     //
4010     // FIXME: We allow class template partial specializations here too, per the
4011     // obvious intent of DR1819.
4012     //
4013     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4014     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4015         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4016     return nullptr;
4017   }
4018
4019   // Track whether this decl-specifier declares anything.
4020   bool DeclaresAnything = true;
4021
4022   // Handle anonymous struct definitions.
4023   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4024     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4025         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4026       if (getLangOpts().CPlusPlus ||
4027           Record->getDeclContext()->isRecord()) {
4028         // If CurContext is a DeclContext that can contain statements,
4029         // RecursiveASTVisitor won't visit the decls that
4030         // BuildAnonymousStructOrUnion() will put into CurContext.
4031         // Also store them here so that they can be part of the
4032         // DeclStmt that gets created in this case.
4033         // FIXME: Also return the IndirectFieldDecls created by
4034         // BuildAnonymousStructOr union, for the same reason?
4035         if (CurContext->isFunctionOrMethod())
4036           AnonRecord = Record;
4037         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4038                                            Context.getPrintingPolicy());
4039       }
4040
4041       DeclaresAnything = false;
4042     }
4043   }
4044
4045   // C11 6.7.2.1p2:
4046   //   A struct-declaration that does not declare an anonymous structure or
4047   //   anonymous union shall contain a struct-declarator-list.
4048   //
4049   // This rule also existed in C89 and C99; the grammar for struct-declaration
4050   // did not permit a struct-declaration without a struct-declarator-list.
4051   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4052       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4053     // Check for Microsoft C extension: anonymous struct/union member.
4054     // Handle 2 kinds of anonymous struct/union:
4055     //   struct STRUCT;
4056     //   union UNION;
4057     // and
4058     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4059     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4060     if ((Tag && Tag->getDeclName()) ||
4061         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4062       RecordDecl *Record = nullptr;
4063       if (Tag)
4064         Record = dyn_cast<RecordDecl>(Tag);
4065       else if (const RecordType *RT =
4066                    DS.getRepAsType().get()->getAsStructureType())
4067         Record = RT->getDecl();
4068       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4069         Record = UT->getDecl();
4070
4071       if (Record && getLangOpts().MicrosoftExt) {
4072         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4073           << Record->isUnion() << DS.getSourceRange();
4074         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4075       }
4076
4077       DeclaresAnything = false;
4078     }
4079   }
4080
4081   // Skip all the checks below if we have a type error.
4082   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4083       (TagD && TagD->isInvalidDecl()))
4084     return TagD;
4085
4086   if (getLangOpts().CPlusPlus &&
4087       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4088     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4089       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4090           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4091         DeclaresAnything = false;
4092
4093   if (!DS.isMissingDeclaratorOk()) {
4094     // Customize diagnostic for a typedef missing a name.
4095     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4096       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4097         << DS.getSourceRange();
4098     else
4099       DeclaresAnything = false;
4100   }
4101
4102   if (DS.isModulePrivateSpecified() &&
4103       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4104     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4105       << Tag->getTagKind()
4106       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4107
4108   ActOnDocumentableDecl(TagD);
4109
4110   // C 6.7/2:
4111   //   A declaration [...] shall declare at least a declarator [...], a tag,
4112   //   or the members of an enumeration.
4113   // C++ [dcl.dcl]p3:
4114   //   [If there are no declarators], and except for the declaration of an
4115   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4116   //   names into the program, or shall redeclare a name introduced by a
4117   //   previous declaration.
4118   if (!DeclaresAnything) {
4119     // In C, we allow this as a (popular) extension / bug. Don't bother
4120     // producing further diagnostics for redundant qualifiers after this.
4121     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4122     return TagD;
4123   }
4124
4125   // C++ [dcl.stc]p1:
4126   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4127   //   init-declarator-list of the declaration shall not be empty.
4128   // C++ [dcl.fct.spec]p1:
4129   //   If a cv-qualifier appears in a decl-specifier-seq, the
4130   //   init-declarator-list of the declaration shall not be empty.
4131   //
4132   // Spurious qualifiers here appear to be valid in C.
4133   unsigned DiagID = diag::warn_standalone_specifier;
4134   if (getLangOpts().CPlusPlus)
4135     DiagID = diag::ext_standalone_specifier;
4136
4137   // Note that a linkage-specification sets a storage class, but
4138   // 'extern "C" struct foo;' is actually valid and not theoretically
4139   // useless.
4140   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4141     if (SCS == DeclSpec::SCS_mutable)
4142       // Since mutable is not a viable storage class specifier in C, there is
4143       // no reason to treat it as an extension. Instead, diagnose as an error.
4144       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4145     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4146       Diag(DS.getStorageClassSpecLoc(), DiagID)
4147         << DeclSpec::getSpecifierName(SCS);
4148   }
4149
4150   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4151     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4152       << DeclSpec::getSpecifierName(TSCS);
4153   if (DS.getTypeQualifiers()) {
4154     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4155       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4156     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4157       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4158     // Restrict is covered above.
4159     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4160       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4161     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4162       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4163   }
4164
4165   // Warn about ignored type attributes, for example:
4166   // __attribute__((aligned)) struct A;
4167   // Attributes should be placed after tag to apply to type declaration.
4168   if (!DS.getAttributes().empty()) {
4169     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4170     if (TypeSpecType == DeclSpec::TST_class ||
4171         TypeSpecType == DeclSpec::TST_struct ||
4172         TypeSpecType == DeclSpec::TST_interface ||
4173         TypeSpecType == DeclSpec::TST_union ||
4174         TypeSpecType == DeclSpec::TST_enum) {
4175       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4176            attrs = attrs->getNext())
4177         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4178             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4179     }
4180   }
4181
4182   return TagD;
4183 }
4184
4185 /// We are trying to inject an anonymous member into the given scope;
4186 /// check if there's an existing declaration that can't be overloaded.
4187 ///
4188 /// \return true if this is a forbidden redeclaration
4189 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4190                                          Scope *S,
4191                                          DeclContext *Owner,
4192                                          DeclarationName Name,
4193                                          SourceLocation NameLoc,
4194                                          bool IsUnion) {
4195   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4196                  Sema::ForRedeclaration);
4197   if (!SemaRef.LookupName(R, S)) return false;
4198
4199   // Pick a representative declaration.
4200   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4201   assert(PrevDecl && "Expected a non-null Decl");
4202
4203   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4204     return false;
4205
4206   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4207     << IsUnion << Name;
4208   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4209
4210   return true;
4211 }
4212
4213 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4214 /// anonymous struct or union AnonRecord into the owning context Owner
4215 /// and scope S. This routine will be invoked just after we realize
4216 /// that an unnamed union or struct is actually an anonymous union or
4217 /// struct, e.g.,
4218 ///
4219 /// @code
4220 /// union {
4221 ///   int i;
4222 ///   float f;
4223 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4224 ///    // f into the surrounding scope.x
4225 /// @endcode
4226 ///
4227 /// This routine is recursive, injecting the names of nested anonymous
4228 /// structs/unions into the owning context and scope as well.
4229 static bool
4230 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4231                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4232                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4233   bool Invalid = false;
4234
4235   // Look every FieldDecl and IndirectFieldDecl with a name.
4236   for (auto *D : AnonRecord->decls()) {
4237     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4238         cast<NamedDecl>(D)->getDeclName()) {
4239       ValueDecl *VD = cast<ValueDecl>(D);
4240       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4241                                        VD->getLocation(),
4242                                        AnonRecord->isUnion())) {
4243         // C++ [class.union]p2:
4244         //   The names of the members of an anonymous union shall be
4245         //   distinct from the names of any other entity in the
4246         //   scope in which the anonymous union is declared.
4247         Invalid = true;
4248       } else {
4249         // C++ [class.union]p2:
4250         //   For the purpose of name lookup, after the anonymous union
4251         //   definition, the members of the anonymous union are
4252         //   considered to have been defined in the scope in which the
4253         //   anonymous union is declared.
4254         unsigned OldChainingSize = Chaining.size();
4255         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4256           Chaining.append(IF->chain_begin(), IF->chain_end());
4257         else
4258           Chaining.push_back(VD);
4259
4260         assert(Chaining.size() >= 2);
4261         NamedDecl **NamedChain =
4262           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4263         for (unsigned i = 0; i < Chaining.size(); i++)
4264           NamedChain[i] = Chaining[i];
4265
4266         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4267             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4268             VD->getType(), {NamedChain, Chaining.size()});
4269
4270         for (const auto *Attr : VD->attrs())
4271           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4272
4273         IndirectField->setAccess(AS);
4274         IndirectField->setImplicit();
4275         SemaRef.PushOnScopeChains(IndirectField, S);
4276
4277         // That includes picking up the appropriate access specifier.
4278         if (AS != AS_none) IndirectField->setAccess(AS);
4279
4280         Chaining.resize(OldChainingSize);
4281       }
4282     }
4283   }
4284
4285   return Invalid;
4286 }
4287
4288 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4289 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4290 /// illegal input values are mapped to SC_None.
4291 static StorageClass
4292 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4293   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4294   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4295          "Parser allowed 'typedef' as storage class VarDecl.");
4296   switch (StorageClassSpec) {
4297   case DeclSpec::SCS_unspecified:    return SC_None;
4298   case DeclSpec::SCS_extern:
4299     if (DS.isExternInLinkageSpec())
4300       return SC_None;
4301     return SC_Extern;
4302   case DeclSpec::SCS_static:         return SC_Static;
4303   case DeclSpec::SCS_auto:           return SC_Auto;
4304   case DeclSpec::SCS_register:       return SC_Register;
4305   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4306     // Illegal SCSs map to None: error reporting is up to the caller.
4307   case DeclSpec::SCS_mutable:        // Fall through.
4308   case DeclSpec::SCS_typedef:        return SC_None;
4309   }
4310   llvm_unreachable("unknown storage class specifier");
4311 }
4312
4313 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4314   assert(Record->hasInClassInitializer());
4315
4316   for (const auto *I : Record->decls()) {
4317     const auto *FD = dyn_cast<FieldDecl>(I);
4318     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4319       FD = IFD->getAnonField();
4320     if (FD && FD->hasInClassInitializer())
4321       return FD->getLocation();
4322   }
4323
4324   llvm_unreachable("couldn't find in-class initializer");
4325 }
4326
4327 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4328                                       SourceLocation DefaultInitLoc) {
4329   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4330     return;
4331
4332   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4333   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4334 }
4335
4336 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4337                                       CXXRecordDecl *AnonUnion) {
4338   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4339     return;
4340
4341   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4342 }
4343
4344 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4345 /// anonymous structure or union. Anonymous unions are a C++ feature
4346 /// (C++ [class.union]) and a C11 feature; anonymous structures
4347 /// are a C11 feature and GNU C++ extension.
4348 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4349                                         AccessSpecifier AS,
4350                                         RecordDecl *Record,
4351                                         const PrintingPolicy &Policy) {
4352   DeclContext *Owner = Record->getDeclContext();
4353
4354   // Diagnose whether this anonymous struct/union is an extension.
4355   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4356     Diag(Record->getLocation(), diag::ext_anonymous_union);
4357   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4358     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4359   else if (!Record->isUnion() && !getLangOpts().C11)
4360     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4361
4362   // C and C++ require different kinds of checks for anonymous
4363   // structs/unions.
4364   bool Invalid = false;
4365   if (getLangOpts().CPlusPlus) {
4366     const char *PrevSpec = nullptr;
4367     unsigned DiagID;
4368     if (Record->isUnion()) {
4369       // C++ [class.union]p6:
4370       //   Anonymous unions declared in a named namespace or in the
4371       //   global namespace shall be declared static.
4372       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4373           (isa<TranslationUnitDecl>(Owner) ||
4374            (isa<NamespaceDecl>(Owner) &&
4375             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4376         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4377           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4378
4379         // Recover by adding 'static'.
4380         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4381                                PrevSpec, DiagID, Policy);
4382       }
4383       // C++ [class.union]p6:
4384       //   A storage class is not allowed in a declaration of an
4385       //   anonymous union in a class scope.
4386       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4387                isa<RecordDecl>(Owner)) {
4388         Diag(DS.getStorageClassSpecLoc(),
4389              diag::err_anonymous_union_with_storage_spec)
4390           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4391
4392         // Recover by removing the storage specifier.
4393         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4394                                SourceLocation(),
4395                                PrevSpec, DiagID, Context.getPrintingPolicy());
4396       }
4397     }
4398
4399     // Ignore const/volatile/restrict qualifiers.
4400     if (DS.getTypeQualifiers()) {
4401       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4402         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4403           << Record->isUnion() << "const"
4404           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4405       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4406         Diag(DS.getVolatileSpecLoc(),
4407              diag::ext_anonymous_struct_union_qualified)
4408           << Record->isUnion() << "volatile"
4409           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4410       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4411         Diag(DS.getRestrictSpecLoc(),
4412              diag::ext_anonymous_struct_union_qualified)
4413           << Record->isUnion() << "restrict"
4414           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4415       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4416         Diag(DS.getAtomicSpecLoc(),
4417              diag::ext_anonymous_struct_union_qualified)
4418           << Record->isUnion() << "_Atomic"
4419           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4420       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4421         Diag(DS.getUnalignedSpecLoc(),
4422              diag::ext_anonymous_struct_union_qualified)
4423           << Record->isUnion() << "__unaligned"
4424           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4425
4426       DS.ClearTypeQualifiers();
4427     }
4428
4429     // C++ [class.union]p2:
4430     //   The member-specification of an anonymous union shall only
4431     //   define non-static data members. [Note: nested types and
4432     //   functions cannot be declared within an anonymous union. ]
4433     for (auto *Mem : Record->decls()) {
4434       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4435         // C++ [class.union]p3:
4436         //   An anonymous union shall not have private or protected
4437         //   members (clause 11).
4438         assert(FD->getAccess() != AS_none);
4439         if (FD->getAccess() != AS_public) {
4440           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4441             << Record->isUnion() << (FD->getAccess() == AS_protected);
4442           Invalid = true;
4443         }
4444
4445         // C++ [class.union]p1
4446         //   An object of a class with a non-trivial constructor, a non-trivial
4447         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4448         //   assignment operator cannot be a member of a union, nor can an
4449         //   array of such objects.
4450         if (CheckNontrivialField(FD))
4451           Invalid = true;
4452       } else if (Mem->isImplicit()) {
4453         // Any implicit members are fine.
4454       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4455         // This is a type that showed up in an
4456         // elaborated-type-specifier inside the anonymous struct or
4457         // union, but which actually declares a type outside of the
4458         // anonymous struct or union. It's okay.
4459       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4460         if (!MemRecord->isAnonymousStructOrUnion() &&
4461             MemRecord->getDeclName()) {
4462           // Visual C++ allows type definition in anonymous struct or union.
4463           if (getLangOpts().MicrosoftExt)
4464             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4465               << Record->isUnion();
4466           else {
4467             // This is a nested type declaration.
4468             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4469               << Record->isUnion();
4470             Invalid = true;
4471           }
4472         } else {
4473           // This is an anonymous type definition within another anonymous type.
4474           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4475           // not part of standard C++.
4476           Diag(MemRecord->getLocation(),
4477                diag::ext_anonymous_record_with_anonymous_type)
4478             << Record->isUnion();
4479         }
4480       } else if (isa<AccessSpecDecl>(Mem)) {
4481         // Any access specifier is fine.
4482       } else if (isa<StaticAssertDecl>(Mem)) {
4483         // In C++1z, static_assert declarations are also fine.
4484       } else {
4485         // We have something that isn't a non-static data
4486         // member. Complain about it.
4487         unsigned DK = diag::err_anonymous_record_bad_member;
4488         if (isa<TypeDecl>(Mem))
4489           DK = diag::err_anonymous_record_with_type;
4490         else if (isa<FunctionDecl>(Mem))
4491           DK = diag::err_anonymous_record_with_function;
4492         else if (isa<VarDecl>(Mem))
4493           DK = diag::err_anonymous_record_with_static;
4494
4495         // Visual C++ allows type definition in anonymous struct or union.
4496         if (getLangOpts().MicrosoftExt &&
4497             DK == diag::err_anonymous_record_with_type)
4498           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4499             << Record->isUnion();
4500         else {
4501           Diag(Mem->getLocation(), DK) << Record->isUnion();
4502           Invalid = true;
4503         }
4504       }
4505     }
4506
4507     // C++11 [class.union]p8 (DR1460):
4508     //   At most one variant member of a union may have a
4509     //   brace-or-equal-initializer.
4510     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4511         Owner->isRecord())
4512       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4513                                 cast<CXXRecordDecl>(Record));
4514   }
4515
4516   if (!Record->isUnion() && !Owner->isRecord()) {
4517     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4518       << getLangOpts().CPlusPlus;
4519     Invalid = true;
4520   }
4521
4522   // Mock up a declarator.
4523   Declarator Dc(DS, Declarator::MemberContext);
4524   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4525   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4526
4527   // Create a declaration for this anonymous struct/union.
4528   NamedDecl *Anon = nullptr;
4529   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4530     Anon = FieldDecl::Create(Context, OwningClass,
4531                              DS.getLocStart(),
4532                              Record->getLocation(),
4533                              /*IdentifierInfo=*/nullptr,
4534                              Context.getTypeDeclType(Record),
4535                              TInfo,
4536                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4537                              /*InitStyle=*/ICIS_NoInit);
4538     Anon->setAccess(AS);
4539     if (getLangOpts().CPlusPlus)
4540       FieldCollector->Add(cast<FieldDecl>(Anon));
4541   } else {
4542     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4543     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4544     if (SCSpec == DeclSpec::SCS_mutable) {
4545       // mutable can only appear on non-static class members, so it's always
4546       // an error here
4547       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4548       Invalid = true;
4549       SC = SC_None;
4550     }
4551
4552     Anon = VarDecl::Create(Context, Owner,
4553                            DS.getLocStart(),
4554                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4555                            Context.getTypeDeclType(Record),
4556                            TInfo, SC);
4557
4558     // Default-initialize the implicit variable. This initialization will be
4559     // trivial in almost all cases, except if a union member has an in-class
4560     // initializer:
4561     //   union { int n = 0; };
4562     ActOnUninitializedDecl(Anon);
4563   }
4564   Anon->setImplicit();
4565
4566   // Mark this as an anonymous struct/union type.
4567   Record->setAnonymousStructOrUnion(true);
4568
4569   // Add the anonymous struct/union object to the current
4570   // context. We'll be referencing this object when we refer to one of
4571   // its members.
4572   Owner->addDecl(Anon);
4573
4574   // Inject the members of the anonymous struct/union into the owning
4575   // context and into the identifier resolver chain for name lookup
4576   // purposes.
4577   SmallVector<NamedDecl*, 2> Chain;
4578   Chain.push_back(Anon);
4579
4580   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4581     Invalid = true;
4582
4583   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4584     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4585       Decl *ManglingContextDecl;
4586       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4587               NewVD->getDeclContext(), ManglingContextDecl)) {
4588         Context.setManglingNumber(
4589             NewVD, MCtx->getManglingNumber(
4590                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4591         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4592       }
4593     }
4594   }
4595
4596   if (Invalid)
4597     Anon->setInvalidDecl();
4598
4599   return Anon;
4600 }
4601
4602 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4603 /// Microsoft C anonymous structure.
4604 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4605 /// Example:
4606 ///
4607 /// struct A { int a; };
4608 /// struct B { struct A; int b; };
4609 ///
4610 /// void foo() {
4611 ///   B var;
4612 ///   var.a = 3;
4613 /// }
4614 ///
4615 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4616                                            RecordDecl *Record) {
4617   assert(Record && "expected a record!");
4618
4619   // Mock up a declarator.
4620   Declarator Dc(DS, Declarator::TypeNameContext);
4621   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4622   assert(TInfo && "couldn't build declarator info for anonymous struct");
4623
4624   auto *ParentDecl = cast<RecordDecl>(CurContext);
4625   QualType RecTy = Context.getTypeDeclType(Record);
4626
4627   // Create a declaration for this anonymous struct.
4628   NamedDecl *Anon = FieldDecl::Create(Context,
4629                              ParentDecl,
4630                              DS.getLocStart(),
4631                              DS.getLocStart(),
4632                              /*IdentifierInfo=*/nullptr,
4633                              RecTy,
4634                              TInfo,
4635                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4636                              /*InitStyle=*/ICIS_NoInit);
4637   Anon->setImplicit();
4638
4639   // Add the anonymous struct object to the current context.
4640   CurContext->addDecl(Anon);
4641
4642   // Inject the members of the anonymous struct into the current
4643   // context and into the identifier resolver chain for name lookup
4644   // purposes.
4645   SmallVector<NamedDecl*, 2> Chain;
4646   Chain.push_back(Anon);
4647
4648   RecordDecl *RecordDef = Record->getDefinition();
4649   if (RequireCompleteType(Anon->getLocation(), RecTy,
4650                           diag::err_field_incomplete) ||
4651       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4652                                           AS_none, Chain)) {
4653     Anon->setInvalidDecl();
4654     ParentDecl->setInvalidDecl();
4655   }
4656
4657   return Anon;
4658 }
4659
4660 /// GetNameForDeclarator - Determine the full declaration name for the
4661 /// given Declarator.
4662 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4663   return GetNameFromUnqualifiedId(D.getName());
4664 }
4665
4666 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4667 DeclarationNameInfo
4668 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4669   DeclarationNameInfo NameInfo;
4670   NameInfo.setLoc(Name.StartLocation);
4671
4672   switch (Name.getKind()) {
4673
4674   case UnqualifiedId::IK_ImplicitSelfParam:
4675   case UnqualifiedId::IK_Identifier:
4676     NameInfo.setName(Name.Identifier);
4677     NameInfo.setLoc(Name.StartLocation);
4678     return NameInfo;
4679
4680   case UnqualifiedId::IK_DeductionGuideName: {
4681     // C++ [temp.deduct.guide]p3:
4682     //   The simple-template-id shall name a class template specialization.
4683     //   The template-name shall be the same identifier as the template-name
4684     //   of the simple-template-id.
4685     // These together intend to imply that the template-name shall name a
4686     // class template.
4687     // FIXME: template<typename T> struct X {};
4688     //        template<typename T> using Y = X<T>;
4689     //        Y(int) -> Y<int>;
4690     //   satisfies these rules but does not name a class template.
4691     TemplateName TN = Name.TemplateName.get().get();
4692     auto *Template = TN.getAsTemplateDecl();
4693     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4694       Diag(Name.StartLocation,
4695            diag::err_deduction_guide_name_not_class_template)
4696         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4697       if (Template)
4698         Diag(Template->getLocation(), diag::note_template_decl_here);
4699       return DeclarationNameInfo();
4700     }
4701
4702     NameInfo.setName(
4703         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4704     NameInfo.setLoc(Name.StartLocation);
4705     return NameInfo;
4706   }
4707
4708   case UnqualifiedId::IK_OperatorFunctionId:
4709     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4710                                            Name.OperatorFunctionId.Operator));
4711     NameInfo.setLoc(Name.StartLocation);
4712     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4713       = Name.OperatorFunctionId.SymbolLocations[0];
4714     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4715       = Name.EndLocation.getRawEncoding();
4716     return NameInfo;
4717
4718   case UnqualifiedId::IK_LiteralOperatorId:
4719     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4720                                                            Name.Identifier));
4721     NameInfo.setLoc(Name.StartLocation);
4722     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4723     return NameInfo;
4724
4725   case UnqualifiedId::IK_ConversionFunctionId: {
4726     TypeSourceInfo *TInfo;
4727     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4728     if (Ty.isNull())
4729       return DeclarationNameInfo();
4730     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4731                                                Context.getCanonicalType(Ty)));
4732     NameInfo.setLoc(Name.StartLocation);
4733     NameInfo.setNamedTypeInfo(TInfo);
4734     return NameInfo;
4735   }
4736
4737   case UnqualifiedId::IK_ConstructorName: {
4738     TypeSourceInfo *TInfo;
4739     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4740     if (Ty.isNull())
4741       return DeclarationNameInfo();
4742     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4743                                               Context.getCanonicalType(Ty)));
4744     NameInfo.setLoc(Name.StartLocation);
4745     NameInfo.setNamedTypeInfo(TInfo);
4746     return NameInfo;
4747   }
4748
4749   case UnqualifiedId::IK_ConstructorTemplateId: {
4750     // In well-formed code, we can only have a constructor
4751     // template-id that refers to the current context, so go there
4752     // to find the actual type being constructed.
4753     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4754     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4755       return DeclarationNameInfo();
4756
4757     // Determine the type of the class being constructed.
4758     QualType CurClassType = Context.getTypeDeclType(CurClass);
4759
4760     // FIXME: Check two things: that the template-id names the same type as
4761     // CurClassType, and that the template-id does not occur when the name
4762     // was qualified.
4763
4764     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4765                                     Context.getCanonicalType(CurClassType)));
4766     NameInfo.setLoc(Name.StartLocation);
4767     // FIXME: should we retrieve TypeSourceInfo?
4768     NameInfo.setNamedTypeInfo(nullptr);
4769     return NameInfo;
4770   }
4771
4772   case UnqualifiedId::IK_DestructorName: {
4773     TypeSourceInfo *TInfo;
4774     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4775     if (Ty.isNull())
4776       return DeclarationNameInfo();
4777     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4778                                               Context.getCanonicalType(Ty)));
4779     NameInfo.setLoc(Name.StartLocation);
4780     NameInfo.setNamedTypeInfo(TInfo);
4781     return NameInfo;
4782   }
4783
4784   case UnqualifiedId::IK_TemplateId: {
4785     TemplateName TName = Name.TemplateId->Template.get();
4786     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4787     return Context.getNameForTemplate(TName, TNameLoc);
4788   }
4789
4790   } // switch (Name.getKind())
4791
4792   llvm_unreachable("Unknown name kind");
4793 }
4794
4795 static QualType getCoreType(QualType Ty) {
4796   do {
4797     if (Ty->isPointerType() || Ty->isReferenceType())
4798       Ty = Ty->getPointeeType();
4799     else if (Ty->isArrayType())
4800       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4801     else
4802       return Ty.withoutLocalFastQualifiers();
4803   } while (true);
4804 }
4805
4806 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4807 /// and Definition have "nearly" matching parameters. This heuristic is
4808 /// used to improve diagnostics in the case where an out-of-line function
4809 /// definition doesn't match any declaration within the class or namespace.
4810 /// Also sets Params to the list of indices to the parameters that differ
4811 /// between the declaration and the definition. If hasSimilarParameters
4812 /// returns true and Params is empty, then all of the parameters match.
4813 static bool hasSimilarParameters(ASTContext &Context,
4814                                      FunctionDecl *Declaration,
4815                                      FunctionDecl *Definition,
4816                                      SmallVectorImpl<unsigned> &Params) {
4817   Params.clear();
4818   if (Declaration->param_size() != Definition->param_size())
4819     return false;
4820   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4821     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4822     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4823
4824     // The parameter types are identical
4825     if (Context.hasSameType(DefParamTy, DeclParamTy))
4826       continue;
4827
4828     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4829     QualType DefParamBaseTy = getCoreType(DefParamTy);
4830     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4831     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4832
4833     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4834         (DeclTyName && DeclTyName == DefTyName))
4835       Params.push_back(Idx);
4836     else  // The two parameters aren't even close
4837       return false;
4838   }
4839
4840   return true;
4841 }
4842
4843 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4844 /// declarator needs to be rebuilt in the current instantiation.
4845 /// Any bits of declarator which appear before the name are valid for
4846 /// consideration here.  That's specifically the type in the decl spec
4847 /// and the base type in any member-pointer chunks.
4848 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4849                                                     DeclarationName Name) {
4850   // The types we specifically need to rebuild are:
4851   //   - typenames, typeofs, and decltypes
4852   //   - types which will become injected class names
4853   // Of course, we also need to rebuild any type referencing such a
4854   // type.  It's safest to just say "dependent", but we call out a
4855   // few cases here.
4856
4857   DeclSpec &DS = D.getMutableDeclSpec();
4858   switch (DS.getTypeSpecType()) {
4859   case DeclSpec::TST_typename:
4860   case DeclSpec::TST_typeofType:
4861   case DeclSpec::TST_underlyingType:
4862   case DeclSpec::TST_atomic: {
4863     // Grab the type from the parser.
4864     TypeSourceInfo *TSI = nullptr;
4865     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4866     if (T.isNull() || !T->isDependentType()) break;
4867
4868     // Make sure there's a type source info.  This isn't really much
4869     // of a waste; most dependent types should have type source info
4870     // attached already.
4871     if (!TSI)
4872       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4873
4874     // Rebuild the type in the current instantiation.
4875     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4876     if (!TSI) return true;
4877
4878     // Store the new type back in the decl spec.
4879     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4880     DS.UpdateTypeRep(LocType);
4881     break;
4882   }
4883
4884   case DeclSpec::TST_decltype:
4885   case DeclSpec::TST_typeofExpr: {
4886     Expr *E = DS.getRepAsExpr();
4887     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4888     if (Result.isInvalid()) return true;
4889     DS.UpdateExprRep(Result.get());
4890     break;
4891   }
4892
4893   default:
4894     // Nothing to do for these decl specs.
4895     break;
4896   }
4897
4898   // It doesn't matter what order we do this in.
4899   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4900     DeclaratorChunk &Chunk = D.getTypeObject(I);
4901
4902     // The only type information in the declarator which can come
4903     // before the declaration name is the base type of a member
4904     // pointer.
4905     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4906       continue;
4907
4908     // Rebuild the scope specifier in-place.
4909     CXXScopeSpec &SS = Chunk.Mem.Scope();
4910     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4911       return true;
4912   }
4913
4914   return false;
4915 }
4916
4917 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4918   D.setFunctionDefinitionKind(FDK_Declaration);
4919   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4920
4921   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4922       Dcl && Dcl->getDeclContext()->isFileContext())
4923     Dcl->setTopLevelDeclInObjCContainer();
4924
4925   if (getLangOpts().OpenCL)
4926     setCurrentOpenCLExtensionForDecl(Dcl);
4927
4928   return Dcl;
4929 }
4930
4931 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4932 ///   If T is the name of a class, then each of the following shall have a
4933 ///   name different from T:
4934 ///     - every static data member of class T;
4935 ///     - every member function of class T
4936 ///     - every member of class T that is itself a type;
4937 /// \returns true if the declaration name violates these rules.
4938 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4939                                    DeclarationNameInfo NameInfo) {
4940   DeclarationName Name = NameInfo.getName();
4941
4942   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4943   while (Record && Record->isAnonymousStructOrUnion())
4944     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4945   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4946     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4947     return true;
4948   }
4949
4950   return false;
4951 }
4952
4953 /// \brief Diagnose a declaration whose declarator-id has the given
4954 /// nested-name-specifier.
4955 ///
4956 /// \param SS The nested-name-specifier of the declarator-id.
4957 ///
4958 /// \param DC The declaration context to which the nested-name-specifier
4959 /// resolves.
4960 ///
4961 /// \param Name The name of the entity being declared.
4962 ///
4963 /// \param Loc The location of the name of the entity being declared.
4964 ///
4965 /// \returns true if we cannot safely recover from this error, false otherwise.
4966 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4967                                         DeclarationName Name,
4968                                         SourceLocation Loc) {
4969   DeclContext *Cur = CurContext;
4970   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4971     Cur = Cur->getParent();
4972
4973   // If the user provided a superfluous scope specifier that refers back to the
4974   // class in which the entity is already declared, diagnose and ignore it.
4975   //
4976   // class X {
4977   //   void X::f();
4978   // };
4979   //
4980   // Note, it was once ill-formed to give redundant qualification in all
4981   // contexts, but that rule was removed by DR482.
4982   if (Cur->Equals(DC)) {
4983     if (Cur->isRecord()) {
4984       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4985                                       : diag::err_member_extra_qualification)
4986         << Name << FixItHint::CreateRemoval(SS.getRange());
4987       SS.clear();
4988     } else {
4989       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4990     }
4991     return false;
4992   }
4993
4994   // Check whether the qualifying scope encloses the scope of the original
4995   // declaration.
4996   if (!Cur->Encloses(DC)) {
4997     if (Cur->isRecord())
4998       Diag(Loc, diag::err_member_qualification)
4999         << Name << SS.getRange();
5000     else if (isa<TranslationUnitDecl>(DC))
5001       Diag(Loc, diag::err_invalid_declarator_global_scope)
5002         << Name << SS.getRange();
5003     else if (isa<FunctionDecl>(Cur))
5004       Diag(Loc, diag::err_invalid_declarator_in_function)
5005         << Name << SS.getRange();
5006     else if (isa<BlockDecl>(Cur))
5007       Diag(Loc, diag::err_invalid_declarator_in_block)
5008         << Name << SS.getRange();
5009     else
5010       Diag(Loc, diag::err_invalid_declarator_scope)
5011       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5012
5013     return true;
5014   }
5015
5016   if (Cur->isRecord()) {
5017     // Cannot qualify members within a class.
5018     Diag(Loc, diag::err_member_qualification)
5019       << Name << SS.getRange();
5020     SS.clear();
5021
5022     // C++ constructors and destructors with incorrect scopes can break
5023     // our AST invariants by having the wrong underlying types. If
5024     // that's the case, then drop this declaration entirely.
5025     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5026          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5027         !Context.hasSameType(Name.getCXXNameType(),
5028                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5029       return true;
5030
5031     return false;
5032   }
5033
5034   // C++11 [dcl.meaning]p1:
5035   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5036   //   not begin with a decltype-specifer"
5037   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5038   while (SpecLoc.getPrefix())
5039     SpecLoc = SpecLoc.getPrefix();
5040   if (dyn_cast_or_null<DecltypeType>(
5041         SpecLoc.getNestedNameSpecifier()->getAsType()))
5042     Diag(Loc, diag::err_decltype_in_declarator)
5043       << SpecLoc.getTypeLoc().getSourceRange();
5044
5045   return false;
5046 }
5047
5048 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5049                                   MultiTemplateParamsArg TemplateParamLists) {
5050   // TODO: consider using NameInfo for diagnostic.
5051   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5052   DeclarationName Name = NameInfo.getName();
5053
5054   // All of these full declarators require an identifier.  If it doesn't have
5055   // one, the ParsedFreeStandingDeclSpec action should be used.
5056   if (D.isDecompositionDeclarator()) {
5057     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5058   } else if (!Name) {
5059     if (!D.isInvalidType())  // Reject this if we think it is valid.
5060       Diag(D.getDeclSpec().getLocStart(),
5061            diag::err_declarator_need_ident)
5062         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5063     return nullptr;
5064   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5065     return nullptr;
5066
5067   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5068   // we find one that is.
5069   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5070          (S->getFlags() & Scope::TemplateParamScope) != 0)
5071     S = S->getParent();
5072
5073   DeclContext *DC = CurContext;
5074   if (D.getCXXScopeSpec().isInvalid())
5075     D.setInvalidType();
5076   else if (D.getCXXScopeSpec().isSet()) {
5077     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5078                                         UPPC_DeclarationQualifier))
5079       return nullptr;
5080
5081     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5082     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5083     if (!DC || isa<EnumDecl>(DC)) {
5084       // If we could not compute the declaration context, it's because the
5085       // declaration context is dependent but does not refer to a class,
5086       // class template, or class template partial specialization. Complain
5087       // and return early, to avoid the coming semantic disaster.
5088       Diag(D.getIdentifierLoc(),
5089            diag::err_template_qualified_declarator_no_match)
5090         << D.getCXXScopeSpec().getScopeRep()
5091         << D.getCXXScopeSpec().getRange();
5092       return nullptr;
5093     }
5094     bool IsDependentContext = DC->isDependentContext();
5095
5096     if (!IsDependentContext &&
5097         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5098       return nullptr;
5099
5100     // If a class is incomplete, do not parse entities inside it.
5101     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5102       Diag(D.getIdentifierLoc(),
5103            diag::err_member_def_undefined_record)
5104         << Name << DC << D.getCXXScopeSpec().getRange();
5105       return nullptr;
5106     }
5107     if (!D.getDeclSpec().isFriendSpecified()) {
5108       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5109                                       Name, D.getIdentifierLoc())) {
5110         if (DC->isRecord())
5111           return nullptr;
5112
5113         D.setInvalidType();
5114       }
5115     }
5116
5117     // Check whether we need to rebuild the type of the given
5118     // declaration in the current instantiation.
5119     if (EnteringContext && IsDependentContext &&
5120         TemplateParamLists.size() != 0) {
5121       ContextRAII SavedContext(*this, DC);
5122       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5123         D.setInvalidType();
5124     }
5125   }
5126
5127   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5128   QualType R = TInfo->getType();
5129
5130   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5131     // If this is a typedef, we'll end up spewing multiple diagnostics.
5132     // Just return early; it's safer. If this is a function, let the
5133     // "constructor cannot have a return type" diagnostic handle it.
5134     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5135       return nullptr;
5136
5137   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5138                                       UPPC_DeclarationType))
5139     D.setInvalidType();
5140
5141   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5142                         ForRedeclaration);
5143
5144   // See if this is a redefinition of a variable in the same scope.
5145   if (!D.getCXXScopeSpec().isSet()) {
5146     bool IsLinkageLookup = false;
5147     bool CreateBuiltins = false;
5148
5149     // If the declaration we're planning to build will be a function
5150     // or object with linkage, then look for another declaration with
5151     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5152     //
5153     // If the declaration we're planning to build will be declared with
5154     // external linkage in the translation unit, create any builtin with
5155     // the same name.
5156     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5157       /* Do nothing*/;
5158     else if (CurContext->isFunctionOrMethod() &&
5159              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5160               R->isFunctionType())) {
5161       IsLinkageLookup = true;
5162       CreateBuiltins =
5163           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5164     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5165                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5166       CreateBuiltins = true;
5167
5168     if (IsLinkageLookup)
5169       Previous.clear(LookupRedeclarationWithLinkage);
5170
5171     LookupName(Previous, S, CreateBuiltins);
5172   } else { // Something like "int foo::x;"
5173     LookupQualifiedName(Previous, DC);
5174
5175     // C++ [dcl.meaning]p1:
5176     //   When the declarator-id is qualified, the declaration shall refer to a
5177     //  previously declared member of the class or namespace to which the
5178     //  qualifier refers (or, in the case of a namespace, of an element of the
5179     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5180     //  thereof; [...]
5181     //
5182     // Note that we already checked the context above, and that we do not have
5183     // enough information to make sure that Previous contains the declaration
5184     // we want to match. For example, given:
5185     //
5186     //   class X {
5187     //     void f();
5188     //     void f(float);
5189     //   };
5190     //
5191     //   void X::f(int) { } // ill-formed
5192     //
5193     // In this case, Previous will point to the overload set
5194     // containing the two f's declared in X, but neither of them
5195     // matches.
5196
5197     // C++ [dcl.meaning]p1:
5198     //   [...] the member shall not merely have been introduced by a
5199     //   using-declaration in the scope of the class or namespace nominated by
5200     //   the nested-name-specifier of the declarator-id.
5201     RemoveUsingDecls(Previous);
5202   }
5203
5204   if (Previous.isSingleResult() &&
5205       Previous.getFoundDecl()->isTemplateParameter()) {
5206     // Maybe we will complain about the shadowed template parameter.
5207     if (!D.isInvalidType())
5208       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5209                                       Previous.getFoundDecl());
5210
5211     // Just pretend that we didn't see the previous declaration.
5212     Previous.clear();
5213   }
5214
5215   // In C++, the previous declaration we find might be a tag type
5216   // (class or enum). In this case, the new declaration will hide the
5217   // tag type. Note that this does does not apply if we're declaring a
5218   // typedef (C++ [dcl.typedef]p4).
5219   if (Previous.isSingleTagDecl() &&
5220       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5221     Previous.clear();
5222
5223   // Check that there are no default arguments other than in the parameters
5224   // of a function declaration (C++ only).
5225   if (getLangOpts().CPlusPlus)
5226     CheckExtraCXXDefaultArguments(D);
5227
5228   if (D.getDeclSpec().isConceptSpecified()) {
5229     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5230     // applied only to the definition of a function template or variable
5231     // template, declared in namespace scope
5232     if (!TemplateParamLists.size()) {
5233       Diag(D.getDeclSpec().getConceptSpecLoc(),
5234            diag:: err_concept_wrong_decl_kind);
5235       return nullptr;
5236     }
5237
5238     if (!DC->getRedeclContext()->isFileContext()) {
5239       Diag(D.getIdentifierLoc(),
5240            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5241       return nullptr;
5242     }
5243   }
5244
5245   NamedDecl *New;
5246
5247   bool AddToScope = true;
5248   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5249     if (TemplateParamLists.size()) {
5250       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5251       return nullptr;
5252     }
5253
5254     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5255   } else if (R->isFunctionType()) {
5256     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5257                                   TemplateParamLists,
5258                                   AddToScope);
5259   } else {
5260     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5261                                   AddToScope);
5262   }
5263
5264   if (!New)
5265     return nullptr;
5266
5267   // If this has an identifier and is not a function template specialization,
5268   // add it to the scope stack.
5269   if (New->getDeclName() && AddToScope) {
5270     // Only make a locally-scoped extern declaration visible if it is the first
5271     // declaration of this entity. Qualified lookup for such an entity should
5272     // only find this declaration if there is no visible declaration of it.
5273     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5274     PushOnScopeChains(New, S, AddToContext);
5275     if (!AddToContext)
5276       CurContext->addHiddenDecl(New);
5277   }
5278
5279   if (isInOpenMPDeclareTargetContext())
5280     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5281
5282   return New;
5283 }
5284
5285 /// Helper method to turn variable array types into constant array
5286 /// types in certain situations which would otherwise be errors (for
5287 /// GCC compatibility).
5288 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5289                                                     ASTContext &Context,
5290                                                     bool &SizeIsNegative,
5291                                                     llvm::APSInt &Oversized) {
5292   // This method tries to turn a variable array into a constant
5293   // array even when the size isn't an ICE.  This is necessary
5294   // for compatibility with code that depends on gcc's buggy
5295   // constant expression folding, like struct {char x[(int)(char*)2];}
5296   SizeIsNegative = false;
5297   Oversized = 0;
5298
5299   if (T->isDependentType())
5300     return QualType();
5301
5302   QualifierCollector Qs;
5303   const Type *Ty = Qs.strip(T);
5304
5305   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5306     QualType Pointee = PTy->getPointeeType();
5307     QualType FixedType =
5308         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5309                                             Oversized);
5310     if (FixedType.isNull()) return FixedType;
5311     FixedType = Context.getPointerType(FixedType);
5312     return Qs.apply(Context, FixedType);
5313   }
5314   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5315     QualType Inner = PTy->getInnerType();
5316     QualType FixedType =
5317         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5318                                             Oversized);
5319     if (FixedType.isNull()) return FixedType;
5320     FixedType = Context.getParenType(FixedType);
5321     return Qs.apply(Context, FixedType);
5322   }
5323
5324   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5325   if (!VLATy)
5326     return QualType();
5327   // FIXME: We should probably handle this case
5328   if (VLATy->getElementType()->isVariablyModifiedType())
5329     return QualType();
5330
5331   llvm::APSInt Res;
5332   if (!VLATy->getSizeExpr() ||
5333       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5334     return QualType();
5335
5336   // Check whether the array size is negative.
5337   if (Res.isSigned() && Res.isNegative()) {
5338     SizeIsNegative = true;
5339     return QualType();
5340   }
5341
5342   // Check whether the array is too large to be addressed.
5343   unsigned ActiveSizeBits
5344     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5345                                               Res);
5346   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5347     Oversized = Res;
5348     return QualType();
5349   }
5350
5351   return Context.getConstantArrayType(VLATy->getElementType(),
5352                                       Res, ArrayType::Normal, 0);
5353 }
5354
5355 static void
5356 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5357   SrcTL = SrcTL.getUnqualifiedLoc();
5358   DstTL = DstTL.getUnqualifiedLoc();
5359   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5360     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5361     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5362                                       DstPTL.getPointeeLoc());
5363     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5364     return;
5365   }
5366   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5367     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5368     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5369                                       DstPTL.getInnerLoc());
5370     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5371     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5372     return;
5373   }
5374   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5375   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5376   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5377   TypeLoc DstElemTL = DstATL.getElementLoc();
5378   DstElemTL.initializeFullCopy(SrcElemTL);
5379   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5380   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5381   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5382 }
5383
5384 /// Helper method to turn variable array types into constant array
5385 /// types in certain situations which would otherwise be errors (for
5386 /// GCC compatibility).
5387 static TypeSourceInfo*
5388 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5389                                               ASTContext &Context,
5390                                               bool &SizeIsNegative,
5391                                               llvm::APSInt &Oversized) {
5392   QualType FixedTy
5393     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5394                                           SizeIsNegative, Oversized);
5395   if (FixedTy.isNull())
5396     return nullptr;
5397   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5398   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5399                                     FixedTInfo->getTypeLoc());
5400   return FixedTInfo;
5401 }
5402
5403 /// \brief Register the given locally-scoped extern "C" declaration so
5404 /// that it can be found later for redeclarations. We include any extern "C"
5405 /// declaration that is not visible in the translation unit here, not just
5406 /// function-scope declarations.
5407 void
5408 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5409   if (!getLangOpts().CPlusPlus &&
5410       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5411     // Don't need to track declarations in the TU in C.
5412     return;
5413
5414   // Note that we have a locally-scoped external with this name.
5415   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5416 }
5417
5418 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5419   // FIXME: We can have multiple results via __attribute__((overloadable)).
5420   auto Result = Context.getExternCContextDecl()->lookup(Name);
5421   return Result.empty() ? nullptr : *Result.begin();
5422 }
5423
5424 /// \brief Diagnose function specifiers on a declaration of an identifier that
5425 /// does not identify a function.
5426 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5427   // FIXME: We should probably indicate the identifier in question to avoid
5428   // confusion for constructs like "virtual int a(), b;"
5429   if (DS.isVirtualSpecified())
5430     Diag(DS.getVirtualSpecLoc(),
5431          diag::err_virtual_non_function);
5432
5433   if (DS.isExplicitSpecified())
5434     Diag(DS.getExplicitSpecLoc(),
5435          diag::err_explicit_non_function);
5436
5437   if (DS.isNoreturnSpecified())
5438     Diag(DS.getNoreturnSpecLoc(),
5439          diag::err_noreturn_non_function);
5440 }
5441
5442 NamedDecl*
5443 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5444                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5445   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5446   if (D.getCXXScopeSpec().isSet()) {
5447     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5448       << D.getCXXScopeSpec().getRange();
5449     D.setInvalidType();
5450     // Pretend we didn't see the scope specifier.
5451     DC = CurContext;
5452     Previous.clear();
5453   }
5454
5455   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5456
5457   if (D.getDeclSpec().isInlineSpecified())
5458     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5459         << getLangOpts().CPlusPlus1z;
5460   if (D.getDeclSpec().isConstexprSpecified())
5461     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5462       << 1;
5463   if (D.getDeclSpec().isConceptSpecified())
5464     Diag(D.getDeclSpec().getConceptSpecLoc(),
5465          diag::err_concept_wrong_decl_kind);
5466
5467   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5468     if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5469       Diag(D.getName().StartLocation,
5470            diag::err_deduction_guide_invalid_specifier)
5471           << "typedef";
5472     else
5473       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5474           << D.getName().getSourceRange();
5475     return nullptr;
5476   }
5477
5478   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5479   if (!NewTD) return nullptr;
5480
5481   // Handle attributes prior to checking for duplicates in MergeVarDecl
5482   ProcessDeclAttributes(S, NewTD, D);
5483
5484   CheckTypedefForVariablyModifiedType(S, NewTD);
5485
5486   bool Redeclaration = D.isRedeclaration();
5487   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5488   D.setRedeclaration(Redeclaration);
5489   return ND;
5490 }
5491
5492 void
5493 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5494   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5495   // then it shall have block scope.
5496   // Note that variably modified types must be fixed before merging the decl so
5497   // that redeclarations will match.
5498   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5499   QualType T = TInfo->getType();
5500   if (T->isVariablyModifiedType()) {
5501     getCurFunction()->setHasBranchProtectedScope();
5502
5503     if (S->getFnParent() == nullptr) {
5504       bool SizeIsNegative;
5505       llvm::APSInt Oversized;
5506       TypeSourceInfo *FixedTInfo =
5507         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5508                                                       SizeIsNegative,
5509                                                       Oversized);
5510       if (FixedTInfo) {
5511         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5512         NewTD->setTypeSourceInfo(FixedTInfo);
5513       } else {
5514         if (SizeIsNegative)
5515           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5516         else if (T->isVariableArrayType())
5517           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5518         else if (Oversized.getBoolValue())
5519           Diag(NewTD->getLocation(), diag::err_array_too_large)
5520             << Oversized.toString(10);
5521         else
5522           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5523         NewTD->setInvalidDecl();
5524       }
5525     }
5526   }
5527 }
5528
5529 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5530 /// declares a typedef-name, either using the 'typedef' type specifier or via
5531 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5532 NamedDecl*
5533 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5534                            LookupResult &Previous, bool &Redeclaration) {
5535
5536   // Find the shadowed declaration before filtering for scope.
5537   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5538
5539   // Merge the decl with the existing one if appropriate. If the decl is
5540   // in an outer scope, it isn't the same thing.
5541   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5542                        /*AllowInlineNamespace*/false);
5543   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5544   if (!Previous.empty()) {
5545     Redeclaration = true;
5546     MergeTypedefNameDecl(S, NewTD, Previous);
5547   }
5548
5549   if (ShadowedDecl && !Redeclaration)
5550     CheckShadow(NewTD, ShadowedDecl, Previous);
5551
5552   // If this is the C FILE type, notify the AST context.
5553   if (IdentifierInfo *II = NewTD->getIdentifier())
5554     if (!NewTD->isInvalidDecl() &&
5555         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5556       if (II->isStr("FILE"))
5557         Context.setFILEDecl(NewTD);
5558       else if (II->isStr("jmp_buf"))
5559         Context.setjmp_bufDecl(NewTD);
5560       else if (II->isStr("sigjmp_buf"))
5561         Context.setsigjmp_bufDecl(NewTD);
5562       else if (II->isStr("ucontext_t"))
5563         Context.setucontext_tDecl(NewTD);
5564     }
5565
5566   return NewTD;
5567 }
5568
5569 /// \brief Determines whether the given declaration is an out-of-scope
5570 /// previous declaration.
5571 ///
5572 /// This routine should be invoked when name lookup has found a
5573 /// previous declaration (PrevDecl) that is not in the scope where a
5574 /// new declaration by the same name is being introduced. If the new
5575 /// declaration occurs in a local scope, previous declarations with
5576 /// linkage may still be considered previous declarations (C99
5577 /// 6.2.2p4-5, C++ [basic.link]p6).
5578 ///
5579 /// \param PrevDecl the previous declaration found by name
5580 /// lookup
5581 ///
5582 /// \param DC the context in which the new declaration is being
5583 /// declared.
5584 ///
5585 /// \returns true if PrevDecl is an out-of-scope previous declaration
5586 /// for a new delcaration with the same name.
5587 static bool
5588 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5589                                 ASTContext &Context) {
5590   if (!PrevDecl)
5591     return false;
5592
5593   if (!PrevDecl->hasLinkage())
5594     return false;
5595
5596   if (Context.getLangOpts().CPlusPlus) {
5597     // C++ [basic.link]p6:
5598     //   If there is a visible declaration of an entity with linkage
5599     //   having the same name and type, ignoring entities declared
5600     //   outside the innermost enclosing namespace scope, the block
5601     //   scope declaration declares that same entity and receives the
5602     //   linkage of the previous declaration.
5603     DeclContext *OuterContext = DC->getRedeclContext();
5604     if (!OuterContext->isFunctionOrMethod())
5605       // This rule only applies to block-scope declarations.
5606       return false;
5607
5608     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5609     if (PrevOuterContext->isRecord())
5610       // We found a member function: ignore it.
5611       return false;
5612
5613     // Find the innermost enclosing namespace for the new and
5614     // previous declarations.
5615     OuterContext = OuterContext->getEnclosingNamespaceContext();
5616     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5617
5618     // The previous declaration is in a different namespace, so it
5619     // isn't the same function.
5620     if (!OuterContext->Equals(PrevOuterContext))
5621       return false;
5622   }
5623
5624   return true;
5625 }
5626
5627 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5628   CXXScopeSpec &SS = D.getCXXScopeSpec();
5629   if (!SS.isSet()) return;
5630   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5631 }
5632
5633 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5634   QualType type = decl->getType();
5635   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5636   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5637     // Various kinds of declaration aren't allowed to be __autoreleasing.
5638     unsigned kind = -1U;
5639     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5640       if (var->hasAttr<BlocksAttr>())
5641         kind = 0; // __block
5642       else if (!var->hasLocalStorage())
5643         kind = 1; // global
5644     } else if (isa<ObjCIvarDecl>(decl)) {
5645       kind = 3; // ivar
5646     } else if (isa<FieldDecl>(decl)) {
5647       kind = 2; // field
5648     }
5649
5650     if (kind != -1U) {
5651       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5652         << kind;
5653     }
5654   } else if (lifetime == Qualifiers::OCL_None) {
5655     // Try to infer lifetime.
5656     if (!type->isObjCLifetimeType())
5657       return false;
5658
5659     lifetime = type->getObjCARCImplicitLifetime();
5660     type = Context.getLifetimeQualifiedType(type, lifetime);
5661     decl->setType(type);
5662   }
5663
5664   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5665     // Thread-local variables cannot have lifetime.
5666     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5667         var->getTLSKind()) {
5668       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5669         << var->getType();
5670       return true;
5671     }
5672   }
5673
5674   return false;
5675 }
5676
5677 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5678   // Ensure that an auto decl is deduced otherwise the checks below might cache
5679   // the wrong linkage.
5680   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5681
5682   // 'weak' only applies to declarations with external linkage.
5683   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5684     if (!ND.isExternallyVisible()) {
5685       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5686       ND.dropAttr<WeakAttr>();
5687     }
5688   }
5689   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5690     if (ND.isExternallyVisible()) {
5691       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5692       ND.dropAttr<WeakRefAttr>();
5693       ND.dropAttr<AliasAttr>();
5694     }
5695   }
5696
5697   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5698     if (VD->hasInit()) {
5699       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5700         assert(VD->isThisDeclarationADefinition() &&
5701                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5702         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5703         VD->dropAttr<AliasAttr>();
5704       }
5705     }
5706   }
5707
5708   // 'selectany' only applies to externally visible variable declarations.
5709   // It does not apply to functions.
5710   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5711     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5712       S.Diag(Attr->getLocation(),
5713              diag::err_attribute_selectany_non_extern_data);
5714       ND.dropAttr<SelectAnyAttr>();
5715     }
5716   }
5717
5718   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5719     // dll attributes require external linkage. Static locals may have external
5720     // linkage but still cannot be explicitly imported or exported.
5721     auto *VD = dyn_cast<VarDecl>(&ND);
5722     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5723       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5724         << &ND << Attr;
5725       ND.setInvalidDecl();
5726     }
5727   }
5728
5729   // Virtual functions cannot be marked as 'notail'.
5730   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5731     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5732       if (MD->isVirtual()) {
5733         S.Diag(ND.getLocation(),
5734                diag::err_invalid_attribute_on_virtual_function)
5735             << Attr;
5736         ND.dropAttr<NotTailCalledAttr>();
5737       }
5738 }
5739
5740 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5741                                            NamedDecl *NewDecl,
5742                                            bool IsSpecialization,
5743                                            bool IsDefinition) {
5744   if (OldDecl->isInvalidDecl())
5745     return;
5746
5747   bool IsTemplate = false;
5748   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5749     OldDecl = OldTD->getTemplatedDecl();
5750     IsTemplate = true;
5751     if (!IsSpecialization)
5752       IsDefinition = false;
5753   }
5754   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5755     NewDecl = NewTD->getTemplatedDecl();
5756     IsTemplate = true;
5757   }
5758
5759   if (!OldDecl || !NewDecl)
5760     return;
5761
5762   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5763   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5764   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5765   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5766
5767   // dllimport and dllexport are inheritable attributes so we have to exclude
5768   // inherited attribute instances.
5769   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5770                     (NewExportAttr && !NewExportAttr->isInherited());
5771
5772   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5773   // the only exception being explicit specializations.
5774   // Implicitly generated declarations are also excluded for now because there
5775   // is no other way to switch these to use dllimport or dllexport.
5776   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5777
5778   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5779     // Allow with a warning for free functions and global variables.
5780     bool JustWarn = false;
5781     if (!OldDecl->isCXXClassMember()) {
5782       auto *VD = dyn_cast<VarDecl>(OldDecl);
5783       if (VD && !VD->getDescribedVarTemplate())
5784         JustWarn = true;
5785       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5786       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5787         JustWarn = true;
5788     }
5789
5790     // We cannot change a declaration that's been used because IR has already
5791     // been emitted. Dllimported functions will still work though (modulo
5792     // address equality) as they can use the thunk.
5793     if (OldDecl->isUsed())
5794       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5795         JustWarn = false;
5796
5797     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5798                                : diag::err_attribute_dll_redeclaration;
5799     S.Diag(NewDecl->getLocation(), DiagID)
5800         << NewDecl
5801         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5802     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5803     if (!JustWarn) {
5804       NewDecl->setInvalidDecl();
5805       return;
5806     }
5807   }
5808
5809   // A redeclaration is not allowed to drop a dllimport attribute, the only
5810   // exceptions being inline function definitions (except for function
5811   // templates), local extern declarations, qualified friend declarations or
5812   // special MSVC extension: in the last case, the declaration is treated as if
5813   // it were marked dllexport.
5814   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5815   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5816   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5817     // Ignore static data because out-of-line definitions are diagnosed
5818     // separately.
5819     IsStaticDataMember = VD->isStaticDataMember();
5820     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5821                    VarDecl::DeclarationOnly;
5822   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5823     IsInline = FD->isInlined();
5824     IsQualifiedFriend = FD->getQualifier() &&
5825                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5826   }
5827
5828   if (OldImportAttr && !HasNewAttr &&
5829       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
5830       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5831     if (IsMicrosoft && IsDefinition) {
5832       S.Diag(NewDecl->getLocation(),
5833              diag::warn_redeclaration_without_import_attribute)
5834           << NewDecl;
5835       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5836       NewDecl->dropAttr<DLLImportAttr>();
5837       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5838           NewImportAttr->getRange(), S.Context,
5839           NewImportAttr->getSpellingListIndex()));
5840     } else {
5841       S.Diag(NewDecl->getLocation(),
5842              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5843           << NewDecl << OldImportAttr;
5844       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5845       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5846       OldDecl->dropAttr<DLLImportAttr>();
5847       NewDecl->dropAttr<DLLImportAttr>();
5848     }
5849   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5850     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5851     OldDecl->dropAttr<DLLImportAttr>();
5852     NewDecl->dropAttr<DLLImportAttr>();
5853     S.Diag(NewDecl->getLocation(),
5854            diag::warn_dllimport_dropped_from_inline_function)
5855         << NewDecl << OldImportAttr;
5856   }
5857 }
5858
5859 /// Given that we are within the definition of the given function,
5860 /// will that definition behave like C99's 'inline', where the
5861 /// definition is discarded except for optimization purposes?
5862 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5863   // Try to avoid calling GetGVALinkageForFunction.
5864
5865   // All cases of this require the 'inline' keyword.
5866   if (!FD->isInlined()) return false;
5867
5868   // This is only possible in C++ with the gnu_inline attribute.
5869   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5870     return false;
5871
5872   // Okay, go ahead and call the relatively-more-expensive function.
5873   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5874 }
5875
5876 /// Determine whether a variable is extern "C" prior to attaching
5877 /// an initializer. We can't just call isExternC() here, because that
5878 /// will also compute and cache whether the declaration is externally
5879 /// visible, which might change when we attach the initializer.
5880 ///
5881 /// This can only be used if the declaration is known to not be a
5882 /// redeclaration of an internal linkage declaration.
5883 ///
5884 /// For instance:
5885 ///
5886 ///   auto x = []{};
5887 ///
5888 /// Attaching the initializer here makes this declaration not externally
5889 /// visible, because its type has internal linkage.
5890 ///
5891 /// FIXME: This is a hack.
5892 template<typename T>
5893 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5894   if (S.getLangOpts().CPlusPlus) {
5895     // In C++, the overloadable attribute negates the effects of extern "C".
5896     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5897       return false;
5898
5899     // So do CUDA's host/device attributes.
5900     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5901                                  D->template hasAttr<CUDAHostAttr>()))
5902       return false;
5903   }
5904   return D->isExternC();
5905 }
5906
5907 static bool shouldConsiderLinkage(const VarDecl *VD) {
5908   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5909   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5910     return VD->hasExternalStorage();
5911   if (DC->isFileContext())
5912     return true;
5913   if (DC->isRecord())
5914     return false;
5915   llvm_unreachable("Unexpected context");
5916 }
5917
5918 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5919   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5920   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5921       isa<OMPDeclareReductionDecl>(DC))
5922     return true;
5923   if (DC->isRecord())
5924     return false;
5925   llvm_unreachable("Unexpected context");
5926 }
5927
5928 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5929                           AttributeList::Kind Kind) {
5930   for (const AttributeList *L = AttrList; L; L = L->getNext())
5931     if (L->getKind() == Kind)
5932       return true;
5933   return false;
5934 }
5935
5936 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5937                           AttributeList::Kind Kind) {
5938   // Check decl attributes on the DeclSpec.
5939   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5940     return true;
5941
5942   // Walk the declarator structure, checking decl attributes that were in a type
5943   // position to the decl itself.
5944   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5945     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5946       return true;
5947   }
5948
5949   // Finally, check attributes on the decl itself.
5950   return hasParsedAttr(S, PD.getAttributes(), Kind);
5951 }
5952
5953 /// Adjust the \c DeclContext for a function or variable that might be a
5954 /// function-local external declaration.
5955 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5956   if (!DC->isFunctionOrMethod())
5957     return false;
5958
5959   // If this is a local extern function or variable declared within a function
5960   // template, don't add it into the enclosing namespace scope until it is
5961   // instantiated; it might have a dependent type right now.
5962   if (DC->isDependentContext())
5963     return true;
5964
5965   // C++11 [basic.link]p7:
5966   //   When a block scope declaration of an entity with linkage is not found to
5967   //   refer to some other declaration, then that entity is a member of the
5968   //   innermost enclosing namespace.
5969   //
5970   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5971   // semantically-enclosing namespace, not a lexically-enclosing one.
5972   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5973     DC = DC->getParent();
5974   return true;
5975 }
5976
5977 /// \brief Returns true if given declaration has external C language linkage.
5978 static bool isDeclExternC(const Decl *D) {
5979   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5980     return FD->isExternC();
5981   if (const auto *VD = dyn_cast<VarDecl>(D))
5982     return VD->isExternC();
5983
5984   llvm_unreachable("Unknown type of decl!");
5985 }
5986
5987 NamedDecl *Sema::ActOnVariableDeclarator(
5988     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
5989     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
5990     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
5991   QualType R = TInfo->getType();
5992   DeclarationName Name = GetNameForDeclarator(D).getName();
5993
5994   IdentifierInfo *II = Name.getAsIdentifierInfo();
5995
5996   if (D.isDecompositionDeclarator()) {
5997     AddToScope = false;
5998     // Take the name of the first declarator as our name for diagnostic
5999     // purposes.
6000     auto &Decomp = D.getDecompositionDeclarator();
6001     if (!Decomp.bindings().empty()) {
6002       II = Decomp.bindings()[0].Name;
6003       Name = II;
6004     }
6005   } else if (!II) {
6006     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6007     return nullptr;
6008   }
6009
6010   if (getLangOpts().OpenCL) {
6011     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6012     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6013     // argument.
6014     if (R->isImageType() || R->isPipeType()) {
6015       Diag(D.getIdentifierLoc(),
6016            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6017           << R;
6018       D.setInvalidType();
6019       return nullptr;
6020     }
6021
6022     // OpenCL v1.2 s6.9.r:
6023     // The event type cannot be used to declare a program scope variable.
6024     // OpenCL v2.0 s6.9.q:
6025     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6026     if (NULL == S->getParent()) {
6027       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6028         Diag(D.getIdentifierLoc(),
6029              diag::err_invalid_type_for_program_scope_var) << R;
6030         D.setInvalidType();
6031         return nullptr;
6032       }
6033     }
6034
6035     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6036     QualType NR = R;
6037     while (NR->isPointerType()) {
6038       if (NR->isFunctionPointerType()) {
6039         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
6040         D.setInvalidType();
6041         break;
6042       }
6043       NR = NR->getPointeeType();
6044     }
6045
6046     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6047       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6048       // half array type (unless the cl_khr_fp16 extension is enabled).
6049       if (Context.getBaseElementType(R)->isHalfType()) {
6050         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6051         D.setInvalidType();
6052       }
6053     }
6054
6055     // OpenCL v1.2 s6.9.b p4:
6056     // The sampler type cannot be used with the __local and __global address
6057     // space qualifiers.
6058     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
6059       R.getAddressSpace() == LangAS::opencl_global)) {
6060       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6061     }
6062
6063     // OpenCL v1.2 s6.9.r:
6064     // The event type cannot be used with the __local, __constant and __global
6065     // address space qualifiers.
6066     if (R->isEventT()) {
6067       if (R.getAddressSpace()) {
6068         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6069         D.setInvalidType();
6070       }
6071     }
6072   }
6073
6074   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6075   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6076
6077   // dllimport globals without explicit storage class are treated as extern. We
6078   // have to change the storage class this early to get the right DeclContext.
6079   if (SC == SC_None && !DC->isRecord() &&
6080       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6081       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6082     SC = SC_Extern;
6083
6084   DeclContext *OriginalDC = DC;
6085   bool IsLocalExternDecl = SC == SC_Extern &&
6086                            adjustContextForLocalExternDecl(DC);
6087
6088   if (SCSpec == DeclSpec::SCS_mutable) {
6089     // mutable can only appear on non-static class members, so it's always
6090     // an error here
6091     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6092     D.setInvalidType();
6093     SC = SC_None;
6094   }
6095
6096   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6097       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6098                               D.getDeclSpec().getStorageClassSpecLoc())) {
6099     // In C++11, the 'register' storage class specifier is deprecated.
6100     // Suppress the warning in system macros, it's used in macros in some
6101     // popular C system headers, such as in glibc's htonl() macro.
6102     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6103          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6104                                    : diag::warn_deprecated_register)
6105       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6106   }
6107
6108   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6109
6110   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6111     // C99 6.9p2: The storage-class specifiers auto and register shall not
6112     // appear in the declaration specifiers in an external declaration.
6113     // Global Register+Asm is a GNU extension we support.
6114     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6115       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6116       D.setInvalidType();
6117     }
6118   }
6119
6120   bool IsMemberSpecialization = false;
6121   bool IsVariableTemplateSpecialization = false;
6122   bool IsPartialSpecialization = false;
6123   bool IsVariableTemplate = false;
6124   VarDecl *NewVD = nullptr;
6125   VarTemplateDecl *NewTemplate = nullptr;
6126   TemplateParameterList *TemplateParams = nullptr;
6127   if (!getLangOpts().CPlusPlus) {
6128     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6129                             D.getIdentifierLoc(), II,
6130                             R, TInfo, SC);
6131
6132     if (R->getContainedDeducedType())
6133       ParsingInitForAutoVars.insert(NewVD);
6134
6135     if (D.isInvalidType())
6136       NewVD->setInvalidDecl();
6137   } else {
6138     bool Invalid = false;
6139
6140     if (DC->isRecord() && !CurContext->isRecord()) {
6141       // This is an out-of-line definition of a static data member.
6142       switch (SC) {
6143       case SC_None:
6144         break;
6145       case SC_Static:
6146         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6147              diag::err_static_out_of_line)
6148           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6149         break;
6150       case SC_Auto:
6151       case SC_Register:
6152       case SC_Extern:
6153         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6154         // to names of variables declared in a block or to function parameters.
6155         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6156         // of class members
6157
6158         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6159              diag::err_storage_class_for_static_member)
6160           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6161         break;
6162       case SC_PrivateExtern:
6163         llvm_unreachable("C storage class in c++!");
6164       }
6165     }
6166
6167     if (SC == SC_Static && CurContext->isRecord()) {
6168       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6169         if (RD->isLocalClass())
6170           Diag(D.getIdentifierLoc(),
6171                diag::err_static_data_member_not_allowed_in_local_class)
6172             << Name << RD->getDeclName();
6173
6174         // C++98 [class.union]p1: If a union contains a static data member,
6175         // the program is ill-formed. C++11 drops this restriction.
6176         if (RD->isUnion())
6177           Diag(D.getIdentifierLoc(),
6178                getLangOpts().CPlusPlus11
6179                  ? diag::warn_cxx98_compat_static_data_member_in_union
6180                  : diag::ext_static_data_member_in_union) << Name;
6181         // We conservatively disallow static data members in anonymous structs.
6182         else if (!RD->getDeclName())
6183           Diag(D.getIdentifierLoc(),
6184                diag::err_static_data_member_not_allowed_in_anon_struct)
6185             << Name << RD->isUnion();
6186       }
6187     }
6188
6189     // Match up the template parameter lists with the scope specifier, then
6190     // determine whether we have a template or a template specialization.
6191     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6192         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6193         D.getCXXScopeSpec(),
6194         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6195             ? D.getName().TemplateId
6196             : nullptr,
6197         TemplateParamLists,
6198         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6199
6200     if (TemplateParams) {
6201       if (!TemplateParams->size() &&
6202           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6203         // There is an extraneous 'template<>' for this variable. Complain
6204         // about it, but allow the declaration of the variable.
6205         Diag(TemplateParams->getTemplateLoc(),
6206              diag::err_template_variable_noparams)
6207           << II
6208           << SourceRange(TemplateParams->getTemplateLoc(),
6209                          TemplateParams->getRAngleLoc());
6210         TemplateParams = nullptr;
6211       } else {
6212         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6213           // This is an explicit specialization or a partial specialization.
6214           // FIXME: Check that we can declare a specialization here.
6215           IsVariableTemplateSpecialization = true;
6216           IsPartialSpecialization = TemplateParams->size() > 0;
6217         } else { // if (TemplateParams->size() > 0)
6218           // This is a template declaration.
6219           IsVariableTemplate = true;
6220
6221           // Check that we can declare a template here.
6222           if (CheckTemplateDeclScope(S, TemplateParams))
6223             return nullptr;
6224
6225           // Only C++1y supports variable templates (N3651).
6226           Diag(D.getIdentifierLoc(),
6227                getLangOpts().CPlusPlus14
6228                    ? diag::warn_cxx11_compat_variable_template
6229                    : diag::ext_variable_template);
6230         }
6231       }
6232     } else {
6233       assert(
6234           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6235           "should have a 'template<>' for this decl");
6236     }
6237
6238     if (IsVariableTemplateSpecialization) {
6239       SourceLocation TemplateKWLoc =
6240           TemplateParamLists.size() > 0
6241               ? TemplateParamLists[0]->getTemplateLoc()
6242               : SourceLocation();
6243       DeclResult Res = ActOnVarTemplateSpecialization(
6244           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6245           IsPartialSpecialization);
6246       if (Res.isInvalid())
6247         return nullptr;
6248       NewVD = cast<VarDecl>(Res.get());
6249       AddToScope = false;
6250     } else if (D.isDecompositionDeclarator()) {
6251       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6252                                         D.getIdentifierLoc(), R, TInfo, SC,
6253                                         Bindings);
6254     } else
6255       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6256                               D.getIdentifierLoc(), II, R, TInfo, SC);
6257
6258     // If this is supposed to be a variable template, create it as such.
6259     if (IsVariableTemplate) {
6260       NewTemplate =
6261           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6262                                   TemplateParams, NewVD);
6263       NewVD->setDescribedVarTemplate(NewTemplate);
6264     }
6265
6266     // If this decl has an auto type in need of deduction, make a note of the
6267     // Decl so we can diagnose uses of it in its own initializer.
6268     if (R->getContainedDeducedType())
6269       ParsingInitForAutoVars.insert(NewVD);
6270
6271     if (D.isInvalidType() || Invalid) {
6272       NewVD->setInvalidDecl();
6273       if (NewTemplate)
6274         NewTemplate->setInvalidDecl();
6275     }
6276
6277     SetNestedNameSpecifier(NewVD, D);
6278
6279     // If we have any template parameter lists that don't directly belong to
6280     // the variable (matching the scope specifier), store them.
6281     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6282     if (TemplateParamLists.size() > VDTemplateParamLists)
6283       NewVD->setTemplateParameterListsInfo(
6284           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6285
6286     if (D.getDeclSpec().isConstexprSpecified()) {
6287       NewVD->setConstexpr(true);
6288       // C++1z [dcl.spec.constexpr]p1:
6289       //   A static data member declared with the constexpr specifier is
6290       //   implicitly an inline variable.
6291       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6292         NewVD->setImplicitlyInline();
6293     }
6294
6295     if (D.getDeclSpec().isConceptSpecified()) {
6296       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6297         VTD->setConcept();
6298
6299       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6300       // be declared with the thread_local, inline, friend, or constexpr
6301       // specifiers, [...]
6302       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6303         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6304              diag::err_concept_decl_invalid_specifiers)
6305             << 0 << 0;
6306         NewVD->setInvalidDecl(true);
6307       }
6308
6309       if (D.getDeclSpec().isConstexprSpecified()) {
6310         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6311              diag::err_concept_decl_invalid_specifiers)
6312             << 0 << 3;
6313         NewVD->setInvalidDecl(true);
6314       }
6315
6316       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6317       // applied only to the definition of a function template or variable
6318       // template, declared in namespace scope.
6319       if (IsVariableTemplateSpecialization) {
6320         Diag(D.getDeclSpec().getConceptSpecLoc(),
6321              diag::err_concept_specified_specialization)
6322             << (IsPartialSpecialization ? 2 : 1);
6323       }
6324
6325       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6326       // following restrictions:
6327       // - The declared type shall have the type bool.
6328       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6329           !NewVD->isInvalidDecl()) {
6330         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6331         NewVD->setInvalidDecl(true);
6332       }
6333     }
6334   }
6335
6336   if (D.getDeclSpec().isInlineSpecified()) {
6337     if (!getLangOpts().CPlusPlus) {
6338       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6339           << 0;
6340     } else if (CurContext->isFunctionOrMethod()) {
6341       // 'inline' is not allowed on block scope variable declaration.
6342       Diag(D.getDeclSpec().getInlineSpecLoc(),
6343            diag::err_inline_declaration_block_scope) << Name
6344         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6345     } else {
6346       Diag(D.getDeclSpec().getInlineSpecLoc(),
6347            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6348                                      : diag::ext_inline_variable);
6349       NewVD->setInlineSpecified();
6350     }
6351   }
6352
6353   // Set the lexical context. If the declarator has a C++ scope specifier, the
6354   // lexical context will be different from the semantic context.
6355   NewVD->setLexicalDeclContext(CurContext);
6356   if (NewTemplate)
6357     NewTemplate->setLexicalDeclContext(CurContext);
6358
6359   if (IsLocalExternDecl) {
6360     if (D.isDecompositionDeclarator())
6361       for (auto *B : Bindings)
6362         B->setLocalExternDecl();
6363     else
6364       NewVD->setLocalExternDecl();
6365   }
6366
6367   bool EmitTLSUnsupportedError = false;
6368   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6369     // C++11 [dcl.stc]p4:
6370     //   When thread_local is applied to a variable of block scope the
6371     //   storage-class-specifier static is implied if it does not appear
6372     //   explicitly.
6373     // Core issue: 'static' is not implied if the variable is declared
6374     //   'extern'.
6375     if (NewVD->hasLocalStorage() &&
6376         (SCSpec != DeclSpec::SCS_unspecified ||
6377          TSCS != DeclSpec::TSCS_thread_local ||
6378          !DC->isFunctionOrMethod()))
6379       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6380            diag::err_thread_non_global)
6381         << DeclSpec::getSpecifierName(TSCS);
6382     else if (!Context.getTargetInfo().isTLSSupported()) {
6383       if (getLangOpts().CUDA) {
6384         // Postpone error emission until we've collected attributes required to
6385         // figure out whether it's a host or device variable and whether the
6386         // error should be ignored.
6387         EmitTLSUnsupportedError = true;
6388         // We still need to mark the variable as TLS so it shows up in AST with
6389         // proper storage class for other tools to use even if we're not going
6390         // to emit any code for it.
6391         NewVD->setTSCSpec(TSCS);
6392       } else
6393         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6394              diag::err_thread_unsupported);
6395     } else
6396       NewVD->setTSCSpec(TSCS);
6397   }
6398
6399   // C99 6.7.4p3
6400   //   An inline definition of a function with external linkage shall
6401   //   not contain a definition of a modifiable object with static or
6402   //   thread storage duration...
6403   // We only apply this when the function is required to be defined
6404   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6405   // that a local variable with thread storage duration still has to
6406   // be marked 'static'.  Also note that it's possible to get these
6407   // semantics in C++ using __attribute__((gnu_inline)).
6408   if (SC == SC_Static && S->getFnParent() != nullptr &&
6409       !NewVD->getType().isConstQualified()) {
6410     FunctionDecl *CurFD = getCurFunctionDecl();
6411     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6412       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6413            diag::warn_static_local_in_extern_inline);
6414       MaybeSuggestAddingStaticToDecl(CurFD);
6415     }
6416   }
6417
6418   if (D.getDeclSpec().isModulePrivateSpecified()) {
6419     if (IsVariableTemplateSpecialization)
6420       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6421           << (IsPartialSpecialization ? 1 : 0)
6422           << FixItHint::CreateRemoval(
6423                  D.getDeclSpec().getModulePrivateSpecLoc());
6424     else if (IsMemberSpecialization)
6425       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6426         << 2
6427         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6428     else if (NewVD->hasLocalStorage())
6429       Diag(NewVD->getLocation(), diag::err_module_private_local)
6430         << 0 << NewVD->getDeclName()
6431         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6432         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6433     else {
6434       NewVD->setModulePrivate();
6435       if (NewTemplate)
6436         NewTemplate->setModulePrivate();
6437       for (auto *B : Bindings)
6438         B->setModulePrivate();
6439     }
6440   }
6441
6442   // Handle attributes prior to checking for duplicates in MergeVarDecl
6443   ProcessDeclAttributes(S, NewVD, D);
6444
6445   if (getLangOpts().CUDA) {
6446     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6447       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6448            diag::err_thread_unsupported);
6449     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6450     // storage [duration]."
6451     if (SC == SC_None && S->getFnParent() != nullptr &&
6452         (NewVD->hasAttr<CUDASharedAttr>() ||
6453          NewVD->hasAttr<CUDAConstantAttr>())) {
6454       NewVD->setStorageClass(SC_Static);
6455     }
6456   }
6457
6458   // Ensure that dllimport globals without explicit storage class are treated as
6459   // extern. The storage class is set above using parsed attributes. Now we can
6460   // check the VarDecl itself.
6461   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6462          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6463          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6464
6465   // In auto-retain/release, infer strong retension for variables of
6466   // retainable type.
6467   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6468     NewVD->setInvalidDecl();
6469
6470   // Handle GNU asm-label extension (encoded as an attribute).
6471   if (Expr *E = (Expr*)D.getAsmLabel()) {
6472     // The parser guarantees this is a string.
6473     StringLiteral *SE = cast<StringLiteral>(E);
6474     StringRef Label = SE->getString();
6475     if (S->getFnParent() != nullptr) {
6476       switch (SC) {
6477       case SC_None:
6478       case SC_Auto:
6479         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6480         break;
6481       case SC_Register:
6482         // Local Named register
6483         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6484             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6485           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6486         break;
6487       case SC_Static:
6488       case SC_Extern:
6489       case SC_PrivateExtern:
6490         break;
6491       }
6492     } else if (SC == SC_Register) {
6493       // Global Named register
6494       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6495         const auto &TI = Context.getTargetInfo();
6496         bool HasSizeMismatch;
6497
6498         if (!TI.isValidGCCRegisterName(Label))
6499           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6500         else if (!TI.validateGlobalRegisterVariable(Label,
6501                                                     Context.getTypeSize(R),
6502                                                     HasSizeMismatch))
6503           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6504         else if (HasSizeMismatch)
6505           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6506       }
6507
6508       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6509         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6510         NewVD->setInvalidDecl(true);
6511       }
6512     }
6513
6514     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6515                                                 Context, Label, 0));
6516   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6517     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6518       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6519     if (I != ExtnameUndeclaredIdentifiers.end()) {
6520       if (isDeclExternC(NewVD)) {
6521         NewVD->addAttr(I->second);
6522         ExtnameUndeclaredIdentifiers.erase(I);
6523       } else
6524         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6525             << /*Variable*/1 << NewVD;
6526     }
6527   }
6528
6529   // Find the shadowed declaration before filtering for scope.
6530   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6531                                 ? getShadowedDeclaration(NewVD, Previous)
6532                                 : nullptr;
6533
6534   // Don't consider existing declarations that are in a different
6535   // scope and are out-of-semantic-context declarations (if the new
6536   // declaration has linkage).
6537   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6538                        D.getCXXScopeSpec().isNotEmpty() ||
6539                        IsMemberSpecialization ||
6540                        IsVariableTemplateSpecialization);
6541
6542   // Check whether the previous declaration is in the same block scope. This
6543   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6544   if (getLangOpts().CPlusPlus &&
6545       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6546     NewVD->setPreviousDeclInSameBlockScope(
6547         Previous.isSingleResult() && !Previous.isShadowed() &&
6548         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6549
6550   if (!getLangOpts().CPlusPlus) {
6551     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6552   } else {
6553     // If this is an explicit specialization of a static data member, check it.
6554     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6555         CheckMemberSpecialization(NewVD, Previous))
6556       NewVD->setInvalidDecl();
6557
6558     // Merge the decl with the existing one if appropriate.
6559     if (!Previous.empty()) {
6560       if (Previous.isSingleResult() &&
6561           isa<FieldDecl>(Previous.getFoundDecl()) &&
6562           D.getCXXScopeSpec().isSet()) {
6563         // The user tried to define a non-static data member
6564         // out-of-line (C++ [dcl.meaning]p1).
6565         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6566           << D.getCXXScopeSpec().getRange();
6567         Previous.clear();
6568         NewVD->setInvalidDecl();
6569       }
6570     } else if (D.getCXXScopeSpec().isSet()) {
6571       // No previous declaration in the qualifying scope.
6572       Diag(D.getIdentifierLoc(), diag::err_no_member)
6573         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6574         << D.getCXXScopeSpec().getRange();
6575       NewVD->setInvalidDecl();
6576     }
6577
6578     if (!IsVariableTemplateSpecialization)
6579       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6580
6581     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6582     // an explicit specialization (14.8.3) or a partial specialization of a
6583     // concept definition.
6584     if (IsVariableTemplateSpecialization &&
6585         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6586         Previous.isSingleResult()) {
6587       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6588       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6589         if (VarTmpl->isConcept()) {
6590           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6591               << 1                            /*variable*/
6592               << (IsPartialSpecialization ? 2 /*partially specialized*/
6593                                           : 1 /*explicitly specialized*/);
6594           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6595           NewVD->setInvalidDecl();
6596         }
6597       }
6598     }
6599
6600     if (NewTemplate) {
6601       VarTemplateDecl *PrevVarTemplate =
6602           NewVD->getPreviousDecl()
6603               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6604               : nullptr;
6605
6606       // Check the template parameter list of this declaration, possibly
6607       // merging in the template parameter list from the previous variable
6608       // template declaration.
6609       if (CheckTemplateParameterList(
6610               TemplateParams,
6611               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6612                               : nullptr,
6613               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6614                DC->isDependentContext())
6615                   ? TPC_ClassTemplateMember
6616                   : TPC_VarTemplate))
6617         NewVD->setInvalidDecl();
6618
6619       // If we are providing an explicit specialization of a static variable
6620       // template, make a note of that.
6621       if (PrevVarTemplate &&
6622           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6623         PrevVarTemplate->setMemberSpecialization();
6624     }
6625   }
6626
6627   // Diagnose shadowed variables iff this isn't a redeclaration.
6628   if (ShadowedDecl && !D.isRedeclaration())
6629     CheckShadow(NewVD, ShadowedDecl, Previous);
6630
6631   ProcessPragmaWeak(S, NewVD);
6632
6633   // If this is the first declaration of an extern C variable, update
6634   // the map of such variables.
6635   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6636       isIncompleteDeclExternC(*this, NewVD))
6637     RegisterLocallyScopedExternCDecl(NewVD, S);
6638
6639   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6640     Decl *ManglingContextDecl;
6641     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6642             NewVD->getDeclContext(), ManglingContextDecl)) {
6643       Context.setManglingNumber(
6644           NewVD, MCtx->getManglingNumber(
6645                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6646       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6647     }
6648   }
6649
6650   // Special handling of variable named 'main'.
6651   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6652       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6653       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6654
6655     // C++ [basic.start.main]p3
6656     // A program that declares a variable main at global scope is ill-formed.
6657     if (getLangOpts().CPlusPlus)
6658       Diag(D.getLocStart(), diag::err_main_global_variable);
6659
6660     // In C, and external-linkage variable named main results in undefined
6661     // behavior.
6662     else if (NewVD->hasExternalFormalLinkage())
6663       Diag(D.getLocStart(), diag::warn_main_redefined);
6664   }
6665
6666   if (D.isRedeclaration() && !Previous.empty()) {
6667     checkDLLAttributeRedeclaration(
6668         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6669         IsMemberSpecialization, D.isFunctionDefinition());
6670   }
6671
6672   if (NewTemplate) {
6673     if (NewVD->isInvalidDecl())
6674       NewTemplate->setInvalidDecl();
6675     ActOnDocumentableDecl(NewTemplate);
6676     return NewTemplate;
6677   }
6678
6679   return NewVD;
6680 }
6681
6682 /// Enum describing the %select options in diag::warn_decl_shadow.
6683 enum ShadowedDeclKind {
6684   SDK_Local,
6685   SDK_Global,
6686   SDK_StaticMember,
6687   SDK_Field,
6688   SDK_Typedef,
6689   SDK_Using
6690 };
6691
6692 /// Determine what kind of declaration we're shadowing.
6693 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6694                                                 const DeclContext *OldDC) {
6695   if (isa<TypeAliasDecl>(ShadowedDecl))
6696     return SDK_Using;
6697   else if (isa<TypedefDecl>(ShadowedDecl))
6698     return SDK_Typedef;
6699   else if (isa<RecordDecl>(OldDC))
6700     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6701
6702   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6703 }
6704
6705 /// Return the location of the capture if the given lambda captures the given
6706 /// variable \p VD, or an invalid source location otherwise.
6707 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6708                                          const VarDecl *VD) {
6709   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6710     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6711       return Capture.getLocation();
6712   }
6713   return SourceLocation();
6714 }
6715
6716 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6717                                      const LookupResult &R) {
6718   // Only diagnose if we're shadowing an unambiguous field or variable.
6719   if (R.getResultKind() != LookupResult::Found)
6720     return false;
6721
6722   // Return false if warning is ignored.
6723   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6724 }
6725
6726 /// \brief Return the declaration shadowed by the given variable \p D, or null
6727 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6728 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6729                                         const LookupResult &R) {
6730   if (!shouldWarnIfShadowedDecl(Diags, R))
6731     return nullptr;
6732
6733   // Don't diagnose declarations at file scope.
6734   if (D->hasGlobalStorage())
6735     return nullptr;
6736
6737   NamedDecl *ShadowedDecl = R.getFoundDecl();
6738   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6739              ? ShadowedDecl
6740              : nullptr;
6741 }
6742
6743 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6744 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6745 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6746                                         const LookupResult &R) {
6747   // Don't warn if typedef declaration is part of a class
6748   if (D->getDeclContext()->isRecord())
6749     return nullptr;
6750   
6751   if (!shouldWarnIfShadowedDecl(Diags, R))
6752     return nullptr;
6753
6754   NamedDecl *ShadowedDecl = R.getFoundDecl();
6755   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6756 }
6757
6758 /// \brief Diagnose variable or built-in function shadowing.  Implements
6759 /// -Wshadow.
6760 ///
6761 /// This method is called whenever a VarDecl is added to a "useful"
6762 /// scope.
6763 ///
6764 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6765 /// \param R the lookup of the name
6766 ///
6767 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6768                        const LookupResult &R) {
6769   DeclContext *NewDC = D->getDeclContext();
6770
6771   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6772     // Fields are not shadowed by variables in C++ static methods.
6773     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6774       if (MD->isStatic())
6775         return;
6776
6777     // Fields shadowed by constructor parameters are a special case. Usually
6778     // the constructor initializes the field with the parameter.
6779     if (isa<CXXConstructorDecl>(NewDC))
6780       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6781         // Remember that this was shadowed so we can either warn about its
6782         // modification or its existence depending on warning settings.
6783         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6784         return;
6785       }
6786   }
6787
6788   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6789     if (shadowedVar->isExternC()) {
6790       // For shadowing external vars, make sure that we point to the global
6791       // declaration, not a locally scoped extern declaration.
6792       for (auto I : shadowedVar->redecls())
6793         if (I->isFileVarDecl()) {
6794           ShadowedDecl = I;
6795           break;
6796         }
6797     }
6798
6799   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6800
6801   unsigned WarningDiag = diag::warn_decl_shadow;
6802   SourceLocation CaptureLoc;
6803   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6804       isa<CXXMethodDecl>(NewDC)) {
6805     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6806       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6807         if (RD->getLambdaCaptureDefault() == LCD_None) {
6808           // Try to avoid warnings for lambdas with an explicit capture list.
6809           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6810           // Warn only when the lambda captures the shadowed decl explicitly.
6811           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6812           if (CaptureLoc.isInvalid())
6813             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6814         } else {
6815           // Remember that this was shadowed so we can avoid the warning if the
6816           // shadowed decl isn't captured and the warning settings allow it.
6817           cast<LambdaScopeInfo>(getCurFunction())
6818               ->ShadowingDecls.push_back(
6819                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
6820           return;
6821         }
6822       }
6823     }
6824   }
6825
6826   // Only warn about certain kinds of shadowing for class members.
6827   if (NewDC && NewDC->isRecord()) {
6828     // In particular, don't warn about shadowing non-class members.
6829     if (!OldDC->isRecord())
6830       return;
6831
6832     // TODO: should we warn about static data members shadowing
6833     // static data members from base classes?
6834
6835     // TODO: don't diagnose for inaccessible shadowed members.
6836     // This is hard to do perfectly because we might friend the
6837     // shadowing context, but that's just a false negative.
6838   }
6839
6840
6841   DeclarationName Name = R.getLookupName();
6842
6843   // Emit warning and note.
6844   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6845     return;
6846   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6847   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
6848   if (!CaptureLoc.isInvalid())
6849     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6850         << Name << /*explicitly*/ 1;
6851   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6852 }
6853
6854 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
6855 /// when these variables are captured by the lambda.
6856 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
6857   for (const auto &Shadow : LSI->ShadowingDecls) {
6858     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
6859     // Try to avoid the warning when the shadowed decl isn't captured.
6860     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
6861     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6862     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
6863                                        ? diag::warn_decl_shadow_uncaptured_local
6864                                        : diag::warn_decl_shadow)
6865         << Shadow.VD->getDeclName()
6866         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
6867     if (!CaptureLoc.isInvalid())
6868       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6869           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
6870     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6871   }
6872 }
6873
6874 /// \brief Check -Wshadow without the advantage of a previous lookup.
6875 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6876   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6877     return;
6878
6879   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6880                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6881   LookupName(R, S);
6882   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
6883     CheckShadow(D, ShadowedDecl, R);
6884 }
6885
6886 /// Check if 'E', which is an expression that is about to be modified, refers
6887 /// to a constructor parameter that shadows a field.
6888 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6889   // Quickly ignore expressions that can't be shadowing ctor parameters.
6890   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6891     return;
6892   E = E->IgnoreParenImpCasts();
6893   auto *DRE = dyn_cast<DeclRefExpr>(E);
6894   if (!DRE)
6895     return;
6896   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6897   auto I = ShadowingDecls.find(D);
6898   if (I == ShadowingDecls.end())
6899     return;
6900   const NamedDecl *ShadowedDecl = I->second;
6901   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6902   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6903   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6904   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6905
6906   // Avoid issuing multiple warnings about the same decl.
6907   ShadowingDecls.erase(I);
6908 }
6909
6910 /// Check for conflict between this global or extern "C" declaration and
6911 /// previous global or extern "C" declarations. This is only used in C++.
6912 template<typename T>
6913 static bool checkGlobalOrExternCConflict(
6914     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6915   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6916   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6917
6918   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6919     // The common case: this global doesn't conflict with any extern "C"
6920     // declaration.
6921     return false;
6922   }
6923
6924   if (Prev) {
6925     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6926       // Both the old and new declarations have C language linkage. This is a
6927       // redeclaration.
6928       Previous.clear();
6929       Previous.addDecl(Prev);
6930       return true;
6931     }
6932
6933     // This is a global, non-extern "C" declaration, and there is a previous
6934     // non-global extern "C" declaration. Diagnose if this is a variable
6935     // declaration.
6936     if (!isa<VarDecl>(ND))
6937       return false;
6938   } else {
6939     // The declaration is extern "C". Check for any declaration in the
6940     // translation unit which might conflict.
6941     if (IsGlobal) {
6942       // We have already performed the lookup into the translation unit.
6943       IsGlobal = false;
6944       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6945            I != E; ++I) {
6946         if (isa<VarDecl>(*I)) {
6947           Prev = *I;
6948           break;
6949         }
6950       }
6951     } else {
6952       DeclContext::lookup_result R =
6953           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6954       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6955            I != E; ++I) {
6956         if (isa<VarDecl>(*I)) {
6957           Prev = *I;
6958           break;
6959         }
6960         // FIXME: If we have any other entity with this name in global scope,
6961         // the declaration is ill-formed, but that is a defect: it breaks the
6962         // 'stat' hack, for instance. Only variables can have mangled name
6963         // clashes with extern "C" declarations, so only they deserve a
6964         // diagnostic.
6965       }
6966     }
6967
6968     if (!Prev)
6969       return false;
6970   }
6971
6972   // Use the first declaration's location to ensure we point at something which
6973   // is lexically inside an extern "C" linkage-spec.
6974   assert(Prev && "should have found a previous declaration to diagnose");
6975   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6976     Prev = FD->getFirstDecl();
6977   else
6978     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6979
6980   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6981     << IsGlobal << ND;
6982   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6983     << IsGlobal;
6984   return false;
6985 }
6986
6987 /// Apply special rules for handling extern "C" declarations. Returns \c true
6988 /// if we have found that this is a redeclaration of some prior entity.
6989 ///
6990 /// Per C++ [dcl.link]p6:
6991 ///   Two declarations [for a function or variable] with C language linkage
6992 ///   with the same name that appear in different scopes refer to the same
6993 ///   [entity]. An entity with C language linkage shall not be declared with
6994 ///   the same name as an entity in global scope.
6995 template<typename T>
6996 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6997                                                   LookupResult &Previous) {
6998   if (!S.getLangOpts().CPlusPlus) {
6999     // In C, when declaring a global variable, look for a corresponding 'extern'
7000     // variable declared in function scope. We don't need this in C++, because
7001     // we find local extern decls in the surrounding file-scope DeclContext.
7002     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7003       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7004         Previous.clear();
7005         Previous.addDecl(Prev);
7006         return true;
7007       }
7008     }
7009     return false;
7010   }
7011
7012   // A declaration in the translation unit can conflict with an extern "C"
7013   // declaration.
7014   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7015     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7016
7017   // An extern "C" declaration can conflict with a declaration in the
7018   // translation unit or can be a redeclaration of an extern "C" declaration
7019   // in another scope.
7020   if (isIncompleteDeclExternC(S,ND))
7021     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7022
7023   // Neither global nor extern "C": nothing to do.
7024   return false;
7025 }
7026
7027 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7028   // If the decl is already known invalid, don't check it.
7029   if (NewVD->isInvalidDecl())
7030     return;
7031
7032   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7033   QualType T = TInfo->getType();
7034
7035   // Defer checking an 'auto' type until its initializer is attached.
7036   if (T->isUndeducedType())
7037     return;
7038
7039   if (NewVD->hasAttrs())
7040     CheckAlignasUnderalignment(NewVD);
7041
7042   if (T->isObjCObjectType()) {
7043     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7044       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7045     T = Context.getObjCObjectPointerType(T);
7046     NewVD->setType(T);
7047   }
7048
7049   // Emit an error if an address space was applied to decl with local storage.
7050   // This includes arrays of objects with address space qualifiers, but not
7051   // automatic variables that point to other address spaces.
7052   // ISO/IEC TR 18037 S5.1.2
7053   if (!getLangOpts().OpenCL
7054       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7055     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
7056     NewVD->setInvalidDecl();
7057     return;
7058   }
7059
7060   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7061   // scope.
7062   if (getLangOpts().OpenCLVersion == 120 &&
7063       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7064       NewVD->isStaticLocal()) {
7065     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7066     NewVD->setInvalidDecl();
7067     return;
7068   }
7069
7070   if (getLangOpts().OpenCL) {
7071     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7072     if (NewVD->hasAttr<BlocksAttr>()) {
7073       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7074       return;
7075     }
7076
7077     if (T->isBlockPointerType()) {
7078       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7079       // can't use 'extern' storage class.
7080       if (!T.isConstQualified()) {
7081         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7082             << 0 /*const*/;
7083         NewVD->setInvalidDecl();
7084         return;
7085       }
7086       if (NewVD->hasExternalStorage()) {
7087         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7088         NewVD->setInvalidDecl();
7089         return;
7090       }
7091     }
7092     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7093     // __constant address space.
7094     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7095     // variables inside a function can also be declared in the global
7096     // address space.
7097     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7098         NewVD->hasExternalStorage()) {
7099       if (!T->isSamplerT() &&
7100           !(T.getAddressSpace() == LangAS::opencl_constant ||
7101             (T.getAddressSpace() == LangAS::opencl_global &&
7102              getLangOpts().OpenCLVersion == 200))) {
7103         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7104         if (getLangOpts().OpenCLVersion == 200)
7105           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7106               << Scope << "global or constant";
7107         else
7108           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7109               << Scope << "constant";
7110         NewVD->setInvalidDecl();
7111         return;
7112       }
7113     } else {
7114       if (T.getAddressSpace() == LangAS::opencl_global) {
7115         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7116             << 1 /*is any function*/ << "global";
7117         NewVD->setInvalidDecl();
7118         return;
7119       }
7120       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
7121       // in functions.
7122       if (T.getAddressSpace() == LangAS::opencl_constant ||
7123           T.getAddressSpace() == LangAS::opencl_local) {
7124         FunctionDecl *FD = getCurFunctionDecl();
7125         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7126           if (T.getAddressSpace() == LangAS::opencl_constant)
7127             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7128                 << 0 /*non-kernel only*/ << "constant";
7129           else
7130             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7131                 << 0 /*non-kernel only*/ << "local";
7132           NewVD->setInvalidDecl();
7133           return;
7134         }
7135       }
7136     }
7137   }
7138
7139   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7140       && !NewVD->hasAttr<BlocksAttr>()) {
7141     if (getLangOpts().getGC() != LangOptions::NonGC)
7142       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7143     else {
7144       assert(!getLangOpts().ObjCAutoRefCount);
7145       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7146     }
7147   }
7148
7149   bool isVM = T->isVariablyModifiedType();
7150   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7151       NewVD->hasAttr<BlocksAttr>())
7152     getCurFunction()->setHasBranchProtectedScope();
7153
7154   if ((isVM && NewVD->hasLinkage()) ||
7155       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7156     bool SizeIsNegative;
7157     llvm::APSInt Oversized;
7158     TypeSourceInfo *FixedTInfo =
7159       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7160                                                     SizeIsNegative, Oversized);
7161     if (!FixedTInfo && T->isVariableArrayType()) {
7162       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7163       // FIXME: This won't give the correct result for
7164       // int a[10][n];
7165       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7166
7167       if (NewVD->isFileVarDecl())
7168         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7169         << SizeRange;
7170       else if (NewVD->isStaticLocal())
7171         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7172         << SizeRange;
7173       else
7174         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7175         << SizeRange;
7176       NewVD->setInvalidDecl();
7177       return;
7178     }
7179
7180     if (!FixedTInfo) {
7181       if (NewVD->isFileVarDecl())
7182         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7183       else
7184         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7185       NewVD->setInvalidDecl();
7186       return;
7187     }
7188
7189     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7190     NewVD->setType(FixedTInfo->getType());
7191     NewVD->setTypeSourceInfo(FixedTInfo);
7192   }
7193
7194   if (T->isVoidType()) {
7195     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7196     //                    of objects and functions.
7197     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7198       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7199         << T;
7200       NewVD->setInvalidDecl();
7201       return;
7202     }
7203   }
7204
7205   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7206     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7207     NewVD->setInvalidDecl();
7208     return;
7209   }
7210
7211   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7212     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7213     NewVD->setInvalidDecl();
7214     return;
7215   }
7216
7217   if (NewVD->isConstexpr() && !T->isDependentType() &&
7218       RequireLiteralType(NewVD->getLocation(), T,
7219                          diag::err_constexpr_var_non_literal)) {
7220     NewVD->setInvalidDecl();
7221     return;
7222   }
7223 }
7224
7225 /// \brief Perform semantic checking on a newly-created variable
7226 /// declaration.
7227 ///
7228 /// This routine performs all of the type-checking required for a
7229 /// variable declaration once it has been built. It is used both to
7230 /// check variables after they have been parsed and their declarators
7231 /// have been translated into a declaration, and to check variables
7232 /// that have been instantiated from a template.
7233 ///
7234 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7235 ///
7236 /// Returns true if the variable declaration is a redeclaration.
7237 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7238   CheckVariableDeclarationType(NewVD);
7239
7240   // If the decl is already known invalid, don't check it.
7241   if (NewVD->isInvalidDecl())
7242     return false;
7243
7244   // If we did not find anything by this name, look for a non-visible
7245   // extern "C" declaration with the same name.
7246   if (Previous.empty() &&
7247       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7248     Previous.setShadowed();
7249
7250   if (!Previous.empty()) {
7251     MergeVarDecl(NewVD, Previous);
7252     return true;
7253   }
7254   return false;
7255 }
7256
7257 namespace {
7258 struct FindOverriddenMethod {
7259   Sema *S;
7260   CXXMethodDecl *Method;
7261
7262   /// Member lookup function that determines whether a given C++
7263   /// method overrides a method in a base class, to be used with
7264   /// CXXRecordDecl::lookupInBases().
7265   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7266     RecordDecl *BaseRecord =
7267         Specifier->getType()->getAs<RecordType>()->getDecl();
7268
7269     DeclarationName Name = Method->getDeclName();
7270
7271     // FIXME: Do we care about other names here too?
7272     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7273       // We really want to find the base class destructor here.
7274       QualType T = S->Context.getTypeDeclType(BaseRecord);
7275       CanQualType CT = S->Context.getCanonicalType(T);
7276
7277       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7278     }
7279
7280     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7281          Path.Decls = Path.Decls.slice(1)) {
7282       NamedDecl *D = Path.Decls.front();
7283       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7284         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7285           return true;
7286       }
7287     }
7288
7289     return false;
7290   }
7291 };
7292
7293 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7294 } // end anonymous namespace
7295
7296 /// \brief Report an error regarding overriding, along with any relevant
7297 /// overriden methods.
7298 ///
7299 /// \param DiagID the primary error to report.
7300 /// \param MD the overriding method.
7301 /// \param OEK which overrides to include as notes.
7302 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7303                             OverrideErrorKind OEK = OEK_All) {
7304   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7305   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7306                                       E = MD->end_overridden_methods();
7307        I != E; ++I) {
7308     // This check (& the OEK parameter) could be replaced by a predicate, but
7309     // without lambdas that would be overkill. This is still nicer than writing
7310     // out the diag loop 3 times.
7311     if ((OEK == OEK_All) ||
7312         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7313         (OEK == OEK_Deleted && (*I)->isDeleted()))
7314       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7315   }
7316 }
7317
7318 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7319 /// and if so, check that it's a valid override and remember it.
7320 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7321   // Look for methods in base classes that this method might override.
7322   CXXBasePaths Paths;
7323   FindOverriddenMethod FOM;
7324   FOM.Method = MD;
7325   FOM.S = this;
7326   bool hasDeletedOverridenMethods = false;
7327   bool hasNonDeletedOverridenMethods = false;
7328   bool AddedAny = false;
7329   if (DC->lookupInBases(FOM, Paths)) {
7330     for (auto *I : Paths.found_decls()) {
7331       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7332         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7333         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7334             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7335             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7336             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7337           hasDeletedOverridenMethods |= OldMD->isDeleted();
7338           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7339           AddedAny = true;
7340         }
7341       }
7342     }
7343   }
7344
7345   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7346     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7347   }
7348   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7349     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7350   }
7351
7352   return AddedAny;
7353 }
7354
7355 namespace {
7356   // Struct for holding all of the extra arguments needed by
7357   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7358   struct ActOnFDArgs {
7359     Scope *S;
7360     Declarator &D;
7361     MultiTemplateParamsArg TemplateParamLists;
7362     bool AddToScope;
7363   };
7364 } // end anonymous namespace
7365
7366 namespace {
7367
7368 // Callback to only accept typo corrections that have a non-zero edit distance.
7369 // Also only accept corrections that have the same parent decl.
7370 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7371  public:
7372   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7373                             CXXRecordDecl *Parent)
7374       : Context(Context), OriginalFD(TypoFD),
7375         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7376
7377   bool ValidateCandidate(const TypoCorrection &candidate) override {
7378     if (candidate.getEditDistance() == 0)
7379       return false;
7380
7381     SmallVector<unsigned, 1> MismatchedParams;
7382     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7383                                           CDeclEnd = candidate.end();
7384          CDecl != CDeclEnd; ++CDecl) {
7385       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7386
7387       if (FD && !FD->hasBody() &&
7388           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7389         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7390           CXXRecordDecl *Parent = MD->getParent();
7391           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7392             return true;
7393         } else if (!ExpectedParent) {
7394           return true;
7395         }
7396       }
7397     }
7398
7399     return false;
7400   }
7401
7402  private:
7403   ASTContext &Context;
7404   FunctionDecl *OriginalFD;
7405   CXXRecordDecl *ExpectedParent;
7406 };
7407
7408 } // end anonymous namespace
7409
7410 /// \brief Generate diagnostics for an invalid function redeclaration.
7411 ///
7412 /// This routine handles generating the diagnostic messages for an invalid
7413 /// function redeclaration, including finding possible similar declarations
7414 /// or performing typo correction if there are no previous declarations with
7415 /// the same name.
7416 ///
7417 /// Returns a NamedDecl iff typo correction was performed and substituting in
7418 /// the new declaration name does not cause new errors.
7419 static NamedDecl *DiagnoseInvalidRedeclaration(
7420     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7421     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7422   DeclarationName Name = NewFD->getDeclName();
7423   DeclContext *NewDC = NewFD->getDeclContext();
7424   SmallVector<unsigned, 1> MismatchedParams;
7425   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7426   TypoCorrection Correction;
7427   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7428   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7429                                    : diag::err_member_decl_does_not_match;
7430   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7431                     IsLocalFriend ? Sema::LookupLocalFriendName
7432                                   : Sema::LookupOrdinaryName,
7433                     Sema::ForRedeclaration);
7434
7435   NewFD->setInvalidDecl();
7436   if (IsLocalFriend)
7437     SemaRef.LookupName(Prev, S);
7438   else
7439     SemaRef.LookupQualifiedName(Prev, NewDC);
7440   assert(!Prev.isAmbiguous() &&
7441          "Cannot have an ambiguity in previous-declaration lookup");
7442   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7443   if (!Prev.empty()) {
7444     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7445          Func != FuncEnd; ++Func) {
7446       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7447       if (FD &&
7448           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7449         // Add 1 to the index so that 0 can mean the mismatch didn't
7450         // involve a parameter
7451         unsigned ParamNum =
7452             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7453         NearMatches.push_back(std::make_pair(FD, ParamNum));
7454       }
7455     }
7456   // If the qualified name lookup yielded nothing, try typo correction
7457   } else if ((Correction = SemaRef.CorrectTypo(
7458                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7459                   &ExtraArgs.D.getCXXScopeSpec(),
7460                   llvm::make_unique<DifferentNameValidatorCCC>(
7461                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7462                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7463     // Set up everything for the call to ActOnFunctionDeclarator
7464     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7465                               ExtraArgs.D.getIdentifierLoc());
7466     Previous.clear();
7467     Previous.setLookupName(Correction.getCorrection());
7468     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7469                                     CDeclEnd = Correction.end();
7470          CDecl != CDeclEnd; ++CDecl) {
7471       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7472       if (FD && !FD->hasBody() &&
7473           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7474         Previous.addDecl(FD);
7475       }
7476     }
7477     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7478
7479     NamedDecl *Result;
7480     // Retry building the function declaration with the new previous
7481     // declarations, and with errors suppressed.
7482     {
7483       // Trap errors.
7484       Sema::SFINAETrap Trap(SemaRef);
7485
7486       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7487       // pieces need to verify the typo-corrected C++ declaration and hopefully
7488       // eliminate the need for the parameter pack ExtraArgs.
7489       Result = SemaRef.ActOnFunctionDeclarator(
7490           ExtraArgs.S, ExtraArgs.D,
7491           Correction.getCorrectionDecl()->getDeclContext(),
7492           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7493           ExtraArgs.AddToScope);
7494
7495       if (Trap.hasErrorOccurred())
7496         Result = nullptr;
7497     }
7498
7499     if (Result) {
7500       // Determine which correction we picked.
7501       Decl *Canonical = Result->getCanonicalDecl();
7502       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7503            I != E; ++I)
7504         if ((*I)->getCanonicalDecl() == Canonical)
7505           Correction.setCorrectionDecl(*I);
7506
7507       SemaRef.diagnoseTypo(
7508           Correction,
7509           SemaRef.PDiag(IsLocalFriend
7510                           ? diag::err_no_matching_local_friend_suggest
7511                           : diag::err_member_decl_does_not_match_suggest)
7512             << Name << NewDC << IsDefinition);
7513       return Result;
7514     }
7515
7516     // Pretend the typo correction never occurred
7517     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7518                               ExtraArgs.D.getIdentifierLoc());
7519     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7520     Previous.clear();
7521     Previous.setLookupName(Name);
7522   }
7523
7524   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7525       << Name << NewDC << IsDefinition << NewFD->getLocation();
7526
7527   bool NewFDisConst = false;
7528   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7529     NewFDisConst = NewMD->isConst();
7530
7531   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7532        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7533        NearMatch != NearMatchEnd; ++NearMatch) {
7534     FunctionDecl *FD = NearMatch->first;
7535     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7536     bool FDisConst = MD && MD->isConst();
7537     bool IsMember = MD || !IsLocalFriend;
7538
7539     // FIXME: These notes are poorly worded for the local friend case.
7540     if (unsigned Idx = NearMatch->second) {
7541       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7542       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7543       if (Loc.isInvalid()) Loc = FD->getLocation();
7544       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7545                                  : diag::note_local_decl_close_param_match)
7546         << Idx << FDParam->getType()
7547         << NewFD->getParamDecl(Idx - 1)->getType();
7548     } else if (FDisConst != NewFDisConst) {
7549       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7550           << NewFDisConst << FD->getSourceRange().getEnd();
7551     } else
7552       SemaRef.Diag(FD->getLocation(),
7553                    IsMember ? diag::note_member_def_close_match
7554                             : diag::note_local_decl_close_match);
7555   }
7556   return nullptr;
7557 }
7558
7559 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7560   switch (D.getDeclSpec().getStorageClassSpec()) {
7561   default: llvm_unreachable("Unknown storage class!");
7562   case DeclSpec::SCS_auto:
7563   case DeclSpec::SCS_register:
7564   case DeclSpec::SCS_mutable:
7565     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7566                  diag::err_typecheck_sclass_func);
7567     D.getMutableDeclSpec().ClearStorageClassSpecs();
7568     D.setInvalidType();
7569     break;
7570   case DeclSpec::SCS_unspecified: break;
7571   case DeclSpec::SCS_extern:
7572     if (D.getDeclSpec().isExternInLinkageSpec())
7573       return SC_None;
7574     return SC_Extern;
7575   case DeclSpec::SCS_static: {
7576     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7577       // C99 6.7.1p5:
7578       //   The declaration of an identifier for a function that has
7579       //   block scope shall have no explicit storage-class specifier
7580       //   other than extern
7581       // See also (C++ [dcl.stc]p4).
7582       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7583                    diag::err_static_block_func);
7584       break;
7585     } else
7586       return SC_Static;
7587   }
7588   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7589   }
7590
7591   // No explicit storage class has already been returned
7592   return SC_None;
7593 }
7594
7595 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7596                                            DeclContext *DC, QualType &R,
7597                                            TypeSourceInfo *TInfo,
7598                                            StorageClass SC,
7599                                            bool &IsVirtualOkay) {
7600   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7601   DeclarationName Name = NameInfo.getName();
7602
7603   FunctionDecl *NewFD = nullptr;
7604   bool isInline = D.getDeclSpec().isInlineSpecified();
7605
7606   if (!SemaRef.getLangOpts().CPlusPlus) {
7607     // Determine whether the function was written with a
7608     // prototype. This true when:
7609     //   - there is a prototype in the declarator, or
7610     //   - the type R of the function is some kind of typedef or other non-
7611     //     attributed reference to a type name (which eventually refers to a
7612     //     function type).
7613     bool HasPrototype =
7614       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7615       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7616
7617     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7618                                  D.getLocStart(), NameInfo, R,
7619                                  TInfo, SC, isInline,
7620                                  HasPrototype, false);
7621     if (D.isInvalidType())
7622       NewFD->setInvalidDecl();
7623
7624     return NewFD;
7625   }
7626
7627   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7628   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7629
7630   // Check that the return type is not an abstract class type.
7631   // For record types, this is done by the AbstractClassUsageDiagnoser once
7632   // the class has been completely parsed.
7633   if (!DC->isRecord() &&
7634       SemaRef.RequireNonAbstractType(
7635           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7636           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7637     D.setInvalidType();
7638
7639   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7640     // This is a C++ constructor declaration.
7641     assert(DC->isRecord() &&
7642            "Constructors can only be declared in a member context");
7643
7644     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7645     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7646                                       D.getLocStart(), NameInfo,
7647                                       R, TInfo, isExplicit, isInline,
7648                                       /*isImplicitlyDeclared=*/false,
7649                                       isConstexpr);
7650
7651   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7652     // This is a C++ destructor declaration.
7653     if (DC->isRecord()) {
7654       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7655       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7656       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7657                                         SemaRef.Context, Record,
7658                                         D.getLocStart(),
7659                                         NameInfo, R, TInfo, isInline,
7660                                         /*isImplicitlyDeclared=*/false);
7661
7662       // If the class is complete, then we now create the implicit exception
7663       // specification. If the class is incomplete or dependent, we can't do
7664       // it yet.
7665       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7666           Record->getDefinition() && !Record->isBeingDefined() &&
7667           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7668         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7669       }
7670
7671       IsVirtualOkay = true;
7672       return NewDD;
7673
7674     } else {
7675       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7676       D.setInvalidType();
7677
7678       // Create a FunctionDecl to satisfy the function definition parsing
7679       // code path.
7680       return FunctionDecl::Create(SemaRef.Context, DC,
7681                                   D.getLocStart(),
7682                                   D.getIdentifierLoc(), Name, R, TInfo,
7683                                   SC, isInline,
7684                                   /*hasPrototype=*/true, isConstexpr);
7685     }
7686
7687   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7688     if (!DC->isRecord()) {
7689       SemaRef.Diag(D.getIdentifierLoc(),
7690            diag::err_conv_function_not_member);
7691       return nullptr;
7692     }
7693
7694     SemaRef.CheckConversionDeclarator(D, R, SC);
7695     IsVirtualOkay = true;
7696     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7697                                      D.getLocStart(), NameInfo,
7698                                      R, TInfo, isInline, isExplicit,
7699                                      isConstexpr, SourceLocation());
7700
7701   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7702     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7703
7704     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7705                                          isExplicit, NameInfo, R, TInfo,
7706                                          D.getLocEnd());
7707   } else if (DC->isRecord()) {
7708     // If the name of the function is the same as the name of the record,
7709     // then this must be an invalid constructor that has a return type.
7710     // (The parser checks for a return type and makes the declarator a
7711     // constructor if it has no return type).
7712     if (Name.getAsIdentifierInfo() &&
7713         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7714       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7715         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7716         << SourceRange(D.getIdentifierLoc());
7717       return nullptr;
7718     }
7719
7720     // This is a C++ method declaration.
7721     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7722                                                cast<CXXRecordDecl>(DC),
7723                                                D.getLocStart(), NameInfo, R,
7724                                                TInfo, SC, isInline,
7725                                                isConstexpr, SourceLocation());
7726     IsVirtualOkay = !Ret->isStatic();
7727     return Ret;
7728   } else {
7729     bool isFriend =
7730         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7731     if (!isFriend && SemaRef.CurContext->isRecord())
7732       return nullptr;
7733
7734     // Determine whether the function was written with a
7735     // prototype. This true when:
7736     //   - we're in C++ (where every function has a prototype),
7737     return FunctionDecl::Create(SemaRef.Context, DC,
7738                                 D.getLocStart(),
7739                                 NameInfo, R, TInfo, SC, isInline,
7740                                 true/*HasPrototype*/, isConstexpr);
7741   }
7742 }
7743
7744 enum OpenCLParamType {
7745   ValidKernelParam,
7746   PtrPtrKernelParam,
7747   PtrKernelParam,
7748   InvalidAddrSpacePtrKernelParam,
7749   InvalidKernelParam,
7750   RecordKernelParam
7751 };
7752
7753 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7754   if (PT->isPointerType()) {
7755     QualType PointeeType = PT->getPointeeType();
7756     if (PointeeType->isPointerType())
7757       return PtrPtrKernelParam;
7758     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7759         PointeeType.getAddressSpace() == 0)
7760       return InvalidAddrSpacePtrKernelParam;
7761     return PtrKernelParam;
7762   }
7763
7764   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7765   // be used as builtin types.
7766
7767   if (PT->isImageType())
7768     return PtrKernelParam;
7769
7770   if (PT->isBooleanType())
7771     return InvalidKernelParam;
7772
7773   if (PT->isEventT())
7774     return InvalidKernelParam;
7775
7776   // OpenCL extension spec v1.2 s9.5:
7777   // This extension adds support for half scalar and vector types as built-in
7778   // types that can be used for arithmetic operations, conversions etc.
7779   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7780     return InvalidKernelParam;
7781
7782   if (PT->isRecordType())
7783     return RecordKernelParam;
7784
7785   return ValidKernelParam;
7786 }
7787
7788 static void checkIsValidOpenCLKernelParameter(
7789   Sema &S,
7790   Declarator &D,
7791   ParmVarDecl *Param,
7792   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7793   QualType PT = Param->getType();
7794
7795   // Cache the valid types we encounter to avoid rechecking structs that are
7796   // used again
7797   if (ValidTypes.count(PT.getTypePtr()))
7798     return;
7799
7800   switch (getOpenCLKernelParameterType(S, PT)) {
7801   case PtrPtrKernelParam:
7802     // OpenCL v1.2 s6.9.a:
7803     // A kernel function argument cannot be declared as a
7804     // pointer to a pointer type.
7805     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7806     D.setInvalidType();
7807     return;
7808
7809   case InvalidAddrSpacePtrKernelParam:
7810     // OpenCL v1.0 s6.5:
7811     // __kernel function arguments declared to be a pointer of a type can point
7812     // to one of the following address spaces only : __global, __local or
7813     // __constant.
7814     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
7815     D.setInvalidType();
7816     return;
7817
7818     // OpenCL v1.2 s6.9.k:
7819     // Arguments to kernel functions in a program cannot be declared with the
7820     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7821     // uintptr_t or a struct and/or union that contain fields declared to be
7822     // one of these built-in scalar types.
7823
7824   case InvalidKernelParam:
7825     // OpenCL v1.2 s6.8 n:
7826     // A kernel function argument cannot be declared
7827     // of event_t type.
7828     // Do not diagnose half type since it is diagnosed as invalid argument
7829     // type for any function elsewhere.
7830     if (!PT->isHalfType())
7831       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7832     D.setInvalidType();
7833     return;
7834
7835   case PtrKernelParam:
7836   case ValidKernelParam:
7837     ValidTypes.insert(PT.getTypePtr());
7838     return;
7839
7840   case RecordKernelParam:
7841     break;
7842   }
7843
7844   // Track nested structs we will inspect
7845   SmallVector<const Decl *, 4> VisitStack;
7846
7847   // Track where we are in the nested structs. Items will migrate from
7848   // VisitStack to HistoryStack as we do the DFS for bad field.
7849   SmallVector<const FieldDecl *, 4> HistoryStack;
7850   HistoryStack.push_back(nullptr);
7851
7852   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7853   VisitStack.push_back(PD);
7854
7855   assert(VisitStack.back() && "First decl null?");
7856
7857   do {
7858     const Decl *Next = VisitStack.pop_back_val();
7859     if (!Next) {
7860       assert(!HistoryStack.empty());
7861       // Found a marker, we have gone up a level
7862       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7863         ValidTypes.insert(Hist->getType().getTypePtr());
7864
7865       continue;
7866     }
7867
7868     // Adds everything except the original parameter declaration (which is not a
7869     // field itself) to the history stack.
7870     const RecordDecl *RD;
7871     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7872       HistoryStack.push_back(Field);
7873       RD = Field->getType()->castAs<RecordType>()->getDecl();
7874     } else {
7875       RD = cast<RecordDecl>(Next);
7876     }
7877
7878     // Add a null marker so we know when we've gone back up a level
7879     VisitStack.push_back(nullptr);
7880
7881     for (const auto *FD : RD->fields()) {
7882       QualType QT = FD->getType();
7883
7884       if (ValidTypes.count(QT.getTypePtr()))
7885         continue;
7886
7887       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
7888       if (ParamType == ValidKernelParam)
7889         continue;
7890
7891       if (ParamType == RecordKernelParam) {
7892         VisitStack.push_back(FD);
7893         continue;
7894       }
7895
7896       // OpenCL v1.2 s6.9.p:
7897       // Arguments to kernel functions that are declared to be a struct or union
7898       // do not allow OpenCL objects to be passed as elements of the struct or
7899       // union.
7900       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7901           ParamType == InvalidAddrSpacePtrKernelParam) {
7902         S.Diag(Param->getLocation(),
7903                diag::err_record_with_pointers_kernel_param)
7904           << PT->isUnionType()
7905           << PT;
7906       } else {
7907         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7908       }
7909
7910       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7911         << PD->getDeclName();
7912
7913       // We have an error, now let's go back up through history and show where
7914       // the offending field came from
7915       for (ArrayRef<const FieldDecl *>::const_iterator
7916                I = HistoryStack.begin() + 1,
7917                E = HistoryStack.end();
7918            I != E; ++I) {
7919         const FieldDecl *OuterField = *I;
7920         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7921           << OuterField->getType();
7922       }
7923
7924       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7925         << QT->isPointerType()
7926         << QT;
7927       D.setInvalidType();
7928       return;
7929     }
7930   } while (!VisitStack.empty());
7931 }
7932
7933 /// Find the DeclContext in which a tag is implicitly declared if we see an
7934 /// elaborated type specifier in the specified context, and lookup finds
7935 /// nothing.
7936 static DeclContext *getTagInjectionContext(DeclContext *DC) {
7937   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
7938     DC = DC->getParent();
7939   return DC;
7940 }
7941
7942 /// Find the Scope in which a tag is implicitly declared if we see an
7943 /// elaborated type specifier in the specified context, and lookup finds
7944 /// nothing.
7945 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
7946   while (S->isClassScope() ||
7947          (LangOpts.CPlusPlus &&
7948           S->isFunctionPrototypeScope()) ||
7949          ((S->getFlags() & Scope::DeclScope) == 0) ||
7950          (S->getEntity() && S->getEntity()->isTransparentContext()))
7951     S = S->getParent();
7952   return S;
7953 }
7954
7955 NamedDecl*
7956 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7957                               TypeSourceInfo *TInfo, LookupResult &Previous,
7958                               MultiTemplateParamsArg TemplateParamLists,
7959                               bool &AddToScope) {
7960   QualType R = TInfo->getType();
7961
7962   assert(R.getTypePtr()->isFunctionType());
7963
7964   // TODO: consider using NameInfo for diagnostic.
7965   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7966   DeclarationName Name = NameInfo.getName();
7967   StorageClass SC = getFunctionStorageClass(*this, D);
7968
7969   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7970     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7971          diag::err_invalid_thread)
7972       << DeclSpec::getSpecifierName(TSCS);
7973
7974   if (D.isFirstDeclarationOfMember())
7975     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7976                            D.getIdentifierLoc());
7977
7978   bool isFriend = false;
7979   FunctionTemplateDecl *FunctionTemplate = nullptr;
7980   bool isMemberSpecialization = false;
7981   bool isFunctionTemplateSpecialization = false;
7982
7983   bool isDependentClassScopeExplicitSpecialization = false;
7984   bool HasExplicitTemplateArgs = false;
7985   TemplateArgumentListInfo TemplateArgs;
7986
7987   bool isVirtualOkay = false;
7988
7989   DeclContext *OriginalDC = DC;
7990   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7991
7992   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7993                                               isVirtualOkay);
7994   if (!NewFD) return nullptr;
7995
7996   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7997     NewFD->setTopLevelDeclInObjCContainer();
7998
7999   // Set the lexical context. If this is a function-scope declaration, or has a
8000   // C++ scope specifier, or is the object of a friend declaration, the lexical
8001   // context will be different from the semantic context.
8002   NewFD->setLexicalDeclContext(CurContext);
8003
8004   if (IsLocalExternDecl)
8005     NewFD->setLocalExternDecl();
8006
8007   if (getLangOpts().CPlusPlus) {
8008     bool isInline = D.getDeclSpec().isInlineSpecified();
8009     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8010     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8011     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8012     bool isConcept = D.getDeclSpec().isConceptSpecified();
8013     isFriend = D.getDeclSpec().isFriendSpecified();
8014     if (isFriend && !isInline && D.isFunctionDefinition()) {
8015       // C++ [class.friend]p5
8016       //   A function can be defined in a friend declaration of a
8017       //   class . . . . Such a function is implicitly inline.
8018       NewFD->setImplicitlyInline();
8019     }
8020
8021     // If this is a method defined in an __interface, and is not a constructor
8022     // or an overloaded operator, then set the pure flag (isVirtual will already
8023     // return true).
8024     if (const CXXRecordDecl *Parent =
8025           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8026       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8027         NewFD->setPure(true);
8028
8029       // C++ [class.union]p2
8030       //   A union can have member functions, but not virtual functions.
8031       if (isVirtual && Parent->isUnion())
8032         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8033     }
8034
8035     SetNestedNameSpecifier(NewFD, D);
8036     isMemberSpecialization = false;
8037     isFunctionTemplateSpecialization = false;
8038     if (D.isInvalidType())
8039       NewFD->setInvalidDecl();
8040
8041     // Match up the template parameter lists with the scope specifier, then
8042     // determine whether we have a template or a template specialization.
8043     bool Invalid = false;
8044     if (TemplateParameterList *TemplateParams =
8045             MatchTemplateParametersToScopeSpecifier(
8046                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8047                 D.getCXXScopeSpec(),
8048                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8049                     ? D.getName().TemplateId
8050                     : nullptr,
8051                 TemplateParamLists, isFriend, isMemberSpecialization,
8052                 Invalid)) {
8053       if (TemplateParams->size() > 0) {
8054         // This is a function template
8055
8056         // Check that we can declare a template here.
8057         if (CheckTemplateDeclScope(S, TemplateParams))
8058           NewFD->setInvalidDecl();
8059
8060         // A destructor cannot be a template.
8061         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8062           Diag(NewFD->getLocation(), diag::err_destructor_template);
8063           NewFD->setInvalidDecl();
8064         }
8065
8066         // If we're adding a template to a dependent context, we may need to
8067         // rebuilding some of the types used within the template parameter list,
8068         // now that we know what the current instantiation is.
8069         if (DC->isDependentContext()) {
8070           ContextRAII SavedContext(*this, DC);
8071           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8072             Invalid = true;
8073         }
8074
8075         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8076                                                         NewFD->getLocation(),
8077                                                         Name, TemplateParams,
8078                                                         NewFD);
8079         FunctionTemplate->setLexicalDeclContext(CurContext);
8080         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8081
8082         // For source fidelity, store the other template param lists.
8083         if (TemplateParamLists.size() > 1) {
8084           NewFD->setTemplateParameterListsInfo(Context,
8085                                                TemplateParamLists.drop_back(1));
8086         }
8087       } else {
8088         // This is a function template specialization.
8089         isFunctionTemplateSpecialization = true;
8090         // For source fidelity, store all the template param lists.
8091         if (TemplateParamLists.size() > 0)
8092           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8093
8094         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8095         if (isFriend) {
8096           // We want to remove the "template<>", found here.
8097           SourceRange RemoveRange = TemplateParams->getSourceRange();
8098
8099           // If we remove the template<> and the name is not a
8100           // template-id, we're actually silently creating a problem:
8101           // the friend declaration will refer to an untemplated decl,
8102           // and clearly the user wants a template specialization.  So
8103           // we need to insert '<>' after the name.
8104           SourceLocation InsertLoc;
8105           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8106             InsertLoc = D.getName().getSourceRange().getEnd();
8107             InsertLoc = getLocForEndOfToken(InsertLoc);
8108           }
8109
8110           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8111             << Name << RemoveRange
8112             << FixItHint::CreateRemoval(RemoveRange)
8113             << FixItHint::CreateInsertion(InsertLoc, "<>");
8114         }
8115       }
8116     }
8117     else {
8118       // All template param lists were matched against the scope specifier:
8119       // this is NOT (an explicit specialization of) a template.
8120       if (TemplateParamLists.size() > 0)
8121         // For source fidelity, store all the template param lists.
8122         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8123     }
8124
8125     if (Invalid) {
8126       NewFD->setInvalidDecl();
8127       if (FunctionTemplate)
8128         FunctionTemplate->setInvalidDecl();
8129     }
8130
8131     // C++ [dcl.fct.spec]p5:
8132     //   The virtual specifier shall only be used in declarations of
8133     //   nonstatic class member functions that appear within a
8134     //   member-specification of a class declaration; see 10.3.
8135     //
8136     if (isVirtual && !NewFD->isInvalidDecl()) {
8137       if (!isVirtualOkay) {
8138         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8139              diag::err_virtual_non_function);
8140       } else if (!CurContext->isRecord()) {
8141         // 'virtual' was specified outside of the class.
8142         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8143              diag::err_virtual_out_of_class)
8144           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8145       } else if (NewFD->getDescribedFunctionTemplate()) {
8146         // C++ [temp.mem]p3:
8147         //  A member function template shall not be virtual.
8148         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8149              diag::err_virtual_member_function_template)
8150           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8151       } else {
8152         // Okay: Add virtual to the method.
8153         NewFD->setVirtualAsWritten(true);
8154       }
8155
8156       if (getLangOpts().CPlusPlus14 &&
8157           NewFD->getReturnType()->isUndeducedType())
8158         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8159     }
8160
8161     if (getLangOpts().CPlusPlus14 &&
8162         (NewFD->isDependentContext() ||
8163          (isFriend && CurContext->isDependentContext())) &&
8164         NewFD->getReturnType()->isUndeducedType()) {
8165       // If the function template is referenced directly (for instance, as a
8166       // member of the current instantiation), pretend it has a dependent type.
8167       // This is not really justified by the standard, but is the only sane
8168       // thing to do.
8169       // FIXME: For a friend function, we have not marked the function as being
8170       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8171       const FunctionProtoType *FPT =
8172           NewFD->getType()->castAs<FunctionProtoType>();
8173       QualType Result =
8174           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8175       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8176                                              FPT->getExtProtoInfo()));
8177     }
8178
8179     // C++ [dcl.fct.spec]p3:
8180     //  The inline specifier shall not appear on a block scope function
8181     //  declaration.
8182     if (isInline && !NewFD->isInvalidDecl()) {
8183       if (CurContext->isFunctionOrMethod()) {
8184         // 'inline' is not allowed on block scope function declaration.
8185         Diag(D.getDeclSpec().getInlineSpecLoc(),
8186              diag::err_inline_declaration_block_scope) << Name
8187           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8188       }
8189     }
8190
8191     // C++ [dcl.fct.spec]p6:
8192     //  The explicit specifier shall be used only in the declaration of a
8193     //  constructor or conversion function within its class definition;
8194     //  see 12.3.1 and 12.3.2.
8195     if (isExplicit && !NewFD->isInvalidDecl() &&
8196         !isa<CXXDeductionGuideDecl>(NewFD)) {
8197       if (!CurContext->isRecord()) {
8198         // 'explicit' was specified outside of the class.
8199         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8200              diag::err_explicit_out_of_class)
8201           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8202       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8203                  !isa<CXXConversionDecl>(NewFD)) {
8204         // 'explicit' was specified on a function that wasn't a constructor
8205         // or conversion function.
8206         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8207              diag::err_explicit_non_ctor_or_conv_function)
8208           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8209       }
8210     }
8211
8212     if (isConstexpr) {
8213       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8214       // are implicitly inline.
8215       NewFD->setImplicitlyInline();
8216
8217       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8218       // be either constructors or to return a literal type. Therefore,
8219       // destructors cannot be declared constexpr.
8220       if (isa<CXXDestructorDecl>(NewFD))
8221         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8222     }
8223
8224     if (isConcept) {
8225       // This is a function concept.
8226       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8227         FTD->setConcept();
8228
8229       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8230       // applied only to the definition of a function template [...]
8231       if (!D.isFunctionDefinition()) {
8232         Diag(D.getDeclSpec().getConceptSpecLoc(),
8233              diag::err_function_concept_not_defined);
8234         NewFD->setInvalidDecl();
8235       }
8236
8237       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8238       // have no exception-specification and is treated as if it were specified
8239       // with noexcept(true) (15.4). [...]
8240       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8241         if (FPT->hasExceptionSpec()) {
8242           SourceRange Range;
8243           if (D.isFunctionDeclarator())
8244             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8245           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8246               << FixItHint::CreateRemoval(Range);
8247           NewFD->setInvalidDecl();
8248         } else {
8249           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8250         }
8251
8252         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8253         // following restrictions:
8254         // - The declared return type shall have the type bool.
8255         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8256           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8257           NewFD->setInvalidDecl();
8258         }
8259
8260         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8261         // following restrictions:
8262         // - The declaration's parameter list shall be equivalent to an empty
8263         //   parameter list.
8264         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8265           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8266       }
8267
8268       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8269       // implicity defined to be a constexpr declaration (implicitly inline)
8270       NewFD->setImplicitlyInline();
8271
8272       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8273       // be declared with the thread_local, inline, friend, or constexpr
8274       // specifiers, [...]
8275       if (isInline) {
8276         Diag(D.getDeclSpec().getInlineSpecLoc(),
8277              diag::err_concept_decl_invalid_specifiers)
8278             << 1 << 1;
8279         NewFD->setInvalidDecl(true);
8280       }
8281
8282       if (isFriend) {
8283         Diag(D.getDeclSpec().getFriendSpecLoc(),
8284              diag::err_concept_decl_invalid_specifiers)
8285             << 1 << 2;
8286         NewFD->setInvalidDecl(true);
8287       }
8288
8289       if (isConstexpr) {
8290         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8291              diag::err_concept_decl_invalid_specifiers)
8292             << 1 << 3;
8293         NewFD->setInvalidDecl(true);
8294       }
8295
8296       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8297       // applied only to the definition of a function template or variable
8298       // template, declared in namespace scope.
8299       if (isFunctionTemplateSpecialization) {
8300         Diag(D.getDeclSpec().getConceptSpecLoc(),
8301              diag::err_concept_specified_specialization) << 1;
8302         NewFD->setInvalidDecl(true);
8303         return NewFD;
8304       }
8305     }
8306
8307     // If __module_private__ was specified, mark the function accordingly.
8308     if (D.getDeclSpec().isModulePrivateSpecified()) {
8309       if (isFunctionTemplateSpecialization) {
8310         SourceLocation ModulePrivateLoc
8311           = D.getDeclSpec().getModulePrivateSpecLoc();
8312         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8313           << 0
8314           << FixItHint::CreateRemoval(ModulePrivateLoc);
8315       } else {
8316         NewFD->setModulePrivate();
8317         if (FunctionTemplate)
8318           FunctionTemplate->setModulePrivate();
8319       }
8320     }
8321
8322     if (isFriend) {
8323       if (FunctionTemplate) {
8324         FunctionTemplate->setObjectOfFriendDecl();
8325         FunctionTemplate->setAccess(AS_public);
8326       }
8327       NewFD->setObjectOfFriendDecl();
8328       NewFD->setAccess(AS_public);
8329     }
8330
8331     // If a function is defined as defaulted or deleted, mark it as such now.
8332     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8333     // definition kind to FDK_Definition.
8334     switch (D.getFunctionDefinitionKind()) {
8335       case FDK_Declaration:
8336       case FDK_Definition:
8337         break;
8338
8339       case FDK_Defaulted:
8340         NewFD->setDefaulted();
8341         break;
8342
8343       case FDK_Deleted:
8344         NewFD->setDeletedAsWritten();
8345         break;
8346     }
8347
8348     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8349         D.isFunctionDefinition()) {
8350       // C++ [class.mfct]p2:
8351       //   A member function may be defined (8.4) in its class definition, in
8352       //   which case it is an inline member function (7.1.2)
8353       NewFD->setImplicitlyInline();
8354     }
8355
8356     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8357         !CurContext->isRecord()) {
8358       // C++ [class.static]p1:
8359       //   A data or function member of a class may be declared static
8360       //   in a class definition, in which case it is a static member of
8361       //   the class.
8362
8363       // Complain about the 'static' specifier if it's on an out-of-line
8364       // member function definition.
8365       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8366            diag::err_static_out_of_line)
8367         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8368     }
8369
8370     // C++11 [except.spec]p15:
8371     //   A deallocation function with no exception-specification is treated
8372     //   as if it were specified with noexcept(true).
8373     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8374     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8375          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8376         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8377       NewFD->setType(Context.getFunctionType(
8378           FPT->getReturnType(), FPT->getParamTypes(),
8379           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8380   }
8381
8382   // Filter out previous declarations that don't match the scope.
8383   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8384                        D.getCXXScopeSpec().isNotEmpty() ||
8385                        isMemberSpecialization ||
8386                        isFunctionTemplateSpecialization);
8387
8388   // Handle GNU asm-label extension (encoded as an attribute).
8389   if (Expr *E = (Expr*) D.getAsmLabel()) {
8390     // The parser guarantees this is a string.
8391     StringLiteral *SE = cast<StringLiteral>(E);
8392     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8393                                                 SE->getString(), 0));
8394   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8395     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8396       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8397     if (I != ExtnameUndeclaredIdentifiers.end()) {
8398       if (isDeclExternC(NewFD)) {
8399         NewFD->addAttr(I->second);
8400         ExtnameUndeclaredIdentifiers.erase(I);
8401       } else
8402         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8403             << /*Variable*/0 << NewFD;
8404     }
8405   }
8406
8407   // Copy the parameter declarations from the declarator D to the function
8408   // declaration NewFD, if they are available.  First scavenge them into Params.
8409   SmallVector<ParmVarDecl*, 16> Params;
8410   unsigned FTIIdx;
8411   if (D.isFunctionDeclarator(FTIIdx)) {
8412     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8413
8414     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8415     // function that takes no arguments, not a function that takes a
8416     // single void argument.
8417     // We let through "const void" here because Sema::GetTypeForDeclarator
8418     // already checks for that case.
8419     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8420       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8421         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8422         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8423         Param->setDeclContext(NewFD);
8424         Params.push_back(Param);
8425
8426         if (Param->isInvalidDecl())
8427           NewFD->setInvalidDecl();
8428       }
8429     }
8430
8431     if (!getLangOpts().CPlusPlus) {
8432       // In C, find all the tag declarations from the prototype and move them
8433       // into the function DeclContext. Remove them from the surrounding tag
8434       // injection context of the function, which is typically but not always
8435       // the TU.
8436       DeclContext *PrototypeTagContext =
8437           getTagInjectionContext(NewFD->getLexicalDeclContext());
8438       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8439         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8440
8441         // We don't want to reparent enumerators. Look at their parent enum
8442         // instead.
8443         if (!TD) {
8444           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8445             TD = cast<EnumDecl>(ECD->getDeclContext());
8446         }
8447         if (!TD)
8448           continue;
8449         DeclContext *TagDC = TD->getLexicalDeclContext();
8450         if (!TagDC->containsDecl(TD))
8451           continue;
8452         TagDC->removeDecl(TD);
8453         TD->setDeclContext(NewFD);
8454         NewFD->addDecl(TD);
8455
8456         // Preserve the lexical DeclContext if it is not the surrounding tag
8457         // injection context of the FD. In this example, the semantic context of
8458         // E will be f and the lexical context will be S, while both the
8459         // semantic and lexical contexts of S will be f:
8460         //   void f(struct S { enum E { a } f; } s);
8461         if (TagDC != PrototypeTagContext)
8462           TD->setLexicalDeclContext(TagDC);
8463       }
8464     }
8465   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8466     // When we're declaring a function with a typedef, typeof, etc as in the
8467     // following example, we'll need to synthesize (unnamed)
8468     // parameters for use in the declaration.
8469     //
8470     // @code
8471     // typedef void fn(int);
8472     // fn f;
8473     // @endcode
8474
8475     // Synthesize a parameter for each argument type.
8476     for (const auto &AI : FT->param_types()) {
8477       ParmVarDecl *Param =
8478           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8479       Param->setScopeInfo(0, Params.size());
8480       Params.push_back(Param);
8481     }
8482   } else {
8483     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8484            "Should not need args for typedef of non-prototype fn");
8485   }
8486
8487   // Finally, we know we have the right number of parameters, install them.
8488   NewFD->setParams(Params);
8489
8490   if (D.getDeclSpec().isNoreturnSpecified())
8491     NewFD->addAttr(
8492         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8493                                        Context, 0));
8494
8495   // Functions returning a variably modified type violate C99 6.7.5.2p2
8496   // because all functions have linkage.
8497   if (!NewFD->isInvalidDecl() &&
8498       NewFD->getReturnType()->isVariablyModifiedType()) {
8499     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8500     NewFD->setInvalidDecl();
8501   }
8502
8503   // Apply an implicit SectionAttr if #pragma code_seg is active.
8504   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8505       !NewFD->hasAttr<SectionAttr>()) {
8506     NewFD->addAttr(
8507         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8508                                     CodeSegStack.CurrentValue->getString(),
8509                                     CodeSegStack.CurrentPragmaLocation));
8510     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8511                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8512                          ASTContext::PSF_Read,
8513                      NewFD))
8514       NewFD->dropAttr<SectionAttr>();
8515   }
8516
8517   // Handle attributes.
8518   ProcessDeclAttributes(S, NewFD, D);
8519
8520   if (getLangOpts().OpenCL) {
8521     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8522     // type declaration will generate a compilation error.
8523     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8524     if (AddressSpace == LangAS::opencl_local ||
8525         AddressSpace == LangAS::opencl_global ||
8526         AddressSpace == LangAS::opencl_constant) {
8527       Diag(NewFD->getLocation(),
8528            diag::err_opencl_return_value_with_address_space);
8529       NewFD->setInvalidDecl();
8530     }
8531   }
8532
8533   if (!getLangOpts().CPlusPlus) {
8534     // Perform semantic checking on the function declaration.
8535     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8536       CheckMain(NewFD, D.getDeclSpec());
8537
8538     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8539       CheckMSVCRTEntryPoint(NewFD);
8540
8541     if (!NewFD->isInvalidDecl())
8542       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8543                                                   isMemberSpecialization));
8544     else if (!Previous.empty())
8545       // Recover gracefully from an invalid redeclaration.
8546       D.setRedeclaration(true);
8547     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8548             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8549            "previous declaration set still overloaded");
8550
8551     // Diagnose no-prototype function declarations with calling conventions that
8552     // don't support variadic calls. Only do this in C and do it after merging
8553     // possibly prototyped redeclarations.
8554     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8555     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8556       CallingConv CC = FT->getExtInfo().getCC();
8557       if (!supportsVariadicCall(CC)) {
8558         // Windows system headers sometimes accidentally use stdcall without
8559         // (void) parameters, so we relax this to a warning.
8560         int DiagID =
8561             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8562         Diag(NewFD->getLocation(), DiagID)
8563             << FunctionType::getNameForCallConv(CC);
8564       }
8565     }
8566   } else {
8567     // C++11 [replacement.functions]p3:
8568     //  The program's definitions shall not be specified as inline.
8569     //
8570     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8571     //
8572     // Suppress the diagnostic if the function is __attribute__((used)), since
8573     // that forces an external definition to be emitted.
8574     if (D.getDeclSpec().isInlineSpecified() &&
8575         NewFD->isReplaceableGlobalAllocationFunction() &&
8576         !NewFD->hasAttr<UsedAttr>())
8577       Diag(D.getDeclSpec().getInlineSpecLoc(),
8578            diag::ext_operator_new_delete_declared_inline)
8579         << NewFD->getDeclName();
8580
8581     // If the declarator is a template-id, translate the parser's template
8582     // argument list into our AST format.
8583     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8584       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8585       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8586       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8587       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8588                                          TemplateId->NumArgs);
8589       translateTemplateArguments(TemplateArgsPtr,
8590                                  TemplateArgs);
8591
8592       HasExplicitTemplateArgs = true;
8593
8594       if (NewFD->isInvalidDecl()) {
8595         HasExplicitTemplateArgs = false;
8596       } else if (FunctionTemplate) {
8597         // Function template with explicit template arguments.
8598         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8599           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8600
8601         HasExplicitTemplateArgs = false;
8602       } else {
8603         assert((isFunctionTemplateSpecialization ||
8604                 D.getDeclSpec().isFriendSpecified()) &&
8605                "should have a 'template<>' for this decl");
8606         // "friend void foo<>(int);" is an implicit specialization decl.
8607         isFunctionTemplateSpecialization = true;
8608       }
8609     } else if (isFriend && isFunctionTemplateSpecialization) {
8610       // This combination is only possible in a recovery case;  the user
8611       // wrote something like:
8612       //   template <> friend void foo(int);
8613       // which we're recovering from as if the user had written:
8614       //   friend void foo<>(int);
8615       // Go ahead and fake up a template id.
8616       HasExplicitTemplateArgs = true;
8617       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8618       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8619     }
8620
8621     // We do not add HD attributes to specializations here because
8622     // they may have different constexpr-ness compared to their
8623     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8624     // may end up with different effective targets. Instead, a
8625     // specialization inherits its target attributes from its template
8626     // in the CheckFunctionTemplateSpecialization() call below.
8627     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8628       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8629
8630     // If it's a friend (and only if it's a friend), it's possible
8631     // that either the specialized function type or the specialized
8632     // template is dependent, and therefore matching will fail.  In
8633     // this case, don't check the specialization yet.
8634     bool InstantiationDependent = false;
8635     if (isFunctionTemplateSpecialization && isFriend &&
8636         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8637          TemplateSpecializationType::anyDependentTemplateArguments(
8638             TemplateArgs,
8639             InstantiationDependent))) {
8640       assert(HasExplicitTemplateArgs &&
8641              "friend function specialization without template args");
8642       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8643                                                        Previous))
8644         NewFD->setInvalidDecl();
8645     } else if (isFunctionTemplateSpecialization) {
8646       if (CurContext->isDependentContext() && CurContext->isRecord()
8647           && !isFriend) {
8648         isDependentClassScopeExplicitSpecialization = true;
8649         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8650           diag::ext_function_specialization_in_class :
8651           diag::err_function_specialization_in_class)
8652           << NewFD->getDeclName();
8653       } else if (CheckFunctionTemplateSpecialization(NewFD,
8654                                   (HasExplicitTemplateArgs ? &TemplateArgs
8655                                                            : nullptr),
8656                                                      Previous))
8657         NewFD->setInvalidDecl();
8658
8659       // C++ [dcl.stc]p1:
8660       //   A storage-class-specifier shall not be specified in an explicit
8661       //   specialization (14.7.3)
8662       FunctionTemplateSpecializationInfo *Info =
8663           NewFD->getTemplateSpecializationInfo();
8664       if (Info && SC != SC_None) {
8665         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8666           Diag(NewFD->getLocation(),
8667                diag::err_explicit_specialization_inconsistent_storage_class)
8668             << SC
8669             << FixItHint::CreateRemoval(
8670                                       D.getDeclSpec().getStorageClassSpecLoc());
8671
8672         else
8673           Diag(NewFD->getLocation(),
8674                diag::ext_explicit_specialization_storage_class)
8675             << FixItHint::CreateRemoval(
8676                                       D.getDeclSpec().getStorageClassSpecLoc());
8677       }
8678     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8679       if (CheckMemberSpecialization(NewFD, Previous))
8680           NewFD->setInvalidDecl();
8681     }
8682
8683     // Perform semantic checking on the function declaration.
8684     if (!isDependentClassScopeExplicitSpecialization) {
8685       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8686         CheckMain(NewFD, D.getDeclSpec());
8687
8688       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8689         CheckMSVCRTEntryPoint(NewFD);
8690
8691       if (!NewFD->isInvalidDecl())
8692         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8693                                                     isMemberSpecialization));
8694       else if (!Previous.empty())
8695         // Recover gracefully from an invalid redeclaration.
8696         D.setRedeclaration(true);
8697     }
8698
8699     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8700             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8701            "previous declaration set still overloaded");
8702
8703     NamedDecl *PrincipalDecl = (FunctionTemplate
8704                                 ? cast<NamedDecl>(FunctionTemplate)
8705                                 : NewFD);
8706
8707     if (isFriend && NewFD->getPreviousDecl()) {
8708       AccessSpecifier Access = AS_public;
8709       if (!NewFD->isInvalidDecl())
8710         Access = NewFD->getPreviousDecl()->getAccess();
8711
8712       NewFD->setAccess(Access);
8713       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8714     }
8715
8716     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8717         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8718       PrincipalDecl->setNonMemberOperator();
8719
8720     // If we have a function template, check the template parameter
8721     // list. This will check and merge default template arguments.
8722     if (FunctionTemplate) {
8723       FunctionTemplateDecl *PrevTemplate =
8724                                      FunctionTemplate->getPreviousDecl();
8725       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8726                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8727                                     : nullptr,
8728                             D.getDeclSpec().isFriendSpecified()
8729                               ? (D.isFunctionDefinition()
8730                                    ? TPC_FriendFunctionTemplateDefinition
8731                                    : TPC_FriendFunctionTemplate)
8732                               : (D.getCXXScopeSpec().isSet() &&
8733                                  DC && DC->isRecord() &&
8734                                  DC->isDependentContext())
8735                                   ? TPC_ClassTemplateMember
8736                                   : TPC_FunctionTemplate);
8737     }
8738
8739     if (NewFD->isInvalidDecl()) {
8740       // Ignore all the rest of this.
8741     } else if (!D.isRedeclaration()) {
8742       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8743                                        AddToScope };
8744       // Fake up an access specifier if it's supposed to be a class member.
8745       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8746         NewFD->setAccess(AS_public);
8747
8748       // Qualified decls generally require a previous declaration.
8749       if (D.getCXXScopeSpec().isSet()) {
8750         // ...with the major exception of templated-scope or
8751         // dependent-scope friend declarations.
8752
8753         // TODO: we currently also suppress this check in dependent
8754         // contexts because (1) the parameter depth will be off when
8755         // matching friend templates and (2) we might actually be
8756         // selecting a friend based on a dependent factor.  But there
8757         // are situations where these conditions don't apply and we
8758         // can actually do this check immediately.
8759         if (isFriend &&
8760             (TemplateParamLists.size() ||
8761              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8762              CurContext->isDependentContext())) {
8763           // ignore these
8764         } else {
8765           // The user tried to provide an out-of-line definition for a
8766           // function that is a member of a class or namespace, but there
8767           // was no such member function declared (C++ [class.mfct]p2,
8768           // C++ [namespace.memdef]p2). For example:
8769           //
8770           // class X {
8771           //   void f() const;
8772           // };
8773           //
8774           // void X::f() { } // ill-formed
8775           //
8776           // Complain about this problem, and attempt to suggest close
8777           // matches (e.g., those that differ only in cv-qualifiers and
8778           // whether the parameter types are references).
8779
8780           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8781                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8782             AddToScope = ExtraArgs.AddToScope;
8783             return Result;
8784           }
8785         }
8786
8787         // Unqualified local friend declarations are required to resolve
8788         // to something.
8789       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8790         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8791                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8792           AddToScope = ExtraArgs.AddToScope;
8793           return Result;
8794         }
8795       }
8796     } else if (!D.isFunctionDefinition() &&
8797                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8798                !isFriend && !isFunctionTemplateSpecialization &&
8799                !isMemberSpecialization) {
8800       // An out-of-line member function declaration must also be a
8801       // definition (C++ [class.mfct]p2).
8802       // Note that this is not the case for explicit specializations of
8803       // function templates or member functions of class templates, per
8804       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8805       // extension for compatibility with old SWIG code which likes to
8806       // generate them.
8807       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8808         << D.getCXXScopeSpec().getRange();
8809     }
8810   }
8811
8812   ProcessPragmaWeak(S, NewFD);
8813   checkAttributesAfterMerging(*this, *NewFD);
8814
8815   AddKnownFunctionAttributes(NewFD);
8816
8817   if (NewFD->hasAttr<OverloadableAttr>() &&
8818       !NewFD->getType()->getAs<FunctionProtoType>()) {
8819     Diag(NewFD->getLocation(),
8820          diag::err_attribute_overloadable_no_prototype)
8821       << NewFD;
8822
8823     // Turn this into a variadic function with no parameters.
8824     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8825     FunctionProtoType::ExtProtoInfo EPI(
8826         Context.getDefaultCallingConvention(true, false));
8827     EPI.Variadic = true;
8828     EPI.ExtInfo = FT->getExtInfo();
8829
8830     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8831     NewFD->setType(R);
8832   }
8833
8834   // If there's a #pragma GCC visibility in scope, and this isn't a class
8835   // member, set the visibility of this function.
8836   if (!DC->isRecord() && NewFD->isExternallyVisible())
8837     AddPushedVisibilityAttribute(NewFD);
8838
8839   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8840   // marking the function.
8841   AddCFAuditedAttribute(NewFD);
8842
8843   // If this is a function definition, check if we have to apply optnone due to
8844   // a pragma.
8845   if(D.isFunctionDefinition())
8846     AddRangeBasedOptnone(NewFD);
8847
8848   // If this is the first declaration of an extern C variable, update
8849   // the map of such variables.
8850   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8851       isIncompleteDeclExternC(*this, NewFD))
8852     RegisterLocallyScopedExternCDecl(NewFD, S);
8853
8854   // Set this FunctionDecl's range up to the right paren.
8855   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8856
8857   if (D.isRedeclaration() && !Previous.empty()) {
8858     checkDLLAttributeRedeclaration(
8859         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8860         isMemberSpecialization || isFunctionTemplateSpecialization,
8861         D.isFunctionDefinition());
8862   }
8863
8864   if (getLangOpts().CUDA) {
8865     IdentifierInfo *II = NewFD->getIdentifier();
8866     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8867         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8868       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8869         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8870
8871       Context.setcudaConfigureCallDecl(NewFD);
8872     }
8873
8874     // Variadic functions, other than a *declaration* of printf, are not allowed
8875     // in device-side CUDA code, unless someone passed
8876     // -fcuda-allow-variadic-functions.
8877     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8878         (NewFD->hasAttr<CUDADeviceAttr>() ||
8879          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8880         !(II && II->isStr("printf") && NewFD->isExternC() &&
8881           !D.isFunctionDefinition())) {
8882       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8883     }
8884   }
8885
8886   if (getLangOpts().CPlusPlus) {
8887     if (FunctionTemplate) {
8888       if (NewFD->isInvalidDecl())
8889         FunctionTemplate->setInvalidDecl();
8890       return FunctionTemplate;
8891     }
8892   }
8893
8894   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8895     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8896     if ((getLangOpts().OpenCLVersion >= 120)
8897         && (SC == SC_Static)) {
8898       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8899       D.setInvalidType();
8900     }
8901
8902     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8903     if (!NewFD->getReturnType()->isVoidType()) {
8904       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8905       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8906           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8907                                 : FixItHint());
8908       D.setInvalidType();
8909     }
8910
8911     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8912     for (auto Param : NewFD->parameters())
8913       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8914   }
8915   for (const ParmVarDecl *Param : NewFD->parameters()) {
8916     QualType PT = Param->getType();
8917
8918     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8919     // types.
8920     if (getLangOpts().OpenCLVersion >= 200) {
8921       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8922         QualType ElemTy = PipeTy->getElementType();
8923           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8924             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8925             D.setInvalidType();
8926           }
8927       }
8928     }
8929   }
8930
8931   MarkUnusedFileScopedDecl(NewFD);
8932
8933   // Here we have an function template explicit specialization at class scope.
8934   // The actually specialization will be postponed to template instatiation
8935   // time via the ClassScopeFunctionSpecializationDecl node.
8936   if (isDependentClassScopeExplicitSpecialization) {
8937     ClassScopeFunctionSpecializationDecl *NewSpec =
8938                          ClassScopeFunctionSpecializationDecl::Create(
8939                                 Context, CurContext, SourceLocation(),
8940                                 cast<CXXMethodDecl>(NewFD),
8941                                 HasExplicitTemplateArgs, TemplateArgs);
8942     CurContext->addDecl(NewSpec);
8943     AddToScope = false;
8944   }
8945
8946   return NewFD;
8947 }
8948
8949 /// \brief Checks if the new declaration declared in dependent context must be
8950 /// put in the same redeclaration chain as the specified declaration.
8951 ///
8952 /// \param D Declaration that is checked.
8953 /// \param PrevDecl Previous declaration found with proper lookup method for the
8954 ///                 same declaration name.
8955 /// \returns True if D must be added to the redeclaration chain which PrevDecl
8956 ///          belongs to.
8957 ///
8958 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
8959   // Any declarations should be put into redeclaration chains except for
8960   // friend declaration in a dependent context that names a function in
8961   // namespace scope.
8962   //
8963   // This allows to compile code like:
8964   //
8965   //       void func();
8966   //       template<typename T> class C1 { friend void func() { } };
8967   //       template<typename T> class C2 { friend void func() { } };
8968   //
8969   // This code snippet is a valid code unless both templates are instantiated.
8970   return !(D->getLexicalDeclContext()->isDependentContext() &&
8971            D->getDeclContext()->isFileContext() &&
8972            D->getFriendObjectKind() != Decl::FOK_None);
8973 }
8974
8975 /// \brief Perform semantic checking of a new function declaration.
8976 ///
8977 /// Performs semantic analysis of the new function declaration
8978 /// NewFD. This routine performs all semantic checking that does not
8979 /// require the actual declarator involved in the declaration, and is
8980 /// used both for the declaration of functions as they are parsed
8981 /// (called via ActOnDeclarator) and for the declaration of functions
8982 /// that have been instantiated via C++ template instantiation (called
8983 /// via InstantiateDecl).
8984 ///
8985 /// \param IsMemberSpecialization whether this new function declaration is
8986 /// a member specialization (that replaces any definition provided by the
8987 /// previous declaration).
8988 ///
8989 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8990 ///
8991 /// \returns true if the function declaration is a redeclaration.
8992 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8993                                     LookupResult &Previous,
8994                                     bool IsMemberSpecialization) {
8995   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8996          "Variably modified return types are not handled here");
8997
8998   // Determine whether the type of this function should be merged with
8999   // a previous visible declaration. This never happens for functions in C++,
9000   // and always happens in C if the previous declaration was visible.
9001   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9002                                !Previous.isShadowed();
9003
9004   bool Redeclaration = false;
9005   NamedDecl *OldDecl = nullptr;
9006
9007   // Merge or overload the declaration with an existing declaration of
9008   // the same name, if appropriate.
9009   if (!Previous.empty()) {
9010     // Determine whether NewFD is an overload of PrevDecl or
9011     // a declaration that requires merging. If it's an overload,
9012     // there's no more work to do here; we'll just add the new
9013     // function to the scope.
9014     if (!AllowOverloadingOfFunction(Previous, Context)) {
9015       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9016       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9017         Redeclaration = true;
9018         OldDecl = Candidate;
9019       }
9020     } else {
9021       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9022                             /*NewIsUsingDecl*/ false)) {
9023       case Ovl_Match:
9024         Redeclaration = true;
9025         break;
9026
9027       case Ovl_NonFunction:
9028         Redeclaration = true;
9029         break;
9030
9031       case Ovl_Overload:
9032         Redeclaration = false;
9033         break;
9034       }
9035
9036       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9037         // If a function name is overloadable in C, then every function
9038         // with that name must be marked "overloadable".
9039         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9040           << Redeclaration << NewFD;
9041         NamedDecl *OverloadedDecl =
9042             Redeclaration ? OldDecl : Previous.getRepresentativeDecl();
9043         Diag(OverloadedDecl->getLocation(),
9044              diag::note_attribute_overloadable_prev_overload);
9045         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9046       }
9047     }
9048   }
9049
9050   // Check for a previous extern "C" declaration with this name.
9051   if (!Redeclaration &&
9052       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9053     if (!Previous.empty()) {
9054       // This is an extern "C" declaration with the same name as a previous
9055       // declaration, and thus redeclares that entity...
9056       Redeclaration = true;
9057       OldDecl = Previous.getFoundDecl();
9058       MergeTypeWithPrevious = false;
9059
9060       // ... except in the presence of __attribute__((overloadable)).
9061       if (OldDecl->hasAttr<OverloadableAttr>()) {
9062         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9063           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9064             << Redeclaration << NewFD;
9065           Diag(Previous.getFoundDecl()->getLocation(),
9066                diag::note_attribute_overloadable_prev_overload);
9067           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9068         }
9069         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9070           Redeclaration = false;
9071           OldDecl = nullptr;
9072         }
9073       }
9074     }
9075   }
9076
9077   // C++11 [dcl.constexpr]p8:
9078   //   A constexpr specifier for a non-static member function that is not
9079   //   a constructor declares that member function to be const.
9080   //
9081   // This needs to be delayed until we know whether this is an out-of-line
9082   // definition of a static member function.
9083   //
9084   // This rule is not present in C++1y, so we produce a backwards
9085   // compatibility warning whenever it happens in C++11.
9086   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9087   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9088       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9089       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9090     CXXMethodDecl *OldMD = nullptr;
9091     if (OldDecl)
9092       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9093     if (!OldMD || !OldMD->isStatic()) {
9094       const FunctionProtoType *FPT =
9095         MD->getType()->castAs<FunctionProtoType>();
9096       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9097       EPI.TypeQuals |= Qualifiers::Const;
9098       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9099                                           FPT->getParamTypes(), EPI));
9100
9101       // Warn that we did this, if we're not performing template instantiation.
9102       // In that case, we'll have warned already when the template was defined.
9103       if (!inTemplateInstantiation()) {
9104         SourceLocation AddConstLoc;
9105         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9106                 .IgnoreParens().getAs<FunctionTypeLoc>())
9107           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9108
9109         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9110           << FixItHint::CreateInsertion(AddConstLoc, " const");
9111       }
9112     }
9113   }
9114
9115   if (Redeclaration) {
9116     // NewFD and OldDecl represent declarations that need to be
9117     // merged.
9118     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9119       NewFD->setInvalidDecl();
9120       return Redeclaration;
9121     }
9122
9123     Previous.clear();
9124     Previous.addDecl(OldDecl);
9125
9126     if (FunctionTemplateDecl *OldTemplateDecl
9127                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9128       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9129       FunctionTemplateDecl *NewTemplateDecl
9130         = NewFD->getDescribedFunctionTemplate();
9131       assert(NewTemplateDecl && "Template/non-template mismatch");
9132       if (CXXMethodDecl *Method
9133             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9134         Method->setAccess(OldTemplateDecl->getAccess());
9135         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9136       }
9137
9138       // If this is an explicit specialization of a member that is a function
9139       // template, mark it as a member specialization.
9140       if (IsMemberSpecialization &&
9141           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9142         NewTemplateDecl->setMemberSpecialization();
9143         assert(OldTemplateDecl->isMemberSpecialization());
9144         // Explicit specializations of a member template do not inherit deleted
9145         // status from the parent member template that they are specializing.
9146         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9147           FunctionDecl *const OldTemplatedDecl =
9148               OldTemplateDecl->getTemplatedDecl();
9149           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9150           OldTemplatedDecl->setDeletedAsWritten(false);
9151         }
9152       }
9153
9154     } else {
9155       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9156         // This needs to happen first so that 'inline' propagates.
9157         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9158         if (isa<CXXMethodDecl>(NewFD))
9159           NewFD->setAccess(OldDecl->getAccess());
9160       }
9161     }
9162   }
9163
9164   // Semantic checking for this function declaration (in isolation).
9165
9166   if (getLangOpts().CPlusPlus) {
9167     // C++-specific checks.
9168     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9169       CheckConstructor(Constructor);
9170     } else if (CXXDestructorDecl *Destructor =
9171                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9172       CXXRecordDecl *Record = Destructor->getParent();
9173       QualType ClassType = Context.getTypeDeclType(Record);
9174
9175       // FIXME: Shouldn't we be able to perform this check even when the class
9176       // type is dependent? Both gcc and edg can handle that.
9177       if (!ClassType->isDependentType()) {
9178         DeclarationName Name
9179           = Context.DeclarationNames.getCXXDestructorName(
9180                                         Context.getCanonicalType(ClassType));
9181         if (NewFD->getDeclName() != Name) {
9182           Diag(NewFD->getLocation(), diag::err_destructor_name);
9183           NewFD->setInvalidDecl();
9184           return Redeclaration;
9185         }
9186       }
9187     } else if (CXXConversionDecl *Conversion
9188                = dyn_cast<CXXConversionDecl>(NewFD)) {
9189       ActOnConversionDeclarator(Conversion);
9190     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9191       if (auto *TD = Guide->getDescribedFunctionTemplate())
9192         CheckDeductionGuideTemplate(TD);
9193
9194       // A deduction guide is not on the list of entities that can be
9195       // explicitly specialized.
9196       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9197         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9198             << /*explicit specialization*/ 1;
9199     }
9200
9201     // Find any virtual functions that this function overrides.
9202     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9203       if (!Method->isFunctionTemplateSpecialization() &&
9204           !Method->getDescribedFunctionTemplate() &&
9205           Method->isCanonicalDecl()) {
9206         if (AddOverriddenMethods(Method->getParent(), Method)) {
9207           // If the function was marked as "static", we have a problem.
9208           if (NewFD->getStorageClass() == SC_Static) {
9209             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9210           }
9211         }
9212       }
9213
9214       if (Method->isStatic())
9215         checkThisInStaticMemberFunctionType(Method);
9216     }
9217
9218     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9219     if (NewFD->isOverloadedOperator() &&
9220         CheckOverloadedOperatorDeclaration(NewFD)) {
9221       NewFD->setInvalidDecl();
9222       return Redeclaration;
9223     }
9224
9225     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9226     if (NewFD->getLiteralIdentifier() &&
9227         CheckLiteralOperatorDeclaration(NewFD)) {
9228       NewFD->setInvalidDecl();
9229       return Redeclaration;
9230     }
9231
9232     // In C++, check default arguments now that we have merged decls. Unless
9233     // the lexical context is the class, because in this case this is done
9234     // during delayed parsing anyway.
9235     if (!CurContext->isRecord())
9236       CheckCXXDefaultArguments(NewFD);
9237
9238     // If this function declares a builtin function, check the type of this
9239     // declaration against the expected type for the builtin.
9240     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9241       ASTContext::GetBuiltinTypeError Error;
9242       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9243       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9244       // If the type of the builtin differs only in its exception
9245       // specification, that's OK.
9246       // FIXME: If the types do differ in this way, it would be better to
9247       // retain the 'noexcept' form of the type.
9248       if (!T.isNull() &&
9249           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9250                                                             NewFD->getType()))
9251         // The type of this function differs from the type of the builtin,
9252         // so forget about the builtin entirely.
9253         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9254     }
9255
9256     // If this function is declared as being extern "C", then check to see if
9257     // the function returns a UDT (class, struct, or union type) that is not C
9258     // compatible, and if it does, warn the user.
9259     // But, issue any diagnostic on the first declaration only.
9260     if (Previous.empty() && NewFD->isExternC()) {
9261       QualType R = NewFD->getReturnType();
9262       if (R->isIncompleteType() && !R->isVoidType())
9263         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9264             << NewFD << R;
9265       else if (!R.isPODType(Context) && !R->isVoidType() &&
9266                !R->isObjCObjectPointerType())
9267         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9268     }
9269
9270     // C++1z [dcl.fct]p6:
9271     //   [...] whether the function has a non-throwing exception-specification
9272     //   [is] part of the function type
9273     //
9274     // This results in an ABI break between C++14 and C++17 for functions whose
9275     // declared type includes an exception-specification in a parameter or
9276     // return type. (Exception specifications on the function itself are OK in
9277     // most cases, and exception specifications are not permitted in most other
9278     // contexts where they could make it into a mangling.)
9279     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9280       auto HasNoexcept = [&](QualType T) -> bool {
9281         // Strip off declarator chunks that could be between us and a function
9282         // type. We don't need to look far, exception specifications are very
9283         // restricted prior to C++17.
9284         if (auto *RT = T->getAs<ReferenceType>())
9285           T = RT->getPointeeType();
9286         else if (T->isAnyPointerType())
9287           T = T->getPointeeType();
9288         else if (auto *MPT = T->getAs<MemberPointerType>())
9289           T = MPT->getPointeeType();
9290         if (auto *FPT = T->getAs<FunctionProtoType>())
9291           if (FPT->isNothrow(Context))
9292             return true;
9293         return false;
9294       };
9295
9296       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9297       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9298       for (QualType T : FPT->param_types())
9299         AnyNoexcept |= HasNoexcept(T);
9300       if (AnyNoexcept)
9301         Diag(NewFD->getLocation(),
9302              diag::warn_cxx1z_compat_exception_spec_in_signature)
9303             << NewFD;
9304     }
9305
9306     if (!Redeclaration && LangOpts.CUDA)
9307       checkCUDATargetOverload(NewFD, Previous);
9308   }
9309   return Redeclaration;
9310 }
9311
9312 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9313   // C++11 [basic.start.main]p3:
9314   //   A program that [...] declares main to be inline, static or
9315   //   constexpr is ill-formed.
9316   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9317   //   appear in a declaration of main.
9318   // static main is not an error under C99, but we should warn about it.
9319   // We accept _Noreturn main as an extension.
9320   if (FD->getStorageClass() == SC_Static)
9321     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9322          ? diag::err_static_main : diag::warn_static_main)
9323       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9324   if (FD->isInlineSpecified())
9325     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9326       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9327   if (DS.isNoreturnSpecified()) {
9328     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9329     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9330     Diag(NoreturnLoc, diag::ext_noreturn_main);
9331     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9332       << FixItHint::CreateRemoval(NoreturnRange);
9333   }
9334   if (FD->isConstexpr()) {
9335     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9336       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9337     FD->setConstexpr(false);
9338   }
9339
9340   if (getLangOpts().OpenCL) {
9341     Diag(FD->getLocation(), diag::err_opencl_no_main)
9342         << FD->hasAttr<OpenCLKernelAttr>();
9343     FD->setInvalidDecl();
9344     return;
9345   }
9346
9347   QualType T = FD->getType();
9348   assert(T->isFunctionType() && "function decl is not of function type");
9349   const FunctionType* FT = T->castAs<FunctionType>();
9350
9351   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9352     // In C with GNU extensions we allow main() to have non-integer return
9353     // type, but we should warn about the extension, and we disable the
9354     // implicit-return-zero rule.
9355
9356     // GCC in C mode accepts qualified 'int'.
9357     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9358       FD->setHasImplicitReturnZero(true);
9359     else {
9360       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9361       SourceRange RTRange = FD->getReturnTypeSourceRange();
9362       if (RTRange.isValid())
9363         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9364             << FixItHint::CreateReplacement(RTRange, "int");
9365     }
9366   } else {
9367     // In C and C++, main magically returns 0 if you fall off the end;
9368     // set the flag which tells us that.
9369     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9370
9371     // All the standards say that main() should return 'int'.
9372     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9373       FD->setHasImplicitReturnZero(true);
9374     else {
9375       // Otherwise, this is just a flat-out error.
9376       SourceRange RTRange = FD->getReturnTypeSourceRange();
9377       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9378           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9379                                 : FixItHint());
9380       FD->setInvalidDecl(true);
9381     }
9382   }
9383
9384   // Treat protoless main() as nullary.
9385   if (isa<FunctionNoProtoType>(FT)) return;
9386
9387   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9388   unsigned nparams = FTP->getNumParams();
9389   assert(FD->getNumParams() == nparams);
9390
9391   bool HasExtraParameters = (nparams > 3);
9392
9393   if (FTP->isVariadic()) {
9394     Diag(FD->getLocation(), diag::ext_variadic_main);
9395     // FIXME: if we had information about the location of the ellipsis, we
9396     // could add a FixIt hint to remove it as a parameter.
9397   }
9398
9399   // Darwin passes an undocumented fourth argument of type char**.  If
9400   // other platforms start sprouting these, the logic below will start
9401   // getting shifty.
9402   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9403     HasExtraParameters = false;
9404
9405   if (HasExtraParameters) {
9406     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9407     FD->setInvalidDecl(true);
9408     nparams = 3;
9409   }
9410
9411   // FIXME: a lot of the following diagnostics would be improved
9412   // if we had some location information about types.
9413
9414   QualType CharPP =
9415     Context.getPointerType(Context.getPointerType(Context.CharTy));
9416   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9417
9418   for (unsigned i = 0; i < nparams; ++i) {
9419     QualType AT = FTP->getParamType(i);
9420
9421     bool mismatch = true;
9422
9423     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9424       mismatch = false;
9425     else if (Expected[i] == CharPP) {
9426       // As an extension, the following forms are okay:
9427       //   char const **
9428       //   char const * const *
9429       //   char * const *
9430
9431       QualifierCollector qs;
9432       const PointerType* PT;
9433       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9434           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9435           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9436                               Context.CharTy)) {
9437         qs.removeConst();
9438         mismatch = !qs.empty();
9439       }
9440     }
9441
9442     if (mismatch) {
9443       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9444       // TODO: suggest replacing given type with expected type
9445       FD->setInvalidDecl(true);
9446     }
9447   }
9448
9449   if (nparams == 1 && !FD->isInvalidDecl()) {
9450     Diag(FD->getLocation(), diag::warn_main_one_arg);
9451   }
9452
9453   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9454     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9455     FD->setInvalidDecl();
9456   }
9457 }
9458
9459 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9460   QualType T = FD->getType();
9461   assert(T->isFunctionType() && "function decl is not of function type");
9462   const FunctionType *FT = T->castAs<FunctionType>();
9463
9464   // Set an implicit return of 'zero' if the function can return some integral,
9465   // enumeration, pointer or nullptr type.
9466   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9467       FT->getReturnType()->isAnyPointerType() ||
9468       FT->getReturnType()->isNullPtrType())
9469     // DllMain is exempt because a return value of zero means it failed.
9470     if (FD->getName() != "DllMain")
9471       FD->setHasImplicitReturnZero(true);
9472
9473   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9474     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9475     FD->setInvalidDecl();
9476   }
9477 }
9478
9479 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9480   // FIXME: Need strict checking.  In C89, we need to check for
9481   // any assignment, increment, decrement, function-calls, or
9482   // commas outside of a sizeof.  In C99, it's the same list,
9483   // except that the aforementioned are allowed in unevaluated
9484   // expressions.  Everything else falls under the
9485   // "may accept other forms of constant expressions" exception.
9486   // (We never end up here for C++, so the constant expression
9487   // rules there don't matter.)
9488   const Expr *Culprit;
9489   if (Init->isConstantInitializer(Context, false, &Culprit))
9490     return false;
9491   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9492     << Culprit->getSourceRange();
9493   return true;
9494 }
9495
9496 namespace {
9497   // Visits an initialization expression to see if OrigDecl is evaluated in
9498   // its own initialization and throws a warning if it does.
9499   class SelfReferenceChecker
9500       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9501     Sema &S;
9502     Decl *OrigDecl;
9503     bool isRecordType;
9504     bool isPODType;
9505     bool isReferenceType;
9506
9507     bool isInitList;
9508     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9509
9510   public:
9511     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9512
9513     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9514                                                     S(S), OrigDecl(OrigDecl) {
9515       isPODType = false;
9516       isRecordType = false;
9517       isReferenceType = false;
9518       isInitList = false;
9519       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9520         isPODType = VD->getType().isPODType(S.Context);
9521         isRecordType = VD->getType()->isRecordType();
9522         isReferenceType = VD->getType()->isReferenceType();
9523       }
9524     }
9525
9526     // For most expressions, just call the visitor.  For initializer lists,
9527     // track the index of the field being initialized since fields are
9528     // initialized in order allowing use of previously initialized fields.
9529     void CheckExpr(Expr *E) {
9530       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9531       if (!InitList) {
9532         Visit(E);
9533         return;
9534       }
9535
9536       // Track and increment the index here.
9537       isInitList = true;
9538       InitFieldIndex.push_back(0);
9539       for (auto Child : InitList->children()) {
9540         CheckExpr(cast<Expr>(Child));
9541         ++InitFieldIndex.back();
9542       }
9543       InitFieldIndex.pop_back();
9544     }
9545
9546     // Returns true if MemberExpr is checked and no further checking is needed.
9547     // Returns false if additional checking is required.
9548     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9549       llvm::SmallVector<FieldDecl*, 4> Fields;
9550       Expr *Base = E;
9551       bool ReferenceField = false;
9552
9553       // Get the field memebers used.
9554       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9555         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9556         if (!FD)
9557           return false;
9558         Fields.push_back(FD);
9559         if (FD->getType()->isReferenceType())
9560           ReferenceField = true;
9561         Base = ME->getBase()->IgnoreParenImpCasts();
9562       }
9563
9564       // Keep checking only if the base Decl is the same.
9565       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9566       if (!DRE || DRE->getDecl() != OrigDecl)
9567         return false;
9568
9569       // A reference field can be bound to an unininitialized field.
9570       if (CheckReference && !ReferenceField)
9571         return true;
9572
9573       // Convert FieldDecls to their index number.
9574       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9575       for (const FieldDecl *I : llvm::reverse(Fields))
9576         UsedFieldIndex.push_back(I->getFieldIndex());
9577
9578       // See if a warning is needed by checking the first difference in index
9579       // numbers.  If field being used has index less than the field being
9580       // initialized, then the use is safe.
9581       for (auto UsedIter = UsedFieldIndex.begin(),
9582                 UsedEnd = UsedFieldIndex.end(),
9583                 OrigIter = InitFieldIndex.begin(),
9584                 OrigEnd = InitFieldIndex.end();
9585            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9586         if (*UsedIter < *OrigIter)
9587           return true;
9588         if (*UsedIter > *OrigIter)
9589           break;
9590       }
9591
9592       // TODO: Add a different warning which will print the field names.
9593       HandleDeclRefExpr(DRE);
9594       return true;
9595     }
9596
9597     // For most expressions, the cast is directly above the DeclRefExpr.
9598     // For conditional operators, the cast can be outside the conditional
9599     // operator if both expressions are DeclRefExpr's.
9600     void HandleValue(Expr *E) {
9601       E = E->IgnoreParens();
9602       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9603         HandleDeclRefExpr(DRE);
9604         return;
9605       }
9606
9607       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9608         Visit(CO->getCond());
9609         HandleValue(CO->getTrueExpr());
9610         HandleValue(CO->getFalseExpr());
9611         return;
9612       }
9613
9614       if (BinaryConditionalOperator *BCO =
9615               dyn_cast<BinaryConditionalOperator>(E)) {
9616         Visit(BCO->getCond());
9617         HandleValue(BCO->getFalseExpr());
9618         return;
9619       }
9620
9621       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9622         HandleValue(OVE->getSourceExpr());
9623         return;
9624       }
9625
9626       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9627         if (BO->getOpcode() == BO_Comma) {
9628           Visit(BO->getLHS());
9629           HandleValue(BO->getRHS());
9630           return;
9631         }
9632       }
9633
9634       if (isa<MemberExpr>(E)) {
9635         if (isInitList) {
9636           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9637                                       false /*CheckReference*/))
9638             return;
9639         }
9640
9641         Expr *Base = E->IgnoreParenImpCasts();
9642         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9643           // Check for static member variables and don't warn on them.
9644           if (!isa<FieldDecl>(ME->getMemberDecl()))
9645             return;
9646           Base = ME->getBase()->IgnoreParenImpCasts();
9647         }
9648         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9649           HandleDeclRefExpr(DRE);
9650         return;
9651       }
9652
9653       Visit(E);
9654     }
9655
9656     // Reference types not handled in HandleValue are handled here since all
9657     // uses of references are bad, not just r-value uses.
9658     void VisitDeclRefExpr(DeclRefExpr *E) {
9659       if (isReferenceType)
9660         HandleDeclRefExpr(E);
9661     }
9662
9663     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9664       if (E->getCastKind() == CK_LValueToRValue) {
9665         HandleValue(E->getSubExpr());
9666         return;
9667       }
9668
9669       Inherited::VisitImplicitCastExpr(E);
9670     }
9671
9672     void VisitMemberExpr(MemberExpr *E) {
9673       if (isInitList) {
9674         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9675           return;
9676       }
9677
9678       // Don't warn on arrays since they can be treated as pointers.
9679       if (E->getType()->canDecayToPointerType()) return;
9680
9681       // Warn when a non-static method call is followed by non-static member
9682       // field accesses, which is followed by a DeclRefExpr.
9683       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9684       bool Warn = (MD && !MD->isStatic());
9685       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9686       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9687         if (!isa<FieldDecl>(ME->getMemberDecl()))
9688           Warn = false;
9689         Base = ME->getBase()->IgnoreParenImpCasts();
9690       }
9691
9692       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9693         if (Warn)
9694           HandleDeclRefExpr(DRE);
9695         return;
9696       }
9697
9698       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9699       // Visit that expression.
9700       Visit(Base);
9701     }
9702
9703     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9704       Expr *Callee = E->getCallee();
9705
9706       if (isa<UnresolvedLookupExpr>(Callee))
9707         return Inherited::VisitCXXOperatorCallExpr(E);
9708
9709       Visit(Callee);
9710       for (auto Arg: E->arguments())
9711         HandleValue(Arg->IgnoreParenImpCasts());
9712     }
9713
9714     void VisitUnaryOperator(UnaryOperator *E) {
9715       // For POD record types, addresses of its own members are well-defined.
9716       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9717           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9718         if (!isPODType)
9719           HandleValue(E->getSubExpr());
9720         return;
9721       }
9722
9723       if (E->isIncrementDecrementOp()) {
9724         HandleValue(E->getSubExpr());
9725         return;
9726       }
9727
9728       Inherited::VisitUnaryOperator(E);
9729     }
9730
9731     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9732
9733     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9734       if (E->getConstructor()->isCopyConstructor()) {
9735         Expr *ArgExpr = E->getArg(0);
9736         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9737           if (ILE->getNumInits() == 1)
9738             ArgExpr = ILE->getInit(0);
9739         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9740           if (ICE->getCastKind() == CK_NoOp)
9741             ArgExpr = ICE->getSubExpr();
9742         HandleValue(ArgExpr);
9743         return;
9744       }
9745       Inherited::VisitCXXConstructExpr(E);
9746     }
9747
9748     void VisitCallExpr(CallExpr *E) {
9749       // Treat std::move as a use.
9750       if (E->getNumArgs() == 1) {
9751         if (FunctionDecl *FD = E->getDirectCallee()) {
9752           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9753               FD->getIdentifier()->isStr("move")) {
9754             HandleValue(E->getArg(0));
9755             return;
9756           }
9757         }
9758       }
9759
9760       Inherited::VisitCallExpr(E);
9761     }
9762
9763     void VisitBinaryOperator(BinaryOperator *E) {
9764       if (E->isCompoundAssignmentOp()) {
9765         HandleValue(E->getLHS());
9766         Visit(E->getRHS());
9767         return;
9768       }
9769
9770       Inherited::VisitBinaryOperator(E);
9771     }
9772
9773     // A custom visitor for BinaryConditionalOperator is needed because the
9774     // regular visitor would check the condition and true expression separately
9775     // but both point to the same place giving duplicate diagnostics.
9776     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9777       Visit(E->getCond());
9778       Visit(E->getFalseExpr());
9779     }
9780
9781     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9782       Decl* ReferenceDecl = DRE->getDecl();
9783       if (OrigDecl != ReferenceDecl) return;
9784       unsigned diag;
9785       if (isReferenceType) {
9786         diag = diag::warn_uninit_self_reference_in_reference_init;
9787       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9788         diag = diag::warn_static_self_reference_in_init;
9789       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9790                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9791                  DRE->getDecl()->getType()->isRecordType()) {
9792         diag = diag::warn_uninit_self_reference_in_init;
9793       } else {
9794         // Local variables will be handled by the CFG analysis.
9795         return;
9796       }
9797
9798       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9799                             S.PDiag(diag)
9800                               << DRE->getNameInfo().getName()
9801                               << OrigDecl->getLocation()
9802                               << DRE->getSourceRange());
9803     }
9804   };
9805
9806   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9807   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9808                                  bool DirectInit) {
9809     // Parameters arguments are occassionially constructed with itself,
9810     // for instance, in recursive functions.  Skip them.
9811     if (isa<ParmVarDecl>(OrigDecl))
9812       return;
9813
9814     E = E->IgnoreParens();
9815
9816     // Skip checking T a = a where T is not a record or reference type.
9817     // Doing so is a way to silence uninitialized warnings.
9818     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9819       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9820         if (ICE->getCastKind() == CK_LValueToRValue)
9821           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9822             if (DRE->getDecl() == OrigDecl)
9823               return;
9824
9825     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9826   }
9827 } // end anonymous namespace
9828
9829 namespace {
9830   // Simple wrapper to add the name of a variable or (if no variable is
9831   // available) a DeclarationName into a diagnostic.
9832   struct VarDeclOrName {
9833     VarDecl *VDecl;
9834     DeclarationName Name;
9835
9836     friend const Sema::SemaDiagnosticBuilder &
9837     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
9838       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
9839     }
9840   };
9841 } // end anonymous namespace
9842
9843 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9844                                             DeclarationName Name, QualType Type,
9845                                             TypeSourceInfo *TSI,
9846                                             SourceRange Range, bool DirectInit,
9847                                             Expr *Init) {
9848   bool IsInitCapture = !VDecl;
9849   assert((!VDecl || !VDecl->isInitCapture()) &&
9850          "init captures are expected to be deduced prior to initialization");
9851
9852   VarDeclOrName VN{VDecl, Name};
9853
9854   DeducedType *Deduced = Type->getContainedDeducedType();
9855   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
9856
9857   // C++11 [dcl.spec.auto]p3
9858   if (!Init) {
9859     assert(VDecl && "no init for init capture deduction?");
9860     Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
9861       << VDecl->getDeclName() << Type;
9862     return QualType();
9863   }
9864
9865   ArrayRef<Expr*> DeduceInits = Init;
9866   if (DirectInit) {
9867     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
9868       DeduceInits = PL->exprs();
9869   }
9870
9871   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
9872     assert(VDecl && "non-auto type for init capture deduction?");
9873     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9874     InitializationKind Kind = InitializationKind::CreateForInit(
9875         VDecl->getLocation(), DirectInit, Init);
9876     // FIXME: Initialization should not be taking a mutable list of inits. 
9877     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
9878     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
9879                                                        InitsCopy);
9880   }
9881
9882   if (DirectInit) {
9883     if (auto *IL = dyn_cast<InitListExpr>(Init))
9884       DeduceInits = IL->inits();
9885   }
9886
9887   // Deduction only works if we have exactly one source expression.
9888   if (DeduceInits.empty()) {
9889     // It isn't possible to write this directly, but it is possible to
9890     // end up in this situation with "auto x(some_pack...);"
9891     Diag(Init->getLocStart(), IsInitCapture
9892                                   ? diag::err_init_capture_no_expression
9893                                   : diag::err_auto_var_init_no_expression)
9894         << VN << Type << Range;
9895     return QualType();
9896   }
9897
9898   if (DeduceInits.size() > 1) {
9899     Diag(DeduceInits[1]->getLocStart(),
9900          IsInitCapture ? diag::err_init_capture_multiple_expressions
9901                        : diag::err_auto_var_init_multiple_expressions)
9902         << VN << Type << Range;
9903     return QualType();
9904   }
9905
9906   Expr *DeduceInit = DeduceInits[0];
9907   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9908     Diag(Init->getLocStart(), IsInitCapture
9909                                   ? diag::err_init_capture_paren_braces
9910                                   : diag::err_auto_var_init_paren_braces)
9911         << isa<InitListExpr>(Init) << VN << Type << Range;
9912     return QualType();
9913   }
9914
9915   // Expressions default to 'id' when we're in a debugger.
9916   bool DefaultedAnyToId = false;
9917   if (getLangOpts().DebuggerCastResultToId &&
9918       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9919     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9920     if (Result.isInvalid()) {
9921       return QualType();
9922     }
9923     Init = Result.get();
9924     DefaultedAnyToId = true;
9925   }
9926
9927   // C++ [dcl.decomp]p1:
9928   //   If the assignment-expression [...] has array type A and no ref-qualifier
9929   //   is present, e has type cv A
9930   if (VDecl && isa<DecompositionDecl>(VDecl) &&
9931       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
9932       DeduceInit->getType()->isConstantArrayType())
9933     return Context.getQualifiedType(DeduceInit->getType(),
9934                                     Type.getQualifiers());
9935
9936   QualType DeducedType;
9937   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9938     if (!IsInitCapture)
9939       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9940     else if (isa<InitListExpr>(Init))
9941       Diag(Range.getBegin(),
9942            diag::err_init_capture_deduction_failure_from_init_list)
9943           << VN
9944           << (DeduceInit->getType().isNull() ? TSI->getType()
9945                                              : DeduceInit->getType())
9946           << DeduceInit->getSourceRange();
9947     else
9948       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9949           << VN << TSI->getType()
9950           << (DeduceInit->getType().isNull() ? TSI->getType()
9951                                              : DeduceInit->getType())
9952           << DeduceInit->getSourceRange();
9953   }
9954
9955   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9956   // 'id' instead of a specific object type prevents most of our usual
9957   // checks.
9958   // We only want to warn outside of template instantiations, though:
9959   // inside a template, the 'id' could have come from a parameter.
9960   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
9961       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9962     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9963     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
9964   }
9965
9966   return DeducedType;
9967 }
9968
9969 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
9970                                          Expr *Init) {
9971   QualType DeducedType = deduceVarTypeFromInitializer(
9972       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
9973       VDecl->getSourceRange(), DirectInit, Init);
9974   if (DeducedType.isNull()) {
9975     VDecl->setInvalidDecl();
9976     return true;
9977   }
9978
9979   VDecl->setType(DeducedType);
9980   assert(VDecl->isLinkageValid());
9981
9982   // In ARC, infer lifetime.
9983   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9984     VDecl->setInvalidDecl();
9985
9986   // If this is a redeclaration, check that the type we just deduced matches
9987   // the previously declared type.
9988   if (VarDecl *Old = VDecl->getPreviousDecl()) {
9989     // We never need to merge the type, because we cannot form an incomplete
9990     // array of auto, nor deduce such a type.
9991     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9992   }
9993
9994   // Check the deduced type is valid for a variable declaration.
9995   CheckVariableDeclarationType(VDecl);
9996   return VDecl->isInvalidDecl();
9997 }
9998
9999 /// AddInitializerToDecl - Adds the initializer Init to the
10000 /// declaration dcl. If DirectInit is true, this is C++ direct
10001 /// initialization rather than copy initialization.
10002 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10003   // If there is no declaration, there was an error parsing it.  Just ignore
10004   // the initializer.
10005   if (!RealDecl || RealDecl->isInvalidDecl()) {
10006     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10007     return;
10008   }
10009
10010   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10011     // Pure-specifiers are handled in ActOnPureSpecifier.
10012     Diag(Method->getLocation(), diag::err_member_function_initialization)
10013       << Method->getDeclName() << Init->getSourceRange();
10014     Method->setInvalidDecl();
10015     return;
10016   }
10017
10018   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10019   if (!VDecl) {
10020     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10021     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10022     RealDecl->setInvalidDecl();
10023     return;
10024   }
10025
10026   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10027   if (VDecl->getType()->isUndeducedType()) {
10028     // Attempt typo correction early so that the type of the init expression can
10029     // be deduced based on the chosen correction if the original init contains a
10030     // TypoExpr.
10031     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10032     if (!Res.isUsable()) {
10033       RealDecl->setInvalidDecl();
10034       return;
10035     }
10036     Init = Res.get();
10037
10038     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10039       return;
10040   }
10041
10042   // dllimport cannot be used on variable definitions.
10043   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10044     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10045     VDecl->setInvalidDecl();
10046     return;
10047   }
10048
10049   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10050     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10051     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10052     VDecl->setInvalidDecl();
10053     return;
10054   }
10055
10056   if (!VDecl->getType()->isDependentType()) {
10057     // A definition must end up with a complete type, which means it must be
10058     // complete with the restriction that an array type might be completed by
10059     // the initializer; note that later code assumes this restriction.
10060     QualType BaseDeclType = VDecl->getType();
10061     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10062       BaseDeclType = Array->getElementType();
10063     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10064                             diag::err_typecheck_decl_incomplete_type)) {
10065       RealDecl->setInvalidDecl();
10066       return;
10067     }
10068
10069     // The variable can not have an abstract class type.
10070     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10071                                diag::err_abstract_type_in_decl,
10072                                AbstractVariableType))
10073       VDecl->setInvalidDecl();
10074   }
10075
10076   // If adding the initializer will turn this declaration into a definition,
10077   // and we already have a definition for this variable, diagnose or otherwise
10078   // handle the situation.
10079   VarDecl *Def;
10080   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10081       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10082       !VDecl->isThisDeclarationADemotedDefinition() &&
10083       checkVarDeclRedefinition(Def, VDecl))
10084     return;
10085
10086   if (getLangOpts().CPlusPlus) {
10087     // C++ [class.static.data]p4
10088     //   If a static data member is of const integral or const
10089     //   enumeration type, its declaration in the class definition can
10090     //   specify a constant-initializer which shall be an integral
10091     //   constant expression (5.19). In that case, the member can appear
10092     //   in integral constant expressions. The member shall still be
10093     //   defined in a namespace scope if it is used in the program and the
10094     //   namespace scope definition shall not contain an initializer.
10095     //
10096     // We already performed a redefinition check above, but for static
10097     // data members we also need to check whether there was an in-class
10098     // declaration with an initializer.
10099     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10100       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10101           << VDecl->getDeclName();
10102       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10103            diag::note_previous_initializer)
10104           << 0;
10105       return;
10106     }
10107
10108     if (VDecl->hasLocalStorage())
10109       getCurFunction()->setHasBranchProtectedScope();
10110
10111     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10112       VDecl->setInvalidDecl();
10113       return;
10114     }
10115   }
10116
10117   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10118   // a kernel function cannot be initialized."
10119   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10120     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10121     VDecl->setInvalidDecl();
10122     return;
10123   }
10124
10125   // Get the decls type and save a reference for later, since
10126   // CheckInitializerTypes may change it.
10127   QualType DclT = VDecl->getType(), SavT = DclT;
10128
10129   // Expressions default to 'id' when we're in a debugger
10130   // and we are assigning it to a variable of Objective-C pointer type.
10131   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10132       Init->getType() == Context.UnknownAnyTy) {
10133     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10134     if (Result.isInvalid()) {
10135       VDecl->setInvalidDecl();
10136       return;
10137     }
10138     Init = Result.get();
10139   }
10140
10141   // Perform the initialization.
10142   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10143   if (!VDecl->isInvalidDecl()) {
10144     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10145     InitializationKind Kind = InitializationKind::CreateForInit(
10146         VDecl->getLocation(), DirectInit, Init);
10147
10148     MultiExprArg Args = Init;
10149     if (CXXDirectInit)
10150       Args = MultiExprArg(CXXDirectInit->getExprs(),
10151                           CXXDirectInit->getNumExprs());
10152
10153     // Try to correct any TypoExprs in the initialization arguments.
10154     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10155       ExprResult Res = CorrectDelayedTyposInExpr(
10156           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10157             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10158             return Init.Failed() ? ExprError() : E;
10159           });
10160       if (Res.isInvalid()) {
10161         VDecl->setInvalidDecl();
10162       } else if (Res.get() != Args[Idx]) {
10163         Args[Idx] = Res.get();
10164       }
10165     }
10166     if (VDecl->isInvalidDecl())
10167       return;
10168
10169     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10170                                    /*TopLevelOfInitList=*/false,
10171                                    /*TreatUnavailableAsInvalid=*/false);
10172     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10173     if (Result.isInvalid()) {
10174       VDecl->setInvalidDecl();
10175       return;
10176     }
10177
10178     Init = Result.getAs<Expr>();
10179   }
10180
10181   // Check for self-references within variable initializers.
10182   // Variables declared within a function/method body (except for references)
10183   // are handled by a dataflow analysis.
10184   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10185       VDecl->getType()->isReferenceType()) {
10186     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10187   }
10188
10189   // If the type changed, it means we had an incomplete type that was
10190   // completed by the initializer. For example:
10191   //   int ary[] = { 1, 3, 5 };
10192   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10193   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10194     VDecl->setType(DclT);
10195
10196   if (!VDecl->isInvalidDecl()) {
10197     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10198
10199     if (VDecl->hasAttr<BlocksAttr>())
10200       checkRetainCycles(VDecl, Init);
10201
10202     // It is safe to assign a weak reference into a strong variable.
10203     // Although this code can still have problems:
10204     //   id x = self.weakProp;
10205     //   id y = self.weakProp;
10206     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10207     // paths through the function. This should be revisited if
10208     // -Wrepeated-use-of-weak is made flow-sensitive.
10209     if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10210          VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10211         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10212                          Init->getLocStart()))
10213       getCurFunction()->markSafeWeakUse(Init);
10214   }
10215
10216   // The initialization is usually a full-expression.
10217   //
10218   // FIXME: If this is a braced initialization of an aggregate, it is not
10219   // an expression, and each individual field initializer is a separate
10220   // full-expression. For instance, in:
10221   //
10222   //   struct Temp { ~Temp(); };
10223   //   struct S { S(Temp); };
10224   //   struct T { S a, b; } t = { Temp(), Temp() }
10225   //
10226   // we should destroy the first Temp before constructing the second.
10227   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10228                                           false,
10229                                           VDecl->isConstexpr());
10230   if (Result.isInvalid()) {
10231     VDecl->setInvalidDecl();
10232     return;
10233   }
10234   Init = Result.get();
10235
10236   // Attach the initializer to the decl.
10237   VDecl->setInit(Init);
10238
10239   if (VDecl->isLocalVarDecl()) {
10240     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10241     // static storage duration shall be constant expressions or string literals.
10242     // C++ does not have this restriction.
10243     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
10244       const Expr *Culprit;
10245       if (VDecl->getStorageClass() == SC_Static)
10246         CheckForConstantInitializer(Init, DclT);
10247       // C89 is stricter than C99 for non-static aggregate types.
10248       // C89 6.5.7p3: All the expressions [...] in an initializer list
10249       // for an object that has aggregate or union type shall be
10250       // constant expressions.
10251       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10252                isa<InitListExpr>(Init) &&
10253                !Init->isConstantInitializer(Context, false, &Culprit))
10254         Diag(Culprit->getExprLoc(),
10255              diag::ext_aggregate_init_not_constant)
10256           << Culprit->getSourceRange();
10257     }
10258   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10259              VDecl->getLexicalDeclContext()->isRecord()) {
10260     // This is an in-class initialization for a static data member, e.g.,
10261     //
10262     // struct S {
10263     //   static const int value = 17;
10264     // };
10265
10266     // C++ [class.mem]p4:
10267     //   A member-declarator can contain a constant-initializer only
10268     //   if it declares a static member (9.4) of const integral or
10269     //   const enumeration type, see 9.4.2.
10270     //
10271     // C++11 [class.static.data]p3:
10272     //   If a non-volatile non-inline const static data member is of integral
10273     //   or enumeration type, its declaration in the class definition can
10274     //   specify a brace-or-equal-initializer in which every initializer-clause
10275     //   that is an assignment-expression is a constant expression. A static
10276     //   data member of literal type can be declared in the class definition
10277     //   with the constexpr specifier; if so, its declaration shall specify a
10278     //   brace-or-equal-initializer in which every initializer-clause that is
10279     //   an assignment-expression is a constant expression.
10280
10281     // Do nothing on dependent types.
10282     if (DclT->isDependentType()) {
10283
10284     // Allow any 'static constexpr' members, whether or not they are of literal
10285     // type. We separately check that every constexpr variable is of literal
10286     // type.
10287     } else if (VDecl->isConstexpr()) {
10288
10289     // Require constness.
10290     } else if (!DclT.isConstQualified()) {
10291       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10292         << Init->getSourceRange();
10293       VDecl->setInvalidDecl();
10294
10295     // We allow integer constant expressions in all cases.
10296     } else if (DclT->isIntegralOrEnumerationType()) {
10297       // Check whether the expression is a constant expression.
10298       SourceLocation Loc;
10299       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10300         // In C++11, a non-constexpr const static data member with an
10301         // in-class initializer cannot be volatile.
10302         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10303       else if (Init->isValueDependent())
10304         ; // Nothing to check.
10305       else if (Init->isIntegerConstantExpr(Context, &Loc))
10306         ; // Ok, it's an ICE!
10307       else if (Init->isEvaluatable(Context)) {
10308         // If we can constant fold the initializer through heroics, accept it,
10309         // but report this as a use of an extension for -pedantic.
10310         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10311           << Init->getSourceRange();
10312       } else {
10313         // Otherwise, this is some crazy unknown case.  Report the issue at the
10314         // location provided by the isIntegerConstantExpr failed check.
10315         Diag(Loc, diag::err_in_class_initializer_non_constant)
10316           << Init->getSourceRange();
10317         VDecl->setInvalidDecl();
10318       }
10319
10320     // We allow foldable floating-point constants as an extension.
10321     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10322       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10323       // it anyway and provide a fixit to add the 'constexpr'.
10324       if (getLangOpts().CPlusPlus11) {
10325         Diag(VDecl->getLocation(),
10326              diag::ext_in_class_initializer_float_type_cxx11)
10327             << DclT << Init->getSourceRange();
10328         Diag(VDecl->getLocStart(),
10329              diag::note_in_class_initializer_float_type_cxx11)
10330             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10331       } else {
10332         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10333           << DclT << Init->getSourceRange();
10334
10335         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10336           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10337             << Init->getSourceRange();
10338           VDecl->setInvalidDecl();
10339         }
10340       }
10341
10342     // Suggest adding 'constexpr' in C++11 for literal types.
10343     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10344       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10345         << DclT << Init->getSourceRange()
10346         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10347       VDecl->setConstexpr(true);
10348
10349     } else {
10350       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10351         << DclT << Init->getSourceRange();
10352       VDecl->setInvalidDecl();
10353     }
10354   } else if (VDecl->isFileVarDecl()) {
10355     // In C, extern is typically used to avoid tentative definitions when
10356     // declaring variables in headers, but adding an intializer makes it a
10357     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10358     // In C++, extern is often used to give implictly static const variables
10359     // external linkage, so don't warn in that case. If selectany is present,
10360     // this might be header code intended for C and C++ inclusion, so apply the
10361     // C++ rules.
10362     if (VDecl->getStorageClass() == SC_Extern &&
10363         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10364          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10365         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10366         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10367       Diag(VDecl->getLocation(), diag::warn_extern_init);
10368
10369     // C99 6.7.8p4. All file scoped initializers need to be constant.
10370     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10371       CheckForConstantInitializer(Init, DclT);
10372   }
10373
10374   // We will represent direct-initialization similarly to copy-initialization:
10375   //    int x(1);  -as-> int x = 1;
10376   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10377   //
10378   // Clients that want to distinguish between the two forms, can check for
10379   // direct initializer using VarDecl::getInitStyle().
10380   // A major benefit is that clients that don't particularly care about which
10381   // exactly form was it (like the CodeGen) can handle both cases without
10382   // special case code.
10383
10384   // C++ 8.5p11:
10385   // The form of initialization (using parentheses or '=') is generally
10386   // insignificant, but does matter when the entity being initialized has a
10387   // class type.
10388   if (CXXDirectInit) {
10389     assert(DirectInit && "Call-style initializer must be direct init.");
10390     VDecl->setInitStyle(VarDecl::CallInit);
10391   } else if (DirectInit) {
10392     // This must be list-initialization. No other way is direct-initialization.
10393     VDecl->setInitStyle(VarDecl::ListInit);
10394   }
10395
10396   CheckCompleteVariableDeclaration(VDecl);
10397 }
10398
10399 /// ActOnInitializerError - Given that there was an error parsing an
10400 /// initializer for the given declaration, try to return to some form
10401 /// of sanity.
10402 void Sema::ActOnInitializerError(Decl *D) {
10403   // Our main concern here is re-establishing invariants like "a
10404   // variable's type is either dependent or complete".
10405   if (!D || D->isInvalidDecl()) return;
10406
10407   VarDecl *VD = dyn_cast<VarDecl>(D);
10408   if (!VD) return;
10409
10410   // Bindings are not usable if we can't make sense of the initializer.
10411   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10412     for (auto *BD : DD->bindings())
10413       BD->setInvalidDecl();
10414
10415   // Auto types are meaningless if we can't make sense of the initializer.
10416   if (ParsingInitForAutoVars.count(D)) {
10417     D->setInvalidDecl();
10418     return;
10419   }
10420
10421   QualType Ty = VD->getType();
10422   if (Ty->isDependentType()) return;
10423
10424   // Require a complete type.
10425   if (RequireCompleteType(VD->getLocation(),
10426                           Context.getBaseElementType(Ty),
10427                           diag::err_typecheck_decl_incomplete_type)) {
10428     VD->setInvalidDecl();
10429     return;
10430   }
10431
10432   // Require a non-abstract type.
10433   if (RequireNonAbstractType(VD->getLocation(), Ty,
10434                              diag::err_abstract_type_in_decl,
10435                              AbstractVariableType)) {
10436     VD->setInvalidDecl();
10437     return;
10438   }
10439
10440   // Don't bother complaining about constructors or destructors,
10441   // though.
10442 }
10443
10444 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10445   // If there is no declaration, there was an error parsing it. Just ignore it.
10446   if (!RealDecl)
10447     return;
10448
10449   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10450     QualType Type = Var->getType();
10451
10452     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10453     if (isa<DecompositionDecl>(RealDecl)) {
10454       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10455       Var->setInvalidDecl();
10456       return;
10457     }
10458
10459     if (Type->isUndeducedType() &&
10460         DeduceVariableDeclarationType(Var, false, nullptr))
10461       return;
10462
10463     // C++11 [class.static.data]p3: A static data member can be declared with
10464     // the constexpr specifier; if so, its declaration shall specify
10465     // a brace-or-equal-initializer.
10466     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10467     // the definition of a variable [...] or the declaration of a static data
10468     // member.
10469     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10470         !Var->isThisDeclarationADemotedDefinition()) {
10471       if (Var->isStaticDataMember()) {
10472         // C++1z removes the relevant rule; the in-class declaration is always
10473         // a definition there.
10474         if (!getLangOpts().CPlusPlus1z) {
10475           Diag(Var->getLocation(),
10476                diag::err_constexpr_static_mem_var_requires_init)
10477             << Var->getDeclName();
10478           Var->setInvalidDecl();
10479           return;
10480         }
10481       } else {
10482         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10483         Var->setInvalidDecl();
10484         return;
10485       }
10486     }
10487
10488     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10489     // definition having the concept specifier is called a variable concept. A
10490     // concept definition refers to [...] a variable concept and its initializer.
10491     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10492       if (VTD->isConcept()) {
10493         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10494         Var->setInvalidDecl();
10495         return;
10496       }
10497     }
10498
10499     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10500     // be initialized.
10501     if (!Var->isInvalidDecl() &&
10502         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10503         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10504       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10505       Var->setInvalidDecl();
10506       return;
10507     }
10508
10509     switch (Var->isThisDeclarationADefinition()) {
10510     case VarDecl::Definition:
10511       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10512         break;
10513
10514       // We have an out-of-line definition of a static data member
10515       // that has an in-class initializer, so we type-check this like
10516       // a declaration.
10517       //
10518       // Fall through
10519
10520     case VarDecl::DeclarationOnly:
10521       // It's only a declaration.
10522
10523       // Block scope. C99 6.7p7: If an identifier for an object is
10524       // declared with no linkage (C99 6.2.2p6), the type for the
10525       // object shall be complete.
10526       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10527           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10528           RequireCompleteType(Var->getLocation(), Type,
10529                               diag::err_typecheck_decl_incomplete_type))
10530         Var->setInvalidDecl();
10531
10532       // Make sure that the type is not abstract.
10533       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10534           RequireNonAbstractType(Var->getLocation(), Type,
10535                                  diag::err_abstract_type_in_decl,
10536                                  AbstractVariableType))
10537         Var->setInvalidDecl();
10538       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10539           Var->getStorageClass() == SC_PrivateExtern) {
10540         Diag(Var->getLocation(), diag::warn_private_extern);
10541         Diag(Var->getLocation(), diag::note_private_extern);
10542       }
10543
10544       return;
10545
10546     case VarDecl::TentativeDefinition:
10547       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10548       // object that has file scope without an initializer, and without a
10549       // storage-class specifier or with the storage-class specifier "static",
10550       // constitutes a tentative definition. Note: A tentative definition with
10551       // external linkage is valid (C99 6.2.2p5).
10552       if (!Var->isInvalidDecl()) {
10553         if (const IncompleteArrayType *ArrayT
10554                                     = Context.getAsIncompleteArrayType(Type)) {
10555           if (RequireCompleteType(Var->getLocation(),
10556                                   ArrayT->getElementType(),
10557                                   diag::err_illegal_decl_array_incomplete_type))
10558             Var->setInvalidDecl();
10559         } else if (Var->getStorageClass() == SC_Static) {
10560           // C99 6.9.2p3: If the declaration of an identifier for an object is
10561           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10562           // declared type shall not be an incomplete type.
10563           // NOTE: code such as the following
10564           //     static struct s;
10565           //     struct s { int a; };
10566           // is accepted by gcc. Hence here we issue a warning instead of
10567           // an error and we do not invalidate the static declaration.
10568           // NOTE: to avoid multiple warnings, only check the first declaration.
10569           if (Var->isFirstDecl())
10570             RequireCompleteType(Var->getLocation(), Type,
10571                                 diag::ext_typecheck_decl_incomplete_type);
10572         }
10573       }
10574
10575       // Record the tentative definition; we're done.
10576       if (!Var->isInvalidDecl())
10577         TentativeDefinitions.push_back(Var);
10578       return;
10579     }
10580
10581     // Provide a specific diagnostic for uninitialized variable
10582     // definitions with incomplete array type.
10583     if (Type->isIncompleteArrayType()) {
10584       Diag(Var->getLocation(),
10585            diag::err_typecheck_incomplete_array_needs_initializer);
10586       Var->setInvalidDecl();
10587       return;
10588     }
10589
10590     // Provide a specific diagnostic for uninitialized variable
10591     // definitions with reference type.
10592     if (Type->isReferenceType()) {
10593       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10594         << Var->getDeclName()
10595         << SourceRange(Var->getLocation(), Var->getLocation());
10596       Var->setInvalidDecl();
10597       return;
10598     }
10599
10600     // Do not attempt to type-check the default initializer for a
10601     // variable with dependent type.
10602     if (Type->isDependentType())
10603       return;
10604
10605     if (Var->isInvalidDecl())
10606       return;
10607
10608     if (!Var->hasAttr<AliasAttr>()) {
10609       if (RequireCompleteType(Var->getLocation(),
10610                               Context.getBaseElementType(Type),
10611                               diag::err_typecheck_decl_incomplete_type)) {
10612         Var->setInvalidDecl();
10613         return;
10614       }
10615     } else {
10616       return;
10617     }
10618
10619     // The variable can not have an abstract class type.
10620     if (RequireNonAbstractType(Var->getLocation(), Type,
10621                                diag::err_abstract_type_in_decl,
10622                                AbstractVariableType)) {
10623       Var->setInvalidDecl();
10624       return;
10625     }
10626
10627     // Check for jumps past the implicit initializer.  C++0x
10628     // clarifies that this applies to a "variable with automatic
10629     // storage duration", not a "local variable".
10630     // C++11 [stmt.dcl]p3
10631     //   A program that jumps from a point where a variable with automatic
10632     //   storage duration is not in scope to a point where it is in scope is
10633     //   ill-formed unless the variable has scalar type, class type with a
10634     //   trivial default constructor and a trivial destructor, a cv-qualified
10635     //   version of one of these types, or an array of one of the preceding
10636     //   types and is declared without an initializer.
10637     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10638       if (const RecordType *Record
10639             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10640         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10641         // Mark the function for further checking even if the looser rules of
10642         // C++11 do not require such checks, so that we can diagnose
10643         // incompatibilities with C++98.
10644         if (!CXXRecord->isPOD())
10645           getCurFunction()->setHasBranchProtectedScope();
10646       }
10647     }
10648
10649     // C++03 [dcl.init]p9:
10650     //   If no initializer is specified for an object, and the
10651     //   object is of (possibly cv-qualified) non-POD class type (or
10652     //   array thereof), the object shall be default-initialized; if
10653     //   the object is of const-qualified type, the underlying class
10654     //   type shall have a user-declared default
10655     //   constructor. Otherwise, if no initializer is specified for
10656     //   a non- static object, the object and its subobjects, if
10657     //   any, have an indeterminate initial value); if the object
10658     //   or any of its subobjects are of const-qualified type, the
10659     //   program is ill-formed.
10660     // C++0x [dcl.init]p11:
10661     //   If no initializer is specified for an object, the object is
10662     //   default-initialized; [...].
10663     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10664     InitializationKind Kind
10665       = InitializationKind::CreateDefault(Var->getLocation());
10666
10667     InitializationSequence InitSeq(*this, Entity, Kind, None);
10668     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10669     if (Init.isInvalid())
10670       Var->setInvalidDecl();
10671     else if (Init.get()) {
10672       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10673       // This is important for template substitution.
10674       Var->setInitStyle(VarDecl::CallInit);
10675     }
10676
10677     CheckCompleteVariableDeclaration(Var);
10678   }
10679 }
10680
10681 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10682   // If there is no declaration, there was an error parsing it. Ignore it.
10683   if (!D)
10684     return;
10685
10686   VarDecl *VD = dyn_cast<VarDecl>(D);
10687   if (!VD) {
10688     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10689     D->setInvalidDecl();
10690     return;
10691   }
10692
10693   VD->setCXXForRangeDecl(true);
10694
10695   // for-range-declaration cannot be given a storage class specifier.
10696   int Error = -1;
10697   switch (VD->getStorageClass()) {
10698   case SC_None:
10699     break;
10700   case SC_Extern:
10701     Error = 0;
10702     break;
10703   case SC_Static:
10704     Error = 1;
10705     break;
10706   case SC_PrivateExtern:
10707     Error = 2;
10708     break;
10709   case SC_Auto:
10710     Error = 3;
10711     break;
10712   case SC_Register:
10713     Error = 4;
10714     break;
10715   }
10716   if (Error != -1) {
10717     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10718       << VD->getDeclName() << Error;
10719     D->setInvalidDecl();
10720   }
10721 }
10722
10723 StmtResult
10724 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10725                                  IdentifierInfo *Ident,
10726                                  ParsedAttributes &Attrs,
10727                                  SourceLocation AttrEnd) {
10728   // C++1y [stmt.iter]p1:
10729   //   A range-based for statement of the form
10730   //      for ( for-range-identifier : for-range-initializer ) statement
10731   //   is equivalent to
10732   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10733   DeclSpec DS(Attrs.getPool().getFactory());
10734
10735   const char *PrevSpec;
10736   unsigned DiagID;
10737   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10738                      getPrintingPolicy());
10739
10740   Declarator D(DS, Declarator::ForContext);
10741   D.SetIdentifier(Ident, IdentLoc);
10742   D.takeAttributes(Attrs, AttrEnd);
10743
10744   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10745   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10746                 EmptyAttrs, IdentLoc);
10747   Decl *Var = ActOnDeclarator(S, D);
10748   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10749   FinalizeDeclaration(Var);
10750   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10751                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10752 }
10753
10754 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10755   if (var->isInvalidDecl()) return;
10756
10757   if (getLangOpts().OpenCL) {
10758     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10759     // initialiser
10760     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10761         !var->hasInit()) {
10762       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10763           << 1 /*Init*/;
10764       var->setInvalidDecl();
10765       return;
10766     }
10767   }
10768
10769   // In Objective-C, don't allow jumps past the implicit initialization of a
10770   // local retaining variable.
10771   if (getLangOpts().ObjC1 &&
10772       var->hasLocalStorage()) {
10773     switch (var->getType().getObjCLifetime()) {
10774     case Qualifiers::OCL_None:
10775     case Qualifiers::OCL_ExplicitNone:
10776     case Qualifiers::OCL_Autoreleasing:
10777       break;
10778
10779     case Qualifiers::OCL_Weak:
10780     case Qualifiers::OCL_Strong:
10781       getCurFunction()->setHasBranchProtectedScope();
10782       break;
10783     }
10784   }
10785
10786   // Warn about externally-visible variables being defined without a
10787   // prior declaration.  We only want to do this for global
10788   // declarations, but we also specifically need to avoid doing it for
10789   // class members because the linkage of an anonymous class can
10790   // change if it's later given a typedef name.
10791   if (var->isThisDeclarationADefinition() &&
10792       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10793       var->isExternallyVisible() && var->hasLinkage() &&
10794       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10795                                   var->getLocation())) {
10796     // Find a previous declaration that's not a definition.
10797     VarDecl *prev = var->getPreviousDecl();
10798     while (prev && prev->isThisDeclarationADefinition())
10799       prev = prev->getPreviousDecl();
10800
10801     if (!prev)
10802       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10803   }
10804
10805   // Cache the result of checking for constant initialization.
10806   Optional<bool> CacheHasConstInit;
10807   const Expr *CacheCulprit;
10808   auto checkConstInit = [&]() mutable {
10809     if (!CacheHasConstInit)
10810       CacheHasConstInit = var->getInit()->isConstantInitializer(
10811             Context, var->getType()->isReferenceType(), &CacheCulprit);
10812     return *CacheHasConstInit;
10813   };
10814
10815   if (var->getTLSKind() == VarDecl::TLS_Static) {
10816     if (var->getType().isDestructedType()) {
10817       // GNU C++98 edits for __thread, [basic.start.term]p3:
10818       //   The type of an object with thread storage duration shall not
10819       //   have a non-trivial destructor.
10820       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10821       if (getLangOpts().CPlusPlus11)
10822         Diag(var->getLocation(), diag::note_use_thread_local);
10823     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
10824       if (!checkConstInit()) {
10825         // GNU C++98 edits for __thread, [basic.start.init]p4:
10826         //   An object of thread storage duration shall not require dynamic
10827         //   initialization.
10828         // FIXME: Need strict checking here.
10829         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
10830           << CacheCulprit->getSourceRange();
10831         if (getLangOpts().CPlusPlus11)
10832           Diag(var->getLocation(), diag::note_use_thread_local);
10833       }
10834     }
10835   }
10836
10837   // Apply section attributes and pragmas to global variables.
10838   bool GlobalStorage = var->hasGlobalStorage();
10839   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10840       !inTemplateInstantiation()) {
10841     PragmaStack<StringLiteral *> *Stack = nullptr;
10842     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10843     if (var->getType().isConstQualified())
10844       Stack = &ConstSegStack;
10845     else if (!var->getInit()) {
10846       Stack = &BSSSegStack;
10847       SectionFlags |= ASTContext::PSF_Write;
10848     } else {
10849       Stack = &DataSegStack;
10850       SectionFlags |= ASTContext::PSF_Write;
10851     }
10852     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10853       var->addAttr(SectionAttr::CreateImplicit(
10854           Context, SectionAttr::Declspec_allocate,
10855           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10856     }
10857     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10858       if (UnifySection(SA->getName(), SectionFlags, var))
10859         var->dropAttr<SectionAttr>();
10860
10861     // Apply the init_seg attribute if this has an initializer.  If the
10862     // initializer turns out to not be dynamic, we'll end up ignoring this
10863     // attribute.
10864     if (CurInitSeg && var->getInit())
10865       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10866                                                CurInitSegLoc));
10867   }
10868
10869   // All the following checks are C++ only.
10870   if (!getLangOpts().CPlusPlus) {
10871       // If this variable must be emitted, add it as an initializer for the
10872       // current module.
10873      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10874        Context.addModuleInitializer(ModuleScopes.back().Module, var);
10875      return;
10876   }
10877
10878   if (auto *DD = dyn_cast<DecompositionDecl>(var))
10879     CheckCompleteDecompositionDeclaration(DD);
10880
10881   QualType type = var->getType();
10882   if (type->isDependentType()) return;
10883
10884   // __block variables might require us to capture a copy-initializer.
10885   if (var->hasAttr<BlocksAttr>()) {
10886     // It's currently invalid to ever have a __block variable with an
10887     // array type; should we diagnose that here?
10888
10889     // Regardless, we don't want to ignore array nesting when
10890     // constructing this copy.
10891     if (type->isStructureOrClassType()) {
10892       EnterExpressionEvaluationContext scope(
10893           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
10894       SourceLocation poi = var->getLocation();
10895       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10896       ExprResult result
10897         = PerformMoveOrCopyInitialization(
10898             InitializedEntity::InitializeBlock(poi, type, false),
10899             var, var->getType(), varRef, /*AllowNRVO=*/true);
10900       if (!result.isInvalid()) {
10901         result = MaybeCreateExprWithCleanups(result);
10902         Expr *init = result.getAs<Expr>();
10903         Context.setBlockVarCopyInits(var, init);
10904       }
10905     }
10906   }
10907
10908   Expr *Init = var->getInit();
10909   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10910   QualType baseType = Context.getBaseElementType(type);
10911
10912   if (!var->getDeclContext()->isDependentContext() &&
10913       Init && !Init->isValueDependent()) {
10914
10915     if (var->isConstexpr()) {
10916       SmallVector<PartialDiagnosticAt, 8> Notes;
10917       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10918         SourceLocation DiagLoc = var->getLocation();
10919         // If the note doesn't add any useful information other than a source
10920         // location, fold it into the primary diagnostic.
10921         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10922               diag::note_invalid_subexpr_in_const_expr) {
10923           DiagLoc = Notes[0].first;
10924           Notes.clear();
10925         }
10926         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10927           << var << Init->getSourceRange();
10928         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10929           Diag(Notes[I].first, Notes[I].second);
10930       }
10931     } else if (var->isUsableInConstantExpressions(Context)) {
10932       // Check whether the initializer of a const variable of integral or
10933       // enumeration type is an ICE now, since we can't tell whether it was
10934       // initialized by a constant expression if we check later.
10935       var->checkInitIsICE();
10936     }
10937
10938     // Don't emit further diagnostics about constexpr globals since they
10939     // were just diagnosed.
10940     if (!var->isConstexpr() && GlobalStorage &&
10941             var->hasAttr<RequireConstantInitAttr>()) {
10942       // FIXME: Need strict checking in C++03 here.
10943       bool DiagErr = getLangOpts().CPlusPlus11
10944           ? !var->checkInitIsICE() : !checkConstInit();
10945       if (DiagErr) {
10946         auto attr = var->getAttr<RequireConstantInitAttr>();
10947         Diag(var->getLocation(), diag::err_require_constant_init_failed)
10948           << Init->getSourceRange();
10949         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
10950           << attr->getRange();
10951       }
10952     }
10953     else if (!var->isConstexpr() && IsGlobal &&
10954              !getDiagnostics().isIgnored(diag::warn_global_constructor,
10955                                     var->getLocation())) {
10956       // Warn about globals which don't have a constant initializer.  Don't
10957       // warn about globals with a non-trivial destructor because we already
10958       // warned about them.
10959       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10960       if (!(RD && !RD->hasTrivialDestructor())) {
10961         if (!checkConstInit())
10962           Diag(var->getLocation(), diag::warn_global_constructor)
10963             << Init->getSourceRange();
10964       }
10965     }
10966   }
10967
10968   // Require the destructor.
10969   if (const RecordType *recordType = baseType->getAs<RecordType>())
10970     FinalizeVarWithDestructor(var, recordType);
10971
10972   // If this variable must be emitted, add it as an initializer for the current
10973   // module.
10974   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10975     Context.addModuleInitializer(ModuleScopes.back().Module, var);
10976 }
10977
10978 /// \brief Determines if a variable's alignment is dependent.
10979 static bool hasDependentAlignment(VarDecl *VD) {
10980   if (VD->getType()->isDependentType())
10981     return true;
10982   for (auto *I : VD->specific_attrs<AlignedAttr>())
10983     if (I->isAlignmentDependent())
10984       return true;
10985   return false;
10986 }
10987
10988 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10989 /// any semantic actions necessary after any initializer has been attached.
10990 void
10991 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10992   // Note that we are no longer parsing the initializer for this declaration.
10993   ParsingInitForAutoVars.erase(ThisDecl);
10994
10995   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10996   if (!VD)
10997     return;
10998
10999   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11000     for (auto *BD : DD->bindings()) {
11001       FinalizeDeclaration(BD);
11002     }
11003   }
11004
11005   checkAttributesAfterMerging(*this, *VD);
11006
11007   // Perform TLS alignment check here after attributes attached to the variable
11008   // which may affect the alignment have been processed. Only perform the check
11009   // if the target has a maximum TLS alignment (zero means no constraints).
11010   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11011     // Protect the check so that it's not performed on dependent types and
11012     // dependent alignments (we can't determine the alignment in that case).
11013     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11014         !VD->isInvalidDecl()) {
11015       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11016       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11017         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11018           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11019           << (unsigned)MaxAlignChars.getQuantity();
11020       }
11021     }
11022   }
11023
11024   if (VD->isStaticLocal()) {
11025     if (FunctionDecl *FD =
11026             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11027       // Static locals inherit dll attributes from their function.
11028       if (Attr *A = getDLLAttr(FD)) {
11029         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11030         NewAttr->setInherited(true);
11031         VD->addAttr(NewAttr);
11032       }
11033       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11034       // function, only __shared__ variables may be declared with
11035       // static storage class.
11036       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11037           CUDADiagIfDeviceCode(VD->getLocation(),
11038                                diag::err_device_static_local_var)
11039               << CurrentCUDATarget())
11040         VD->setInvalidDecl();
11041     }
11042   }
11043
11044   // Perform check for initializers of device-side global variables.
11045   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11046   // 7.5). We must also apply the same checks to all __shared__
11047   // variables whether they are local or not. CUDA also allows
11048   // constant initializers for __constant__ and __device__ variables.
11049   if (getLangOpts().CUDA) {
11050     const Expr *Init = VD->getInit();
11051     if (Init && VD->hasGlobalStorage()) {
11052       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11053           VD->hasAttr<CUDASharedAttr>()) {
11054         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11055         bool AllowedInit = false;
11056         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11057           AllowedInit =
11058               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11059         // We'll allow constant initializers even if it's a non-empty
11060         // constructor according to CUDA rules. This deviates from NVCC,
11061         // but allows us to handle things like constexpr constructors.
11062         if (!AllowedInit &&
11063             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11064           AllowedInit = VD->getInit()->isConstantInitializer(
11065               Context, VD->getType()->isReferenceType());
11066
11067         // Also make sure that destructor, if there is one, is empty.
11068         if (AllowedInit)
11069           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11070             AllowedInit =
11071                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11072
11073         if (!AllowedInit) {
11074           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11075                                       ? diag::err_shared_var_init
11076                                       : diag::err_dynamic_var_init)
11077               << Init->getSourceRange();
11078           VD->setInvalidDecl();
11079         }
11080       } else {
11081         // This is a host-side global variable.  Check that the initializer is
11082         // callable from the host side.
11083         const FunctionDecl *InitFn = nullptr;
11084         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11085           InitFn = CE->getConstructor();
11086         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11087           InitFn = CE->getDirectCallee();
11088         }
11089         if (InitFn) {
11090           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11091           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11092             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11093                 << InitFnTarget << InitFn;
11094             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11095             VD->setInvalidDecl();
11096           }
11097         }
11098       }
11099     }
11100   }
11101
11102   // Grab the dllimport or dllexport attribute off of the VarDecl.
11103   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11104
11105   // Imported static data members cannot be defined out-of-line.
11106   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11107     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11108         VD->isThisDeclarationADefinition()) {
11109       // We allow definitions of dllimport class template static data members
11110       // with a warning.
11111       CXXRecordDecl *Context =
11112         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11113       bool IsClassTemplateMember =
11114           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11115           Context->getDescribedClassTemplate();
11116
11117       Diag(VD->getLocation(),
11118            IsClassTemplateMember
11119                ? diag::warn_attribute_dllimport_static_field_definition
11120                : diag::err_attribute_dllimport_static_field_definition);
11121       Diag(IA->getLocation(), diag::note_attribute);
11122       if (!IsClassTemplateMember)
11123         VD->setInvalidDecl();
11124     }
11125   }
11126
11127   // dllimport/dllexport variables cannot be thread local, their TLS index
11128   // isn't exported with the variable.
11129   if (DLLAttr && VD->getTLSKind()) {
11130     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11131     if (F && getDLLAttr(F)) {
11132       assert(VD->isStaticLocal());
11133       // But if this is a static local in a dlimport/dllexport function, the
11134       // function will never be inlined, which means the var would never be
11135       // imported, so having it marked import/export is safe.
11136     } else {
11137       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11138                                                                     << DLLAttr;
11139       VD->setInvalidDecl();
11140     }
11141   }
11142
11143   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11144     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11145       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11146       VD->dropAttr<UsedAttr>();
11147     }
11148   }
11149
11150   const DeclContext *DC = VD->getDeclContext();
11151   // If there's a #pragma GCC visibility in scope, and this isn't a class
11152   // member, set the visibility of this variable.
11153   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11154     AddPushedVisibilityAttribute(VD);
11155
11156   // FIXME: Warn on unused templates.
11157   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
11158       !isa<VarTemplatePartialSpecializationDecl>(VD))
11159     MarkUnusedFileScopedDecl(VD);
11160
11161   // Now we have parsed the initializer and can update the table of magic
11162   // tag values.
11163   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11164       !VD->getType()->isIntegralOrEnumerationType())
11165     return;
11166
11167   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11168     const Expr *MagicValueExpr = VD->getInit();
11169     if (!MagicValueExpr) {
11170       continue;
11171     }
11172     llvm::APSInt MagicValueInt;
11173     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11174       Diag(I->getRange().getBegin(),
11175            diag::err_type_tag_for_datatype_not_ice)
11176         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11177       continue;
11178     }
11179     if (MagicValueInt.getActiveBits() > 64) {
11180       Diag(I->getRange().getBegin(),
11181            diag::err_type_tag_for_datatype_too_large)
11182         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11183       continue;
11184     }
11185     uint64_t MagicValue = MagicValueInt.getZExtValue();
11186     RegisterTypeTagForDatatype(I->getArgumentKind(),
11187                                MagicValue,
11188                                I->getMatchingCType(),
11189                                I->getLayoutCompatible(),
11190                                I->getMustBeNull());
11191   }
11192 }
11193
11194 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11195   auto *VD = dyn_cast<VarDecl>(DD);
11196   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11197 }
11198
11199 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11200                                                    ArrayRef<Decl *> Group) {
11201   SmallVector<Decl*, 8> Decls;
11202
11203   if (DS.isTypeSpecOwned())
11204     Decls.push_back(DS.getRepAsDecl());
11205
11206   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11207   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11208   bool DiagnosedMultipleDecomps = false;
11209   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11210   bool DiagnosedNonDeducedAuto = false;
11211
11212   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11213     if (Decl *D = Group[i]) {
11214       // For declarators, there are some additional syntactic-ish checks we need
11215       // to perform.
11216       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11217         if (!FirstDeclaratorInGroup)
11218           FirstDeclaratorInGroup = DD;
11219         if (!FirstDecompDeclaratorInGroup)
11220           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11221         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11222             !hasDeducedAuto(DD))
11223           FirstNonDeducedAutoInGroup = DD;
11224
11225         if (FirstDeclaratorInGroup != DD) {
11226           // A decomposition declaration cannot be combined with any other
11227           // declaration in the same group.
11228           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11229             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11230                  diag::err_decomp_decl_not_alone)
11231                 << FirstDeclaratorInGroup->getSourceRange()
11232                 << DD->getSourceRange();
11233             DiagnosedMultipleDecomps = true;
11234           }
11235
11236           // A declarator that uses 'auto' in any way other than to declare a
11237           // variable with a deduced type cannot be combined with any other
11238           // declarator in the same group.
11239           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11240             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11241                  diag::err_auto_non_deduced_not_alone)
11242                 << FirstNonDeducedAutoInGroup->getType()
11243                        ->hasAutoForTrailingReturnType()
11244                 << FirstDeclaratorInGroup->getSourceRange()
11245                 << DD->getSourceRange();
11246             DiagnosedNonDeducedAuto = true;
11247           }
11248         }
11249       }
11250
11251       Decls.push_back(D);
11252     }
11253   }
11254
11255   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11256     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11257       handleTagNumbering(Tag, S);
11258       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11259           getLangOpts().CPlusPlus)
11260         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11261     }
11262   }
11263
11264   return BuildDeclaratorGroup(Decls);
11265 }
11266
11267 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11268 /// group, performing any necessary semantic checking.
11269 Sema::DeclGroupPtrTy
11270 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11271   // C++14 [dcl.spec.auto]p7: (DR1347)
11272   //   If the type that replaces the placeholder type is not the same in each
11273   //   deduction, the program is ill-formed.
11274   if (Group.size() > 1) {
11275     QualType Deduced;
11276     VarDecl *DeducedDecl = nullptr;
11277     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11278       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11279       if (!D || D->isInvalidDecl())
11280         break;
11281       DeducedType *DT = D->getType()->getContainedDeducedType();
11282       if (!DT || DT->getDeducedType().isNull())
11283         continue;
11284       if (Deduced.isNull()) {
11285         Deduced = DT->getDeducedType();
11286         DeducedDecl = D;
11287       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11288         auto *AT = dyn_cast<AutoType>(DT);
11289         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11290              diag::err_auto_different_deductions)
11291           << (AT ? (unsigned)AT->getKeyword() : 3)
11292           << Deduced << DeducedDecl->getDeclName()
11293           << DT->getDeducedType() << D->getDeclName()
11294           << DeducedDecl->getInit()->getSourceRange()
11295           << D->getInit()->getSourceRange();
11296         D->setInvalidDecl();
11297         break;
11298       }
11299     }
11300   }
11301
11302   ActOnDocumentableDecls(Group);
11303
11304   return DeclGroupPtrTy::make(
11305       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11306 }
11307
11308 void Sema::ActOnDocumentableDecl(Decl *D) {
11309   ActOnDocumentableDecls(D);
11310 }
11311
11312 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11313   // Don't parse the comment if Doxygen diagnostics are ignored.
11314   if (Group.empty() || !Group[0])
11315     return;
11316
11317   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11318                       Group[0]->getLocation()) &&
11319       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11320                       Group[0]->getLocation()))
11321     return;
11322
11323   if (Group.size() >= 2) {
11324     // This is a decl group.  Normally it will contain only declarations
11325     // produced from declarator list.  But in case we have any definitions or
11326     // additional declaration references:
11327     //   'typedef struct S {} S;'
11328     //   'typedef struct S *S;'
11329     //   'struct S *pS;'
11330     // FinalizeDeclaratorGroup adds these as separate declarations.
11331     Decl *MaybeTagDecl = Group[0];
11332     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11333       Group = Group.slice(1);
11334     }
11335   }
11336
11337   // See if there are any new comments that are not attached to a decl.
11338   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11339   if (!Comments.empty() &&
11340       !Comments.back()->isAttached()) {
11341     // There is at least one comment that not attached to a decl.
11342     // Maybe it should be attached to one of these decls?
11343     //
11344     // Note that this way we pick up not only comments that precede the
11345     // declaration, but also comments that *follow* the declaration -- thanks to
11346     // the lookahead in the lexer: we've consumed the semicolon and looked
11347     // ahead through comments.
11348     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11349       Context.getCommentForDecl(Group[i], &PP);
11350   }
11351 }
11352
11353 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11354 /// to introduce parameters into function prototype scope.
11355 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11356   const DeclSpec &DS = D.getDeclSpec();
11357
11358   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11359
11360   // C++03 [dcl.stc]p2 also permits 'auto'.
11361   StorageClass SC = SC_None;
11362   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11363     SC = SC_Register;
11364   } else if (getLangOpts().CPlusPlus &&
11365              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11366     SC = SC_Auto;
11367   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11368     Diag(DS.getStorageClassSpecLoc(),
11369          diag::err_invalid_storage_class_in_func_decl);
11370     D.getMutableDeclSpec().ClearStorageClassSpecs();
11371   }
11372
11373   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11374     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11375       << DeclSpec::getSpecifierName(TSCS);
11376   if (DS.isInlineSpecified())
11377     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11378         << getLangOpts().CPlusPlus1z;
11379   if (DS.isConstexprSpecified())
11380     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11381       << 0;
11382   if (DS.isConceptSpecified())
11383     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11384
11385   DiagnoseFunctionSpecifiers(DS);
11386
11387   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11388   QualType parmDeclType = TInfo->getType();
11389
11390   if (getLangOpts().CPlusPlus) {
11391     // Check that there are no default arguments inside the type of this
11392     // parameter.
11393     CheckExtraCXXDefaultArguments(D);
11394
11395     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11396     if (D.getCXXScopeSpec().isSet()) {
11397       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11398         << D.getCXXScopeSpec().getRange();
11399       D.getCXXScopeSpec().clear();
11400     }
11401   }
11402
11403   // Ensure we have a valid name
11404   IdentifierInfo *II = nullptr;
11405   if (D.hasName()) {
11406     II = D.getIdentifier();
11407     if (!II) {
11408       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11409         << GetNameForDeclarator(D).getName();
11410       D.setInvalidType(true);
11411     }
11412   }
11413
11414   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11415   if (II) {
11416     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11417                    ForRedeclaration);
11418     LookupName(R, S);
11419     if (R.isSingleResult()) {
11420       NamedDecl *PrevDecl = R.getFoundDecl();
11421       if (PrevDecl->isTemplateParameter()) {
11422         // Maybe we will complain about the shadowed template parameter.
11423         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11424         // Just pretend that we didn't see the previous declaration.
11425         PrevDecl = nullptr;
11426       } else if (S->isDeclScope(PrevDecl)) {
11427         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11428         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11429
11430         // Recover by removing the name
11431         II = nullptr;
11432         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11433         D.setInvalidType(true);
11434       }
11435     }
11436   }
11437
11438   // Temporarily put parameter variables in the translation unit, not
11439   // the enclosing context.  This prevents them from accidentally
11440   // looking like class members in C++.
11441   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11442                                     D.getLocStart(),
11443                                     D.getIdentifierLoc(), II,
11444                                     parmDeclType, TInfo,
11445                                     SC);
11446
11447   if (D.isInvalidType())
11448     New->setInvalidDecl();
11449
11450   assert(S->isFunctionPrototypeScope());
11451   assert(S->getFunctionPrototypeDepth() >= 1);
11452   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11453                     S->getNextFunctionPrototypeIndex());
11454
11455   // Add the parameter declaration into this scope.
11456   S->AddDecl(New);
11457   if (II)
11458     IdResolver.AddDecl(New);
11459
11460   ProcessDeclAttributes(S, New, D);
11461
11462   if (D.getDeclSpec().isModulePrivateSpecified())
11463     Diag(New->getLocation(), diag::err_module_private_local)
11464       << 1 << New->getDeclName()
11465       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11466       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11467
11468   if (New->hasAttr<BlocksAttr>()) {
11469     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11470   }
11471   return New;
11472 }
11473
11474 /// \brief Synthesizes a variable for a parameter arising from a
11475 /// typedef.
11476 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11477                                               SourceLocation Loc,
11478                                               QualType T) {
11479   /* FIXME: setting StartLoc == Loc.
11480      Would it be worth to modify callers so as to provide proper source
11481      location for the unnamed parameters, embedding the parameter's type? */
11482   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11483                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11484                                            SC_None, nullptr);
11485   Param->setImplicit();
11486   return Param;
11487 }
11488
11489 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11490   // Don't diagnose unused-parameter errors in template instantiations; we
11491   // will already have done so in the template itself.
11492   if (inTemplateInstantiation())
11493     return;
11494
11495   for (const ParmVarDecl *Parameter : Parameters) {
11496     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11497         !Parameter->hasAttr<UnusedAttr>()) {
11498       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11499         << Parameter->getDeclName();
11500     }
11501   }
11502 }
11503
11504 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11505     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11506   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11507     return;
11508
11509   // Warn if the return value is pass-by-value and larger than the specified
11510   // threshold.
11511   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11512     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11513     if (Size > LangOpts.NumLargeByValueCopy)
11514       Diag(D->getLocation(), diag::warn_return_value_size)
11515           << D->getDeclName() << Size;
11516   }
11517
11518   // Warn if any parameter is pass-by-value and larger than the specified
11519   // threshold.
11520   for (const ParmVarDecl *Parameter : Parameters) {
11521     QualType T = Parameter->getType();
11522     if (T->isDependentType() || !T.isPODType(Context))
11523       continue;
11524     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11525     if (Size > LangOpts.NumLargeByValueCopy)
11526       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11527           << Parameter->getDeclName() << Size;
11528   }
11529 }
11530
11531 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11532                                   SourceLocation NameLoc, IdentifierInfo *Name,
11533                                   QualType T, TypeSourceInfo *TSInfo,
11534                                   StorageClass SC) {
11535   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11536   if (getLangOpts().ObjCAutoRefCount &&
11537       T.getObjCLifetime() == Qualifiers::OCL_None &&
11538       T->isObjCLifetimeType()) {
11539
11540     Qualifiers::ObjCLifetime lifetime;
11541
11542     // Special cases for arrays:
11543     //   - if it's const, use __unsafe_unretained
11544     //   - otherwise, it's an error
11545     if (T->isArrayType()) {
11546       if (!T.isConstQualified()) {
11547         DelayedDiagnostics.add(
11548             sema::DelayedDiagnostic::makeForbiddenType(
11549             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11550       }
11551       lifetime = Qualifiers::OCL_ExplicitNone;
11552     } else {
11553       lifetime = T->getObjCARCImplicitLifetime();
11554     }
11555     T = Context.getLifetimeQualifiedType(T, lifetime);
11556   }
11557
11558   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11559                                          Context.getAdjustedParameterType(T),
11560                                          TSInfo, SC, nullptr);
11561
11562   // Parameters can not be abstract class types.
11563   // For record types, this is done by the AbstractClassUsageDiagnoser once
11564   // the class has been completely parsed.
11565   if (!CurContext->isRecord() &&
11566       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11567                              AbstractParamType))
11568     New->setInvalidDecl();
11569
11570   // Parameter declarators cannot be interface types. All ObjC objects are
11571   // passed by reference.
11572   if (T->isObjCObjectType()) {
11573     SourceLocation TypeEndLoc =
11574         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11575     Diag(NameLoc,
11576          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11577       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11578     T = Context.getObjCObjectPointerType(T);
11579     New->setType(T);
11580   }
11581
11582   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11583   // duration shall not be qualified by an address-space qualifier."
11584   // Since all parameters have automatic store duration, they can not have
11585   // an address space.
11586   if (T.getAddressSpace() != 0) {
11587     // OpenCL allows function arguments declared to be an array of a type
11588     // to be qualified with an address space.
11589     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11590       Diag(NameLoc, diag::err_arg_with_address_space);
11591       New->setInvalidDecl();
11592     }
11593   }
11594
11595   return New;
11596 }
11597
11598 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11599                                            SourceLocation LocAfterDecls) {
11600   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11601
11602   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11603   // for a K&R function.
11604   if (!FTI.hasPrototype) {
11605     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11606       --i;
11607       if (FTI.Params[i].Param == nullptr) {
11608         SmallString<256> Code;
11609         llvm::raw_svector_ostream(Code)
11610             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11611         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11612             << FTI.Params[i].Ident
11613             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11614
11615         // Implicitly declare the argument as type 'int' for lack of a better
11616         // type.
11617         AttributeFactory attrs;
11618         DeclSpec DS(attrs);
11619         const char* PrevSpec; // unused
11620         unsigned DiagID; // unused
11621         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11622                            DiagID, Context.getPrintingPolicy());
11623         // Use the identifier location for the type source range.
11624         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11625         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11626         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11627         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11628         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11629       }
11630     }
11631   }
11632 }
11633
11634 Decl *
11635 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11636                               MultiTemplateParamsArg TemplateParameterLists,
11637                               SkipBodyInfo *SkipBody) {
11638   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11639   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11640   Scope *ParentScope = FnBodyScope->getParent();
11641
11642   D.setFunctionDefinitionKind(FDK_Definition);
11643   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11644   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11645 }
11646
11647 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11648   Consumer.HandleInlineFunctionDefinition(D);
11649 }
11650
11651 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11652                              const FunctionDecl*& PossibleZeroParamPrototype) {
11653   // Don't warn about invalid declarations.
11654   if (FD->isInvalidDecl())
11655     return false;
11656
11657   // Or declarations that aren't global.
11658   if (!FD->isGlobal())
11659     return false;
11660
11661   // Don't warn about C++ member functions.
11662   if (isa<CXXMethodDecl>(FD))
11663     return false;
11664
11665   // Don't warn about 'main'.
11666   if (FD->isMain())
11667     return false;
11668
11669   // Don't warn about inline functions.
11670   if (FD->isInlined())
11671     return false;
11672
11673   // Don't warn about function templates.
11674   if (FD->getDescribedFunctionTemplate())
11675     return false;
11676
11677   // Don't warn about function template specializations.
11678   if (FD->isFunctionTemplateSpecialization())
11679     return false;
11680
11681   // Don't warn for OpenCL kernels.
11682   if (FD->hasAttr<OpenCLKernelAttr>())
11683     return false;
11684
11685   // Don't warn on explicitly deleted functions.
11686   if (FD->isDeleted())
11687     return false;
11688
11689   bool MissingPrototype = true;
11690   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11691        Prev; Prev = Prev->getPreviousDecl()) {
11692     // Ignore any declarations that occur in function or method
11693     // scope, because they aren't visible from the header.
11694     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11695       continue;
11696
11697     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11698     if (FD->getNumParams() == 0)
11699       PossibleZeroParamPrototype = Prev;
11700     break;
11701   }
11702
11703   return MissingPrototype;
11704 }
11705
11706 void
11707 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11708                                    const FunctionDecl *EffectiveDefinition,
11709                                    SkipBodyInfo *SkipBody) {
11710   const FunctionDecl *Definition = EffectiveDefinition;
11711   if (!Definition)
11712     if (!FD->isDefined(Definition))
11713       return;
11714
11715   if (canRedefineFunction(Definition, getLangOpts()))
11716     return;
11717
11718   // If we don't have a visible definition of the function, and it's inline or
11719   // a template, skip the new definition.
11720   if (SkipBody && !hasVisibleDefinition(Definition) &&
11721       (Definition->getFormalLinkage() == InternalLinkage ||
11722        Definition->isInlined() ||
11723        Definition->getDescribedFunctionTemplate() ||
11724        Definition->getNumTemplateParameterLists())) {
11725     SkipBody->ShouldSkip = true;
11726     if (auto *TD = Definition->getDescribedFunctionTemplate())
11727       makeMergedDefinitionVisible(TD, FD->getLocation());
11728     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11729                                 FD->getLocation());
11730     return;
11731   }
11732
11733   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11734       Definition->getStorageClass() == SC_Extern)
11735     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11736         << FD->getDeclName() << getLangOpts().CPlusPlus;
11737   else
11738     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11739
11740   Diag(Definition->getLocation(), diag::note_previous_definition);
11741   FD->setInvalidDecl();
11742 }
11743
11744 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11745                                    Sema &S) {
11746   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11747
11748   LambdaScopeInfo *LSI = S.PushLambdaScope();
11749   LSI->CallOperator = CallOperator;
11750   LSI->Lambda = LambdaClass;
11751   LSI->ReturnType = CallOperator->getReturnType();
11752   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11753
11754   if (LCD == LCD_None)
11755     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11756   else if (LCD == LCD_ByCopy)
11757     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11758   else if (LCD == LCD_ByRef)
11759     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11760   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11761
11762   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11763   LSI->Mutable = !CallOperator->isConst();
11764
11765   // Add the captures to the LSI so they can be noted as already
11766   // captured within tryCaptureVar.
11767   auto I = LambdaClass->field_begin();
11768   for (const auto &C : LambdaClass->captures()) {
11769     if (C.capturesVariable()) {
11770       VarDecl *VD = C.getCapturedVar();
11771       if (VD->isInitCapture())
11772         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11773       QualType CaptureType = VD->getType();
11774       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11775       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11776           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11777           /*EllipsisLoc*/C.isPackExpansion()
11778                          ? C.getEllipsisLoc() : SourceLocation(),
11779           CaptureType, /*Expr*/ nullptr);
11780
11781     } else if (C.capturesThis()) {
11782       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11783                               /*Expr*/ nullptr,
11784                               C.getCaptureKind() == LCK_StarThis);
11785     } else {
11786       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11787     }
11788     ++I;
11789   }
11790 }
11791
11792 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11793                                     SkipBodyInfo *SkipBody) {
11794   if (!D)
11795     return D;
11796   FunctionDecl *FD = nullptr;
11797
11798   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11799     FD = FunTmpl->getTemplatedDecl();
11800   else
11801     FD = cast<FunctionDecl>(D);
11802
11803   // Check for defining attributes before the check for redefinition.
11804   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
11805     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
11806     FD->dropAttr<AliasAttr>();
11807     FD->setInvalidDecl();
11808   }
11809   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
11810     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
11811     FD->dropAttr<IFuncAttr>();
11812     FD->setInvalidDecl();
11813   }
11814
11815   // See if this is a redefinition.
11816   if (!FD->isLateTemplateParsed()) {
11817     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11818
11819     // If we're skipping the body, we're done. Don't enter the scope.
11820     if (SkipBody && SkipBody->ShouldSkip)
11821       return D;
11822   }
11823
11824   // Mark this function as "will have a body eventually".  This lets users to
11825   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
11826   // this function.
11827   FD->setWillHaveBody();
11828
11829   // If we are instantiating a generic lambda call operator, push
11830   // a LambdaScopeInfo onto the function stack.  But use the information
11831   // that's already been calculated (ActOnLambdaExpr) to prime the current
11832   // LambdaScopeInfo.
11833   // When the template operator is being specialized, the LambdaScopeInfo,
11834   // has to be properly restored so that tryCaptureVariable doesn't try
11835   // and capture any new variables. In addition when calculating potential
11836   // captures during transformation of nested lambdas, it is necessary to
11837   // have the LSI properly restored.
11838   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11839     assert(inTemplateInstantiation() &&
11840            "There should be an active template instantiation on the stack "
11841            "when instantiating a generic lambda!");
11842     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11843   } else {
11844     // Enter a new function scope
11845     PushFunctionScope();
11846   }
11847
11848   // Builtin functions cannot be defined.
11849   if (unsigned BuiltinID = FD->getBuiltinID()) {
11850     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11851         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11852       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11853       FD->setInvalidDecl();
11854     }
11855   }
11856
11857   // The return type of a function definition must be complete
11858   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11859   QualType ResultType = FD->getReturnType();
11860   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11861       !FD->isInvalidDecl() &&
11862       RequireCompleteType(FD->getLocation(), ResultType,
11863                           diag::err_func_def_incomplete_result))
11864     FD->setInvalidDecl();
11865
11866   if (FnBodyScope)
11867     PushDeclContext(FnBodyScope, FD);
11868
11869   // Check the validity of our function parameters
11870   CheckParmsForFunctionDef(FD->parameters(),
11871                            /*CheckParameterNames=*/true);
11872
11873   // Add non-parameter declarations already in the function to the current
11874   // scope.
11875   if (FnBodyScope) {
11876     for (Decl *NPD : FD->decls()) {
11877       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
11878       if (!NonParmDecl)
11879         continue;
11880       assert(!isa<ParmVarDecl>(NonParmDecl) &&
11881              "parameters should not be in newly created FD yet");
11882
11883       // If the decl has a name, make it accessible in the current scope.
11884       if (NonParmDecl->getDeclName())
11885         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
11886
11887       // Similarly, dive into enums and fish their constants out, making them
11888       // accessible in this scope.
11889       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
11890         for (auto *EI : ED->enumerators())
11891           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11892       }
11893     }
11894   }
11895
11896   // Introduce our parameters into the function scope
11897   for (auto Param : FD->parameters()) {
11898     Param->setOwningFunction(FD);
11899
11900     // If this has an identifier, add it to the scope stack.
11901     if (Param->getIdentifier() && FnBodyScope) {
11902       CheckShadow(FnBodyScope, Param);
11903
11904       PushOnScopeChains(Param, FnBodyScope);
11905     }
11906   }
11907
11908   // Ensure that the function's exception specification is instantiated.
11909   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11910     ResolveExceptionSpec(D->getLocation(), FPT);
11911
11912   // dllimport cannot be applied to non-inline function definitions.
11913   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11914       !FD->isTemplateInstantiation()) {
11915     assert(!FD->hasAttr<DLLExportAttr>());
11916     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11917     FD->setInvalidDecl();
11918     return D;
11919   }
11920   // We want to attach documentation to original Decl (which might be
11921   // a function template).
11922   ActOnDocumentableDecl(D);
11923   if (getCurLexicalContext()->isObjCContainer() &&
11924       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11925       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11926     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11927
11928   return D;
11929 }
11930
11931 /// \brief Given the set of return statements within a function body,
11932 /// compute the variables that are subject to the named return value
11933 /// optimization.
11934 ///
11935 /// Each of the variables that is subject to the named return value
11936 /// optimization will be marked as NRVO variables in the AST, and any
11937 /// return statement that has a marked NRVO variable as its NRVO candidate can
11938 /// use the named return value optimization.
11939 ///
11940 /// This function applies a very simplistic algorithm for NRVO: if every return
11941 /// statement in the scope of a variable has the same NRVO candidate, that
11942 /// candidate is an NRVO variable.
11943 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11944   ReturnStmt **Returns = Scope->Returns.data();
11945
11946   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11947     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11948       if (!NRVOCandidate->isNRVOVariable())
11949         Returns[I]->setNRVOCandidate(nullptr);
11950     }
11951   }
11952 }
11953
11954 bool Sema::canDelayFunctionBody(const Declarator &D) {
11955   // We can't delay parsing the body of a constexpr function template (yet).
11956   if (D.getDeclSpec().isConstexprSpecified())
11957     return false;
11958
11959   // We can't delay parsing the body of a function template with a deduced
11960   // return type (yet).
11961   if (D.getDeclSpec().hasAutoTypeSpec()) {
11962     // If the placeholder introduces a non-deduced trailing return type,
11963     // we can still delay parsing it.
11964     if (D.getNumTypeObjects()) {
11965       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11966       if (Outer.Kind == DeclaratorChunk::Function &&
11967           Outer.Fun.hasTrailingReturnType()) {
11968         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11969         return Ty.isNull() || !Ty->isUndeducedType();
11970       }
11971     }
11972     return false;
11973   }
11974
11975   return true;
11976 }
11977
11978 bool Sema::canSkipFunctionBody(Decl *D) {
11979   // We cannot skip the body of a function (or function template) which is
11980   // constexpr, since we may need to evaluate its body in order to parse the
11981   // rest of the file.
11982   // We cannot skip the body of a function with an undeduced return type,
11983   // because any callers of that function need to know the type.
11984   if (const FunctionDecl *FD = D->getAsFunction())
11985     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11986       return false;
11987   return Consumer.shouldSkipFunctionBody(D);
11988 }
11989
11990 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11991   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11992     FD->setHasSkippedBody();
11993   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11994     MD->setHasSkippedBody();
11995   return Decl;
11996 }
11997
11998 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11999   return ActOnFinishFunctionBody(D, BodyArg, false);
12000 }
12001
12002 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12003                                     bool IsInstantiation) {
12004   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12005
12006   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12007   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12008
12009   if (getLangOpts().CoroutinesTS && getCurFunction()->CoroutinePromise)
12010     CheckCompletedCoroutineBody(FD, Body);
12011
12012   if (FD) {
12013     FD->setBody(Body);
12014
12015     if (getLangOpts().CPlusPlus14) {
12016       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12017           FD->getReturnType()->isUndeducedType()) {
12018         // If the function has a deduced result type but contains no 'return'
12019         // statements, the result type as written must be exactly 'auto', and
12020         // the deduced result type is 'void'.
12021         if (!FD->getReturnType()->getAs<AutoType>()) {
12022           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12023               << FD->getReturnType();
12024           FD->setInvalidDecl();
12025         } else {
12026           // Substitute 'void' for the 'auto' in the type.
12027           TypeLoc ResultType = getReturnTypeLoc(FD);
12028           Context.adjustDeducedFunctionResultType(
12029               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12030         }
12031       }
12032     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12033       // In C++11, we don't use 'auto' deduction rules for lambda call
12034       // operators because we don't support return type deduction.
12035       auto *LSI = getCurLambda();
12036       if (LSI->HasImplicitReturnType) {
12037         deduceClosureReturnType(*LSI);
12038
12039         // C++11 [expr.prim.lambda]p4:
12040         //   [...] if there are no return statements in the compound-statement
12041         //   [the deduced type is] the type void
12042         QualType RetType =
12043             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12044
12045         // Update the return type to the deduced type.
12046         const FunctionProtoType *Proto =
12047             FD->getType()->getAs<FunctionProtoType>();
12048         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12049                                             Proto->getExtProtoInfo()));
12050       }
12051     }
12052
12053     // The only way to be included in UndefinedButUsed is if there is an
12054     // ODR use before the definition. Avoid the expensive map lookup if this
12055     // is the first declaration.
12056     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
12057       if (!FD->isExternallyVisible())
12058         UndefinedButUsed.erase(FD);
12059       else if (FD->isInlined() &&
12060                !LangOpts.GNUInline &&
12061                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
12062         UndefinedButUsed.erase(FD);
12063     }
12064
12065     // If the function implicitly returns zero (like 'main') or is naked,
12066     // don't complain about missing return statements.
12067     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12068       WP.disableCheckFallThrough();
12069
12070     // MSVC permits the use of pure specifier (=0) on function definition,
12071     // defined at class scope, warn about this non-standard construct.
12072     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12073       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12074
12075     if (!FD->isInvalidDecl()) {
12076       // Don't diagnose unused parameters of defaulted or deleted functions.
12077       if (!FD->isDeleted() && !FD->isDefaulted())
12078         DiagnoseUnusedParameters(FD->parameters());
12079       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12080                                              FD->getReturnType(), FD);
12081
12082       // If this is a structor, we need a vtable.
12083       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12084         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12085       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12086         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12087
12088       // Try to apply the named return value optimization. We have to check
12089       // if we can do this here because lambdas keep return statements around
12090       // to deduce an implicit return type.
12091       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12092           !FD->isDependentContext())
12093         computeNRVO(Body, getCurFunction());
12094     }
12095
12096     // GNU warning -Wmissing-prototypes:
12097     //   Warn if a global function is defined without a previous
12098     //   prototype declaration. This warning is issued even if the
12099     //   definition itself provides a prototype. The aim is to detect
12100     //   global functions that fail to be declared in header files.
12101     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12102     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12103       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12104
12105       if (PossibleZeroParamPrototype) {
12106         // We found a declaration that is not a prototype,
12107         // but that could be a zero-parameter prototype
12108         if (TypeSourceInfo *TI =
12109                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12110           TypeLoc TL = TI->getTypeLoc();
12111           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12112             Diag(PossibleZeroParamPrototype->getLocation(),
12113                  diag::note_declaration_not_a_prototype)
12114                 << PossibleZeroParamPrototype
12115                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12116         }
12117       }
12118
12119       // GNU warning -Wstrict-prototypes
12120       //   Warn if K&R function is defined without a previous declaration.
12121       //   This warning is issued only if the definition itself does not provide
12122       //   a prototype. Only K&R definitions do not provide a prototype.
12123       //   An empty list in a function declarator that is part of a definition
12124       //   of that function specifies that the function has no parameters
12125       //   (C99 6.7.5.3p14)
12126       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12127           !LangOpts.CPlusPlus) {
12128         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12129         TypeLoc TL = TI->getTypeLoc();
12130         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12131         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1;
12132       }
12133     }
12134
12135     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12136       const CXXMethodDecl *KeyFunction;
12137       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12138           MD->isVirtual() &&
12139           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12140           MD == KeyFunction->getCanonicalDecl()) {
12141         // Update the key-function state if necessary for this ABI.
12142         if (FD->isInlined() &&
12143             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12144           Context.setNonKeyFunction(MD);
12145
12146           // If the newly-chosen key function is already defined, then we
12147           // need to mark the vtable as used retroactively.
12148           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12149           const FunctionDecl *Definition;
12150           if (KeyFunction && KeyFunction->isDefined(Definition))
12151             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12152         } else {
12153           // We just defined they key function; mark the vtable as used.
12154           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12155         }
12156       }
12157     }
12158
12159     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12160            "Function parsing confused");
12161   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12162     assert(MD == getCurMethodDecl() && "Method parsing confused");
12163     MD->setBody(Body);
12164     if (!MD->isInvalidDecl()) {
12165       DiagnoseUnusedParameters(MD->parameters());
12166       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12167                                              MD->getReturnType(), MD);
12168
12169       if (Body)
12170         computeNRVO(Body, getCurFunction());
12171     }
12172     if (getCurFunction()->ObjCShouldCallSuper) {
12173       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12174         << MD->getSelector().getAsString();
12175       getCurFunction()->ObjCShouldCallSuper = false;
12176     }
12177     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12178       const ObjCMethodDecl *InitMethod = nullptr;
12179       bool isDesignated =
12180           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12181       assert(isDesignated && InitMethod);
12182       (void)isDesignated;
12183
12184       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12185         auto IFace = MD->getClassInterface();
12186         if (!IFace)
12187           return false;
12188         auto SuperD = IFace->getSuperClass();
12189         if (!SuperD)
12190           return false;
12191         return SuperD->getIdentifier() ==
12192             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12193       };
12194       // Don't issue this warning for unavailable inits or direct subclasses
12195       // of NSObject.
12196       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12197         Diag(MD->getLocation(),
12198              diag::warn_objc_designated_init_missing_super_call);
12199         Diag(InitMethod->getLocation(),
12200              diag::note_objc_designated_init_marked_here);
12201       }
12202       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12203     }
12204     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12205       // Don't issue this warning for unavaialable inits.
12206       if (!MD->isUnavailable())
12207         Diag(MD->getLocation(),
12208              diag::warn_objc_secondary_init_missing_init_call);
12209       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12210     }
12211   } else {
12212     return nullptr;
12213   }
12214
12215   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12216     DiagnoseUnguardedAvailabilityViolations(dcl);
12217
12218   assert(!getCurFunction()->ObjCShouldCallSuper &&
12219          "This should only be set for ObjC methods, which should have been "
12220          "handled in the block above.");
12221
12222   // Verify and clean out per-function state.
12223   if (Body && (!FD || !FD->isDefaulted())) {
12224     // C++ constructors that have function-try-blocks can't have return
12225     // statements in the handlers of that block. (C++ [except.handle]p14)
12226     // Verify this.
12227     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12228       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12229
12230     // Verify that gotos and switch cases don't jump into scopes illegally.
12231     if (getCurFunction()->NeedsScopeChecking() &&
12232         !PP.isCodeCompletionEnabled())
12233       DiagnoseInvalidJumps(Body);
12234
12235     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12236       if (!Destructor->getParent()->isDependentType())
12237         CheckDestructor(Destructor);
12238
12239       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12240                                              Destructor->getParent());
12241     }
12242
12243     // If any errors have occurred, clear out any temporaries that may have
12244     // been leftover. This ensures that these temporaries won't be picked up for
12245     // deletion in some later function.
12246     if (getDiagnostics().hasErrorOccurred() ||
12247         getDiagnostics().getSuppressAllDiagnostics()) {
12248       DiscardCleanupsInEvaluationContext();
12249     }
12250     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12251         !isa<FunctionTemplateDecl>(dcl)) {
12252       // Since the body is valid, issue any analysis-based warnings that are
12253       // enabled.
12254       ActivePolicy = &WP;
12255     }
12256
12257     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12258         (!CheckConstexprFunctionDecl(FD) ||
12259          !CheckConstexprFunctionBody(FD, Body)))
12260       FD->setInvalidDecl();
12261
12262     if (FD && FD->hasAttr<NakedAttr>()) {
12263       for (const Stmt *S : Body->children()) {
12264         // Allow local register variables without initializer as they don't
12265         // require prologue.
12266         bool RegisterVariables = false;
12267         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12268           for (const auto *Decl : DS->decls()) {
12269             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12270               RegisterVariables =
12271                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12272               if (!RegisterVariables)
12273                 break;
12274             }
12275           }
12276         }
12277         if (RegisterVariables)
12278           continue;
12279         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12280           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12281           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12282           FD->setInvalidDecl();
12283           break;
12284         }
12285       }
12286     }
12287
12288     assert(ExprCleanupObjects.size() ==
12289                ExprEvalContexts.back().NumCleanupObjects &&
12290            "Leftover temporaries in function");
12291     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12292     assert(MaybeODRUseExprs.empty() &&
12293            "Leftover expressions for odr-use checking");
12294   }
12295
12296   if (!IsInstantiation)
12297     PopDeclContext();
12298
12299   PopFunctionScopeInfo(ActivePolicy, dcl);
12300   // If any errors have occurred, clear out any temporaries that may have
12301   // been leftover. This ensures that these temporaries won't be picked up for
12302   // deletion in some later function.
12303   if (getDiagnostics().hasErrorOccurred()) {
12304     DiscardCleanupsInEvaluationContext();
12305   }
12306
12307   return dcl;
12308 }
12309
12310 /// When we finish delayed parsing of an attribute, we must attach it to the
12311 /// relevant Decl.
12312 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12313                                        ParsedAttributes &Attrs) {
12314   // Always attach attributes to the underlying decl.
12315   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12316     D = TD->getTemplatedDecl();
12317   ProcessDeclAttributeList(S, D, Attrs.getList());
12318
12319   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12320     if (Method->isStatic())
12321       checkThisInStaticMemberFunctionAttributes(Method);
12322 }
12323
12324 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12325 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12326 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12327                                           IdentifierInfo &II, Scope *S) {
12328   // Before we produce a declaration for an implicitly defined
12329   // function, see whether there was a locally-scoped declaration of
12330   // this name as a function or variable. If so, use that
12331   // (non-visible) declaration, and complain about it.
12332   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12333     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12334     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12335     return ExternCPrev;
12336   }
12337
12338   // Extension in C99.  Legal in C90, but warn about it.
12339   unsigned diag_id;
12340   if (II.getName().startswith("__builtin_"))
12341     diag_id = diag::warn_builtin_unknown;
12342   else if (getLangOpts().C99)
12343     diag_id = diag::ext_implicit_function_decl;
12344   else
12345     diag_id = diag::warn_implicit_function_decl;
12346   Diag(Loc, diag_id) << &II;
12347
12348   // Because typo correction is expensive, only do it if the implicit
12349   // function declaration is going to be treated as an error.
12350   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12351     TypoCorrection Corrected;
12352     if (S &&
12353         (Corrected = CorrectTypo(
12354              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12355              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12356       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12357                    /*ErrorRecovery*/false);
12358   }
12359
12360   // Set a Declarator for the implicit definition: int foo();
12361   const char *Dummy;
12362   AttributeFactory attrFactory;
12363   DeclSpec DS(attrFactory);
12364   unsigned DiagID;
12365   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12366                                   Context.getPrintingPolicy());
12367   (void)Error; // Silence warning.
12368   assert(!Error && "Error setting up implicit decl!");
12369   SourceLocation NoLoc;
12370   Declarator D(DS, Declarator::BlockContext);
12371   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12372                                              /*IsAmbiguous=*/false,
12373                                              /*LParenLoc=*/NoLoc,
12374                                              /*Params=*/nullptr,
12375                                              /*NumParams=*/0,
12376                                              /*EllipsisLoc=*/NoLoc,
12377                                              /*RParenLoc=*/NoLoc,
12378                                              /*TypeQuals=*/0,
12379                                              /*RefQualifierIsLvalueRef=*/true,
12380                                              /*RefQualifierLoc=*/NoLoc,
12381                                              /*ConstQualifierLoc=*/NoLoc,
12382                                              /*VolatileQualifierLoc=*/NoLoc,
12383                                              /*RestrictQualifierLoc=*/NoLoc,
12384                                              /*MutableLoc=*/NoLoc,
12385                                              EST_None,
12386                                              /*ESpecRange=*/SourceRange(),
12387                                              /*Exceptions=*/nullptr,
12388                                              /*ExceptionRanges=*/nullptr,
12389                                              /*NumExceptions=*/0,
12390                                              /*NoexceptExpr=*/nullptr,
12391                                              /*ExceptionSpecTokens=*/nullptr,
12392                                              /*DeclsInPrototype=*/None,
12393                                              Loc, Loc, D),
12394                 DS.getAttributes(),
12395                 SourceLocation());
12396   D.SetIdentifier(&II, Loc);
12397
12398   // Insert this function into translation-unit scope.
12399
12400   DeclContext *PrevDC = CurContext;
12401   CurContext = Context.getTranslationUnitDecl();
12402
12403   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12404   FD->setImplicit();
12405
12406   CurContext = PrevDC;
12407
12408   AddKnownFunctionAttributes(FD);
12409
12410   return FD;
12411 }
12412
12413 /// \brief Adds any function attributes that we know a priori based on
12414 /// the declaration of this function.
12415 ///
12416 /// These attributes can apply both to implicitly-declared builtins
12417 /// (like __builtin___printf_chk) or to library-declared functions
12418 /// like NSLog or printf.
12419 ///
12420 /// We need to check for duplicate attributes both here and where user-written
12421 /// attributes are applied to declarations.
12422 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12423   if (FD->isInvalidDecl())
12424     return;
12425
12426   // If this is a built-in function, map its builtin attributes to
12427   // actual attributes.
12428   if (unsigned BuiltinID = FD->getBuiltinID()) {
12429     // Handle printf-formatting attributes.
12430     unsigned FormatIdx;
12431     bool HasVAListArg;
12432     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12433       if (!FD->hasAttr<FormatAttr>()) {
12434         const char *fmt = "printf";
12435         unsigned int NumParams = FD->getNumParams();
12436         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12437             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12438           fmt = "NSString";
12439         FD->addAttr(FormatAttr::CreateImplicit(Context,
12440                                                &Context.Idents.get(fmt),
12441                                                FormatIdx+1,
12442                                                HasVAListArg ? 0 : FormatIdx+2,
12443                                                FD->getLocation()));
12444       }
12445     }
12446     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12447                                              HasVAListArg)) {
12448      if (!FD->hasAttr<FormatAttr>())
12449        FD->addAttr(FormatAttr::CreateImplicit(Context,
12450                                               &Context.Idents.get("scanf"),
12451                                               FormatIdx+1,
12452                                               HasVAListArg ? 0 : FormatIdx+2,
12453                                               FD->getLocation()));
12454     }
12455
12456     // Mark const if we don't care about errno and that is the only
12457     // thing preventing the function from being const. This allows
12458     // IRgen to use LLVM intrinsics for such functions.
12459     if (!getLangOpts().MathErrno &&
12460         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12461       if (!FD->hasAttr<ConstAttr>())
12462         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12463     }
12464
12465     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12466         !FD->hasAttr<ReturnsTwiceAttr>())
12467       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12468                                          FD->getLocation()));
12469     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12470       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12471     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12472       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12473     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12474       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12475     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12476         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12477       // Add the appropriate attribute, depending on the CUDA compilation mode
12478       // and which target the builtin belongs to. For example, during host
12479       // compilation, aux builtins are __device__, while the rest are __host__.
12480       if (getLangOpts().CUDAIsDevice !=
12481           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12482         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12483       else
12484         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12485     }
12486   }
12487
12488   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12489   // throw, add an implicit nothrow attribute to any extern "C" function we come
12490   // across.
12491   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12492       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12493     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12494     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12495       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12496   }
12497
12498   IdentifierInfo *Name = FD->getIdentifier();
12499   if (!Name)
12500     return;
12501   if ((!getLangOpts().CPlusPlus &&
12502        FD->getDeclContext()->isTranslationUnit()) ||
12503       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12504        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12505        LinkageSpecDecl::lang_c)) {
12506     // Okay: this could be a libc/libm/Objective-C function we know
12507     // about.
12508   } else
12509     return;
12510
12511   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12512     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12513     // target-specific builtins, perhaps?
12514     if (!FD->hasAttr<FormatAttr>())
12515       FD->addAttr(FormatAttr::CreateImplicit(Context,
12516                                              &Context.Idents.get("printf"), 2,
12517                                              Name->isStr("vasprintf") ? 0 : 3,
12518                                              FD->getLocation()));
12519   }
12520
12521   if (Name->isStr("__CFStringMakeConstantString")) {
12522     // We already have a __builtin___CFStringMakeConstantString,
12523     // but builds that use -fno-constant-cfstrings don't go through that.
12524     if (!FD->hasAttr<FormatArgAttr>())
12525       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12526                                                 FD->getLocation()));
12527   }
12528 }
12529
12530 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12531                                     TypeSourceInfo *TInfo) {
12532   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12533   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12534
12535   if (!TInfo) {
12536     assert(D.isInvalidType() && "no declarator info for valid type");
12537     TInfo = Context.getTrivialTypeSourceInfo(T);
12538   }
12539
12540   // Scope manipulation handled by caller.
12541   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12542                                            D.getLocStart(),
12543                                            D.getIdentifierLoc(),
12544                                            D.getIdentifier(),
12545                                            TInfo);
12546
12547   // Bail out immediately if we have an invalid declaration.
12548   if (D.isInvalidType()) {
12549     NewTD->setInvalidDecl();
12550     return NewTD;
12551   }
12552
12553   if (D.getDeclSpec().isModulePrivateSpecified()) {
12554     if (CurContext->isFunctionOrMethod())
12555       Diag(NewTD->getLocation(), diag::err_module_private_local)
12556         << 2 << NewTD->getDeclName()
12557         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12558         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12559     else
12560       NewTD->setModulePrivate();
12561   }
12562
12563   // C++ [dcl.typedef]p8:
12564   //   If the typedef declaration defines an unnamed class (or
12565   //   enum), the first typedef-name declared by the declaration
12566   //   to be that class type (or enum type) is used to denote the
12567   //   class type (or enum type) for linkage purposes only.
12568   // We need to check whether the type was declared in the declaration.
12569   switch (D.getDeclSpec().getTypeSpecType()) {
12570   case TST_enum:
12571   case TST_struct:
12572   case TST_interface:
12573   case TST_union:
12574   case TST_class: {
12575     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12576     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12577     break;
12578   }
12579
12580   default:
12581     break;
12582   }
12583
12584   return NewTD;
12585 }
12586
12587 /// \brief Check that this is a valid underlying type for an enum declaration.
12588 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12589   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12590   QualType T = TI->getType();
12591
12592   if (T->isDependentType())
12593     return false;
12594
12595   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12596     if (BT->isInteger())
12597       return false;
12598
12599   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12600   return true;
12601 }
12602
12603 /// Check whether this is a valid redeclaration of a previous enumeration.
12604 /// \return true if the redeclaration was invalid.
12605 bool Sema::CheckEnumRedeclaration(
12606     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12607     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12608   bool IsFixed = !EnumUnderlyingTy.isNull();
12609
12610   if (IsScoped != Prev->isScoped()) {
12611     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12612       << Prev->isScoped();
12613     Diag(Prev->getLocation(), diag::note_previous_declaration);
12614     return true;
12615   }
12616
12617   if (IsFixed && Prev->isFixed()) {
12618     if (!EnumUnderlyingTy->isDependentType() &&
12619         !Prev->getIntegerType()->isDependentType() &&
12620         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12621                                         Prev->getIntegerType())) {
12622       // TODO: Highlight the underlying type of the redeclaration.
12623       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12624         << EnumUnderlyingTy << Prev->getIntegerType();
12625       Diag(Prev->getLocation(), diag::note_previous_declaration)
12626           << Prev->getIntegerTypeRange();
12627       return true;
12628     }
12629   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12630     ;
12631   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12632     ;
12633   } else if (IsFixed != Prev->isFixed()) {
12634     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12635       << Prev->isFixed();
12636     Diag(Prev->getLocation(), diag::note_previous_declaration);
12637     return true;
12638   }
12639
12640   return false;
12641 }
12642
12643 /// \brief Get diagnostic %select index for tag kind for
12644 /// redeclaration diagnostic message.
12645 /// WARNING: Indexes apply to particular diagnostics only!
12646 ///
12647 /// \returns diagnostic %select index.
12648 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12649   switch (Tag) {
12650   case TTK_Struct: return 0;
12651   case TTK_Interface: return 1;
12652   case TTK_Class:  return 2;
12653   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12654   }
12655 }
12656
12657 /// \brief Determine if tag kind is a class-key compatible with
12658 /// class for redeclaration (class, struct, or __interface).
12659 ///
12660 /// \returns true iff the tag kind is compatible.
12661 static bool isClassCompatTagKind(TagTypeKind Tag)
12662 {
12663   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12664 }
12665
12666 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12667                                              TagTypeKind TTK) {
12668   if (isa<TypedefDecl>(PrevDecl))
12669     return NTK_Typedef;
12670   else if (isa<TypeAliasDecl>(PrevDecl))
12671     return NTK_TypeAlias;
12672   else if (isa<ClassTemplateDecl>(PrevDecl))
12673     return NTK_Template;
12674   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12675     return NTK_TypeAliasTemplate;
12676   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12677     return NTK_TemplateTemplateArgument;
12678   switch (TTK) {
12679   case TTK_Struct:
12680   case TTK_Interface:
12681   case TTK_Class:
12682     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12683   case TTK_Union:
12684     return NTK_NonUnion;
12685   case TTK_Enum:
12686     return NTK_NonEnum;
12687   }
12688   llvm_unreachable("invalid TTK");
12689 }
12690
12691 /// \brief Determine whether a tag with a given kind is acceptable
12692 /// as a redeclaration of the given tag declaration.
12693 ///
12694 /// \returns true if the new tag kind is acceptable, false otherwise.
12695 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12696                                         TagTypeKind NewTag, bool isDefinition,
12697                                         SourceLocation NewTagLoc,
12698                                         const IdentifierInfo *Name) {
12699   // C++ [dcl.type.elab]p3:
12700   //   The class-key or enum keyword present in the
12701   //   elaborated-type-specifier shall agree in kind with the
12702   //   declaration to which the name in the elaborated-type-specifier
12703   //   refers. This rule also applies to the form of
12704   //   elaborated-type-specifier that declares a class-name or
12705   //   friend class since it can be construed as referring to the
12706   //   definition of the class. Thus, in any
12707   //   elaborated-type-specifier, the enum keyword shall be used to
12708   //   refer to an enumeration (7.2), the union class-key shall be
12709   //   used to refer to a union (clause 9), and either the class or
12710   //   struct class-key shall be used to refer to a class (clause 9)
12711   //   declared using the class or struct class-key.
12712   TagTypeKind OldTag = Previous->getTagKind();
12713   if (!isDefinition || !isClassCompatTagKind(NewTag))
12714     if (OldTag == NewTag)
12715       return true;
12716
12717   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12718     // Warn about the struct/class tag mismatch.
12719     bool isTemplate = false;
12720     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12721       isTemplate = Record->getDescribedClassTemplate();
12722
12723     if (inTemplateInstantiation()) {
12724       // In a template instantiation, do not offer fix-its for tag mismatches
12725       // since they usually mess up the template instead of fixing the problem.
12726       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12727         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12728         << getRedeclDiagFromTagKind(OldTag);
12729       return true;
12730     }
12731
12732     if (isDefinition) {
12733       // On definitions, check previous tags and issue a fix-it for each
12734       // one that doesn't match the current tag.
12735       if (Previous->getDefinition()) {
12736         // Don't suggest fix-its for redefinitions.
12737         return true;
12738       }
12739
12740       bool previousMismatch = false;
12741       for (auto I : Previous->redecls()) {
12742         if (I->getTagKind() != NewTag) {
12743           if (!previousMismatch) {
12744             previousMismatch = true;
12745             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12746               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12747               << getRedeclDiagFromTagKind(I->getTagKind());
12748           }
12749           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12750             << getRedeclDiagFromTagKind(NewTag)
12751             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12752                  TypeWithKeyword::getTagTypeKindName(NewTag));
12753         }
12754       }
12755       return true;
12756     }
12757
12758     // Check for a previous definition.  If current tag and definition
12759     // are same type, do nothing.  If no definition, but disagree with
12760     // with previous tag type, give a warning, but no fix-it.
12761     const TagDecl *Redecl = Previous->getDefinition() ?
12762                             Previous->getDefinition() : Previous;
12763     if (Redecl->getTagKind() == NewTag) {
12764       return true;
12765     }
12766
12767     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12768       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12769       << getRedeclDiagFromTagKind(OldTag);
12770     Diag(Redecl->getLocation(), diag::note_previous_use);
12771
12772     // If there is a previous definition, suggest a fix-it.
12773     if (Previous->getDefinition()) {
12774         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12775           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12776           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12777                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12778     }
12779
12780     return true;
12781   }
12782   return false;
12783 }
12784
12785 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12786 /// from an outer enclosing namespace or file scope inside a friend declaration.
12787 /// This should provide the commented out code in the following snippet:
12788 ///   namespace N {
12789 ///     struct X;
12790 ///     namespace M {
12791 ///       struct Y { friend struct /*N::*/ X; };
12792 ///     }
12793 ///   }
12794 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12795                                          SourceLocation NameLoc) {
12796   // While the decl is in a namespace, do repeated lookup of that name and see
12797   // if we get the same namespace back.  If we do not, continue until
12798   // translation unit scope, at which point we have a fully qualified NNS.
12799   SmallVector<IdentifierInfo *, 4> Namespaces;
12800   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12801   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12802     // This tag should be declared in a namespace, which can only be enclosed by
12803     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12804     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12805     if (!Namespace || Namespace->isAnonymousNamespace())
12806       return FixItHint();
12807     IdentifierInfo *II = Namespace->getIdentifier();
12808     Namespaces.push_back(II);
12809     NamedDecl *Lookup = SemaRef.LookupSingleName(
12810         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12811     if (Lookup == Namespace)
12812       break;
12813   }
12814
12815   // Once we have all the namespaces, reverse them to go outermost first, and
12816   // build an NNS.
12817   SmallString<64> Insertion;
12818   llvm::raw_svector_ostream OS(Insertion);
12819   if (DC->isTranslationUnit())
12820     OS << "::";
12821   std::reverse(Namespaces.begin(), Namespaces.end());
12822   for (auto *II : Namespaces)
12823     OS << II->getName() << "::";
12824   return FixItHint::CreateInsertion(NameLoc, Insertion);
12825 }
12826
12827 /// \brief Determine whether a tag originally declared in context \p OldDC can
12828 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12829 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12830 /// using-declaration).
12831 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12832                                          DeclContext *NewDC) {
12833   OldDC = OldDC->getRedeclContext();
12834   NewDC = NewDC->getRedeclContext();
12835
12836   if (OldDC->Equals(NewDC))
12837     return true;
12838
12839   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12840   // encloses the other).
12841   if (S.getLangOpts().MSVCCompat &&
12842       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12843     return true;
12844
12845   return false;
12846 }
12847
12848 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12849 /// former case, Name will be non-null.  In the later case, Name will be null.
12850 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12851 /// reference/declaration/definition of a tag.
12852 ///
12853 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12854 /// trailing-type-specifier) other than one in an alias-declaration.
12855 ///
12856 /// \param SkipBody If non-null, will be set to indicate if the caller should
12857 /// skip the definition of this tag and treat it as if it were a declaration.
12858 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12859                      SourceLocation KWLoc, CXXScopeSpec &SS,
12860                      IdentifierInfo *Name, SourceLocation NameLoc,
12861                      AttributeList *Attr, AccessSpecifier AS,
12862                      SourceLocation ModulePrivateLoc,
12863                      MultiTemplateParamsArg TemplateParameterLists,
12864                      bool &OwnedDecl, bool &IsDependent,
12865                      SourceLocation ScopedEnumKWLoc,
12866                      bool ScopedEnumUsesClassTag,
12867                      TypeResult UnderlyingType,
12868                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12869   // If this is not a definition, it must have a name.
12870   IdentifierInfo *OrigName = Name;
12871   assert((Name != nullptr || TUK == TUK_Definition) &&
12872          "Nameless record must be a definition!");
12873   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12874
12875   OwnedDecl = false;
12876   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12877   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12878
12879   // FIXME: Check member specializations more carefully.
12880   bool isMemberSpecialization = false;
12881   bool Invalid = false;
12882
12883   // We only need to do this matching if we have template parameters
12884   // or a scope specifier, which also conveniently avoids this work
12885   // for non-C++ cases.
12886   if (TemplateParameterLists.size() > 0 ||
12887       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12888     if (TemplateParameterList *TemplateParams =
12889             MatchTemplateParametersToScopeSpecifier(
12890                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12891                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
12892       if (Kind == TTK_Enum) {
12893         Diag(KWLoc, diag::err_enum_template);
12894         return nullptr;
12895       }
12896
12897       if (TemplateParams->size() > 0) {
12898         // This is a declaration or definition of a class template (which may
12899         // be a member of another template).
12900
12901         if (Invalid)
12902           return nullptr;
12903
12904         OwnedDecl = false;
12905         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12906                                                SS, Name, NameLoc, Attr,
12907                                                TemplateParams, AS,
12908                                                ModulePrivateLoc,
12909                                                /*FriendLoc*/SourceLocation(),
12910                                                TemplateParameterLists.size()-1,
12911                                                TemplateParameterLists.data(),
12912                                                SkipBody);
12913         return Result.get();
12914       } else {
12915         // The "template<>" header is extraneous.
12916         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12917           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12918         isMemberSpecialization = true;
12919       }
12920     }
12921   }
12922
12923   // Figure out the underlying type if this a enum declaration. We need to do
12924   // this early, because it's needed to detect if this is an incompatible
12925   // redeclaration.
12926   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12927   bool EnumUnderlyingIsImplicit = false;
12928
12929   if (Kind == TTK_Enum) {
12930     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12931       // No underlying type explicitly specified, or we failed to parse the
12932       // type, default to int.
12933       EnumUnderlying = Context.IntTy.getTypePtr();
12934     else if (UnderlyingType.get()) {
12935       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12936       // integral type; any cv-qualification is ignored.
12937       TypeSourceInfo *TI = nullptr;
12938       GetTypeFromParser(UnderlyingType.get(), &TI);
12939       EnumUnderlying = TI;
12940
12941       if (CheckEnumUnderlyingType(TI))
12942         // Recover by falling back to int.
12943         EnumUnderlying = Context.IntTy.getTypePtr();
12944
12945       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12946                                           UPPC_FixedUnderlyingType))
12947         EnumUnderlying = Context.IntTy.getTypePtr();
12948
12949     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12950       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12951         // Microsoft enums are always of int type.
12952         EnumUnderlying = Context.IntTy.getTypePtr();
12953         EnumUnderlyingIsImplicit = true;
12954       }
12955     }
12956   }
12957
12958   DeclContext *SearchDC = CurContext;
12959   DeclContext *DC = CurContext;
12960   bool isStdBadAlloc = false;
12961   bool isStdAlignValT = false;
12962
12963   RedeclarationKind Redecl = ForRedeclaration;
12964   if (TUK == TUK_Friend || TUK == TUK_Reference)
12965     Redecl = NotForRedeclaration;
12966
12967   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12968   if (Name && SS.isNotEmpty()) {
12969     // We have a nested-name tag ('struct foo::bar').
12970
12971     // Check for invalid 'foo::'.
12972     if (SS.isInvalid()) {
12973       Name = nullptr;
12974       goto CreateNewDecl;
12975     }
12976
12977     // If this is a friend or a reference to a class in a dependent
12978     // context, don't try to make a decl for it.
12979     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12980       DC = computeDeclContext(SS, false);
12981       if (!DC) {
12982         IsDependent = true;
12983         return nullptr;
12984       }
12985     } else {
12986       DC = computeDeclContext(SS, true);
12987       if (!DC) {
12988         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12989           << SS.getRange();
12990         return nullptr;
12991       }
12992     }
12993
12994     if (RequireCompleteDeclContext(SS, DC))
12995       return nullptr;
12996
12997     SearchDC = DC;
12998     // Look-up name inside 'foo::'.
12999     LookupQualifiedName(Previous, DC);
13000
13001     if (Previous.isAmbiguous())
13002       return nullptr;
13003
13004     if (Previous.empty()) {
13005       // Name lookup did not find anything. However, if the
13006       // nested-name-specifier refers to the current instantiation,
13007       // and that current instantiation has any dependent base
13008       // classes, we might find something at instantiation time: treat
13009       // this as a dependent elaborated-type-specifier.
13010       // But this only makes any sense for reference-like lookups.
13011       if (Previous.wasNotFoundInCurrentInstantiation() &&
13012           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13013         IsDependent = true;
13014         return nullptr;
13015       }
13016
13017       // A tag 'foo::bar' must already exist.
13018       Diag(NameLoc, diag::err_not_tag_in_scope)
13019         << Kind << Name << DC << SS.getRange();
13020       Name = nullptr;
13021       Invalid = true;
13022       goto CreateNewDecl;
13023     }
13024   } else if (Name) {
13025     // C++14 [class.mem]p14:
13026     //   If T is the name of a class, then each of the following shall have a
13027     //   name different from T:
13028     //    -- every member of class T that is itself a type
13029     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13030         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13031       return nullptr;
13032
13033     // If this is a named struct, check to see if there was a previous forward
13034     // declaration or definition.
13035     // FIXME: We're looking into outer scopes here, even when we
13036     // shouldn't be. Doing so can result in ambiguities that we
13037     // shouldn't be diagnosing.
13038     LookupName(Previous, S);
13039
13040     // When declaring or defining a tag, ignore ambiguities introduced
13041     // by types using'ed into this scope.
13042     if (Previous.isAmbiguous() &&
13043         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13044       LookupResult::Filter F = Previous.makeFilter();
13045       while (F.hasNext()) {
13046         NamedDecl *ND = F.next();
13047         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13048                 SearchDC->getRedeclContext()))
13049           F.erase();
13050       }
13051       F.done();
13052     }
13053
13054     // C++11 [namespace.memdef]p3:
13055     //   If the name in a friend declaration is neither qualified nor
13056     //   a template-id and the declaration is a function or an
13057     //   elaborated-type-specifier, the lookup to determine whether
13058     //   the entity has been previously declared shall not consider
13059     //   any scopes outside the innermost enclosing namespace.
13060     //
13061     // MSVC doesn't implement the above rule for types, so a friend tag
13062     // declaration may be a redeclaration of a type declared in an enclosing
13063     // scope.  They do implement this rule for friend functions.
13064     //
13065     // Does it matter that this should be by scope instead of by
13066     // semantic context?
13067     if (!Previous.empty() && TUK == TUK_Friend) {
13068       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13069       LookupResult::Filter F = Previous.makeFilter();
13070       bool FriendSawTagOutsideEnclosingNamespace = false;
13071       while (F.hasNext()) {
13072         NamedDecl *ND = F.next();
13073         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13074         if (DC->isFileContext() &&
13075             !EnclosingNS->Encloses(ND->getDeclContext())) {
13076           if (getLangOpts().MSVCCompat)
13077             FriendSawTagOutsideEnclosingNamespace = true;
13078           else
13079             F.erase();
13080         }
13081       }
13082       F.done();
13083
13084       // Diagnose this MSVC extension in the easy case where lookup would have
13085       // unambiguously found something outside the enclosing namespace.
13086       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13087         NamedDecl *ND = Previous.getFoundDecl();
13088         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13089             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13090       }
13091     }
13092
13093     // Note:  there used to be some attempt at recovery here.
13094     if (Previous.isAmbiguous())
13095       return nullptr;
13096
13097     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13098       // FIXME: This makes sure that we ignore the contexts associated
13099       // with C structs, unions, and enums when looking for a matching
13100       // tag declaration or definition. See the similar lookup tweak
13101       // in Sema::LookupName; is there a better way to deal with this?
13102       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13103         SearchDC = SearchDC->getParent();
13104     }
13105   }
13106
13107   if (Previous.isSingleResult() &&
13108       Previous.getFoundDecl()->isTemplateParameter()) {
13109     // Maybe we will complain about the shadowed template parameter.
13110     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13111     // Just pretend that we didn't see the previous declaration.
13112     Previous.clear();
13113   }
13114
13115   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13116       DC->Equals(getStdNamespace())) {
13117     if (Name->isStr("bad_alloc")) {
13118       // This is a declaration of or a reference to "std::bad_alloc".
13119       isStdBadAlloc = true;
13120
13121       // If std::bad_alloc has been implicitly declared (but made invisible to
13122       // name lookup), fill in this implicit declaration as the previous
13123       // declaration, so that the declarations get chained appropriately.
13124       if (Previous.empty() && StdBadAlloc)
13125         Previous.addDecl(getStdBadAlloc());
13126     } else if (Name->isStr("align_val_t")) {
13127       isStdAlignValT = true;
13128       if (Previous.empty() && StdAlignValT)
13129         Previous.addDecl(getStdAlignValT());
13130     }
13131   }
13132
13133   // If we didn't find a previous declaration, and this is a reference
13134   // (or friend reference), move to the correct scope.  In C++, we
13135   // also need to do a redeclaration lookup there, just in case
13136   // there's a shadow friend decl.
13137   if (Name && Previous.empty() &&
13138       (TUK == TUK_Reference || TUK == TUK_Friend)) {
13139     if (Invalid) goto CreateNewDecl;
13140     assert(SS.isEmpty());
13141
13142     if (TUK == TUK_Reference) {
13143       // C++ [basic.scope.pdecl]p5:
13144       //   -- for an elaborated-type-specifier of the form
13145       //
13146       //          class-key identifier
13147       //
13148       //      if the elaborated-type-specifier is used in the
13149       //      decl-specifier-seq or parameter-declaration-clause of a
13150       //      function defined in namespace scope, the identifier is
13151       //      declared as a class-name in the namespace that contains
13152       //      the declaration; otherwise, except as a friend
13153       //      declaration, the identifier is declared in the smallest
13154       //      non-class, non-function-prototype scope that contains the
13155       //      declaration.
13156       //
13157       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13158       // C structs and unions.
13159       //
13160       // It is an error in C++ to declare (rather than define) an enum
13161       // type, including via an elaborated type specifier.  We'll
13162       // diagnose that later; for now, declare the enum in the same
13163       // scope as we would have picked for any other tag type.
13164       //
13165       // GNU C also supports this behavior as part of its incomplete
13166       // enum types extension, while GNU C++ does not.
13167       //
13168       // Find the context where we'll be declaring the tag.
13169       // FIXME: We would like to maintain the current DeclContext as the
13170       // lexical context,
13171       SearchDC = getTagInjectionContext(SearchDC);
13172
13173       // Find the scope where we'll be declaring the tag.
13174       S = getTagInjectionScope(S, getLangOpts());
13175     } else {
13176       assert(TUK == TUK_Friend);
13177       // C++ [namespace.memdef]p3:
13178       //   If a friend declaration in a non-local class first declares a
13179       //   class or function, the friend class or function is a member of
13180       //   the innermost enclosing namespace.
13181       SearchDC = SearchDC->getEnclosingNamespaceContext();
13182     }
13183
13184     // In C++, we need to do a redeclaration lookup to properly
13185     // diagnose some problems.
13186     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13187     // hidden declaration so that we don't get ambiguity errors when using a
13188     // type declared by an elaborated-type-specifier.  In C that is not correct
13189     // and we should instead merge compatible types found by lookup.
13190     if (getLangOpts().CPlusPlus) {
13191       Previous.setRedeclarationKind(ForRedeclaration);
13192       LookupQualifiedName(Previous, SearchDC);
13193     } else {
13194       Previous.setRedeclarationKind(ForRedeclaration);
13195       LookupName(Previous, S);
13196     }
13197   }
13198
13199   // If we have a known previous declaration to use, then use it.
13200   if (Previous.empty() && SkipBody && SkipBody->Previous)
13201     Previous.addDecl(SkipBody->Previous);
13202
13203   if (!Previous.empty()) {
13204     NamedDecl *PrevDecl = Previous.getFoundDecl();
13205     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13206
13207     // It's okay to have a tag decl in the same scope as a typedef
13208     // which hides a tag decl in the same scope.  Finding this
13209     // insanity with a redeclaration lookup can only actually happen
13210     // in C++.
13211     //
13212     // This is also okay for elaborated-type-specifiers, which is
13213     // technically forbidden by the current standard but which is
13214     // okay according to the likely resolution of an open issue;
13215     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13216     if (getLangOpts().CPlusPlus) {
13217       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13218         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13219           TagDecl *Tag = TT->getDecl();
13220           if (Tag->getDeclName() == Name &&
13221               Tag->getDeclContext()->getRedeclContext()
13222                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13223             PrevDecl = Tag;
13224             Previous.clear();
13225             Previous.addDecl(Tag);
13226             Previous.resolveKind();
13227           }
13228         }
13229       }
13230     }
13231
13232     // If this is a redeclaration of a using shadow declaration, it must
13233     // declare a tag in the same context. In MSVC mode, we allow a
13234     // redefinition if either context is within the other.
13235     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13236       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13237       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13238           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13239           !(OldTag && isAcceptableTagRedeclContext(
13240                           *this, OldTag->getDeclContext(), SearchDC))) {
13241         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13242         Diag(Shadow->getTargetDecl()->getLocation(),
13243              diag::note_using_decl_target);
13244         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13245             << 0;
13246         // Recover by ignoring the old declaration.
13247         Previous.clear();
13248         goto CreateNewDecl;
13249       }
13250     }
13251
13252     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13253       // If this is a use of a previous tag, or if the tag is already declared
13254       // in the same scope (so that the definition/declaration completes or
13255       // rementions the tag), reuse the decl.
13256       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13257           isDeclInScope(DirectPrevDecl, SearchDC, S,
13258                         SS.isNotEmpty() || isMemberSpecialization)) {
13259         // Make sure that this wasn't declared as an enum and now used as a
13260         // struct or something similar.
13261         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13262                                           TUK == TUK_Definition, KWLoc,
13263                                           Name)) {
13264           bool SafeToContinue
13265             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13266                Kind != TTK_Enum);
13267           if (SafeToContinue)
13268             Diag(KWLoc, diag::err_use_with_wrong_tag)
13269               << Name
13270               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13271                                               PrevTagDecl->getKindName());
13272           else
13273             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13274           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13275
13276           if (SafeToContinue)
13277             Kind = PrevTagDecl->getTagKind();
13278           else {
13279             // Recover by making this an anonymous redefinition.
13280             Name = nullptr;
13281             Previous.clear();
13282             Invalid = true;
13283           }
13284         }
13285
13286         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13287           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13288
13289           // If this is an elaborated-type-specifier for a scoped enumeration,
13290           // the 'class' keyword is not necessary and not permitted.
13291           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13292             if (ScopedEnum)
13293               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13294                 << PrevEnum->isScoped()
13295                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13296             return PrevTagDecl;
13297           }
13298
13299           QualType EnumUnderlyingTy;
13300           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13301             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13302           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13303             EnumUnderlyingTy = QualType(T, 0);
13304
13305           // All conflicts with previous declarations are recovered by
13306           // returning the previous declaration, unless this is a definition,
13307           // in which case we want the caller to bail out.
13308           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13309                                      ScopedEnum, EnumUnderlyingTy,
13310                                      EnumUnderlyingIsImplicit, PrevEnum))
13311             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13312         }
13313
13314         // C++11 [class.mem]p1:
13315         //   A member shall not be declared twice in the member-specification,
13316         //   except that a nested class or member class template can be declared
13317         //   and then later defined.
13318         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13319             S->isDeclScope(PrevDecl)) {
13320           Diag(NameLoc, diag::ext_member_redeclared);
13321           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13322         }
13323
13324         if (!Invalid) {
13325           // If this is a use, just return the declaration we found, unless
13326           // we have attributes.
13327           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13328             if (Attr) {
13329               // FIXME: Diagnose these attributes. For now, we create a new
13330               // declaration to hold them.
13331             } else if (TUK == TUK_Reference &&
13332                        (PrevTagDecl->getFriendObjectKind() ==
13333                             Decl::FOK_Undeclared ||
13334                         PP.getModuleContainingLocation(
13335                             PrevDecl->getLocation()) !=
13336                             PP.getModuleContainingLocation(KWLoc)) &&
13337                        SS.isEmpty()) {
13338               // This declaration is a reference to an existing entity, but
13339               // has different visibility from that entity: it either makes
13340               // a friend visible or it makes a type visible in a new module.
13341               // In either case, create a new declaration. We only do this if
13342               // the declaration would have meant the same thing if no prior
13343               // declaration were found, that is, if it was found in the same
13344               // scope where we would have injected a declaration.
13345               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13346                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13347                 return PrevTagDecl;
13348               // This is in the injected scope, create a new declaration in
13349               // that scope.
13350               S = getTagInjectionScope(S, getLangOpts());
13351             } else {
13352               return PrevTagDecl;
13353             }
13354           }
13355
13356           // Diagnose attempts to redefine a tag.
13357           if (TUK == TUK_Definition) {
13358             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13359               // If we're defining a specialization and the previous definition
13360               // is from an implicit instantiation, don't emit an error
13361               // here; we'll catch this in the general case below.
13362               bool IsExplicitSpecializationAfterInstantiation = false;
13363               if (isMemberSpecialization) {
13364                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13365                   IsExplicitSpecializationAfterInstantiation =
13366                     RD->getTemplateSpecializationKind() !=
13367                     TSK_ExplicitSpecialization;
13368                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13369                   IsExplicitSpecializationAfterInstantiation =
13370                     ED->getTemplateSpecializationKind() !=
13371                     TSK_ExplicitSpecialization;
13372               }
13373
13374               NamedDecl *Hidden = nullptr;
13375               if (SkipBody && getLangOpts().CPlusPlus &&
13376                   !hasVisibleDefinition(Def, &Hidden)) {
13377                 // There is a definition of this tag, but it is not visible. We
13378                 // explicitly make use of C++'s one definition rule here, and
13379                 // assume that this definition is identical to the hidden one
13380                 // we already have. Make the existing definition visible and
13381                 // use it in place of this one.
13382                 SkipBody->ShouldSkip = true;
13383                 makeMergedDefinitionVisible(Hidden, KWLoc);
13384                 return Def;
13385               } else if (!IsExplicitSpecializationAfterInstantiation) {
13386                 // A redeclaration in function prototype scope in C isn't
13387                 // visible elsewhere, so merely issue a warning.
13388                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13389                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13390                 else
13391                   Diag(NameLoc, diag::err_redefinition) << Name;
13392                 Diag(Def->getLocation(), diag::note_previous_definition);
13393                 // If this is a redefinition, recover by making this
13394                 // struct be anonymous, which will make any later
13395                 // references get the previous definition.
13396                 Name = nullptr;
13397                 Previous.clear();
13398                 Invalid = true;
13399               }
13400             } else {
13401               // If the type is currently being defined, complain
13402               // about a nested redefinition.
13403               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13404               if (TD->isBeingDefined()) {
13405                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13406                 Diag(PrevTagDecl->getLocation(),
13407                      diag::note_previous_definition);
13408                 Name = nullptr;
13409                 Previous.clear();
13410                 Invalid = true;
13411               }
13412             }
13413
13414             // Okay, this is definition of a previously declared or referenced
13415             // tag. We're going to create a new Decl for it.
13416           }
13417
13418           // Okay, we're going to make a redeclaration.  If this is some kind
13419           // of reference, make sure we build the redeclaration in the same DC
13420           // as the original, and ignore the current access specifier.
13421           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13422             SearchDC = PrevTagDecl->getDeclContext();
13423             AS = AS_none;
13424           }
13425         }
13426         // If we get here we have (another) forward declaration or we
13427         // have a definition.  Just create a new decl.
13428
13429       } else {
13430         // If we get here, this is a definition of a new tag type in a nested
13431         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13432         // new decl/type.  We set PrevDecl to NULL so that the entities
13433         // have distinct types.
13434         Previous.clear();
13435       }
13436       // If we get here, we're going to create a new Decl. If PrevDecl
13437       // is non-NULL, it's a definition of the tag declared by
13438       // PrevDecl. If it's NULL, we have a new definition.
13439
13440     // Otherwise, PrevDecl is not a tag, but was found with tag
13441     // lookup.  This is only actually possible in C++, where a few
13442     // things like templates still live in the tag namespace.
13443     } else {
13444       // Use a better diagnostic if an elaborated-type-specifier
13445       // found the wrong kind of type on the first
13446       // (non-redeclaration) lookup.
13447       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13448           !Previous.isForRedeclaration()) {
13449         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13450         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13451                                                        << Kind;
13452         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13453         Invalid = true;
13454
13455       // Otherwise, only diagnose if the declaration is in scope.
13456       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13457                                 SS.isNotEmpty() || isMemberSpecialization)) {
13458         // do nothing
13459
13460       // Diagnose implicit declarations introduced by elaborated types.
13461       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13462         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13463         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13464         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13465         Invalid = true;
13466
13467       // Otherwise it's a declaration.  Call out a particularly common
13468       // case here.
13469       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13470         unsigned Kind = 0;
13471         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13472         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13473           << Name << Kind << TND->getUnderlyingType();
13474         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13475         Invalid = true;
13476
13477       // Otherwise, diagnose.
13478       } else {
13479         // The tag name clashes with something else in the target scope,
13480         // issue an error and recover by making this tag be anonymous.
13481         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13482         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13483         Name = nullptr;
13484         Invalid = true;
13485       }
13486
13487       // The existing declaration isn't relevant to us; we're in a
13488       // new scope, so clear out the previous declaration.
13489       Previous.clear();
13490     }
13491   }
13492
13493 CreateNewDecl:
13494
13495   TagDecl *PrevDecl = nullptr;
13496   if (Previous.isSingleResult())
13497     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13498
13499   // If there is an identifier, use the location of the identifier as the
13500   // location of the decl, otherwise use the location of the struct/union
13501   // keyword.
13502   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13503
13504   // Otherwise, create a new declaration. If there is a previous
13505   // declaration of the same entity, the two will be linked via
13506   // PrevDecl.
13507   TagDecl *New;
13508
13509   bool IsForwardReference = false;
13510   if (Kind == TTK_Enum) {
13511     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13512     // enum X { A, B, C } D;    D should chain to X.
13513     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13514                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13515                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13516
13517     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13518       StdAlignValT = cast<EnumDecl>(New);
13519
13520     // If this is an undefined enum, warn.
13521     if (TUK != TUK_Definition && !Invalid) {
13522       TagDecl *Def;
13523       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13524           cast<EnumDecl>(New)->isFixed()) {
13525         // C++0x: 7.2p2: opaque-enum-declaration.
13526         // Conflicts are diagnosed above. Do nothing.
13527       }
13528       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13529         Diag(Loc, diag::ext_forward_ref_enum_def)
13530           << New;
13531         Diag(Def->getLocation(), diag::note_previous_definition);
13532       } else {
13533         unsigned DiagID = diag::ext_forward_ref_enum;
13534         if (getLangOpts().MSVCCompat)
13535           DiagID = diag::ext_ms_forward_ref_enum;
13536         else if (getLangOpts().CPlusPlus)
13537           DiagID = diag::err_forward_ref_enum;
13538         Diag(Loc, DiagID);
13539
13540         // If this is a forward-declared reference to an enumeration, make a
13541         // note of it; we won't actually be introducing the declaration into
13542         // the declaration context.
13543         if (TUK == TUK_Reference)
13544           IsForwardReference = true;
13545       }
13546     }
13547
13548     if (EnumUnderlying) {
13549       EnumDecl *ED = cast<EnumDecl>(New);
13550       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13551         ED->setIntegerTypeSourceInfo(TI);
13552       else
13553         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13554       ED->setPromotionType(ED->getIntegerType());
13555     }
13556   } else {
13557     // struct/union/class
13558
13559     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13560     // struct X { int A; } D;    D should chain to X.
13561     if (getLangOpts().CPlusPlus) {
13562       // FIXME: Look for a way to use RecordDecl for simple structs.
13563       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13564                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13565
13566       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13567         StdBadAlloc = cast<CXXRecordDecl>(New);
13568     } else
13569       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13570                                cast_or_null<RecordDecl>(PrevDecl));
13571   }
13572
13573   // C++11 [dcl.type]p3:
13574   //   A type-specifier-seq shall not define a class or enumeration [...].
13575   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13576     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13577       << Context.getTagDeclType(New);
13578     Invalid = true;
13579   }
13580
13581   // Maybe add qualifier info.
13582   if (SS.isNotEmpty()) {
13583     if (SS.isSet()) {
13584       // If this is either a declaration or a definition, check the
13585       // nested-name-specifier against the current context. We don't do this
13586       // for explicit specializations, because they have similar checking
13587       // (with more specific diagnostics) in the call to
13588       // CheckMemberSpecialization, below.
13589       if (!isMemberSpecialization &&
13590           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13591           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13592         Invalid = true;
13593
13594       New->setQualifierInfo(SS.getWithLocInContext(Context));
13595       if (TemplateParameterLists.size() > 0) {
13596         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13597       }
13598     }
13599     else
13600       Invalid = true;
13601   }
13602
13603   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13604     // Add alignment attributes if necessary; these attributes are checked when
13605     // the ASTContext lays out the structure.
13606     //
13607     // It is important for implementing the correct semantics that this
13608     // happen here (in act on tag decl). The #pragma pack stack is
13609     // maintained as a result of parser callbacks which can occur at
13610     // many points during the parsing of a struct declaration (because
13611     // the #pragma tokens are effectively skipped over during the
13612     // parsing of the struct).
13613     if (TUK == TUK_Definition) {
13614       AddAlignmentAttributesForRecord(RD);
13615       AddMsStructLayoutForRecord(RD);
13616     }
13617   }
13618
13619   if (ModulePrivateLoc.isValid()) {
13620     if (isMemberSpecialization)
13621       Diag(New->getLocation(), diag::err_module_private_specialization)
13622         << 2
13623         << FixItHint::CreateRemoval(ModulePrivateLoc);
13624     // __module_private__ does not apply to local classes. However, we only
13625     // diagnose this as an error when the declaration specifiers are
13626     // freestanding. Here, we just ignore the __module_private__.
13627     else if (!SearchDC->isFunctionOrMethod())
13628       New->setModulePrivate();
13629   }
13630
13631   // If this is a specialization of a member class (of a class template),
13632   // check the specialization.
13633   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13634     Invalid = true;
13635
13636   // If we're declaring or defining a tag in function prototype scope in C,
13637   // note that this type can only be used within the function and add it to
13638   // the list of decls to inject into the function definition scope.
13639   if ((Name || Kind == TTK_Enum) &&
13640       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13641     if (getLangOpts().CPlusPlus) {
13642       // C++ [dcl.fct]p6:
13643       //   Types shall not be defined in return or parameter types.
13644       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13645         Diag(Loc, diag::err_type_defined_in_param_type)
13646             << Name;
13647         Invalid = true;
13648       }
13649     } else if (!PrevDecl) {
13650       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13651     }
13652   }
13653
13654   if (Invalid)
13655     New->setInvalidDecl();
13656
13657   // Set the lexical context. If the tag has a C++ scope specifier, the
13658   // lexical context will be different from the semantic context.
13659   New->setLexicalDeclContext(CurContext);
13660
13661   // Mark this as a friend decl if applicable.
13662   // In Microsoft mode, a friend declaration also acts as a forward
13663   // declaration so we always pass true to setObjectOfFriendDecl to make
13664   // the tag name visible.
13665   if (TUK == TUK_Friend)
13666     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13667
13668   // Set the access specifier.
13669   if (!Invalid && SearchDC->isRecord())
13670     SetMemberAccessSpecifier(New, PrevDecl, AS);
13671
13672   if (TUK == TUK_Definition)
13673     New->startDefinition();
13674
13675   if (Attr)
13676     ProcessDeclAttributeList(S, New, Attr);
13677
13678   // If this has an identifier, add it to the scope stack.
13679   if (TUK == TUK_Friend) {
13680     // We might be replacing an existing declaration in the lookup tables;
13681     // if so, borrow its access specifier.
13682     if (PrevDecl)
13683       New->setAccess(PrevDecl->getAccess());
13684
13685     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13686     DC->makeDeclVisibleInContext(New);
13687     if (Name) // can be null along some error paths
13688       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13689         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13690   } else if (Name) {
13691     S = getNonFieldDeclScope(S);
13692     PushOnScopeChains(New, S, !IsForwardReference);
13693     if (IsForwardReference)
13694       SearchDC->makeDeclVisibleInContext(New);
13695   } else {
13696     CurContext->addDecl(New);
13697   }
13698
13699   // If this is the C FILE type, notify the AST context.
13700   if (IdentifierInfo *II = New->getIdentifier())
13701     if (!New->isInvalidDecl() &&
13702         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13703         II->isStr("FILE"))
13704       Context.setFILEDecl(New);
13705
13706   if (PrevDecl)
13707     mergeDeclAttributes(New, PrevDecl);
13708
13709   // If there's a #pragma GCC visibility in scope, set the visibility of this
13710   // record.
13711   AddPushedVisibilityAttribute(New);
13712
13713   OwnedDecl = true;
13714   // In C++, don't return an invalid declaration. We can't recover well from
13715   // the cases where we make the type anonymous.
13716   if (Invalid && getLangOpts().CPlusPlus) {
13717     if (New->isBeingDefined())
13718       if (auto RD = dyn_cast<RecordDecl>(New))
13719         RD->completeDefinition();
13720     return nullptr;
13721   } else {
13722     return New;
13723   }
13724 }
13725
13726 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13727   AdjustDeclIfTemplate(TagD);
13728   TagDecl *Tag = cast<TagDecl>(TagD);
13729
13730   // Enter the tag context.
13731   PushDeclContext(S, Tag);
13732
13733   ActOnDocumentableDecl(TagD);
13734
13735   // If there's a #pragma GCC visibility in scope, set the visibility of this
13736   // record.
13737   AddPushedVisibilityAttribute(Tag);
13738 }
13739
13740 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13741   assert(isa<ObjCContainerDecl>(IDecl) &&
13742          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13743   DeclContext *OCD = cast<DeclContext>(IDecl);
13744   assert(getContainingDC(OCD) == CurContext &&
13745       "The next DeclContext should be lexically contained in the current one.");
13746   CurContext = OCD;
13747   return IDecl;
13748 }
13749
13750 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13751                                            SourceLocation FinalLoc,
13752                                            bool IsFinalSpelledSealed,
13753                                            SourceLocation LBraceLoc) {
13754   AdjustDeclIfTemplate(TagD);
13755   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13756
13757   FieldCollector->StartClass();
13758
13759   if (!Record->getIdentifier())
13760     return;
13761
13762   if (FinalLoc.isValid())
13763     Record->addAttr(new (Context)
13764                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13765
13766   // C++ [class]p2:
13767   //   [...] The class-name is also inserted into the scope of the
13768   //   class itself; this is known as the injected-class-name. For
13769   //   purposes of access checking, the injected-class-name is treated
13770   //   as if it were a public member name.
13771   CXXRecordDecl *InjectedClassName
13772     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13773                             Record->getLocStart(), Record->getLocation(),
13774                             Record->getIdentifier(),
13775                             /*PrevDecl=*/nullptr,
13776                             /*DelayTypeCreation=*/true);
13777   Context.getTypeDeclType(InjectedClassName, Record);
13778   InjectedClassName->setImplicit();
13779   InjectedClassName->setAccess(AS_public);
13780   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13781       InjectedClassName->setDescribedClassTemplate(Template);
13782   PushOnScopeChains(InjectedClassName, S);
13783   assert(InjectedClassName->isInjectedClassName() &&
13784          "Broken injected-class-name");
13785 }
13786
13787 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13788                                     SourceRange BraceRange) {
13789   AdjustDeclIfTemplate(TagD);
13790   TagDecl *Tag = cast<TagDecl>(TagD);
13791   Tag->setBraceRange(BraceRange);
13792
13793   // Make sure we "complete" the definition even it is invalid.
13794   if (Tag->isBeingDefined()) {
13795     assert(Tag->isInvalidDecl() && "We should already have completed it");
13796     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13797       RD->completeDefinition();
13798   }
13799
13800   if (isa<CXXRecordDecl>(Tag)) {
13801     FieldCollector->FinishClass();
13802   }
13803
13804   // Exit this scope of this tag's definition.
13805   PopDeclContext();
13806
13807   if (getCurLexicalContext()->isObjCContainer() &&
13808       Tag->getDeclContext()->isFileContext())
13809     Tag->setTopLevelDeclInObjCContainer();
13810
13811   // Notify the consumer that we've defined a tag.
13812   if (!Tag->isInvalidDecl())
13813     Consumer.HandleTagDeclDefinition(Tag);
13814 }
13815
13816 void Sema::ActOnObjCContainerFinishDefinition() {
13817   // Exit this scope of this interface definition.
13818   PopDeclContext();
13819 }
13820
13821 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13822   assert(DC == CurContext && "Mismatch of container contexts");
13823   OriginalLexicalContext = DC;
13824   ActOnObjCContainerFinishDefinition();
13825 }
13826
13827 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13828   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13829   OriginalLexicalContext = nullptr;
13830 }
13831
13832 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13833   AdjustDeclIfTemplate(TagD);
13834   TagDecl *Tag = cast<TagDecl>(TagD);
13835   Tag->setInvalidDecl();
13836
13837   // Make sure we "complete" the definition even it is invalid.
13838   if (Tag->isBeingDefined()) {
13839     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13840       RD->completeDefinition();
13841   }
13842
13843   // We're undoing ActOnTagStartDefinition here, not
13844   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13845   // the FieldCollector.
13846
13847   PopDeclContext();
13848 }
13849
13850 // Note that FieldName may be null for anonymous bitfields.
13851 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13852                                 IdentifierInfo *FieldName,
13853                                 QualType FieldTy, bool IsMsStruct,
13854                                 Expr *BitWidth, bool *ZeroWidth) {
13855   // Default to true; that shouldn't confuse checks for emptiness
13856   if (ZeroWidth)
13857     *ZeroWidth = true;
13858
13859   // C99 6.7.2.1p4 - verify the field type.
13860   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13861   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13862     // Handle incomplete types with specific error.
13863     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13864       return ExprError();
13865     if (FieldName)
13866       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13867         << FieldName << FieldTy << BitWidth->getSourceRange();
13868     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13869       << FieldTy << BitWidth->getSourceRange();
13870   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13871                                              UPPC_BitFieldWidth))
13872     return ExprError();
13873
13874   // If the bit-width is type- or value-dependent, don't try to check
13875   // it now.
13876   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13877     return BitWidth;
13878
13879   llvm::APSInt Value;
13880   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13881   if (ICE.isInvalid())
13882     return ICE;
13883   BitWidth = ICE.get();
13884
13885   if (Value != 0 && ZeroWidth)
13886     *ZeroWidth = false;
13887
13888   // Zero-width bitfield is ok for anonymous field.
13889   if (Value == 0 && FieldName)
13890     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13891
13892   if (Value.isSigned() && Value.isNegative()) {
13893     if (FieldName)
13894       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13895                << FieldName << Value.toString(10);
13896     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13897       << Value.toString(10);
13898   }
13899
13900   if (!FieldTy->isDependentType()) {
13901     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13902     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13903     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13904
13905     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13906     // ABI.
13907     bool CStdConstraintViolation =
13908         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13909     bool MSBitfieldViolation =
13910         Value.ugt(TypeStorageSize) &&
13911         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13912     if (CStdConstraintViolation || MSBitfieldViolation) {
13913       unsigned DiagWidth =
13914           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13915       if (FieldName)
13916         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13917                << FieldName << (unsigned)Value.getZExtValue()
13918                << !CStdConstraintViolation << DiagWidth;
13919
13920       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13921              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13922              << DiagWidth;
13923     }
13924
13925     // Warn on types where the user might conceivably expect to get all
13926     // specified bits as value bits: that's all integral types other than
13927     // 'bool'.
13928     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13929       if (FieldName)
13930         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13931             << FieldName << (unsigned)Value.getZExtValue()
13932             << (unsigned)TypeWidth;
13933       else
13934         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13935             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13936     }
13937   }
13938
13939   return BitWidth;
13940 }
13941
13942 /// ActOnField - Each field of a C struct/union is passed into this in order
13943 /// to create a FieldDecl object for it.
13944 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13945                        Declarator &D, Expr *BitfieldWidth) {
13946   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13947                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13948                                /*InitStyle=*/ICIS_NoInit, AS_public);
13949   return Res;
13950 }
13951
13952 /// HandleField - Analyze a field of a C struct or a C++ data member.
13953 ///
13954 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13955                              SourceLocation DeclStart,
13956                              Declarator &D, Expr *BitWidth,
13957                              InClassInitStyle InitStyle,
13958                              AccessSpecifier AS) {
13959   if (D.isDecompositionDeclarator()) {
13960     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
13961     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
13962       << Decomp.getSourceRange();
13963     return nullptr;
13964   }
13965
13966   IdentifierInfo *II = D.getIdentifier();
13967   SourceLocation Loc = DeclStart;
13968   if (II) Loc = D.getIdentifierLoc();
13969
13970   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13971   QualType T = TInfo->getType();
13972   if (getLangOpts().CPlusPlus) {
13973     CheckExtraCXXDefaultArguments(D);
13974
13975     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13976                                         UPPC_DataMemberType)) {
13977       D.setInvalidType();
13978       T = Context.IntTy;
13979       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13980     }
13981   }
13982
13983   // TR 18037 does not allow fields to be declared with address spaces.
13984   if (T.getQualifiers().hasAddressSpace()) {
13985     Diag(Loc, diag::err_field_with_address_space);
13986     D.setInvalidType();
13987   }
13988
13989   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13990   // used as structure or union field: image, sampler, event or block types.
13991   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13992                           T->isSamplerT() || T->isBlockPointerType())) {
13993     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13994     D.setInvalidType();
13995   }
13996
13997   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13998
13999   if (D.getDeclSpec().isInlineSpecified())
14000     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14001         << getLangOpts().CPlusPlus1z;
14002   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14003     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14004          diag::err_invalid_thread)
14005       << DeclSpec::getSpecifierName(TSCS);
14006
14007   // Check to see if this name was declared as a member previously
14008   NamedDecl *PrevDecl = nullptr;
14009   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14010   LookupName(Previous, S);
14011   switch (Previous.getResultKind()) {
14012     case LookupResult::Found:
14013     case LookupResult::FoundUnresolvedValue:
14014       PrevDecl = Previous.getAsSingle<NamedDecl>();
14015       break;
14016
14017     case LookupResult::FoundOverloaded:
14018       PrevDecl = Previous.getRepresentativeDecl();
14019       break;
14020
14021     case LookupResult::NotFound:
14022     case LookupResult::NotFoundInCurrentInstantiation:
14023     case LookupResult::Ambiguous:
14024       break;
14025   }
14026   Previous.suppressDiagnostics();
14027
14028   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14029     // Maybe we will complain about the shadowed template parameter.
14030     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14031     // Just pretend that we didn't see the previous declaration.
14032     PrevDecl = nullptr;
14033   }
14034
14035   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14036     PrevDecl = nullptr;
14037
14038   bool Mutable
14039     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14040   SourceLocation TSSL = D.getLocStart();
14041   FieldDecl *NewFD
14042     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14043                      TSSL, AS, PrevDecl, &D);
14044
14045   if (NewFD->isInvalidDecl())
14046     Record->setInvalidDecl();
14047
14048   if (D.getDeclSpec().isModulePrivateSpecified())
14049     NewFD->setModulePrivate();
14050
14051   if (NewFD->isInvalidDecl() && PrevDecl) {
14052     // Don't introduce NewFD into scope; there's already something
14053     // with the same name in the same scope.
14054   } else if (II) {
14055     PushOnScopeChains(NewFD, S);
14056   } else
14057     Record->addDecl(NewFD);
14058
14059   return NewFD;
14060 }
14061
14062 /// \brief Build a new FieldDecl and check its well-formedness.
14063 ///
14064 /// This routine builds a new FieldDecl given the fields name, type,
14065 /// record, etc. \p PrevDecl should refer to any previous declaration
14066 /// with the same name and in the same scope as the field to be
14067 /// created.
14068 ///
14069 /// \returns a new FieldDecl.
14070 ///
14071 /// \todo The Declarator argument is a hack. It will be removed once
14072 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14073                                 TypeSourceInfo *TInfo,
14074                                 RecordDecl *Record, SourceLocation Loc,
14075                                 bool Mutable, Expr *BitWidth,
14076                                 InClassInitStyle InitStyle,
14077                                 SourceLocation TSSL,
14078                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14079                                 Declarator *D) {
14080   IdentifierInfo *II = Name.getAsIdentifierInfo();
14081   bool InvalidDecl = false;
14082   if (D) InvalidDecl = D->isInvalidType();
14083
14084   // If we receive a broken type, recover by assuming 'int' and
14085   // marking this declaration as invalid.
14086   if (T.isNull()) {
14087     InvalidDecl = true;
14088     T = Context.IntTy;
14089   }
14090
14091   QualType EltTy = Context.getBaseElementType(T);
14092   if (!EltTy->isDependentType()) {
14093     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14094       // Fields of incomplete type force their record to be invalid.
14095       Record->setInvalidDecl();
14096       InvalidDecl = true;
14097     } else {
14098       NamedDecl *Def;
14099       EltTy->isIncompleteType(&Def);
14100       if (Def && Def->isInvalidDecl()) {
14101         Record->setInvalidDecl();
14102         InvalidDecl = true;
14103       }
14104     }
14105   }
14106
14107   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14108   if (BitWidth && getLangOpts().OpenCL) {
14109     Diag(Loc, diag::err_opencl_bitfields);
14110     InvalidDecl = true;
14111   }
14112
14113   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14114   // than a variably modified type.
14115   if (!InvalidDecl && T->isVariablyModifiedType()) {
14116     bool SizeIsNegative;
14117     llvm::APSInt Oversized;
14118
14119     TypeSourceInfo *FixedTInfo =
14120       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14121                                                     SizeIsNegative,
14122                                                     Oversized);
14123     if (FixedTInfo) {
14124       Diag(Loc, diag::warn_illegal_constant_array_size);
14125       TInfo = FixedTInfo;
14126       T = FixedTInfo->getType();
14127     } else {
14128       if (SizeIsNegative)
14129         Diag(Loc, diag::err_typecheck_negative_array_size);
14130       else if (Oversized.getBoolValue())
14131         Diag(Loc, diag::err_array_too_large)
14132           << Oversized.toString(10);
14133       else
14134         Diag(Loc, diag::err_typecheck_field_variable_size);
14135       InvalidDecl = true;
14136     }
14137   }
14138
14139   // Fields can not have abstract class types
14140   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14141                                              diag::err_abstract_type_in_decl,
14142                                              AbstractFieldType))
14143     InvalidDecl = true;
14144
14145   bool ZeroWidth = false;
14146   if (InvalidDecl)
14147     BitWidth = nullptr;
14148   // If this is declared as a bit-field, check the bit-field.
14149   if (BitWidth) {
14150     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14151                               &ZeroWidth).get();
14152     if (!BitWidth) {
14153       InvalidDecl = true;
14154       BitWidth = nullptr;
14155       ZeroWidth = false;
14156     }
14157   }
14158
14159   // Check that 'mutable' is consistent with the type of the declaration.
14160   if (!InvalidDecl && Mutable) {
14161     unsigned DiagID = 0;
14162     if (T->isReferenceType())
14163       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14164                                         : diag::err_mutable_reference;
14165     else if (T.isConstQualified())
14166       DiagID = diag::err_mutable_const;
14167
14168     if (DiagID) {
14169       SourceLocation ErrLoc = Loc;
14170       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14171         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14172       Diag(ErrLoc, DiagID);
14173       if (DiagID != diag::ext_mutable_reference) {
14174         Mutable = false;
14175         InvalidDecl = true;
14176       }
14177     }
14178   }
14179
14180   // C++11 [class.union]p8 (DR1460):
14181   //   At most one variant member of a union may have a
14182   //   brace-or-equal-initializer.
14183   if (InitStyle != ICIS_NoInit)
14184     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14185
14186   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14187                                        BitWidth, Mutable, InitStyle);
14188   if (InvalidDecl)
14189     NewFD->setInvalidDecl();
14190
14191   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14192     Diag(Loc, diag::err_duplicate_member) << II;
14193     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14194     NewFD->setInvalidDecl();
14195   }
14196
14197   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14198     if (Record->isUnion()) {
14199       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14200         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14201         if (RDecl->getDefinition()) {
14202           // C++ [class.union]p1: An object of a class with a non-trivial
14203           // constructor, a non-trivial copy constructor, a non-trivial
14204           // destructor, or a non-trivial copy assignment operator
14205           // cannot be a member of a union, nor can an array of such
14206           // objects.
14207           if (CheckNontrivialField(NewFD))
14208             NewFD->setInvalidDecl();
14209         }
14210       }
14211
14212       // C++ [class.union]p1: If a union contains a member of reference type,
14213       // the program is ill-formed, except when compiling with MSVC extensions
14214       // enabled.
14215       if (EltTy->isReferenceType()) {
14216         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14217                                     diag::ext_union_member_of_reference_type :
14218                                     diag::err_union_member_of_reference_type)
14219           << NewFD->getDeclName() << EltTy;
14220         if (!getLangOpts().MicrosoftExt)
14221           NewFD->setInvalidDecl();
14222       }
14223     }
14224   }
14225
14226   // FIXME: We need to pass in the attributes given an AST
14227   // representation, not a parser representation.
14228   if (D) {
14229     // FIXME: The current scope is almost... but not entirely... correct here.
14230     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14231
14232     if (NewFD->hasAttrs())
14233       CheckAlignasUnderalignment(NewFD);
14234   }
14235
14236   // In auto-retain/release, infer strong retension for fields of
14237   // retainable type.
14238   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14239     NewFD->setInvalidDecl();
14240
14241   if (T.isObjCGCWeak())
14242     Diag(Loc, diag::warn_attribute_weak_on_field);
14243
14244   NewFD->setAccess(AS);
14245   return NewFD;
14246 }
14247
14248 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14249   assert(FD);
14250   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14251
14252   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14253     return false;
14254
14255   QualType EltTy = Context.getBaseElementType(FD->getType());
14256   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14257     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14258     if (RDecl->getDefinition()) {
14259       // We check for copy constructors before constructors
14260       // because otherwise we'll never get complaints about
14261       // copy constructors.
14262
14263       CXXSpecialMember member = CXXInvalid;
14264       // We're required to check for any non-trivial constructors. Since the
14265       // implicit default constructor is suppressed if there are any
14266       // user-declared constructors, we just need to check that there is a
14267       // trivial default constructor and a trivial copy constructor. (We don't
14268       // worry about move constructors here, since this is a C++98 check.)
14269       if (RDecl->hasNonTrivialCopyConstructor())
14270         member = CXXCopyConstructor;
14271       else if (!RDecl->hasTrivialDefaultConstructor())
14272         member = CXXDefaultConstructor;
14273       else if (RDecl->hasNonTrivialCopyAssignment())
14274         member = CXXCopyAssignment;
14275       else if (RDecl->hasNonTrivialDestructor())
14276         member = CXXDestructor;
14277
14278       if (member != CXXInvalid) {
14279         if (!getLangOpts().CPlusPlus11 &&
14280             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14281           // Objective-C++ ARC: it is an error to have a non-trivial field of
14282           // a union. However, system headers in Objective-C programs
14283           // occasionally have Objective-C lifetime objects within unions,
14284           // and rather than cause the program to fail, we make those
14285           // members unavailable.
14286           SourceLocation Loc = FD->getLocation();
14287           if (getSourceManager().isInSystemHeader(Loc)) {
14288             if (!FD->hasAttr<UnavailableAttr>())
14289               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14290                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14291             return false;
14292           }
14293         }
14294
14295         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14296                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14297                diag::err_illegal_union_or_anon_struct_member)
14298           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14299         DiagnoseNontrivial(RDecl, member);
14300         return !getLangOpts().CPlusPlus11;
14301       }
14302     }
14303   }
14304
14305   return false;
14306 }
14307
14308 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14309 ///  AST enum value.
14310 static ObjCIvarDecl::AccessControl
14311 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14312   switch (ivarVisibility) {
14313   default: llvm_unreachable("Unknown visitibility kind");
14314   case tok::objc_private: return ObjCIvarDecl::Private;
14315   case tok::objc_public: return ObjCIvarDecl::Public;
14316   case tok::objc_protected: return ObjCIvarDecl::Protected;
14317   case tok::objc_package: return ObjCIvarDecl::Package;
14318   }
14319 }
14320
14321 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14322 /// in order to create an IvarDecl object for it.
14323 Decl *Sema::ActOnIvar(Scope *S,
14324                                 SourceLocation DeclStart,
14325                                 Declarator &D, Expr *BitfieldWidth,
14326                                 tok::ObjCKeywordKind Visibility) {
14327
14328   IdentifierInfo *II = D.getIdentifier();
14329   Expr *BitWidth = (Expr*)BitfieldWidth;
14330   SourceLocation Loc = DeclStart;
14331   if (II) Loc = D.getIdentifierLoc();
14332
14333   // FIXME: Unnamed fields can be handled in various different ways, for
14334   // example, unnamed unions inject all members into the struct namespace!
14335
14336   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14337   QualType T = TInfo->getType();
14338
14339   if (BitWidth) {
14340     // 6.7.2.1p3, 6.7.2.1p4
14341     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14342     if (!BitWidth)
14343       D.setInvalidType();
14344   } else {
14345     // Not a bitfield.
14346
14347     // validate II.
14348
14349   }
14350   if (T->isReferenceType()) {
14351     Diag(Loc, diag::err_ivar_reference_type);
14352     D.setInvalidType();
14353   }
14354   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14355   // than a variably modified type.
14356   else if (T->isVariablyModifiedType()) {
14357     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14358     D.setInvalidType();
14359   }
14360
14361   // Get the visibility (access control) for this ivar.
14362   ObjCIvarDecl::AccessControl ac =
14363     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14364                                         : ObjCIvarDecl::None;
14365   // Must set ivar's DeclContext to its enclosing interface.
14366   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14367   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14368     return nullptr;
14369   ObjCContainerDecl *EnclosingContext;
14370   if (ObjCImplementationDecl *IMPDecl =
14371       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14372     if (LangOpts.ObjCRuntime.isFragile()) {
14373     // Case of ivar declared in an implementation. Context is that of its class.
14374       EnclosingContext = IMPDecl->getClassInterface();
14375       assert(EnclosingContext && "Implementation has no class interface!");
14376     }
14377     else
14378       EnclosingContext = EnclosingDecl;
14379   } else {
14380     if (ObjCCategoryDecl *CDecl =
14381         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14382       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14383         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14384         return nullptr;
14385       }
14386     }
14387     EnclosingContext = EnclosingDecl;
14388   }
14389
14390   // Construct the decl.
14391   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14392                                              DeclStart, Loc, II, T,
14393                                              TInfo, ac, (Expr *)BitfieldWidth);
14394
14395   if (II) {
14396     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14397                                            ForRedeclaration);
14398     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14399         && !isa<TagDecl>(PrevDecl)) {
14400       Diag(Loc, diag::err_duplicate_member) << II;
14401       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14402       NewID->setInvalidDecl();
14403     }
14404   }
14405
14406   // Process attributes attached to the ivar.
14407   ProcessDeclAttributes(S, NewID, D);
14408
14409   if (D.isInvalidType())
14410     NewID->setInvalidDecl();
14411
14412   // In ARC, infer 'retaining' for ivars of retainable type.
14413   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14414     NewID->setInvalidDecl();
14415
14416   if (D.getDeclSpec().isModulePrivateSpecified())
14417     NewID->setModulePrivate();
14418
14419   if (II) {
14420     // FIXME: When interfaces are DeclContexts, we'll need to add
14421     // these to the interface.
14422     S->AddDecl(NewID);
14423     IdResolver.AddDecl(NewID);
14424   }
14425
14426   if (LangOpts.ObjCRuntime.isNonFragile() &&
14427       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14428     Diag(Loc, diag::warn_ivars_in_interface);
14429
14430   return NewID;
14431 }
14432
14433 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14434 /// class and class extensions. For every class \@interface and class
14435 /// extension \@interface, if the last ivar is a bitfield of any type,
14436 /// then add an implicit `char :0` ivar to the end of that interface.
14437 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14438                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14439   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14440     return;
14441
14442   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14443   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14444
14445   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14446     return;
14447   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14448   if (!ID) {
14449     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14450       if (!CD->IsClassExtension())
14451         return;
14452     }
14453     // No need to add this to end of @implementation.
14454     else
14455       return;
14456   }
14457   // All conditions are met. Add a new bitfield to the tail end of ivars.
14458   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14459   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14460
14461   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14462                               DeclLoc, DeclLoc, nullptr,
14463                               Context.CharTy,
14464                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14465                                                                DeclLoc),
14466                               ObjCIvarDecl::Private, BW,
14467                               true);
14468   AllIvarDecls.push_back(Ivar);
14469 }
14470
14471 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14472                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14473                        SourceLocation RBrac, AttributeList *Attr) {
14474   assert(EnclosingDecl && "missing record or interface decl");
14475
14476   // If this is an Objective-C @implementation or category and we have
14477   // new fields here we should reset the layout of the interface since
14478   // it will now change.
14479   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14480     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14481     switch (DC->getKind()) {
14482     default: break;
14483     case Decl::ObjCCategory:
14484       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14485       break;
14486     case Decl::ObjCImplementation:
14487       Context.
14488         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14489       break;
14490     }
14491   }
14492
14493   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14494
14495   // Start counting up the number of named members; make sure to include
14496   // members of anonymous structs and unions in the total.
14497   unsigned NumNamedMembers = 0;
14498   if (Record) {
14499     for (const auto *I : Record->decls()) {
14500       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14501         if (IFD->getDeclName())
14502           ++NumNamedMembers;
14503     }
14504   }
14505
14506   // Verify that all the fields are okay.
14507   SmallVector<FieldDecl*, 32> RecFields;
14508
14509   bool ObjCFieldLifetimeErrReported = false;
14510   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14511        i != end; ++i) {
14512     FieldDecl *FD = cast<FieldDecl>(*i);
14513
14514     // Get the type for the field.
14515     const Type *FDTy = FD->getType().getTypePtr();
14516
14517     if (!FD->isAnonymousStructOrUnion()) {
14518       // Remember all fields written by the user.
14519       RecFields.push_back(FD);
14520     }
14521
14522     // If the field is already invalid for some reason, don't emit more
14523     // diagnostics about it.
14524     if (FD->isInvalidDecl()) {
14525       EnclosingDecl->setInvalidDecl();
14526       continue;
14527     }
14528
14529     // C99 6.7.2.1p2:
14530     //   A structure or union shall not contain a member with
14531     //   incomplete or function type (hence, a structure shall not
14532     //   contain an instance of itself, but may contain a pointer to
14533     //   an instance of itself), except that the last member of a
14534     //   structure with more than one named member may have incomplete
14535     //   array type; such a structure (and any union containing,
14536     //   possibly recursively, a member that is such a structure)
14537     //   shall not be a member of a structure or an element of an
14538     //   array.
14539     if (FDTy->isFunctionType()) {
14540       // Field declared as a function.
14541       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14542         << FD->getDeclName();
14543       FD->setInvalidDecl();
14544       EnclosingDecl->setInvalidDecl();
14545       continue;
14546     } else if (FDTy->isIncompleteArrayType() && Record &&
14547                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14548                 ((getLangOpts().MicrosoftExt ||
14549                   getLangOpts().CPlusPlus) &&
14550                  (i + 1 == Fields.end() || Record->isUnion())))) {
14551       // Flexible array member.
14552       // Microsoft and g++ is more permissive regarding flexible array.
14553       // It will accept flexible array in union and also
14554       // as the sole element of a struct/class.
14555       unsigned DiagID = 0;
14556       if (Record->isUnion())
14557         DiagID = getLangOpts().MicrosoftExt
14558                      ? diag::ext_flexible_array_union_ms
14559                      : getLangOpts().CPlusPlus
14560                            ? diag::ext_flexible_array_union_gnu
14561                            : diag::err_flexible_array_union;
14562       else if (NumNamedMembers < 1)
14563         DiagID = getLangOpts().MicrosoftExt
14564                      ? diag::ext_flexible_array_empty_aggregate_ms
14565                      : getLangOpts().CPlusPlus
14566                            ? diag::ext_flexible_array_empty_aggregate_gnu
14567                            : diag::err_flexible_array_empty_aggregate;
14568
14569       if (DiagID)
14570         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14571                                         << Record->getTagKind();
14572       // While the layout of types that contain virtual bases is not specified
14573       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14574       // virtual bases after the derived members.  This would make a flexible
14575       // array member declared at the end of an object not adjacent to the end
14576       // of the type.
14577       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14578         if (RD->getNumVBases() != 0)
14579           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14580             << FD->getDeclName() << Record->getTagKind();
14581       if (!getLangOpts().C99)
14582         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14583           << FD->getDeclName() << Record->getTagKind();
14584
14585       // If the element type has a non-trivial destructor, we would not
14586       // implicitly destroy the elements, so disallow it for now.
14587       //
14588       // FIXME: GCC allows this. We should probably either implicitly delete
14589       // the destructor of the containing class, or just allow this.
14590       QualType BaseElem = Context.getBaseElementType(FD->getType());
14591       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14592         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14593           << FD->getDeclName() << FD->getType();
14594         FD->setInvalidDecl();
14595         EnclosingDecl->setInvalidDecl();
14596         continue;
14597       }
14598       // Okay, we have a legal flexible array member at the end of the struct.
14599       Record->setHasFlexibleArrayMember(true);
14600     } else if (!FDTy->isDependentType() &&
14601                RequireCompleteType(FD->getLocation(), FD->getType(),
14602                                    diag::err_field_incomplete)) {
14603       // Incomplete type
14604       FD->setInvalidDecl();
14605       EnclosingDecl->setInvalidDecl();
14606       continue;
14607     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14608       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14609         // A type which contains a flexible array member is considered to be a
14610         // flexible array member.
14611         Record->setHasFlexibleArrayMember(true);
14612         if (!Record->isUnion()) {
14613           // If this is a struct/class and this is not the last element, reject
14614           // it.  Note that GCC supports variable sized arrays in the middle of
14615           // structures.
14616           if (i + 1 != Fields.end())
14617             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14618               << FD->getDeclName() << FD->getType();
14619           else {
14620             // We support flexible arrays at the end of structs in
14621             // other structs as an extension.
14622             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14623               << FD->getDeclName();
14624           }
14625         }
14626       }
14627       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14628           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14629                                  diag::err_abstract_type_in_decl,
14630                                  AbstractIvarType)) {
14631         // Ivars can not have abstract class types
14632         FD->setInvalidDecl();
14633       }
14634       if (Record && FDTTy->getDecl()->hasObjectMember())
14635         Record->setHasObjectMember(true);
14636       if (Record && FDTTy->getDecl()->hasVolatileMember())
14637         Record->setHasVolatileMember(true);
14638     } else if (FDTy->isObjCObjectType()) {
14639       /// A field cannot be an Objective-c object
14640       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14641         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14642       QualType T = Context.getObjCObjectPointerType(FD->getType());
14643       FD->setType(T);
14644     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
14645                Record && !ObjCFieldLifetimeErrReported &&
14646                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14647       // It's an error in ARC or Weak if a field has lifetime.
14648       // We don't want to report this in a system header, though,
14649       // so we just make the field unavailable.
14650       // FIXME: that's really not sufficient; we need to make the type
14651       // itself invalid to, say, initialize or copy.
14652       QualType T = FD->getType();
14653       if (T.hasNonTrivialObjCLifetime()) {
14654         SourceLocation loc = FD->getLocation();
14655         if (getSourceManager().isInSystemHeader(loc)) {
14656           if (!FD->hasAttr<UnavailableAttr>()) {
14657             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14658                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14659           }
14660         } else {
14661           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14662             << T->isBlockPointerType() << Record->getTagKind();
14663         }
14664         ObjCFieldLifetimeErrReported = true;
14665       }
14666     } else if (getLangOpts().ObjC1 &&
14667                getLangOpts().getGC() != LangOptions::NonGC &&
14668                Record && !Record->hasObjectMember()) {
14669       if (FD->getType()->isObjCObjectPointerType() ||
14670           FD->getType().isObjCGCStrong())
14671         Record->setHasObjectMember(true);
14672       else if (Context.getAsArrayType(FD->getType())) {
14673         QualType BaseType = Context.getBaseElementType(FD->getType());
14674         if (BaseType->isRecordType() &&
14675             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14676           Record->setHasObjectMember(true);
14677         else if (BaseType->isObjCObjectPointerType() ||
14678                  BaseType.isObjCGCStrong())
14679                Record->setHasObjectMember(true);
14680       }
14681     }
14682     if (Record && FD->getType().isVolatileQualified())
14683       Record->setHasVolatileMember(true);
14684     // Keep track of the number of named members.
14685     if (FD->getIdentifier())
14686       ++NumNamedMembers;
14687   }
14688
14689   // Okay, we successfully defined 'Record'.
14690   if (Record) {
14691     bool Completed = false;
14692     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14693       if (!CXXRecord->isInvalidDecl()) {
14694         // Set access bits correctly on the directly-declared conversions.
14695         for (CXXRecordDecl::conversion_iterator
14696                I = CXXRecord->conversion_begin(),
14697                E = CXXRecord->conversion_end(); I != E; ++I)
14698           I.setAccess((*I)->getAccess());
14699       }
14700
14701       if (!CXXRecord->isDependentType()) {
14702         if (CXXRecord->hasUserDeclaredDestructor()) {
14703           // Adjust user-defined destructor exception spec.
14704           if (getLangOpts().CPlusPlus11)
14705             AdjustDestructorExceptionSpec(CXXRecord,
14706                                           CXXRecord->getDestructor());
14707         }
14708
14709         if (!CXXRecord->isInvalidDecl()) {
14710           // Add any implicitly-declared members to this class.
14711           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14712
14713           // If we have virtual base classes, we may end up finding multiple
14714           // final overriders for a given virtual function. Check for this
14715           // problem now.
14716           if (CXXRecord->getNumVBases()) {
14717             CXXFinalOverriderMap FinalOverriders;
14718             CXXRecord->getFinalOverriders(FinalOverriders);
14719
14720             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14721                                              MEnd = FinalOverriders.end();
14722                  M != MEnd; ++M) {
14723               for (OverridingMethods::iterator SO = M->second.begin(),
14724                                             SOEnd = M->second.end();
14725                    SO != SOEnd; ++SO) {
14726                 assert(SO->second.size() > 0 &&
14727                        "Virtual function without overridding functions?");
14728                 if (SO->second.size() == 1)
14729                   continue;
14730
14731                 // C++ [class.virtual]p2:
14732                 //   In a derived class, if a virtual member function of a base
14733                 //   class subobject has more than one final overrider the
14734                 //   program is ill-formed.
14735                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14736                   << (const NamedDecl *)M->first << Record;
14737                 Diag(M->first->getLocation(),
14738                      diag::note_overridden_virtual_function);
14739                 for (OverridingMethods::overriding_iterator
14740                           OM = SO->second.begin(),
14741                        OMEnd = SO->second.end();
14742                      OM != OMEnd; ++OM)
14743                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14744                     << (const NamedDecl *)M->first << OM->Method->getParent();
14745
14746                 Record->setInvalidDecl();
14747               }
14748             }
14749             CXXRecord->completeDefinition(&FinalOverriders);
14750             Completed = true;
14751           }
14752         }
14753       }
14754     }
14755
14756     if (!Completed)
14757       Record->completeDefinition();
14758
14759     // We may have deferred checking for a deleted destructor. Check now.
14760     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14761       auto *Dtor = CXXRecord->getDestructor();
14762       if (Dtor && Dtor->isImplicit() &&
14763           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14764         SetDeclDeleted(Dtor, CXXRecord->getLocation());
14765     }
14766
14767     if (Record->hasAttrs()) {
14768       CheckAlignasUnderalignment(Record);
14769
14770       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14771         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14772                                            IA->getRange(), IA->getBestCase(),
14773                                            IA->getSemanticSpelling());
14774     }
14775
14776     // Check if the structure/union declaration is a type that can have zero
14777     // size in C. For C this is a language extension, for C++ it may cause
14778     // compatibility problems.
14779     bool CheckForZeroSize;
14780     if (!getLangOpts().CPlusPlus) {
14781       CheckForZeroSize = true;
14782     } else {
14783       // For C++ filter out types that cannot be referenced in C code.
14784       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14785       CheckForZeroSize =
14786           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14787           !CXXRecord->isDependentType() &&
14788           CXXRecord->isCLike();
14789     }
14790     if (CheckForZeroSize) {
14791       bool ZeroSize = true;
14792       bool IsEmpty = true;
14793       unsigned NonBitFields = 0;
14794       for (RecordDecl::field_iterator I = Record->field_begin(),
14795                                       E = Record->field_end();
14796            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14797         IsEmpty = false;
14798         if (I->isUnnamedBitfield()) {
14799           if (I->getBitWidthValue(Context) > 0)
14800             ZeroSize = false;
14801         } else {
14802           ++NonBitFields;
14803           QualType FieldType = I->getType();
14804           if (FieldType->isIncompleteType() ||
14805               !Context.getTypeSizeInChars(FieldType).isZero())
14806             ZeroSize = false;
14807         }
14808       }
14809
14810       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14811       // allowed in C++, but warn if its declaration is inside
14812       // extern "C" block.
14813       if (ZeroSize) {
14814         Diag(RecLoc, getLangOpts().CPlusPlus ?
14815                          diag::warn_zero_size_struct_union_in_extern_c :
14816                          diag::warn_zero_size_struct_union_compat)
14817           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14818       }
14819
14820       // Structs without named members are extension in C (C99 6.7.2.1p7),
14821       // but are accepted by GCC.
14822       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14823         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14824                                diag::ext_no_named_members_in_struct_union)
14825           << Record->isUnion();
14826       }
14827     }
14828   } else {
14829     ObjCIvarDecl **ClsFields =
14830       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14831     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14832       ID->setEndOfDefinitionLoc(RBrac);
14833       // Add ivar's to class's DeclContext.
14834       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14835         ClsFields[i]->setLexicalDeclContext(ID);
14836         ID->addDecl(ClsFields[i]);
14837       }
14838       // Must enforce the rule that ivars in the base classes may not be
14839       // duplicates.
14840       if (ID->getSuperClass())
14841         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14842     } else if (ObjCImplementationDecl *IMPDecl =
14843                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14844       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14845       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14846         // Ivar declared in @implementation never belongs to the implementation.
14847         // Only it is in implementation's lexical context.
14848         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14849       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14850       IMPDecl->setIvarLBraceLoc(LBrac);
14851       IMPDecl->setIvarRBraceLoc(RBrac);
14852     } else if (ObjCCategoryDecl *CDecl =
14853                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14854       // case of ivars in class extension; all other cases have been
14855       // reported as errors elsewhere.
14856       // FIXME. Class extension does not have a LocEnd field.
14857       // CDecl->setLocEnd(RBrac);
14858       // Add ivar's to class extension's DeclContext.
14859       // Diagnose redeclaration of private ivars.
14860       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14861       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14862         if (IDecl) {
14863           if (const ObjCIvarDecl *ClsIvar =
14864               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14865             Diag(ClsFields[i]->getLocation(),
14866                  diag::err_duplicate_ivar_declaration);
14867             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14868             continue;
14869           }
14870           for (const auto *Ext : IDecl->known_extensions()) {
14871             if (const ObjCIvarDecl *ClsExtIvar
14872                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14873               Diag(ClsFields[i]->getLocation(),
14874                    diag::err_duplicate_ivar_declaration);
14875               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14876               continue;
14877             }
14878           }
14879         }
14880         ClsFields[i]->setLexicalDeclContext(CDecl);
14881         CDecl->addDecl(ClsFields[i]);
14882       }
14883       CDecl->setIvarLBraceLoc(LBrac);
14884       CDecl->setIvarRBraceLoc(RBrac);
14885     }
14886   }
14887
14888   if (Attr)
14889     ProcessDeclAttributeList(S, Record, Attr);
14890 }
14891
14892 /// \brief Determine whether the given integral value is representable within
14893 /// the given type T.
14894 static bool isRepresentableIntegerValue(ASTContext &Context,
14895                                         llvm::APSInt &Value,
14896                                         QualType T) {
14897   assert(T->isIntegralType(Context) && "Integral type required!");
14898   unsigned BitWidth = Context.getIntWidth(T);
14899
14900   if (Value.isUnsigned() || Value.isNonNegative()) {
14901     if (T->isSignedIntegerOrEnumerationType())
14902       --BitWidth;
14903     return Value.getActiveBits() <= BitWidth;
14904   }
14905   return Value.getMinSignedBits() <= BitWidth;
14906 }
14907
14908 // \brief Given an integral type, return the next larger integral type
14909 // (or a NULL type of no such type exists).
14910 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14911   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14912   // enum checking below.
14913   assert(T->isIntegralType(Context) && "Integral type required!");
14914   const unsigned NumTypes = 4;
14915   QualType SignedIntegralTypes[NumTypes] = {
14916     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14917   };
14918   QualType UnsignedIntegralTypes[NumTypes] = {
14919     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14920     Context.UnsignedLongLongTy
14921   };
14922
14923   unsigned BitWidth = Context.getTypeSize(T);
14924   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14925                                                         : UnsignedIntegralTypes;
14926   for (unsigned I = 0; I != NumTypes; ++I)
14927     if (Context.getTypeSize(Types[I]) > BitWidth)
14928       return Types[I];
14929
14930   return QualType();
14931 }
14932
14933 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14934                                           EnumConstantDecl *LastEnumConst,
14935                                           SourceLocation IdLoc,
14936                                           IdentifierInfo *Id,
14937                                           Expr *Val) {
14938   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14939   llvm::APSInt EnumVal(IntWidth);
14940   QualType EltTy;
14941
14942   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14943     Val = nullptr;
14944
14945   if (Val)
14946     Val = DefaultLvalueConversion(Val).get();
14947
14948   if (Val) {
14949     if (Enum->isDependentType() || Val->isTypeDependent())
14950       EltTy = Context.DependentTy;
14951     else {
14952       SourceLocation ExpLoc;
14953       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14954           !getLangOpts().MSVCCompat) {
14955         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14956         // constant-expression in the enumerator-definition shall be a converted
14957         // constant expression of the underlying type.
14958         EltTy = Enum->getIntegerType();
14959         ExprResult Converted =
14960           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14961                                            CCEK_Enumerator);
14962         if (Converted.isInvalid())
14963           Val = nullptr;
14964         else
14965           Val = Converted.get();
14966       } else if (!Val->isValueDependent() &&
14967                  !(Val = VerifyIntegerConstantExpression(Val,
14968                                                          &EnumVal).get())) {
14969         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14970       } else {
14971         if (Enum->isFixed()) {
14972           EltTy = Enum->getIntegerType();
14973
14974           // In Obj-C and Microsoft mode, require the enumeration value to be
14975           // representable in the underlying type of the enumeration. In C++11,
14976           // we perform a non-narrowing conversion as part of converted constant
14977           // expression checking.
14978           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14979             if (getLangOpts().MSVCCompat) {
14980               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14981               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14982             } else
14983               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14984           } else
14985             Val = ImpCastExprToType(Val, EltTy,
14986                                     EltTy->isBooleanType() ?
14987                                     CK_IntegralToBoolean : CK_IntegralCast)
14988                     .get();
14989         } else if (getLangOpts().CPlusPlus) {
14990           // C++11 [dcl.enum]p5:
14991           //   If the underlying type is not fixed, the type of each enumerator
14992           //   is the type of its initializing value:
14993           //     - If an initializer is specified for an enumerator, the
14994           //       initializing value has the same type as the expression.
14995           EltTy = Val->getType();
14996         } else {
14997           // C99 6.7.2.2p2:
14998           //   The expression that defines the value of an enumeration constant
14999           //   shall be an integer constant expression that has a value
15000           //   representable as an int.
15001
15002           // Complain if the value is not representable in an int.
15003           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15004             Diag(IdLoc, diag::ext_enum_value_not_int)
15005               << EnumVal.toString(10) << Val->getSourceRange()
15006               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15007           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15008             // Force the type of the expression to 'int'.
15009             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15010           }
15011           EltTy = Val->getType();
15012         }
15013       }
15014     }
15015   }
15016
15017   if (!Val) {
15018     if (Enum->isDependentType())
15019       EltTy = Context.DependentTy;
15020     else if (!LastEnumConst) {
15021       // C++0x [dcl.enum]p5:
15022       //   If the underlying type is not fixed, the type of each enumerator
15023       //   is the type of its initializing value:
15024       //     - If no initializer is specified for the first enumerator, the
15025       //       initializing value has an unspecified integral type.
15026       //
15027       // GCC uses 'int' for its unspecified integral type, as does
15028       // C99 6.7.2.2p3.
15029       if (Enum->isFixed()) {
15030         EltTy = Enum->getIntegerType();
15031       }
15032       else {
15033         EltTy = Context.IntTy;
15034       }
15035     } else {
15036       // Assign the last value + 1.
15037       EnumVal = LastEnumConst->getInitVal();
15038       ++EnumVal;
15039       EltTy = LastEnumConst->getType();
15040
15041       // Check for overflow on increment.
15042       if (EnumVal < LastEnumConst->getInitVal()) {
15043         // C++0x [dcl.enum]p5:
15044         //   If the underlying type is not fixed, the type of each enumerator
15045         //   is the type of its initializing value:
15046         //
15047         //     - Otherwise the type of the initializing value is the same as
15048         //       the type of the initializing value of the preceding enumerator
15049         //       unless the incremented value is not representable in that type,
15050         //       in which case the type is an unspecified integral type
15051         //       sufficient to contain the incremented value. If no such type
15052         //       exists, the program is ill-formed.
15053         QualType T = getNextLargerIntegralType(Context, EltTy);
15054         if (T.isNull() || Enum->isFixed()) {
15055           // There is no integral type larger enough to represent this
15056           // value. Complain, then allow the value to wrap around.
15057           EnumVal = LastEnumConst->getInitVal();
15058           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15059           ++EnumVal;
15060           if (Enum->isFixed())
15061             // When the underlying type is fixed, this is ill-formed.
15062             Diag(IdLoc, diag::err_enumerator_wrapped)
15063               << EnumVal.toString(10)
15064               << EltTy;
15065           else
15066             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15067               << EnumVal.toString(10);
15068         } else {
15069           EltTy = T;
15070         }
15071
15072         // Retrieve the last enumerator's value, extent that type to the
15073         // type that is supposed to be large enough to represent the incremented
15074         // value, then increment.
15075         EnumVal = LastEnumConst->getInitVal();
15076         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15077         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15078         ++EnumVal;
15079
15080         // If we're not in C++, diagnose the overflow of enumerator values,
15081         // which in C99 means that the enumerator value is not representable in
15082         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15083         // permits enumerator values that are representable in some larger
15084         // integral type.
15085         if (!getLangOpts().CPlusPlus && !T.isNull())
15086           Diag(IdLoc, diag::warn_enum_value_overflow);
15087       } else if (!getLangOpts().CPlusPlus &&
15088                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15089         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15090         Diag(IdLoc, diag::ext_enum_value_not_int)
15091           << EnumVal.toString(10) << 1;
15092       }
15093     }
15094   }
15095
15096   if (!EltTy->isDependentType()) {
15097     // Make the enumerator value match the signedness and size of the
15098     // enumerator's type.
15099     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15100     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15101   }
15102
15103   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15104                                   Val, EnumVal);
15105 }
15106
15107 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15108                                                 SourceLocation IILoc) {
15109   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15110       !getLangOpts().CPlusPlus)
15111     return SkipBodyInfo();
15112
15113   // We have an anonymous enum definition. Look up the first enumerator to
15114   // determine if we should merge the definition with an existing one and
15115   // skip the body.
15116   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15117                                          ForRedeclaration);
15118   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15119   if (!PrevECD)
15120     return SkipBodyInfo();
15121
15122   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15123   NamedDecl *Hidden;
15124   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15125     SkipBodyInfo Skip;
15126     Skip.Previous = Hidden;
15127     return Skip;
15128   }
15129
15130   return SkipBodyInfo();
15131 }
15132
15133 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15134                               SourceLocation IdLoc, IdentifierInfo *Id,
15135                               AttributeList *Attr,
15136                               SourceLocation EqualLoc, Expr *Val) {
15137   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15138   EnumConstantDecl *LastEnumConst =
15139     cast_or_null<EnumConstantDecl>(lastEnumConst);
15140
15141   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15142   // we find one that is.
15143   S = getNonFieldDeclScope(S);
15144
15145   // Verify that there isn't already something declared with this name in this
15146   // scope.
15147   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15148                                          ForRedeclaration);
15149   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15150     // Maybe we will complain about the shadowed template parameter.
15151     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15152     // Just pretend that we didn't see the previous declaration.
15153     PrevDecl = nullptr;
15154   }
15155
15156   // C++ [class.mem]p15:
15157   // If T is the name of a class, then each of the following shall have a name
15158   // different from T:
15159   // - every enumerator of every member of class T that is an unscoped
15160   // enumerated type
15161   if (!TheEnumDecl->isScoped())
15162     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15163                             DeclarationNameInfo(Id, IdLoc));
15164
15165   EnumConstantDecl *New =
15166     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15167   if (!New)
15168     return nullptr;
15169
15170   if (PrevDecl) {
15171     // When in C++, we may get a TagDecl with the same name; in this case the
15172     // enum constant will 'hide' the tag.
15173     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15174            "Received TagDecl when not in C++!");
15175     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15176         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15177       if (isa<EnumConstantDecl>(PrevDecl))
15178         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15179       else
15180         Diag(IdLoc, diag::err_redefinition) << Id;
15181       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15182       return nullptr;
15183     }
15184   }
15185
15186   // Process attributes.
15187   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15188
15189   // Register this decl in the current scope stack.
15190   New->setAccess(TheEnumDecl->getAccess());
15191   PushOnScopeChains(New, S);
15192
15193   ActOnDocumentableDecl(New);
15194
15195   return New;
15196 }
15197
15198 // Returns true when the enum initial expression does not trigger the
15199 // duplicate enum warning.  A few common cases are exempted as follows:
15200 // Element2 = Element1
15201 // Element2 = Element1 + 1
15202 // Element2 = Element1 - 1
15203 // Where Element2 and Element1 are from the same enum.
15204 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15205   Expr *InitExpr = ECD->getInitExpr();
15206   if (!InitExpr)
15207     return true;
15208   InitExpr = InitExpr->IgnoreImpCasts();
15209
15210   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15211     if (!BO->isAdditiveOp())
15212       return true;
15213     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15214     if (!IL)
15215       return true;
15216     if (IL->getValue() != 1)
15217       return true;
15218
15219     InitExpr = BO->getLHS();
15220   }
15221
15222   // This checks if the elements are from the same enum.
15223   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15224   if (!DRE)
15225     return true;
15226
15227   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15228   if (!EnumConstant)
15229     return true;
15230
15231   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15232       Enum)
15233     return true;
15234
15235   return false;
15236 }
15237
15238 namespace {
15239 struct DupKey {
15240   int64_t val;
15241   bool isTombstoneOrEmptyKey;
15242   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15243     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15244 };
15245
15246 static DupKey GetDupKey(const llvm::APSInt& Val) {
15247   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15248                 false);
15249 }
15250
15251 struct DenseMapInfoDupKey {
15252   static DupKey getEmptyKey() { return DupKey(0, true); }
15253   static DupKey getTombstoneKey() { return DupKey(1, true); }
15254   static unsigned getHashValue(const DupKey Key) {
15255     return (unsigned)(Key.val * 37);
15256   }
15257   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15258     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15259            LHS.val == RHS.val;
15260   }
15261 };
15262 } // end anonymous namespace
15263
15264 // Emits a warning when an element is implicitly set a value that
15265 // a previous element has already been set to.
15266 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15267                                         EnumDecl *Enum,
15268                                         QualType EnumType) {
15269   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15270     return;
15271   // Avoid anonymous enums
15272   if (!Enum->getIdentifier())
15273     return;
15274
15275   // Only check for small enums.
15276   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15277     return;
15278
15279   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15280   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15281
15282   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15283   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15284           ValueToVectorMap;
15285
15286   DuplicatesVector DupVector;
15287   ValueToVectorMap EnumMap;
15288
15289   // Populate the EnumMap with all values represented by enum constants without
15290   // an initialier.
15291   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15292     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15293
15294     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15295     // this constant.  Skip this enum since it may be ill-formed.
15296     if (!ECD) {
15297       return;
15298     }
15299
15300     if (ECD->getInitExpr())
15301       continue;
15302
15303     DupKey Key = GetDupKey(ECD->getInitVal());
15304     DeclOrVector &Entry = EnumMap[Key];
15305
15306     // First time encountering this value.
15307     if (Entry.isNull())
15308       Entry = ECD;
15309   }
15310
15311   // Create vectors for any values that has duplicates.
15312   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15313     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15314     if (!ValidDuplicateEnum(ECD, Enum))
15315       continue;
15316
15317     DupKey Key = GetDupKey(ECD->getInitVal());
15318
15319     DeclOrVector& Entry = EnumMap[Key];
15320     if (Entry.isNull())
15321       continue;
15322
15323     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15324       // Ensure constants are different.
15325       if (D == ECD)
15326         continue;
15327
15328       // Create new vector and push values onto it.
15329       ECDVector *Vec = new ECDVector();
15330       Vec->push_back(D);
15331       Vec->push_back(ECD);
15332
15333       // Update entry to point to the duplicates vector.
15334       Entry = Vec;
15335
15336       // Store the vector somewhere we can consult later for quick emission of
15337       // diagnostics.
15338       DupVector.push_back(Vec);
15339       continue;
15340     }
15341
15342     ECDVector *Vec = Entry.get<ECDVector*>();
15343     // Make sure constants are not added more than once.
15344     if (*Vec->begin() == ECD)
15345       continue;
15346
15347     Vec->push_back(ECD);
15348   }
15349
15350   // Emit diagnostics.
15351   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15352                                   DupVectorEnd = DupVector.end();
15353        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15354     ECDVector *Vec = *DupVectorIter;
15355     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15356
15357     // Emit warning for one enum constant.
15358     ECDVector::iterator I = Vec->begin();
15359     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15360       << (*I)->getName() << (*I)->getInitVal().toString(10)
15361       << (*I)->getSourceRange();
15362     ++I;
15363
15364     // Emit one note for each of the remaining enum constants with
15365     // the same value.
15366     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15367       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15368         << (*I)->getName() << (*I)->getInitVal().toString(10)
15369         << (*I)->getSourceRange();
15370     delete Vec;
15371   }
15372 }
15373
15374 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15375                              bool AllowMask) const {
15376   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15377   assert(ED->isCompleteDefinition() && "expected enum definition");
15378
15379   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15380   llvm::APInt &FlagBits = R.first->second;
15381
15382   if (R.second) {
15383     for (auto *E : ED->enumerators()) {
15384       const auto &EVal = E->getInitVal();
15385       // Only single-bit enumerators introduce new flag values.
15386       if (EVal.isPowerOf2())
15387         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15388     }
15389   }
15390
15391   // A value is in a flag enum if either its bits are a subset of the enum's
15392   // flag bits (the first condition) or we are allowing masks and the same is
15393   // true of its complement (the second condition). When masks are allowed, we
15394   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15395   //
15396   // While it's true that any value could be used as a mask, the assumption is
15397   // that a mask will have all of the insignificant bits set. Anything else is
15398   // likely a logic error.
15399   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15400   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15401 }
15402
15403 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15404                          Decl *EnumDeclX,
15405                          ArrayRef<Decl *> Elements,
15406                          Scope *S, AttributeList *Attr) {
15407   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15408   QualType EnumType = Context.getTypeDeclType(Enum);
15409
15410   if (Attr)
15411     ProcessDeclAttributeList(S, Enum, Attr);
15412
15413   if (Enum->isDependentType()) {
15414     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15415       EnumConstantDecl *ECD =
15416         cast_or_null<EnumConstantDecl>(Elements[i]);
15417       if (!ECD) continue;
15418
15419       ECD->setType(EnumType);
15420     }
15421
15422     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15423     return;
15424   }
15425
15426   // TODO: If the result value doesn't fit in an int, it must be a long or long
15427   // long value.  ISO C does not support this, but GCC does as an extension,
15428   // emit a warning.
15429   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15430   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15431   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15432
15433   // Verify that all the values are okay, compute the size of the values, and
15434   // reverse the list.
15435   unsigned NumNegativeBits = 0;
15436   unsigned NumPositiveBits = 0;
15437
15438   // Keep track of whether all elements have type int.
15439   bool AllElementsInt = true;
15440
15441   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15442     EnumConstantDecl *ECD =
15443       cast_or_null<EnumConstantDecl>(Elements[i]);
15444     if (!ECD) continue;  // Already issued a diagnostic.
15445
15446     const llvm::APSInt &InitVal = ECD->getInitVal();
15447
15448     // Keep track of the size of positive and negative values.
15449     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15450       NumPositiveBits = std::max(NumPositiveBits,
15451                                  (unsigned)InitVal.getActiveBits());
15452     else
15453       NumNegativeBits = std::max(NumNegativeBits,
15454                                  (unsigned)InitVal.getMinSignedBits());
15455
15456     // Keep track of whether every enum element has type int (very commmon).
15457     if (AllElementsInt)
15458       AllElementsInt = ECD->getType() == Context.IntTy;
15459   }
15460
15461   // Figure out the type that should be used for this enum.
15462   QualType BestType;
15463   unsigned BestWidth;
15464
15465   // C++0x N3000 [conv.prom]p3:
15466   //   An rvalue of an unscoped enumeration type whose underlying
15467   //   type is not fixed can be converted to an rvalue of the first
15468   //   of the following types that can represent all the values of
15469   //   the enumeration: int, unsigned int, long int, unsigned long
15470   //   int, long long int, or unsigned long long int.
15471   // C99 6.4.4.3p2:
15472   //   An identifier declared as an enumeration constant has type int.
15473   // The C99 rule is modified by a gcc extension
15474   QualType BestPromotionType;
15475
15476   bool Packed = Enum->hasAttr<PackedAttr>();
15477   // -fshort-enums is the equivalent to specifying the packed attribute on all
15478   // enum definitions.
15479   if (LangOpts.ShortEnums)
15480     Packed = true;
15481
15482   if (Enum->isFixed()) {
15483     BestType = Enum->getIntegerType();
15484     if (BestType->isPromotableIntegerType())
15485       BestPromotionType = Context.getPromotedIntegerType(BestType);
15486     else
15487       BestPromotionType = BestType;
15488
15489     BestWidth = Context.getIntWidth(BestType);
15490   }
15491   else if (NumNegativeBits) {
15492     // If there is a negative value, figure out the smallest integer type (of
15493     // int/long/longlong) that fits.
15494     // If it's packed, check also if it fits a char or a short.
15495     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15496       BestType = Context.SignedCharTy;
15497       BestWidth = CharWidth;
15498     } else if (Packed && NumNegativeBits <= ShortWidth &&
15499                NumPositiveBits < ShortWidth) {
15500       BestType = Context.ShortTy;
15501       BestWidth = ShortWidth;
15502     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15503       BestType = Context.IntTy;
15504       BestWidth = IntWidth;
15505     } else {
15506       BestWidth = Context.getTargetInfo().getLongWidth();
15507
15508       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15509         BestType = Context.LongTy;
15510       } else {
15511         BestWidth = Context.getTargetInfo().getLongLongWidth();
15512
15513         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15514           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15515         BestType = Context.LongLongTy;
15516       }
15517     }
15518     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15519   } else {
15520     // If there is no negative value, figure out the smallest type that fits
15521     // all of the enumerator values.
15522     // If it's packed, check also if it fits a char or a short.
15523     if (Packed && NumPositiveBits <= CharWidth) {
15524       BestType = Context.UnsignedCharTy;
15525       BestPromotionType = Context.IntTy;
15526       BestWidth = CharWidth;
15527     } else if (Packed && NumPositiveBits <= ShortWidth) {
15528       BestType = Context.UnsignedShortTy;
15529       BestPromotionType = Context.IntTy;
15530       BestWidth = ShortWidth;
15531     } else if (NumPositiveBits <= IntWidth) {
15532       BestType = Context.UnsignedIntTy;
15533       BestWidth = IntWidth;
15534       BestPromotionType
15535         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15536                            ? Context.UnsignedIntTy : Context.IntTy;
15537     } else if (NumPositiveBits <=
15538                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15539       BestType = Context.UnsignedLongTy;
15540       BestPromotionType
15541         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15542                            ? Context.UnsignedLongTy : Context.LongTy;
15543     } else {
15544       BestWidth = Context.getTargetInfo().getLongLongWidth();
15545       assert(NumPositiveBits <= BestWidth &&
15546              "How could an initializer get larger than ULL?");
15547       BestType = Context.UnsignedLongLongTy;
15548       BestPromotionType
15549         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15550                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15551     }
15552   }
15553
15554   // Loop over all of the enumerator constants, changing their types to match
15555   // the type of the enum if needed.
15556   for (auto *D : Elements) {
15557     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15558     if (!ECD) continue;  // Already issued a diagnostic.
15559
15560     // Standard C says the enumerators have int type, but we allow, as an
15561     // extension, the enumerators to be larger than int size.  If each
15562     // enumerator value fits in an int, type it as an int, otherwise type it the
15563     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15564     // that X has type 'int', not 'unsigned'.
15565
15566     // Determine whether the value fits into an int.
15567     llvm::APSInt InitVal = ECD->getInitVal();
15568
15569     // If it fits into an integer type, force it.  Otherwise force it to match
15570     // the enum decl type.
15571     QualType NewTy;
15572     unsigned NewWidth;
15573     bool NewSign;
15574     if (!getLangOpts().CPlusPlus &&
15575         !Enum->isFixed() &&
15576         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15577       NewTy = Context.IntTy;
15578       NewWidth = IntWidth;
15579       NewSign = true;
15580     } else if (ECD->getType() == BestType) {
15581       // Already the right type!
15582       if (getLangOpts().CPlusPlus)
15583         // C++ [dcl.enum]p4: Following the closing brace of an
15584         // enum-specifier, each enumerator has the type of its
15585         // enumeration.
15586         ECD->setType(EnumType);
15587       continue;
15588     } else {
15589       NewTy = BestType;
15590       NewWidth = BestWidth;
15591       NewSign = BestType->isSignedIntegerOrEnumerationType();
15592     }
15593
15594     // Adjust the APSInt value.
15595     InitVal = InitVal.extOrTrunc(NewWidth);
15596     InitVal.setIsSigned(NewSign);
15597     ECD->setInitVal(InitVal);
15598
15599     // Adjust the Expr initializer and type.
15600     if (ECD->getInitExpr() &&
15601         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15602       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15603                                                 CK_IntegralCast,
15604                                                 ECD->getInitExpr(),
15605                                                 /*base paths*/ nullptr,
15606                                                 VK_RValue));
15607     if (getLangOpts().CPlusPlus)
15608       // C++ [dcl.enum]p4: Following the closing brace of an
15609       // enum-specifier, each enumerator has the type of its
15610       // enumeration.
15611       ECD->setType(EnumType);
15612     else
15613       ECD->setType(NewTy);
15614   }
15615
15616   Enum->completeDefinition(BestType, BestPromotionType,
15617                            NumPositiveBits, NumNegativeBits);
15618
15619   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15620
15621   if (Enum->isClosedFlag()) {
15622     for (Decl *D : Elements) {
15623       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15624       if (!ECD) continue;  // Already issued a diagnostic.
15625
15626       llvm::APSInt InitVal = ECD->getInitVal();
15627       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15628           !IsValueInFlagEnum(Enum, InitVal, true))
15629         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15630           << ECD << Enum;
15631     }
15632   }
15633
15634   // Now that the enum type is defined, ensure it's not been underaligned.
15635   if (Enum->hasAttrs())
15636     CheckAlignasUnderalignment(Enum);
15637 }
15638
15639 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15640                                   SourceLocation StartLoc,
15641                                   SourceLocation EndLoc) {
15642   StringLiteral *AsmString = cast<StringLiteral>(expr);
15643
15644   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15645                                                    AsmString, StartLoc,
15646                                                    EndLoc);
15647   CurContext->addDecl(New);
15648   return New;
15649 }
15650
15651 static void checkModuleImportContext(Sema &S, Module *M,
15652                                      SourceLocation ImportLoc, DeclContext *DC,
15653                                      bool FromInclude = false) {
15654   SourceLocation ExternCLoc;
15655
15656   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15657     switch (LSD->getLanguage()) {
15658     case LinkageSpecDecl::lang_c:
15659       if (ExternCLoc.isInvalid())
15660         ExternCLoc = LSD->getLocStart();
15661       break;
15662     case LinkageSpecDecl::lang_cxx:
15663       break;
15664     }
15665     DC = LSD->getParent();
15666   }
15667
15668   while (isa<LinkageSpecDecl>(DC))
15669     DC = DC->getParent();
15670
15671   if (!isa<TranslationUnitDecl>(DC)) {
15672     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15673                           ? diag::ext_module_import_not_at_top_level_noop
15674                           : diag::err_module_import_not_at_top_level_fatal)
15675         << M->getFullModuleName() << DC;
15676     S.Diag(cast<Decl>(DC)->getLocStart(),
15677            diag::note_module_import_not_at_top_level) << DC;
15678   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15679     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15680       << M->getFullModuleName();
15681     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
15682   }
15683 }
15684
15685 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc,
15686                                            ModuleDeclKind MDK,
15687                                            ModuleIdPath Path) {
15688   // 'module implementation' requires that we are not compiling a module of any
15689   // kind. 'module' and 'module partition' require that we are compiling a
15690   // module inteface (not a module map).
15691   auto CMK = getLangOpts().getCompilingModule();
15692   if (MDK == ModuleDeclKind::Implementation
15693           ? CMK != LangOptions::CMK_None
15694           : CMK != LangOptions::CMK_ModuleInterface) {
15695     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15696       << (unsigned)MDK;
15697     return nullptr;
15698   }
15699
15700   // FIXME: Create a ModuleDecl and return it.
15701
15702   // FIXME: Most of this work should be done by the preprocessor rather than
15703   // here, in case we look ahead across something where the current
15704   // module matters (eg a #include).
15705
15706   // The dots in a module name in the Modules TS are a lie. Unlike Clang's
15707   // hierarchical module map modules, the dots here are just another character
15708   // that can appear in a module name. Flatten down to the actual module name.
15709   std::string ModuleName;
15710   for (auto &Piece : Path) {
15711     if (!ModuleName.empty())
15712       ModuleName += ".";
15713     ModuleName += Piece.first->getName();
15714   }
15715
15716   // If a module name was explicitly specified on the command line, it must be
15717   // correct.
15718   if (!getLangOpts().CurrentModule.empty() &&
15719       getLangOpts().CurrentModule != ModuleName) {
15720     Diag(Path.front().second, diag::err_current_module_name_mismatch)
15721         << SourceRange(Path.front().second, Path.back().second)
15722         << getLangOpts().CurrentModule;
15723     return nullptr;
15724   }
15725   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15726
15727   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15728
15729   switch (MDK) {
15730   case ModuleDeclKind::Module: {
15731     // FIXME: Check we're not in a submodule.
15732
15733     // We can't have imported a definition of this module or parsed a module
15734     // map defining it already.
15735     if (auto *M = Map.findModule(ModuleName)) {
15736       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15737       if (M->DefinitionLoc.isValid())
15738         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15739       else if (const auto *FE = M->getASTFile())
15740         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15741             << FE->getName();
15742       return nullptr;
15743     }
15744
15745     // Create a Module for the module that we're defining.
15746     Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15747     assert(Mod && "module creation should not fail");
15748
15749     // Enter the semantic scope of the module.
15750     ActOnModuleBegin(ModuleLoc, Mod);
15751     return nullptr;
15752   }
15753
15754   case ModuleDeclKind::Partition:
15755     // FIXME: Check we are in a submodule of the named module.
15756     return nullptr;
15757
15758   case ModuleDeclKind::Implementation:
15759     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15760         PP.getIdentifierInfo(ModuleName), Path[0].second);
15761
15762     DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15763     if (Import.isInvalid())
15764       return nullptr;
15765     return ConvertDeclToDeclGroup(Import.get());
15766   }
15767
15768   llvm_unreachable("unexpected module decl kind");
15769 }
15770
15771 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15772                                    SourceLocation ImportLoc,
15773                                    ModuleIdPath Path) {
15774   Module *Mod =
15775       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15776                                    /*IsIncludeDirective=*/false);
15777   if (!Mod)
15778     return true;
15779
15780   VisibleModules.setVisible(Mod, ImportLoc);
15781
15782   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15783
15784   // FIXME: we should support importing a submodule within a different submodule
15785   // of the same top-level module. Until we do, make it an error rather than
15786   // silently ignoring the import.
15787   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
15788   // warn on a redundant import of the current module?
15789   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
15790       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
15791     Diag(ImportLoc, getLangOpts().isCompilingModule()
15792                         ? diag::err_module_self_import
15793                         : diag::err_module_import_in_implementation)
15794         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15795
15796   SmallVector<SourceLocation, 2> IdentifierLocs;
15797   Module *ModCheck = Mod;
15798   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15799     // If we've run out of module parents, just drop the remaining identifiers.
15800     // We need the length to be consistent.
15801     if (!ModCheck)
15802       break;
15803     ModCheck = ModCheck->Parent;
15804
15805     IdentifierLocs.push_back(Path[I].second);
15806   }
15807
15808   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15809   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
15810                                           Mod, IdentifierLocs);
15811   if (!ModuleScopes.empty())
15812     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
15813   TU->addDecl(Import);
15814   return Import;
15815 }
15816
15817 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15818   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15819   BuildModuleInclude(DirectiveLoc, Mod);
15820 }
15821
15822 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15823   // Determine whether we're in the #include buffer for a module. The #includes
15824   // in that buffer do not qualify as module imports; they're just an
15825   // implementation detail of us building the module.
15826   //
15827   // FIXME: Should we even get ActOnModuleInclude calls for those?
15828   bool IsInModuleIncludes =
15829       TUKind == TU_Module &&
15830       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15831
15832   bool ShouldAddImport = !IsInModuleIncludes;
15833
15834   // If this module import was due to an inclusion directive, create an
15835   // implicit import declaration to capture it in the AST.
15836   if (ShouldAddImport) {
15837     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15838     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15839                                                      DirectiveLoc, Mod,
15840                                                      DirectiveLoc);
15841     if (!ModuleScopes.empty())
15842       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
15843     TU->addDecl(ImportD);
15844     Consumer.HandleImplicitImportDecl(ImportD);
15845   }
15846
15847   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15848   VisibleModules.setVisible(Mod, DirectiveLoc);
15849 }
15850
15851 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15852   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15853
15854   ModuleScopes.push_back({});
15855   ModuleScopes.back().Module = Mod;
15856   if (getLangOpts().ModulesLocalVisibility)
15857     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
15858
15859   VisibleModules.setVisible(Mod, DirectiveLoc);
15860 }
15861
15862 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
15863   if (getLangOpts().ModulesLocalVisibility) {
15864     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
15865     // Leaving a module hides namespace names, so our visible namespace cache
15866     // is now out of date.
15867     VisibleNamespaceCache.clear();
15868   }
15869
15870   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
15871          "left the wrong module scope");
15872   ModuleScopes.pop_back();
15873
15874   // We got to the end of processing a #include of a local module. Create an
15875   // ImportDecl as we would for an imported module.
15876   FileID File = getSourceManager().getFileID(EofLoc);
15877   assert(File != getSourceManager().getMainFileID() &&
15878          "end of submodule in main source file");
15879   SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
15880   BuildModuleInclude(DirectiveLoc, Mod);
15881 }
15882
15883 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15884                                                       Module *Mod) {
15885   // Bail if we're not allowed to implicitly import a module here.
15886   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15887     return;
15888
15889   // Create the implicit import declaration.
15890   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15891   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15892                                                    Loc, Mod, Loc);
15893   TU->addDecl(ImportD);
15894   Consumer.HandleImplicitImportDecl(ImportD);
15895
15896   // Make the module visible.
15897   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15898   VisibleModules.setVisible(Mod, Loc);
15899 }
15900
15901 /// We have parsed the start of an export declaration, including the '{'
15902 /// (if present).
15903 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
15904                                  SourceLocation LBraceLoc) {
15905   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
15906
15907   // C++ Modules TS draft:
15908   //   An export-declaration [...] shall not contain more than one
15909   //   export keyword.
15910   //
15911   // The intent here is that an export-declaration cannot appear within another
15912   // export-declaration.
15913   if (D->isExported())
15914     Diag(ExportLoc, diag::err_export_within_export);
15915
15916   CurContext->addDecl(D);
15917   PushDeclContext(S, D);
15918   return D;
15919 }
15920
15921 /// Complete the definition of an export declaration.
15922 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
15923   auto *ED = cast<ExportDecl>(D);
15924   if (RBraceLoc.isValid())
15925     ED->setRBraceLoc(RBraceLoc);
15926
15927   // FIXME: Diagnose export of internal-linkage declaration (including
15928   // anonymous namespace).
15929
15930   PopDeclContext();
15931   return D;
15932 }
15933
15934 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15935                                       IdentifierInfo* AliasName,
15936                                       SourceLocation PragmaLoc,
15937                                       SourceLocation NameLoc,
15938                                       SourceLocation AliasNameLoc) {
15939   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15940                                          LookupOrdinaryName);
15941   AsmLabelAttr *Attr =
15942       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15943
15944   // If a declaration that:
15945   // 1) declares a function or a variable
15946   // 2) has external linkage
15947   // already exists, add a label attribute to it.
15948   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15949     if (isDeclExternC(PrevDecl))
15950       PrevDecl->addAttr(Attr);
15951     else
15952       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15953           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15954   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15955   } else
15956     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15957 }
15958
15959 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15960                              SourceLocation PragmaLoc,
15961                              SourceLocation NameLoc) {
15962   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15963
15964   if (PrevDecl) {
15965     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15966   } else {
15967     (void)WeakUndeclaredIdentifiers.insert(
15968       std::pair<IdentifierInfo*,WeakInfo>
15969         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15970   }
15971 }
15972
15973 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15974                                 IdentifierInfo* AliasName,
15975                                 SourceLocation PragmaLoc,
15976                                 SourceLocation NameLoc,
15977                                 SourceLocation AliasNameLoc) {
15978   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15979                                     LookupOrdinaryName);
15980   WeakInfo W = WeakInfo(Name, NameLoc);
15981
15982   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15983     if (!PrevDecl->hasAttr<AliasAttr>())
15984       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15985         DeclApplyPragmaWeak(TUScope, ND, W);
15986   } else {
15987     (void)WeakUndeclaredIdentifiers.insert(
15988       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15989   }
15990 }
15991
15992 Decl *Sema::getObjCDeclContext() const {
15993   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15994 }