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 "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Parse/ParseDiagnostic.h"
37 #include "clang/Sema/CXXFieldCollector.h"
38 #include "clang/Sema/DeclSpec.h"
39 #include "clang/Sema/DelayedDiagnostic.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
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         AllowClassTemplates(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 = AllowClassTemplates && isa<ClassTemplateDecl>(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 AllowClassTemplates;
90 };
91 
92 }
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_wchar_t:
112   case tok::kw_bool:
113   case tok::kw___underlying_type:
114     return true;
115 
116   case tok::annot_typename:
117   case tok::kw_char16_t:
118   case tok::kw_char32_t:
119   case tok::kw_typeof:
120   case tok::annot_decltype:
121   case tok::kw_decltype:
122     return getLangOpts().CPlusPlus;
123 
124   default:
125     break;
126   }
127 
128   return false;
129 }
130 
131 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
132                                                       const IdentifierInfo &II,
133                                                       SourceLocation NameLoc) {
134   // Find the first parent class template context, if any.
135   // FIXME: Perform the lookup in all enclosing class templates.
136   const CXXRecordDecl *RD = nullptr;
137   for (DeclContext *DC = S.CurContext; DC; DC = DC->getParent()) {
138     RD = dyn_cast<CXXRecordDecl>(DC);
139     if (RD && RD->getDescribedClassTemplate())
140       break;
141   }
142   if (!RD)
143     return ParsedType();
144 
145   // Look for type decls in dependent base classes that have known primary
146   // templates.
147   bool FoundTypeDecl = false;
148   for (const auto &Base : RD->bases()) {
149     auto *TST = Base.getType()->getAs<TemplateSpecializationType>();
150     if (!TST || !TST->isDependentType())
151       continue;
152     auto *TD = TST->getTemplateName().getAsTemplateDecl();
153     if (!TD)
154       continue;
155     auto *BasePrimaryTemplate =
156         dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
157     if (!BasePrimaryTemplate)
158       continue;
159     // FIXME: Allow lookup into non-dependent bases of dependent bases, possibly
160     // by calling or integrating with the main LookupQualifiedName mechanism.
161     for (NamedDecl *ND : BasePrimaryTemplate->lookup(&II)) {
162       if (FoundTypeDecl)
163         return ParsedType();
164       FoundTypeDecl = isa<TypeDecl>(ND);
165       if (!FoundTypeDecl)
166         return ParsedType();
167     }
168   }
169   if (!FoundTypeDecl)
170     return ParsedType();
171 
172   // We found some types in dependent base classes.  Recover as if the user
173   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
174   // lookup during template instantiation.
175   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
176 
177   ASTContext &Context = S.Context;
178   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
179                                           cast<Type>(Context.getRecordType(RD)));
180   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
181 
182   CXXScopeSpec SS;
183   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
184 
185   TypeLocBuilder Builder;
186   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
187   DepTL.setNameLoc(NameLoc);
188   DepTL.setElaboratedKeywordLoc(SourceLocation());
189   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
190   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
191 }
192 
193 /// \brief If the identifier refers to a type name within this scope,
194 /// return the declaration of that type.
195 ///
196 /// This routine performs ordinary name lookup of the identifier II
197 /// within the given scope, with optional C++ scope specifier SS, to
198 /// determine whether the name refers to a type. If so, returns an
199 /// opaque pointer (actually a QualType) corresponding to that
200 /// type. Otherwise, returns NULL.
201 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
202                              Scope *S, CXXScopeSpec *SS,
203                              bool isClassName, bool HasTrailingDot,
204                              ParsedType ObjectTypePtr,
205                              bool IsCtorOrDtorName,
206                              bool WantNontrivialTypeSourceInfo,
207                              IdentifierInfo **CorrectedII) {
208   // Determine where we will perform name lookup.
209   DeclContext *LookupCtx = nullptr;
210   if (ObjectTypePtr) {
211     QualType ObjectType = ObjectTypePtr.get();
212     if (ObjectType->isRecordType())
213       LookupCtx = computeDeclContext(ObjectType);
214   } else if (SS && SS->isNotEmpty()) {
215     LookupCtx = computeDeclContext(*SS, false);
216 
217     if (!LookupCtx) {
218       if (isDependentScopeSpecifier(*SS)) {
219         // C++ [temp.res]p3:
220         //   A qualified-id that refers to a type and in which the
221         //   nested-name-specifier depends on a template-parameter (14.6.2)
222         //   shall be prefixed by the keyword typename to indicate that the
223         //   qualified-id denotes a type, forming an
224         //   elaborated-type-specifier (7.1.5.3).
225         //
226         // We therefore do not perform any name lookup if the result would
227         // refer to a member of an unknown specialization.
228         if (!isClassName && !IsCtorOrDtorName)
229           return ParsedType();
230 
231         // We know from the grammar that this name refers to a type,
232         // so build a dependent node to describe the type.
233         if (WantNontrivialTypeSourceInfo)
234           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
235 
236         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
237         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
238                                        II, NameLoc);
239         return ParsedType::make(T);
240       }
241 
242       return ParsedType();
243     }
244 
245     if (!LookupCtx->isDependentContext() &&
246         RequireCompleteDeclContext(*SS, LookupCtx))
247       return ParsedType();
248   }
249 
250   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
251   // lookup for class-names.
252   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
253                                       LookupOrdinaryName;
254   LookupResult Result(*this, &II, NameLoc, Kind);
255   if (LookupCtx) {
256     // Perform "qualified" name lookup into the declaration context we
257     // computed, which is either the type of the base of a member access
258     // expression or the declaration context associated with a prior
259     // nested-name-specifier.
260     LookupQualifiedName(Result, LookupCtx);
261 
262     if (ObjectTypePtr && Result.empty()) {
263       // C++ [basic.lookup.classref]p3:
264       //   If the unqualified-id is ~type-name, the type-name is looked up
265       //   in the context of the entire postfix-expression. If the type T of
266       //   the object expression is of a class type C, the type-name is also
267       //   looked up in the scope of class C. At least one of the lookups shall
268       //   find a name that refers to (possibly cv-qualified) T.
269       LookupName(Result, S);
270     }
271   } else {
272     // Perform unqualified name lookup.
273     LookupName(Result, S);
274 
275     // For unqualified lookup in a class template in MSVC mode, look into
276     // dependent base classes where the primary class template is known.
277     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
278       if (ParsedType TypeInBase =
279               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
280         return TypeInBase;
281     }
282   }
283 
284   NamedDecl *IIDecl = nullptr;
285   switch (Result.getResultKind()) {
286   case LookupResult::NotFound:
287   case LookupResult::NotFoundInCurrentInstantiation:
288     if (CorrectedII) {
289       TypoCorrection Correction = CorrectTypo(
290           Result.getLookupNameInfo(), Kind, S, SS,
291           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
292           CTK_ErrorRecovery);
293       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
294       TemplateTy Template;
295       bool MemberOfUnknownSpecialization;
296       UnqualifiedId TemplateName;
297       TemplateName.setIdentifier(NewII, NameLoc);
298       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
299       CXXScopeSpec NewSS, *NewSSPtr = SS;
300       if (SS && NNS) {
301         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
302         NewSSPtr = &NewSS;
303       }
304       if (Correction && (NNS || NewII != &II) &&
305           // Ignore a correction to a template type as the to-be-corrected
306           // identifier is not a template (typo correction for template names
307           // is handled elsewhere).
308           !(getLangOpts().CPlusPlus && NewSSPtr &&
309             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
310                            false, Template, MemberOfUnknownSpecialization))) {
311         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
312                                     isClassName, HasTrailingDot, ObjectTypePtr,
313                                     IsCtorOrDtorName,
314                                     WantNontrivialTypeSourceInfo);
315         if (Ty) {
316           diagnoseTypo(Correction,
317                        PDiag(diag::err_unknown_type_or_class_name_suggest)
318                          << Result.getLookupName() << isClassName);
319           if (SS && NNS)
320             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
321           *CorrectedII = NewII;
322           return Ty;
323         }
324       }
325     }
326     // If typo correction failed or was not performed, fall through
327   case LookupResult::FoundOverloaded:
328   case LookupResult::FoundUnresolvedValue:
329     Result.suppressDiagnostics();
330     return ParsedType();
331 
332   case LookupResult::Ambiguous:
333     // Recover from type-hiding ambiguities by hiding the type.  We'll
334     // do the lookup again when looking for an object, and we can
335     // diagnose the error then.  If we don't do this, then the error
336     // about hiding the type will be immediately followed by an error
337     // that only makes sense if the identifier was treated like a type.
338     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
339       Result.suppressDiagnostics();
340       return ParsedType();
341     }
342 
343     // Look to see if we have a type anywhere in the list of results.
344     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
345          Res != ResEnd; ++Res) {
346       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
347         if (!IIDecl ||
348             (*Res)->getLocation().getRawEncoding() <
349               IIDecl->getLocation().getRawEncoding())
350           IIDecl = *Res;
351       }
352     }
353 
354     if (!IIDecl) {
355       // None of the entities we found is a type, so there is no way
356       // to even assume that the result is a type. In this case, don't
357       // complain about the ambiguity. The parser will either try to
358       // perform this lookup again (e.g., as an object name), which
359       // will produce the ambiguity, or will complain that it expected
360       // a type name.
361       Result.suppressDiagnostics();
362       return ParsedType();
363     }
364 
365     // We found a type within the ambiguous lookup; diagnose the
366     // ambiguity and then return that type. This might be the right
367     // answer, or it might not be, but it suppresses any attempt to
368     // perform the name lookup again.
369     break;
370 
371   case LookupResult::Found:
372     IIDecl = Result.getFoundDecl();
373     break;
374   }
375 
376   assert(IIDecl && "Didn't find decl");
377 
378   QualType T;
379   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
380     DiagnoseUseOfDecl(IIDecl, NameLoc);
381 
382     T = Context.getTypeDeclType(TD);
383     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
384 
385     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
386     // constructor or destructor name (in such a case, the scope specifier
387     // will be attached to the enclosing Expr or Decl node).
388     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
389       if (WantNontrivialTypeSourceInfo) {
390         // Construct a type with type-source information.
391         TypeLocBuilder Builder;
392         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
393 
394         T = getElaboratedType(ETK_None, *SS, T);
395         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
396         ElabTL.setElaboratedKeywordLoc(SourceLocation());
397         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
398         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
399       } else {
400         T = getElaboratedType(ETK_None, *SS, T);
401       }
402     }
403   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
404     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
405     if (!HasTrailingDot)
406       T = Context.getObjCInterfaceType(IDecl);
407   }
408 
409   if (T.isNull()) {
410     // If it's not plausibly a type, suppress diagnostics.
411     Result.suppressDiagnostics();
412     return ParsedType();
413   }
414   return ParsedType::make(T);
415 }
416 
417 // Builds a fake NNS for the given decl context.
418 static NestedNameSpecifier *
419 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
420   for (;; DC = DC->getLookupParent()) {
421     DC = DC->getPrimaryContext();
422     auto *ND = dyn_cast<NamespaceDecl>(DC);
423     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
424       return NestedNameSpecifier::Create(Context, nullptr, ND);
425     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
426       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
427                                          RD->getTypeForDecl());
428     else if (isa<TranslationUnitDecl>(DC))
429       return NestedNameSpecifier::GlobalSpecifier(Context);
430   }
431   llvm_unreachable("something isn't in TU scope?");
432 }
433 
434 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
435                                                 SourceLocation NameLoc) {
436   // Accepting an undeclared identifier as a default argument for a template
437   // type parameter is a Microsoft extension.
438   Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
439 
440   // Build a fake DependentNameType that will perform lookup into CurContext at
441   // instantiation time.  The name specifier isn't dependent, so template
442   // instantiation won't transform it.  It will retry the lookup, however.
443   NestedNameSpecifier *NNS =
444       synthesizeCurrentNestedNameSpecifier(Context, CurContext);
445   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
446 
447   // Build type location information.  We synthesized the qualifier, so we have
448   // to build a fake NestedNameSpecifierLoc.
449   NestedNameSpecifierLocBuilder NNSLocBuilder;
450   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
451   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
452 
453   TypeLocBuilder Builder;
454   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
455   DepTL.setNameLoc(NameLoc);
456   DepTL.setElaboratedKeywordLoc(SourceLocation());
457   DepTL.setQualifierLoc(QualifierLoc);
458   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
459 }
460 
461 /// isTagName() - This method is called *for error recovery purposes only*
462 /// to determine if the specified name is a valid tag name ("struct foo").  If
463 /// so, this returns the TST for the tag corresponding to it (TST_enum,
464 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
465 /// cases in C where the user forgot to specify the tag.
466 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
467   // Do a tag name lookup in this scope.
468   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
469   LookupName(R, S, false);
470   R.suppressDiagnostics();
471   if (R.getResultKind() == LookupResult::Found)
472     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
473       switch (TD->getTagKind()) {
474       case TTK_Struct: return DeclSpec::TST_struct;
475       case TTK_Interface: return DeclSpec::TST_interface;
476       case TTK_Union:  return DeclSpec::TST_union;
477       case TTK_Class:  return DeclSpec::TST_class;
478       case TTK_Enum:   return DeclSpec::TST_enum;
479       }
480     }
481 
482   return DeclSpec::TST_unspecified;
483 }
484 
485 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
486 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
487 /// then downgrade the missing typename error to a warning.
488 /// This is needed for MSVC compatibility; Example:
489 /// @code
490 /// template<class T> class A {
491 /// public:
492 ///   typedef int TYPE;
493 /// };
494 /// template<class T> class B : public A<T> {
495 /// public:
496 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
497 /// };
498 /// @endcode
499 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
500   if (CurContext->isRecord()) {
501     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
502       return true;
503 
504     const Type *Ty = SS->getScopeRep()->getAsType();
505 
506     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
507     for (const auto &Base : RD->bases())
508       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
509         return true;
510     return S->isFunctionPrototypeScope();
511   }
512   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
513 }
514 
515 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
516                                    SourceLocation IILoc,
517                                    Scope *S,
518                                    CXXScopeSpec *SS,
519                                    ParsedType &SuggestedType,
520                                    bool AllowClassTemplates) {
521   // We don't have anything to suggest (yet).
522   SuggestedType = ParsedType();
523 
524   // There may have been a typo in the name of the type. Look up typo
525   // results, in case we have something that we can suggest.
526   if (TypoCorrection Corrected =
527           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
528                       llvm::make_unique<TypeNameValidatorCCC>(
529                           false, false, AllowClassTemplates),
530                       CTK_ErrorRecovery)) {
531     if (Corrected.isKeyword()) {
532       // We corrected to a keyword.
533       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
534       II = Corrected.getCorrectionAsIdentifierInfo();
535     } else {
536       // We found a similarly-named type or interface; suggest that.
537       if (!SS || !SS->isSet()) {
538         diagnoseTypo(Corrected,
539                      PDiag(diag::err_unknown_typename_suggest) << II);
540       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
541         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
542         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
543                                 II->getName().equals(CorrectedStr);
544         diagnoseTypo(Corrected,
545                      PDiag(diag::err_unknown_nested_typename_suggest)
546                        << II << DC << DroppedSpecifier << SS->getRange());
547       } else {
548         llvm_unreachable("could not have corrected a typo here");
549       }
550 
551       CXXScopeSpec tmpSS;
552       if (Corrected.getCorrectionSpecifier())
553         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
554                           SourceRange(IILoc));
555       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
556                                   IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
557                                   false, ParsedType(),
558                                   /*IsCtorOrDtorName=*/false,
559                                   /*NonTrivialTypeSourceInfo=*/true);
560     }
561     return;
562   }
563 
564   if (getLangOpts().CPlusPlus) {
565     // See if II is a class template that the user forgot to pass arguments to.
566     UnqualifiedId Name;
567     Name.setIdentifier(II, IILoc);
568     CXXScopeSpec EmptySS;
569     TemplateTy TemplateResult;
570     bool MemberOfUnknownSpecialization;
571     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
572                        Name, ParsedType(), true, TemplateResult,
573                        MemberOfUnknownSpecialization) == TNK_Type_template) {
574       TemplateName TplName = TemplateResult.get();
575       Diag(IILoc, diag::err_template_missing_args) << TplName;
576       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
577         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
578           << TplDecl->getTemplateParameters()->getSourceRange();
579       }
580       return;
581     }
582   }
583 
584   // FIXME: Should we move the logic that tries to recover from a missing tag
585   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
586 
587   if (!SS || (!SS->isSet() && !SS->isInvalid()))
588     Diag(IILoc, diag::err_unknown_typename) << II;
589   else if (DeclContext *DC = computeDeclContext(*SS, false))
590     Diag(IILoc, diag::err_typename_nested_not_found)
591       << II << DC << SS->getRange();
592   else if (isDependentScopeSpecifier(*SS)) {
593     unsigned DiagID = diag::err_typename_missing;
594     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
595       DiagID = diag::ext_typename_missing;
596 
597     Diag(SS->getRange().getBegin(), DiagID)
598       << SS->getScopeRep() << II->getName()
599       << SourceRange(SS->getRange().getBegin(), IILoc)
600       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
601     SuggestedType = ActOnTypenameType(S, SourceLocation(),
602                                       *SS, *II, IILoc).get();
603   } else {
604     assert(SS && SS->isInvalid() &&
605            "Invalid scope specifier has already been diagnosed");
606   }
607 }
608 
609 /// \brief Determine whether the given result set contains either a type name
610 /// or
611 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
612   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
613                        NextToken.is(tok::less);
614 
615   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
616     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
617       return true;
618 
619     if (CheckTemplate && isa<TemplateDecl>(*I))
620       return true;
621   }
622 
623   return false;
624 }
625 
626 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
627                                     Scope *S, CXXScopeSpec &SS,
628                                     IdentifierInfo *&Name,
629                                     SourceLocation NameLoc) {
630   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
631   SemaRef.LookupParsedName(R, S, &SS);
632   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
633     StringRef FixItTagName;
634     switch (Tag->getTagKind()) {
635       case TTK_Class:
636         FixItTagName = "class ";
637         break;
638 
639       case TTK_Enum:
640         FixItTagName = "enum ";
641         break;
642 
643       case TTK_Struct:
644         FixItTagName = "struct ";
645         break;
646 
647       case TTK_Interface:
648         FixItTagName = "__interface ";
649         break;
650 
651       case TTK_Union:
652         FixItTagName = "union ";
653         break;
654     }
655 
656     StringRef TagName = FixItTagName.drop_back();
657     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
658       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
659       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
660 
661     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
662          I != IEnd; ++I)
663       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
664         << Name << TagName;
665 
666     // Replace lookup results with just the tag decl.
667     Result.clear(Sema::LookupTagName);
668     SemaRef.LookupParsedName(Result, S, &SS);
669     return true;
670   }
671 
672   return false;
673 }
674 
675 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
676 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
677                                   QualType T, SourceLocation NameLoc) {
678   ASTContext &Context = S.Context;
679 
680   TypeLocBuilder Builder;
681   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
682 
683   T = S.getElaboratedType(ETK_None, SS, T);
684   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
685   ElabTL.setElaboratedKeywordLoc(SourceLocation());
686   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
687   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
688 }
689 
690 Sema::NameClassification
691 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
692                    SourceLocation NameLoc, const Token &NextToken,
693                    bool IsAddressOfOperand,
694                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
695   DeclarationNameInfo NameInfo(Name, NameLoc);
696   ObjCMethodDecl *CurMethod = getCurMethodDecl();
697 
698   if (NextToken.is(tok::coloncolon)) {
699     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
700                                 QualType(), false, SS, nullptr, false);
701   }
702 
703   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
704   LookupParsedName(Result, S, &SS, !CurMethod);
705 
706   // For unqualified lookup in a class template in MSVC mode, look into
707   // dependent base classes where the primary class template is known.
708   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
709     if (ParsedType TypeInBase =
710             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
711       return TypeInBase;
712   }
713 
714   // Perform lookup for Objective-C instance variables (including automatically
715   // synthesized instance variables), if we're in an Objective-C method.
716   // FIXME: This lookup really, really needs to be folded in to the normal
717   // unqualified lookup mechanism.
718   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
719     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
720     if (E.get() || E.isInvalid())
721       return E;
722   }
723 
724   bool SecondTry = false;
725   bool IsFilteredTemplateName = false;
726 
727 Corrected:
728   switch (Result.getResultKind()) {
729   case LookupResult::NotFound:
730     // If an unqualified-id is followed by a '(', then we have a function
731     // call.
732     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
733       // In C++, this is an ADL-only call.
734       // FIXME: Reference?
735       if (getLangOpts().CPlusPlus)
736         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
737 
738       // C90 6.3.2.2:
739       //   If the expression that precedes the parenthesized argument list in a
740       //   function call consists solely of an identifier, and if no
741       //   declaration is visible for this identifier, the identifier is
742       //   implicitly declared exactly as if, in the innermost block containing
743       //   the function call, the declaration
744       //
745       //     extern int identifier ();
746       //
747       //   appeared.
748       //
749       // We also allow this in C99 as an extension.
750       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
751         Result.addDecl(D);
752         Result.resolveKind();
753         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
754       }
755     }
756 
757     // In C, we first see whether there is a tag type by the same name, in
758     // which case it's likely that the user just forget to write "enum",
759     // "struct", or "union".
760     if (!getLangOpts().CPlusPlus && !SecondTry &&
761         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
762       break;
763     }
764 
765     // Perform typo correction to determine if there is another name that is
766     // close to this name.
767     if (!SecondTry && CCC) {
768       SecondTry = true;
769       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
770                                                  Result.getLookupKind(), S,
771                                                  &SS, std::move(CCC),
772                                                  CTK_ErrorRecovery)) {
773         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
774         unsigned QualifiedDiag = diag::err_no_member_suggest;
775 
776         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
777         NamedDecl *UnderlyingFirstDecl
778           = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
779         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
780             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
781           UnqualifiedDiag = diag::err_no_template_suggest;
782           QualifiedDiag = diag::err_no_member_template_suggest;
783         } else if (UnderlyingFirstDecl &&
784                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
785                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
786                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
787           UnqualifiedDiag = diag::err_unknown_typename_suggest;
788           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
789         }
790 
791         if (SS.isEmpty()) {
792           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
793         } else {// FIXME: is this even reachable? Test it.
794           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
795           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
796                                   Name->getName().equals(CorrectedStr);
797           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
798                                     << Name << computeDeclContext(SS, false)
799                                     << DroppedSpecifier << SS.getRange());
800         }
801 
802         // Update the name, so that the caller has the new name.
803         Name = Corrected.getCorrectionAsIdentifierInfo();
804 
805         // Typo correction corrected to a keyword.
806         if (Corrected.isKeyword())
807           return Name;
808 
809         // Also update the LookupResult...
810         // FIXME: This should probably go away at some point
811         Result.clear();
812         Result.setLookupName(Corrected.getCorrection());
813         if (FirstDecl)
814           Result.addDecl(FirstDecl);
815 
816         // If we found an Objective-C instance variable, let
817         // LookupInObjCMethod build the appropriate expression to
818         // reference the ivar.
819         // FIXME: This is a gross hack.
820         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
821           Result.clear();
822           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
823           return E;
824         }
825 
826         goto Corrected;
827       }
828     }
829 
830     // We failed to correct; just fall through and let the parser deal with it.
831     Result.suppressDiagnostics();
832     return NameClassification::Unknown();
833 
834   case LookupResult::NotFoundInCurrentInstantiation: {
835     // We performed name lookup into the current instantiation, and there were
836     // dependent bases, so we treat this result the same way as any other
837     // dependent nested-name-specifier.
838 
839     // C++ [temp.res]p2:
840     //   A name used in a template declaration or definition and that is
841     //   dependent on a template-parameter is assumed not to name a type
842     //   unless the applicable name lookup finds a type name or the name is
843     //   qualified by the keyword typename.
844     //
845     // FIXME: If the next token is '<', we might want to ask the parser to
846     // perform some heroics to see if we actually have a
847     // template-argument-list, which would indicate a missing 'template'
848     // keyword here.
849     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
850                                       NameInfo, IsAddressOfOperand,
851                                       /*TemplateArgs=*/nullptr);
852   }
853 
854   case LookupResult::Found:
855   case LookupResult::FoundOverloaded:
856   case LookupResult::FoundUnresolvedValue:
857     break;
858 
859   case LookupResult::Ambiguous:
860     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
861         hasAnyAcceptableTemplateNames(Result)) {
862       // C++ [temp.local]p3:
863       //   A lookup that finds an injected-class-name (10.2) can result in an
864       //   ambiguity in certain cases (for example, if it is found in more than
865       //   one base class). If all of the injected-class-names that are found
866       //   refer to specializations of the same class template, and if the name
867       //   is followed by a template-argument-list, the reference refers to the
868       //   class template itself and not a specialization thereof, and is not
869       //   ambiguous.
870       //
871       // This filtering can make an ambiguous result into an unambiguous one,
872       // so try again after filtering out template names.
873       FilterAcceptableTemplateNames(Result);
874       if (!Result.isAmbiguous()) {
875         IsFilteredTemplateName = true;
876         break;
877       }
878     }
879 
880     // Diagnose the ambiguity and return an error.
881     return NameClassification::Error();
882   }
883 
884   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
885       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
886     // C++ [temp.names]p3:
887     //   After name lookup (3.4) finds that a name is a template-name or that
888     //   an operator-function-id or a literal- operator-id refers to a set of
889     //   overloaded functions any member of which is a function template if
890     //   this is followed by a <, the < is always taken as the delimiter of a
891     //   template-argument-list and never as the less-than operator.
892     if (!IsFilteredTemplateName)
893       FilterAcceptableTemplateNames(Result);
894 
895     if (!Result.empty()) {
896       bool IsFunctionTemplate;
897       bool IsVarTemplate;
898       TemplateName Template;
899       if (Result.end() - Result.begin() > 1) {
900         IsFunctionTemplate = true;
901         Template = Context.getOverloadedTemplateName(Result.begin(),
902                                                      Result.end());
903       } else {
904         TemplateDecl *TD
905           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
906         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
907         IsVarTemplate = isa<VarTemplateDecl>(TD);
908 
909         if (SS.isSet() && !SS.isInvalid())
910           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
911                                                     /*TemplateKeyword=*/false,
912                                                       TD);
913         else
914           Template = TemplateName(TD);
915       }
916 
917       if (IsFunctionTemplate) {
918         // Function templates always go through overload resolution, at which
919         // point we'll perform the various checks (e.g., accessibility) we need
920         // to based on which function we selected.
921         Result.suppressDiagnostics();
922 
923         return NameClassification::FunctionTemplate(Template);
924       }
925 
926       return IsVarTemplate ? NameClassification::VarTemplate(Template)
927                            : NameClassification::TypeTemplate(Template);
928     }
929   }
930 
931   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
932   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
933     DiagnoseUseOfDecl(Type, NameLoc);
934     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
935     QualType T = Context.getTypeDeclType(Type);
936     if (SS.isNotEmpty())
937       return buildNestedType(*this, SS, T, NameLoc);
938     return ParsedType::make(T);
939   }
940 
941   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
942   if (!Class) {
943     // FIXME: It's unfortunate that we don't have a Type node for handling this.
944     if (ObjCCompatibleAliasDecl *Alias =
945             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
946       Class = Alias->getClassInterface();
947   }
948 
949   if (Class) {
950     DiagnoseUseOfDecl(Class, NameLoc);
951 
952     if (NextToken.is(tok::period)) {
953       // Interface. <something> is parsed as a property reference expression.
954       // Just return "unknown" as a fall-through for now.
955       Result.suppressDiagnostics();
956       return NameClassification::Unknown();
957     }
958 
959     QualType T = Context.getObjCInterfaceType(Class);
960     return ParsedType::make(T);
961   }
962 
963   // We can have a type template here if we're classifying a template argument.
964   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
965     return NameClassification::TypeTemplate(
966         TemplateName(cast<TemplateDecl>(FirstDecl)));
967 
968   // Check for a tag type hidden by a non-type decl in a few cases where it
969   // seems likely a type is wanted instead of the non-type that was found.
970   bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
971   if ((NextToken.is(tok::identifier) ||
972        (NextIsOp &&
973         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
974       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
975     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
976     DiagnoseUseOfDecl(Type, NameLoc);
977     QualType T = Context.getTypeDeclType(Type);
978     if (SS.isNotEmpty())
979       return buildNestedType(*this, SS, T, NameLoc);
980     return ParsedType::make(T);
981   }
982 
983   if (FirstDecl->isCXXClassMember())
984     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
985                                            nullptr);
986 
987   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
988   return BuildDeclarationNameExpr(SS, Result, ADL);
989 }
990 
991 // Determines the context to return to after temporarily entering a
992 // context.  This depends in an unnecessarily complicated way on the
993 // exact ordering of callbacks from the parser.
994 DeclContext *Sema::getContainingDC(DeclContext *DC) {
995 
996   // Functions defined inline within classes aren't parsed until we've
997   // finished parsing the top-level class, so the top-level class is
998   // the context we'll need to return to.
999   // A Lambda call operator whose parent is a class must not be treated
1000   // as an inline member function.  A Lambda can be used legally
1001   // either as an in-class member initializer or a default argument.  These
1002   // are parsed once the class has been marked complete and so the containing
1003   // context would be the nested class (when the lambda is defined in one);
1004   // If the class is not complete, then the lambda is being used in an
1005   // ill-formed fashion (such as to specify the width of a bit-field, or
1006   // in an array-bound) - in which case we still want to return the
1007   // lexically containing DC (which could be a nested class).
1008   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1009     DC = DC->getLexicalParent();
1010 
1011     // A function not defined within a class will always return to its
1012     // lexical context.
1013     if (!isa<CXXRecordDecl>(DC))
1014       return DC;
1015 
1016     // A C++ inline method/friend is parsed *after* the topmost class
1017     // it was declared in is fully parsed ("complete");  the topmost
1018     // class is the context we need to return to.
1019     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1020       DC = RD;
1021 
1022     // Return the declaration context of the topmost class the inline method is
1023     // declared in.
1024     return DC;
1025   }
1026 
1027   return DC->getLexicalParent();
1028 }
1029 
1030 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1031   assert(getContainingDC(DC) == CurContext &&
1032       "The next DeclContext should be lexically contained in the current one.");
1033   CurContext = DC;
1034   S->setEntity(DC);
1035 }
1036 
1037 void Sema::PopDeclContext() {
1038   assert(CurContext && "DeclContext imbalance!");
1039 
1040   CurContext = getContainingDC(CurContext);
1041   assert(CurContext && "Popped translation unit!");
1042 }
1043 
1044 /// EnterDeclaratorContext - Used when we must lookup names in the context
1045 /// of a declarator's nested name specifier.
1046 ///
1047 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1048   // C++0x [basic.lookup.unqual]p13:
1049   //   A name used in the definition of a static data member of class
1050   //   X (after the qualified-id of the static member) is looked up as
1051   //   if the name was used in a member function of X.
1052   // C++0x [basic.lookup.unqual]p14:
1053   //   If a variable member of a namespace is defined outside of the
1054   //   scope of its namespace then any name used in the definition of
1055   //   the variable member (after the declarator-id) is looked up as
1056   //   if the definition of the variable member occurred in its
1057   //   namespace.
1058   // Both of these imply that we should push a scope whose context
1059   // is the semantic context of the declaration.  We can't use
1060   // PushDeclContext here because that context is not necessarily
1061   // lexically contained in the current context.  Fortunately,
1062   // the containing scope should have the appropriate information.
1063 
1064   assert(!S->getEntity() && "scope already has entity");
1065 
1066 #ifndef NDEBUG
1067   Scope *Ancestor = S->getParent();
1068   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1069   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1070 #endif
1071 
1072   CurContext = DC;
1073   S->setEntity(DC);
1074 }
1075 
1076 void Sema::ExitDeclaratorContext(Scope *S) {
1077   assert(S->getEntity() == CurContext && "Context imbalance!");
1078 
1079   // Switch back to the lexical context.  The safety of this is
1080   // enforced by an assert in EnterDeclaratorContext.
1081   Scope *Ancestor = S->getParent();
1082   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1083   CurContext = Ancestor->getEntity();
1084 
1085   // We don't need to do anything with the scope, which is going to
1086   // disappear.
1087 }
1088 
1089 
1090 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1091   // We assume that the caller has already called
1092   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1093   FunctionDecl *FD = D->getAsFunction();
1094   if (!FD)
1095     return;
1096 
1097   // Same implementation as PushDeclContext, but enters the context
1098   // from the lexical parent, rather than the top-level class.
1099   assert(CurContext == FD->getLexicalParent() &&
1100     "The next DeclContext should be lexically contained in the current one.");
1101   CurContext = FD;
1102   S->setEntity(CurContext);
1103 
1104   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1105     ParmVarDecl *Param = FD->getParamDecl(P);
1106     // If the parameter has an identifier, then add it to the scope
1107     if (Param->getIdentifier()) {
1108       S->AddDecl(Param);
1109       IdResolver.AddDecl(Param);
1110     }
1111   }
1112 }
1113 
1114 
1115 void Sema::ActOnExitFunctionContext() {
1116   // Same implementation as PopDeclContext, but returns to the lexical parent,
1117   // rather than the top-level class.
1118   assert(CurContext && "DeclContext imbalance!");
1119   CurContext = CurContext->getLexicalParent();
1120   assert(CurContext && "Popped translation unit!");
1121 }
1122 
1123 
1124 /// \brief Determine whether we allow overloading of the function
1125 /// PrevDecl with another declaration.
1126 ///
1127 /// This routine determines whether overloading is possible, not
1128 /// whether some new function is actually an overload. It will return
1129 /// true in C++ (where we can always provide overloads) or, as an
1130 /// extension, in C when the previous function is already an
1131 /// overloaded function declaration or has the "overloadable"
1132 /// attribute.
1133 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1134                                        ASTContext &Context) {
1135   if (Context.getLangOpts().CPlusPlus)
1136     return true;
1137 
1138   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1139     return true;
1140 
1141   return (Previous.getResultKind() == LookupResult::Found
1142           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1143 }
1144 
1145 /// Add this decl to the scope shadowed decl chains.
1146 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1147   // Move up the scope chain until we find the nearest enclosing
1148   // non-transparent context. The declaration will be introduced into this
1149   // scope.
1150   while (S->getEntity() && S->getEntity()->isTransparentContext())
1151     S = S->getParent();
1152 
1153   // Add scoped declarations into their context, so that they can be
1154   // found later. Declarations without a context won't be inserted
1155   // into any context.
1156   if (AddToContext)
1157     CurContext->addDecl(D);
1158 
1159   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1160   // are function-local declarations.
1161   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1162       !D->getDeclContext()->getRedeclContext()->Equals(
1163         D->getLexicalDeclContext()->getRedeclContext()) &&
1164       !D->getLexicalDeclContext()->isFunctionOrMethod())
1165     return;
1166 
1167   // Template instantiations should also not be pushed into scope.
1168   if (isa<FunctionDecl>(D) &&
1169       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1170     return;
1171 
1172   // If this replaces anything in the current scope,
1173   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1174                                IEnd = IdResolver.end();
1175   for (; I != IEnd; ++I) {
1176     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1177       S->RemoveDecl(*I);
1178       IdResolver.RemoveDecl(*I);
1179 
1180       // Should only need to replace one decl.
1181       break;
1182     }
1183   }
1184 
1185   S->AddDecl(D);
1186 
1187   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1188     // Implicitly-generated labels may end up getting generated in an order that
1189     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1190     // the label at the appropriate place in the identifier chain.
1191     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1192       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1193       if (IDC == CurContext) {
1194         if (!S->isDeclScope(*I))
1195           continue;
1196       } else if (IDC->Encloses(CurContext))
1197         break;
1198     }
1199 
1200     IdResolver.InsertDeclAfter(I, D);
1201   } else {
1202     IdResolver.AddDecl(D);
1203   }
1204 }
1205 
1206 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1207   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1208     TUScope->AddDecl(D);
1209 }
1210 
1211 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1212                          bool AllowInlineNamespace) {
1213   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1214 }
1215 
1216 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1217   DeclContext *TargetDC = DC->getPrimaryContext();
1218   do {
1219     if (DeclContext *ScopeDC = S->getEntity())
1220       if (ScopeDC->getPrimaryContext() == TargetDC)
1221         return S;
1222   } while ((S = S->getParent()));
1223 
1224   return nullptr;
1225 }
1226 
1227 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1228                                             DeclContext*,
1229                                             ASTContext&);
1230 
1231 /// Filters out lookup results that don't fall within the given scope
1232 /// as determined by isDeclInScope.
1233 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1234                                 bool ConsiderLinkage,
1235                                 bool AllowInlineNamespace) {
1236   LookupResult::Filter F = R.makeFilter();
1237   while (F.hasNext()) {
1238     NamedDecl *D = F.next();
1239 
1240     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1241       continue;
1242 
1243     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1244       continue;
1245 
1246     F.erase();
1247   }
1248 
1249   F.done();
1250 }
1251 
1252 static bool isUsingDecl(NamedDecl *D) {
1253   return isa<UsingShadowDecl>(D) ||
1254          isa<UnresolvedUsingTypenameDecl>(D) ||
1255          isa<UnresolvedUsingValueDecl>(D);
1256 }
1257 
1258 /// Removes using shadow declarations from the lookup results.
1259 static void RemoveUsingDecls(LookupResult &R) {
1260   LookupResult::Filter F = R.makeFilter();
1261   while (F.hasNext())
1262     if (isUsingDecl(F.next()))
1263       F.erase();
1264 
1265   F.done();
1266 }
1267 
1268 /// \brief Check for this common pattern:
1269 /// @code
1270 /// class S {
1271 ///   S(const S&); // DO NOT IMPLEMENT
1272 ///   void operator=(const S&); // DO NOT IMPLEMENT
1273 /// };
1274 /// @endcode
1275 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1276   // FIXME: Should check for private access too but access is set after we get
1277   // the decl here.
1278   if (D->doesThisDeclarationHaveABody())
1279     return false;
1280 
1281   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1282     return CD->isCopyConstructor();
1283   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1284     return Method->isCopyAssignmentOperator();
1285   return false;
1286 }
1287 
1288 // We need this to handle
1289 //
1290 // typedef struct {
1291 //   void *foo() { return 0; }
1292 // } A;
1293 //
1294 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1295 // for example. If 'A', foo will have external linkage. If we have '*A',
1296 // foo will have no linkage. Since we can't know until we get to the end
1297 // of the typedef, this function finds out if D might have non-external linkage.
1298 // Callers should verify at the end of the TU if it D has external linkage or
1299 // not.
1300 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1301   const DeclContext *DC = D->getDeclContext();
1302   while (!DC->isTranslationUnit()) {
1303     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1304       if (!RD->hasNameForLinkage())
1305         return true;
1306     }
1307     DC = DC->getParent();
1308   }
1309 
1310   return !D->isExternallyVisible();
1311 }
1312 
1313 // FIXME: This needs to be refactored; some other isInMainFile users want
1314 // these semantics.
1315 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1316   if (S.TUKind != TU_Complete)
1317     return false;
1318   return S.SourceMgr.isInMainFile(Loc);
1319 }
1320 
1321 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1322   assert(D);
1323 
1324   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1325     return false;
1326 
1327   // Ignore all entities declared within templates, and out-of-line definitions
1328   // of members of class templates.
1329   if (D->getDeclContext()->isDependentContext() ||
1330       D->getLexicalDeclContext()->isDependentContext())
1331     return false;
1332 
1333   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1334     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1335       return false;
1336 
1337     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1338       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1339         return false;
1340     } else {
1341       // 'static inline' functions are defined in headers; don't warn.
1342       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1343         return false;
1344     }
1345 
1346     if (FD->doesThisDeclarationHaveABody() &&
1347         Context.DeclMustBeEmitted(FD))
1348       return false;
1349   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1350     // Constants and utility variables are defined in headers with internal
1351     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1352     // like "inline".)
1353     if (!isMainFileLoc(*this, VD->getLocation()))
1354       return false;
1355 
1356     if (Context.DeclMustBeEmitted(VD))
1357       return false;
1358 
1359     if (VD->isStaticDataMember() &&
1360         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1361       return false;
1362   } else {
1363     return false;
1364   }
1365 
1366   // Only warn for unused decls internal to the translation unit.
1367   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1368   // for inline functions defined in the main source file, for instance.
1369   return mightHaveNonExternalLinkage(D);
1370 }
1371 
1372 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1373   if (!D)
1374     return;
1375 
1376   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1377     const FunctionDecl *First = FD->getFirstDecl();
1378     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1379       return; // First should already be in the vector.
1380   }
1381 
1382   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1383     const VarDecl *First = VD->getFirstDecl();
1384     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1385       return; // First should already be in the vector.
1386   }
1387 
1388   if (ShouldWarnIfUnusedFileScopedDecl(D))
1389     UnusedFileScopedDecls.push_back(D);
1390 }
1391 
1392 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1393   if (D->isInvalidDecl())
1394     return false;
1395 
1396   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1397       D->hasAttr<ObjCPreciseLifetimeAttr>())
1398     return false;
1399 
1400   if (isa<LabelDecl>(D))
1401     return true;
1402 
1403   // Except for labels, we only care about unused decls that are local to
1404   // functions.
1405   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1406   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1407     // For dependent types, the diagnostic is deferred.
1408     WithinFunction =
1409         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1410   if (!WithinFunction)
1411     return false;
1412 
1413   if (isa<TypedefNameDecl>(D))
1414     return true;
1415 
1416   // White-list anything that isn't a local variable.
1417   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1418     return false;
1419 
1420   // Types of valid local variables should be complete, so this should succeed.
1421   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1422 
1423     // White-list anything with an __attribute__((unused)) type.
1424     QualType Ty = VD->getType();
1425 
1426     // Only look at the outermost level of typedef.
1427     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1428       if (TT->getDecl()->hasAttr<UnusedAttr>())
1429         return false;
1430     }
1431 
1432     // If we failed to complete the type for some reason, or if the type is
1433     // dependent, don't diagnose the variable.
1434     if (Ty->isIncompleteType() || Ty->isDependentType())
1435       return false;
1436 
1437     if (const TagType *TT = Ty->getAs<TagType>()) {
1438       const TagDecl *Tag = TT->getDecl();
1439       if (Tag->hasAttr<UnusedAttr>())
1440         return false;
1441 
1442       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1443         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1444           return false;
1445 
1446         if (const Expr *Init = VD->getInit()) {
1447           if (const ExprWithCleanups *Cleanups =
1448                   dyn_cast<ExprWithCleanups>(Init))
1449             Init = Cleanups->getSubExpr();
1450           const CXXConstructExpr *Construct =
1451             dyn_cast<CXXConstructExpr>(Init);
1452           if (Construct && !Construct->isElidable()) {
1453             CXXConstructorDecl *CD = Construct->getConstructor();
1454             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1455               return false;
1456           }
1457         }
1458       }
1459     }
1460 
1461     // TODO: __attribute__((unused)) templates?
1462   }
1463 
1464   return true;
1465 }
1466 
1467 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1468                                      FixItHint &Hint) {
1469   if (isa<LabelDecl>(D)) {
1470     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1471                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1472     if (AfterColon.isInvalid())
1473       return;
1474     Hint = FixItHint::CreateRemoval(CharSourceRange::
1475                                     getCharRange(D->getLocStart(), AfterColon));
1476   }
1477   return;
1478 }
1479 
1480 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1481   if (D->getTypeForDecl()->isDependentType())
1482     return;
1483 
1484   for (auto *TmpD : D->decls()) {
1485     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1486       DiagnoseUnusedDecl(T);
1487     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1488       DiagnoseUnusedNestedTypedefs(R);
1489   }
1490 }
1491 
1492 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1493 /// unless they are marked attr(unused).
1494 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1495   if (!ShouldDiagnoseUnusedDecl(D))
1496     return;
1497 
1498   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1499     // typedefs can be referenced later on, so the diagnostics are emitted
1500     // at end-of-translation-unit.
1501     UnusedLocalTypedefNameCandidates.insert(TD);
1502     return;
1503   }
1504 
1505   FixItHint Hint;
1506   GenerateFixForUnusedDecl(D, Context, Hint);
1507 
1508   unsigned DiagID;
1509   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1510     DiagID = diag::warn_unused_exception_param;
1511   else if (isa<LabelDecl>(D))
1512     DiagID = diag::warn_unused_label;
1513   else
1514     DiagID = diag::warn_unused_variable;
1515 
1516   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1517 }
1518 
1519 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1520   // Verify that we have no forward references left.  If so, there was a goto
1521   // or address of a label taken, but no definition of it.  Label fwd
1522   // definitions are indicated with a null substmt which is also not a resolved
1523   // MS inline assembly label name.
1524   bool Diagnose = false;
1525   if (L->isMSAsmLabel())
1526     Diagnose = !L->isResolvedMSAsmLabel();
1527   else
1528     Diagnose = L->getStmt() == nullptr;
1529   if (Diagnose)
1530     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1531 }
1532 
1533 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1534   S->mergeNRVOIntoParent();
1535 
1536   if (S->decl_empty()) return;
1537   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1538          "Scope shouldn't contain decls!");
1539 
1540   for (auto *TmpD : S->decls()) {
1541     assert(TmpD && "This decl didn't get pushed??");
1542 
1543     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1544     NamedDecl *D = cast<NamedDecl>(TmpD);
1545 
1546     if (!D->getDeclName()) continue;
1547 
1548     // Diagnose unused variables in this scope.
1549     if (!S->hasUnrecoverableErrorOccurred()) {
1550       DiagnoseUnusedDecl(D);
1551       if (const auto *RD = dyn_cast<RecordDecl>(D))
1552         DiagnoseUnusedNestedTypedefs(RD);
1553     }
1554 
1555     // If this was a forward reference to a label, verify it was defined.
1556     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1557       CheckPoppedLabel(LD, *this);
1558 
1559     // Remove this name from our lexical scope.
1560     IdResolver.RemoveDecl(D);
1561   }
1562 }
1563 
1564 /// \brief Look for an Objective-C class in the translation unit.
1565 ///
1566 /// \param Id The name of the Objective-C class we're looking for. If
1567 /// typo-correction fixes this name, the Id will be updated
1568 /// to the fixed name.
1569 ///
1570 /// \param IdLoc The location of the name in the translation unit.
1571 ///
1572 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1573 /// if there is no class with the given name.
1574 ///
1575 /// \returns The declaration of the named Objective-C class, or NULL if the
1576 /// class could not be found.
1577 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1578                                               SourceLocation IdLoc,
1579                                               bool DoTypoCorrection) {
1580   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1581   // creation from this context.
1582   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1583 
1584   if (!IDecl && DoTypoCorrection) {
1585     // Perform typo correction at the given location, but only if we
1586     // find an Objective-C class name.
1587     if (TypoCorrection C = CorrectTypo(
1588             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1589             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1590             CTK_ErrorRecovery)) {
1591       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1592       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1593       Id = IDecl->getIdentifier();
1594     }
1595   }
1596   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1597   // This routine must always return a class definition, if any.
1598   if (Def && Def->getDefinition())
1599       Def = Def->getDefinition();
1600   return Def;
1601 }
1602 
1603 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1604 /// from S, where a non-field would be declared. This routine copes
1605 /// with the difference between C and C++ scoping rules in structs and
1606 /// unions. For example, the following code is well-formed in C but
1607 /// ill-formed in C++:
1608 /// @code
1609 /// struct S6 {
1610 ///   enum { BAR } e;
1611 /// };
1612 ///
1613 /// void test_S6() {
1614 ///   struct S6 a;
1615 ///   a.e = BAR;
1616 /// }
1617 /// @endcode
1618 /// For the declaration of BAR, this routine will return a different
1619 /// scope. The scope S will be the scope of the unnamed enumeration
1620 /// within S6. In C++, this routine will return the scope associated
1621 /// with S6, because the enumeration's scope is a transparent
1622 /// context but structures can contain non-field names. In C, this
1623 /// routine will return the translation unit scope, since the
1624 /// enumeration's scope is a transparent context and structures cannot
1625 /// contain non-field names.
1626 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1627   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1628          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1629          (S->isClassScope() && !getLangOpts().CPlusPlus))
1630     S = S->getParent();
1631   return S;
1632 }
1633 
1634 /// \brief Looks up the declaration of "struct objc_super" and
1635 /// saves it for later use in building builtin declaration of
1636 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1637 /// pre-existing declaration exists no action takes place.
1638 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1639                                         IdentifierInfo *II) {
1640   if (!II->isStr("objc_msgSendSuper"))
1641     return;
1642   ASTContext &Context = ThisSema.Context;
1643 
1644   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1645                       SourceLocation(), Sema::LookupTagName);
1646   ThisSema.LookupName(Result, S);
1647   if (Result.getResultKind() == LookupResult::Found)
1648     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1649       Context.setObjCSuperType(Context.getTagDeclType(TD));
1650 }
1651 
1652 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1653   switch (Error) {
1654   case ASTContext::GE_None:
1655     return "";
1656   case ASTContext::GE_Missing_stdio:
1657     return "stdio.h";
1658   case ASTContext::GE_Missing_setjmp:
1659     return "setjmp.h";
1660   case ASTContext::GE_Missing_ucontext:
1661     return "ucontext.h";
1662   }
1663   llvm_unreachable("unhandled error kind");
1664 }
1665 
1666 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1667 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1668 /// if we're creating this built-in in anticipation of redeclaring the
1669 /// built-in.
1670 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1671                                      Scope *S, bool ForRedeclaration,
1672                                      SourceLocation Loc) {
1673   LookupPredefedObjCSuperType(*this, S, II);
1674 
1675   ASTContext::GetBuiltinTypeError Error;
1676   QualType R = Context.GetBuiltinType(ID, Error);
1677   if (Error) {
1678     if (ForRedeclaration)
1679       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1680           << getHeaderName(Error)
1681           << Context.BuiltinInfo.GetName(ID);
1682     return nullptr;
1683   }
1684 
1685   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1686     Diag(Loc, diag::ext_implicit_lib_function_decl)
1687       << Context.BuiltinInfo.GetName(ID)
1688       << R;
1689     if (Context.BuiltinInfo.getHeaderName(ID) &&
1690         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1691       Diag(Loc, diag::note_include_header_or_declare)
1692           << Context.BuiltinInfo.getHeaderName(ID)
1693           << Context.BuiltinInfo.GetName(ID);
1694   }
1695 
1696   DeclContext *Parent = Context.getTranslationUnitDecl();
1697   if (getLangOpts().CPlusPlus) {
1698     LinkageSpecDecl *CLinkageDecl =
1699         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1700                                 LinkageSpecDecl::lang_c, false);
1701     CLinkageDecl->setImplicit();
1702     Parent->addDecl(CLinkageDecl);
1703     Parent = CLinkageDecl;
1704   }
1705 
1706   FunctionDecl *New = FunctionDecl::Create(Context,
1707                                            Parent,
1708                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1709                                            SC_Extern,
1710                                            false,
1711                                            /*hasPrototype=*/true);
1712   New->setImplicit();
1713 
1714   // Create Decl objects for each parameter, adding them to the
1715   // FunctionDecl.
1716   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1717     SmallVector<ParmVarDecl*, 16> Params;
1718     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1719       ParmVarDecl *parm =
1720           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1721                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1722                               SC_None, nullptr);
1723       parm->setScopeInfo(0, i);
1724       Params.push_back(parm);
1725     }
1726     New->setParams(Params);
1727   }
1728 
1729   AddKnownFunctionAttributes(New);
1730   RegisterLocallyScopedExternCDecl(New, S);
1731 
1732   // TUScope is the translation-unit scope to insert this function into.
1733   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1734   // relate Scopes to DeclContexts, and probably eliminate CurContext
1735   // entirely, but we're not there yet.
1736   DeclContext *SavedContext = CurContext;
1737   CurContext = Parent;
1738   PushOnScopeChains(New, TUScope);
1739   CurContext = SavedContext;
1740   return New;
1741 }
1742 
1743 /// \brief Filter out any previous declarations that the given declaration
1744 /// should not consider because they are not permitted to conflict, e.g.,
1745 /// because they come from hidden sub-modules and do not refer to the same
1746 /// entity.
1747 static void filterNonConflictingPreviousDecls(ASTContext &context,
1748                                               NamedDecl *decl,
1749                                               LookupResult &previous){
1750   // This is only interesting when modules are enabled.
1751   if (!context.getLangOpts().Modules)
1752     return;
1753 
1754   // Empty sets are uninteresting.
1755   if (previous.empty())
1756     return;
1757 
1758   LookupResult::Filter filter = previous.makeFilter();
1759   while (filter.hasNext()) {
1760     NamedDecl *old = filter.next();
1761 
1762     // Non-hidden declarations are never ignored.
1763     if (!old->isHidden())
1764       continue;
1765 
1766     if (!old->isExternallyVisible())
1767       filter.erase();
1768   }
1769 
1770   filter.done();
1771 }
1772 
1773 /// Typedef declarations don't have linkage, but they still denote the same
1774 /// entity if their types are the same.
1775 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1776 /// isSameEntity.
1777 static void filterNonConflictingPreviousTypedefDecls(ASTContext &Context,
1778                                                      TypedefNameDecl *Decl,
1779                                                      LookupResult &Previous) {
1780   // This is only interesting when modules are enabled.
1781   if (!Context.getLangOpts().Modules)
1782     return;
1783 
1784   // Empty sets are uninteresting.
1785   if (Previous.empty())
1786     return;
1787 
1788   LookupResult::Filter Filter = Previous.makeFilter();
1789   while (Filter.hasNext()) {
1790     NamedDecl *Old = Filter.next();
1791 
1792     // Non-hidden declarations are never ignored.
1793     if (!Old->isHidden())
1794       continue;
1795 
1796     // Declarations of the same entity are not ignored, even if they have
1797     // different linkages.
1798     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old))
1799       if (Context.hasSameType(OldTD->getUnderlyingType(),
1800                               Decl->getUnderlyingType()))
1801         continue;
1802 
1803     if (!Old->isExternallyVisible())
1804       Filter.erase();
1805   }
1806 
1807   Filter.done();
1808 }
1809 
1810 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1811   QualType OldType;
1812   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1813     OldType = OldTypedef->getUnderlyingType();
1814   else
1815     OldType = Context.getTypeDeclType(Old);
1816   QualType NewType = New->getUnderlyingType();
1817 
1818   if (NewType->isVariablyModifiedType()) {
1819     // Must not redefine a typedef with a variably-modified type.
1820     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1821     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1822       << Kind << NewType;
1823     if (Old->getLocation().isValid())
1824       Diag(Old->getLocation(), diag::note_previous_definition);
1825     New->setInvalidDecl();
1826     return true;
1827   }
1828 
1829   if (OldType != NewType &&
1830       !OldType->isDependentType() &&
1831       !NewType->isDependentType() &&
1832       !Context.hasSameType(OldType, NewType)) {
1833     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1834     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1835       << Kind << NewType << OldType;
1836     if (Old->getLocation().isValid())
1837       Diag(Old->getLocation(), diag::note_previous_definition);
1838     New->setInvalidDecl();
1839     return true;
1840   }
1841   return false;
1842 }
1843 
1844 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1845 /// same name and scope as a previous declaration 'Old'.  Figure out
1846 /// how to resolve this situation, merging decls or emitting
1847 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1848 ///
1849 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1850   // If the new decl is known invalid already, don't bother doing any
1851   // merging checks.
1852   if (New->isInvalidDecl()) return;
1853 
1854   // Allow multiple definitions for ObjC built-in typedefs.
1855   // FIXME: Verify the underlying types are equivalent!
1856   if (getLangOpts().ObjC1) {
1857     const IdentifierInfo *TypeID = New->getIdentifier();
1858     switch (TypeID->getLength()) {
1859     default: break;
1860     case 2:
1861       {
1862         if (!TypeID->isStr("id"))
1863           break;
1864         QualType T = New->getUnderlyingType();
1865         if (!T->isPointerType())
1866           break;
1867         if (!T->isVoidPointerType()) {
1868           QualType PT = T->getAs<PointerType>()->getPointeeType();
1869           if (!PT->isStructureType())
1870             break;
1871         }
1872         Context.setObjCIdRedefinitionType(T);
1873         // Install the built-in type for 'id', ignoring the current definition.
1874         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1875         return;
1876       }
1877     case 5:
1878       if (!TypeID->isStr("Class"))
1879         break;
1880       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1881       // Install the built-in type for 'Class', ignoring the current definition.
1882       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1883       return;
1884     case 3:
1885       if (!TypeID->isStr("SEL"))
1886         break;
1887       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1888       // Install the built-in type for 'SEL', ignoring the current definition.
1889       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1890       return;
1891     }
1892     // Fall through - the typedef name was not a builtin type.
1893   }
1894 
1895   // Verify the old decl was also a type.
1896   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1897   if (!Old) {
1898     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1899       << New->getDeclName();
1900 
1901     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1902     if (OldD->getLocation().isValid())
1903       Diag(OldD->getLocation(), diag::note_previous_definition);
1904 
1905     return New->setInvalidDecl();
1906   }
1907 
1908   // If the old declaration is invalid, just give up here.
1909   if (Old->isInvalidDecl())
1910     return New->setInvalidDecl();
1911 
1912   // If the typedef types are not identical, reject them in all languages and
1913   // with any extensions enabled.
1914   if (isIncompatibleTypedef(Old, New))
1915     return;
1916 
1917   // The types match.  Link up the redeclaration chain and merge attributes if
1918   // the old declaration was a typedef.
1919   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1920     New->setPreviousDecl(Typedef);
1921     mergeDeclAttributes(New, Old);
1922   }
1923 
1924   if (getLangOpts().MicrosoftExt)
1925     return;
1926 
1927   if (getLangOpts().CPlusPlus) {
1928     // C++ [dcl.typedef]p2:
1929     //   In a given non-class scope, a typedef specifier can be used to
1930     //   redefine the name of any type declared in that scope to refer
1931     //   to the type to which it already refers.
1932     if (!isa<CXXRecordDecl>(CurContext))
1933       return;
1934 
1935     // C++0x [dcl.typedef]p4:
1936     //   In a given class scope, a typedef specifier can be used to redefine
1937     //   any class-name declared in that scope that is not also a typedef-name
1938     //   to refer to the type to which it already refers.
1939     //
1940     // This wording came in via DR424, which was a correction to the
1941     // wording in DR56, which accidentally banned code like:
1942     //
1943     //   struct S {
1944     //     typedef struct A { } A;
1945     //   };
1946     //
1947     // in the C++03 standard. We implement the C++0x semantics, which
1948     // allow the above but disallow
1949     //
1950     //   struct S {
1951     //     typedef int I;
1952     //     typedef int I;
1953     //   };
1954     //
1955     // since that was the intent of DR56.
1956     if (!isa<TypedefNameDecl>(Old))
1957       return;
1958 
1959     Diag(New->getLocation(), diag::err_redefinition)
1960       << New->getDeclName();
1961     Diag(Old->getLocation(), diag::note_previous_definition);
1962     return New->setInvalidDecl();
1963   }
1964 
1965   // Modules always permit redefinition of typedefs, as does C11.
1966   if (getLangOpts().Modules || getLangOpts().C11)
1967     return;
1968 
1969   // If we have a redefinition of a typedef in C, emit a warning.  This warning
1970   // is normally mapped to an error, but can be controlled with
1971   // -Wtypedef-redefinition.  If either the original or the redefinition is
1972   // in a system header, don't emit this for compatibility with GCC.
1973   if (getDiagnostics().getSuppressSystemWarnings() &&
1974       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1975        Context.getSourceManager().isInSystemHeader(New->getLocation())))
1976     return;
1977 
1978   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
1979     << New->getDeclName();
1980   Diag(Old->getLocation(), diag::note_previous_definition);
1981   return;
1982 }
1983 
1984 /// DeclhasAttr - returns true if decl Declaration already has the target
1985 /// attribute.
1986 static bool DeclHasAttr(const Decl *D, const Attr *A) {
1987   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1988   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1989   for (const auto *i : D->attrs())
1990     if (i->getKind() == A->getKind()) {
1991       if (Ann) {
1992         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
1993           return true;
1994         continue;
1995       }
1996       // FIXME: Don't hardcode this check
1997       if (OA && isa<OwnershipAttr>(i))
1998         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
1999       return true;
2000     }
2001 
2002   return false;
2003 }
2004 
2005 static bool isAttributeTargetADefinition(Decl *D) {
2006   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2007     return VD->isThisDeclarationADefinition();
2008   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2009     return TD->isCompleteDefinition() || TD->isBeingDefined();
2010   return true;
2011 }
2012 
2013 /// Merge alignment attributes from \p Old to \p New, taking into account the
2014 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2015 ///
2016 /// \return \c true if any attributes were added to \p New.
2017 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2018   // Look for alignas attributes on Old, and pick out whichever attribute
2019   // specifies the strictest alignment requirement.
2020   AlignedAttr *OldAlignasAttr = nullptr;
2021   AlignedAttr *OldStrictestAlignAttr = nullptr;
2022   unsigned OldAlign = 0;
2023   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2024     // FIXME: We have no way of representing inherited dependent alignments
2025     // in a case like:
2026     //   template<int A, int B> struct alignas(A) X;
2027     //   template<int A, int B> struct alignas(B) X {};
2028     // For now, we just ignore any alignas attributes which are not on the
2029     // definition in such a case.
2030     if (I->isAlignmentDependent())
2031       return false;
2032 
2033     if (I->isAlignas())
2034       OldAlignasAttr = I;
2035 
2036     unsigned Align = I->getAlignment(S.Context);
2037     if (Align > OldAlign) {
2038       OldAlign = Align;
2039       OldStrictestAlignAttr = I;
2040     }
2041   }
2042 
2043   // Look for alignas attributes on New.
2044   AlignedAttr *NewAlignasAttr = nullptr;
2045   unsigned NewAlign = 0;
2046   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2047     if (I->isAlignmentDependent())
2048       return false;
2049 
2050     if (I->isAlignas())
2051       NewAlignasAttr = I;
2052 
2053     unsigned Align = I->getAlignment(S.Context);
2054     if (Align > NewAlign)
2055       NewAlign = Align;
2056   }
2057 
2058   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2059     // Both declarations have 'alignas' attributes. We require them to match.
2060     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2061     // fall short. (If two declarations both have alignas, they must both match
2062     // every definition, and so must match each other if there is a definition.)
2063 
2064     // If either declaration only contains 'alignas(0)' specifiers, then it
2065     // specifies the natural alignment for the type.
2066     if (OldAlign == 0 || NewAlign == 0) {
2067       QualType Ty;
2068       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2069         Ty = VD->getType();
2070       else
2071         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2072 
2073       if (OldAlign == 0)
2074         OldAlign = S.Context.getTypeAlign(Ty);
2075       if (NewAlign == 0)
2076         NewAlign = S.Context.getTypeAlign(Ty);
2077     }
2078 
2079     if (OldAlign != NewAlign) {
2080       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2081         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2082         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2083       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2084     }
2085   }
2086 
2087   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2088     // C++11 [dcl.align]p6:
2089     //   if any declaration of an entity has an alignment-specifier,
2090     //   every defining declaration of that entity shall specify an
2091     //   equivalent alignment.
2092     // C11 6.7.5/7:
2093     //   If the definition of an object does not have an alignment
2094     //   specifier, any other declaration of that object shall also
2095     //   have no alignment specifier.
2096     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2097       << OldAlignasAttr;
2098     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2099       << OldAlignasAttr;
2100   }
2101 
2102   bool AnyAdded = false;
2103 
2104   // Ensure we have an attribute representing the strictest alignment.
2105   if (OldAlign > NewAlign) {
2106     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2107     Clone->setInherited(true);
2108     New->addAttr(Clone);
2109     AnyAdded = true;
2110   }
2111 
2112   // Ensure we have an alignas attribute if the old declaration had one.
2113   if (OldAlignasAttr && !NewAlignasAttr &&
2114       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2115     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2116     Clone->setInherited(true);
2117     New->addAttr(Clone);
2118     AnyAdded = true;
2119   }
2120 
2121   return AnyAdded;
2122 }
2123 
2124 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2125                                const InheritableAttr *Attr, bool Override) {
2126   InheritableAttr *NewAttr = nullptr;
2127   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2128   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2129     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2130                                       AA->getIntroduced(), AA->getDeprecated(),
2131                                       AA->getObsoleted(), AA->getUnavailable(),
2132                                       AA->getMessage(), Override,
2133                                       AttrSpellingListIndex);
2134   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2135     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2136                                     AttrSpellingListIndex);
2137   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2138     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2139                                         AttrSpellingListIndex);
2140   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2141     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2142                                    AttrSpellingListIndex);
2143   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2144     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2145                                    AttrSpellingListIndex);
2146   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2147     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2148                                 FA->getFormatIdx(), FA->getFirstArg(),
2149                                 AttrSpellingListIndex);
2150   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2151     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2152                                  AttrSpellingListIndex);
2153   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2154     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2155                                        AttrSpellingListIndex,
2156                                        IA->getSemanticSpelling());
2157   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2158     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2159                                       &S.Context.Idents.get(AA->getSpelling()),
2160                                       AttrSpellingListIndex);
2161   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2162     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2163   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2164     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2165   else if (isa<AlignedAttr>(Attr))
2166     // AlignedAttrs are handled separately, because we need to handle all
2167     // such attributes on a declaration at the same time.
2168     NewAttr = nullptr;
2169   else if (isa<DeprecatedAttr>(Attr) && Override)
2170     NewAttr = nullptr;
2171   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2172     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2173 
2174   if (NewAttr) {
2175     NewAttr->setInherited(true);
2176     D->addAttr(NewAttr);
2177     return true;
2178   }
2179 
2180   return false;
2181 }
2182 
2183 static const Decl *getDefinition(const Decl *D) {
2184   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2185     return TD->getDefinition();
2186   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2187     const VarDecl *Def = VD->getDefinition();
2188     if (Def)
2189       return Def;
2190     return VD->getActingDefinition();
2191   }
2192   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2193     const FunctionDecl* Def;
2194     if (FD->isDefined(Def))
2195       return Def;
2196   }
2197   return nullptr;
2198 }
2199 
2200 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2201   for (const auto *Attribute : D->attrs())
2202     if (Attribute->getKind() == Kind)
2203       return true;
2204   return false;
2205 }
2206 
2207 /// checkNewAttributesAfterDef - If we already have a definition, check that
2208 /// there are no new attributes in this declaration.
2209 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2210   if (!New->hasAttrs())
2211     return;
2212 
2213   const Decl *Def = getDefinition(Old);
2214   if (!Def || Def == New)
2215     return;
2216 
2217   AttrVec &NewAttributes = New->getAttrs();
2218   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2219     const Attr *NewAttribute = NewAttributes[I];
2220 
2221     if (isa<AliasAttr>(NewAttribute)) {
2222       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2223         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2224       else {
2225         VarDecl *VD = cast<VarDecl>(New);
2226         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2227                                 VarDecl::TentativeDefinition
2228                             ? diag::err_alias_after_tentative
2229                             : diag::err_redefinition;
2230         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2231         S.Diag(Def->getLocation(), diag::note_previous_definition);
2232         VD->setInvalidDecl();
2233       }
2234       ++I;
2235       continue;
2236     }
2237 
2238     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2239       // Tentative definitions are only interesting for the alias check above.
2240       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2241         ++I;
2242         continue;
2243       }
2244     }
2245 
2246     if (hasAttribute(Def, NewAttribute->getKind())) {
2247       ++I;
2248       continue; // regular attr merging will take care of validating this.
2249     }
2250 
2251     if (isa<C11NoReturnAttr>(NewAttribute)) {
2252       // C's _Noreturn is allowed to be added to a function after it is defined.
2253       ++I;
2254       continue;
2255     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2256       if (AA->isAlignas()) {
2257         // C++11 [dcl.align]p6:
2258         //   if any declaration of an entity has an alignment-specifier,
2259         //   every defining declaration of that entity shall specify an
2260         //   equivalent alignment.
2261         // C11 6.7.5/7:
2262         //   If the definition of an object does not have an alignment
2263         //   specifier, any other declaration of that object shall also
2264         //   have no alignment specifier.
2265         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2266           << AA;
2267         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2268           << AA;
2269         NewAttributes.erase(NewAttributes.begin() + I);
2270         --E;
2271         continue;
2272       }
2273     }
2274 
2275     S.Diag(NewAttribute->getLocation(),
2276            diag::warn_attribute_precede_definition);
2277     S.Diag(Def->getLocation(), diag::note_previous_definition);
2278     NewAttributes.erase(NewAttributes.begin() + I);
2279     --E;
2280   }
2281 }
2282 
2283 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2284 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2285                                AvailabilityMergeKind AMK) {
2286   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2287     UsedAttr *NewAttr = OldAttr->clone(Context);
2288     NewAttr->setInherited(true);
2289     New->addAttr(NewAttr);
2290   }
2291 
2292   if (!Old->hasAttrs() && !New->hasAttrs())
2293     return;
2294 
2295   // attributes declared post-definition are currently ignored
2296   checkNewAttributesAfterDef(*this, New, Old);
2297 
2298   if (!Old->hasAttrs())
2299     return;
2300 
2301   bool foundAny = New->hasAttrs();
2302 
2303   // Ensure that any moving of objects within the allocated map is done before
2304   // we process them.
2305   if (!foundAny) New->setAttrs(AttrVec());
2306 
2307   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2308     bool Override = false;
2309     // Ignore deprecated/unavailable/availability attributes if requested.
2310     if (isa<DeprecatedAttr>(I) ||
2311         isa<UnavailableAttr>(I) ||
2312         isa<AvailabilityAttr>(I)) {
2313       switch (AMK) {
2314       case AMK_None:
2315         continue;
2316 
2317       case AMK_Redeclaration:
2318         break;
2319 
2320       case AMK_Override:
2321         Override = true;
2322         break;
2323       }
2324     }
2325 
2326     // Already handled.
2327     if (isa<UsedAttr>(I))
2328       continue;
2329 
2330     if (mergeDeclAttribute(*this, New, I, Override))
2331       foundAny = true;
2332   }
2333 
2334   if (mergeAlignedAttrs(*this, New, Old))
2335     foundAny = true;
2336 
2337   if (!foundAny) New->dropAttrs();
2338 }
2339 
2340 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2341 /// to the new one.
2342 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2343                                      const ParmVarDecl *oldDecl,
2344                                      Sema &S) {
2345   // C++11 [dcl.attr.depend]p2:
2346   //   The first declaration of a function shall specify the
2347   //   carries_dependency attribute for its declarator-id if any declaration
2348   //   of the function specifies the carries_dependency attribute.
2349   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2350   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2351     S.Diag(CDA->getLocation(),
2352            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2353     // Find the first declaration of the parameter.
2354     // FIXME: Should we build redeclaration chains for function parameters?
2355     const FunctionDecl *FirstFD =
2356       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2357     const ParmVarDecl *FirstVD =
2358       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2359     S.Diag(FirstVD->getLocation(),
2360            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2361   }
2362 
2363   if (!oldDecl->hasAttrs())
2364     return;
2365 
2366   bool foundAny = newDecl->hasAttrs();
2367 
2368   // Ensure that any moving of objects within the allocated map is
2369   // done before we process them.
2370   if (!foundAny) newDecl->setAttrs(AttrVec());
2371 
2372   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2373     if (!DeclHasAttr(newDecl, I)) {
2374       InheritableAttr *newAttr =
2375         cast<InheritableParamAttr>(I->clone(S.Context));
2376       newAttr->setInherited(true);
2377       newDecl->addAttr(newAttr);
2378       foundAny = true;
2379     }
2380   }
2381 
2382   if (!foundAny) newDecl->dropAttrs();
2383 }
2384 
2385 namespace {
2386 
2387 /// Used in MergeFunctionDecl to keep track of function parameters in
2388 /// C.
2389 struct GNUCompatibleParamWarning {
2390   ParmVarDecl *OldParm;
2391   ParmVarDecl *NewParm;
2392   QualType PromotedType;
2393 };
2394 
2395 }
2396 
2397 /// getSpecialMember - get the special member enum for a method.
2398 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2399   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2400     if (Ctor->isDefaultConstructor())
2401       return Sema::CXXDefaultConstructor;
2402 
2403     if (Ctor->isCopyConstructor())
2404       return Sema::CXXCopyConstructor;
2405 
2406     if (Ctor->isMoveConstructor())
2407       return Sema::CXXMoveConstructor;
2408   } else if (isa<CXXDestructorDecl>(MD)) {
2409     return Sema::CXXDestructor;
2410   } else if (MD->isCopyAssignmentOperator()) {
2411     return Sema::CXXCopyAssignment;
2412   } else if (MD->isMoveAssignmentOperator()) {
2413     return Sema::CXXMoveAssignment;
2414   }
2415 
2416   return Sema::CXXInvalid;
2417 }
2418 
2419 // Determine whether the previous declaration was a definition, implicit
2420 // declaration, or a declaration.
2421 template <typename T>
2422 static std::pair<diag::kind, SourceLocation>
2423 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2424   diag::kind PrevDiag;
2425   SourceLocation OldLocation = Old->getLocation();
2426   if (Old->isThisDeclarationADefinition())
2427     PrevDiag = diag::note_previous_definition;
2428   else if (Old->isImplicit()) {
2429     PrevDiag = diag::note_previous_implicit_declaration;
2430     if (OldLocation.isInvalid())
2431       OldLocation = New->getLocation();
2432   } else
2433     PrevDiag = diag::note_previous_declaration;
2434   return std::make_pair(PrevDiag, OldLocation);
2435 }
2436 
2437 /// canRedefineFunction - checks if a function can be redefined. Currently,
2438 /// only extern inline functions can be redefined, and even then only in
2439 /// GNU89 mode.
2440 static bool canRedefineFunction(const FunctionDecl *FD,
2441                                 const LangOptions& LangOpts) {
2442   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2443           !LangOpts.CPlusPlus &&
2444           FD->isInlineSpecified() &&
2445           FD->getStorageClass() == SC_Extern);
2446 }
2447 
2448 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2449   const AttributedType *AT = T->getAs<AttributedType>();
2450   while (AT && !AT->isCallingConv())
2451     AT = AT->getModifiedType()->getAs<AttributedType>();
2452   return AT;
2453 }
2454 
2455 template <typename T>
2456 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2457   const DeclContext *DC = Old->getDeclContext();
2458   if (DC->isRecord())
2459     return false;
2460 
2461   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2462   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2463     return true;
2464   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2465     return true;
2466   return false;
2467 }
2468 
2469 /// MergeFunctionDecl - We just parsed a function 'New' from
2470 /// declarator D which has the same name and scope as a previous
2471 /// declaration 'Old'.  Figure out how to resolve this situation,
2472 /// merging decls or emitting diagnostics as appropriate.
2473 ///
2474 /// In C++, New and Old must be declarations that are not
2475 /// overloaded. Use IsOverload to determine whether New and Old are
2476 /// overloaded, and to select the Old declaration that New should be
2477 /// merged with.
2478 ///
2479 /// Returns true if there was an error, false otherwise.
2480 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2481                              Scope *S, bool MergeTypeWithOld) {
2482   // Verify the old decl was also a function.
2483   FunctionDecl *Old = OldD->getAsFunction();
2484   if (!Old) {
2485     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2486       if (New->getFriendObjectKind()) {
2487         Diag(New->getLocation(), diag::err_using_decl_friend);
2488         Diag(Shadow->getTargetDecl()->getLocation(),
2489              diag::note_using_decl_target);
2490         Diag(Shadow->getUsingDecl()->getLocation(),
2491              diag::note_using_decl) << 0;
2492         return true;
2493       }
2494 
2495       // C++11 [namespace.udecl]p14:
2496       //   If a function declaration in namespace scope or block scope has the
2497       //   same name and the same parameter-type-list as a function introduced
2498       //   by a using-declaration, and the declarations do not declare the same
2499       //   function, the program is ill-formed.
2500 
2501       // Check whether the two declarations might declare the same function.
2502       Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2503       if (Old &&
2504           !Old->getDeclContext()->getRedeclContext()->Equals(
2505               New->getDeclContext()->getRedeclContext()) &&
2506           !(Old->isExternC() && New->isExternC()))
2507         Old = nullptr;
2508 
2509       if (!Old) {
2510         Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2511         Diag(Shadow->getTargetDecl()->getLocation(),
2512              diag::note_using_decl_target);
2513         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2514         return true;
2515       }
2516       OldD = Old;
2517     } else {
2518       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2519         << New->getDeclName();
2520       Diag(OldD->getLocation(), diag::note_previous_definition);
2521       return true;
2522     }
2523   }
2524 
2525   // If the old declaration is invalid, just give up here.
2526   if (Old->isInvalidDecl())
2527     return true;
2528 
2529   diag::kind PrevDiag;
2530   SourceLocation OldLocation;
2531   std::tie(PrevDiag, OldLocation) =
2532       getNoteDiagForInvalidRedeclaration(Old, New);
2533 
2534   // Don't complain about this if we're in GNU89 mode and the old function
2535   // is an extern inline function.
2536   // Don't complain about specializations. They are not supposed to have
2537   // storage classes.
2538   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2539       New->getStorageClass() == SC_Static &&
2540       Old->hasExternalFormalLinkage() &&
2541       !New->getTemplateSpecializationInfo() &&
2542       !canRedefineFunction(Old, getLangOpts())) {
2543     if (getLangOpts().MicrosoftExt) {
2544       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2545       Diag(OldLocation, PrevDiag);
2546     } else {
2547       Diag(New->getLocation(), diag::err_static_non_static) << New;
2548       Diag(OldLocation, PrevDiag);
2549       return true;
2550     }
2551   }
2552 
2553 
2554   // If a function is first declared with a calling convention, but is later
2555   // declared or defined without one, all following decls assume the calling
2556   // convention of the first.
2557   //
2558   // It's OK if a function is first declared without a calling convention,
2559   // but is later declared or defined with the default calling convention.
2560   //
2561   // To test if either decl has an explicit calling convention, we look for
2562   // AttributedType sugar nodes on the type as written.  If they are missing or
2563   // were canonicalized away, we assume the calling convention was implicit.
2564   //
2565   // Note also that we DO NOT return at this point, because we still have
2566   // other tests to run.
2567   QualType OldQType = Context.getCanonicalType(Old->getType());
2568   QualType NewQType = Context.getCanonicalType(New->getType());
2569   const FunctionType *OldType = cast<FunctionType>(OldQType);
2570   const FunctionType *NewType = cast<FunctionType>(NewQType);
2571   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2572   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2573   bool RequiresAdjustment = false;
2574 
2575   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2576     FunctionDecl *First = Old->getFirstDecl();
2577     const FunctionType *FT =
2578         First->getType().getCanonicalType()->castAs<FunctionType>();
2579     FunctionType::ExtInfo FI = FT->getExtInfo();
2580     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2581     if (!NewCCExplicit) {
2582       // Inherit the CC from the previous declaration if it was specified
2583       // there but not here.
2584       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2585       RequiresAdjustment = true;
2586     } else {
2587       // Calling conventions aren't compatible, so complain.
2588       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2589       Diag(New->getLocation(), diag::err_cconv_change)
2590         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2591         << !FirstCCExplicit
2592         << (!FirstCCExplicit ? "" :
2593             FunctionType::getNameForCallConv(FI.getCC()));
2594 
2595       // Put the note on the first decl, since it is the one that matters.
2596       Diag(First->getLocation(), diag::note_previous_declaration);
2597       return true;
2598     }
2599   }
2600 
2601   // FIXME: diagnose the other way around?
2602   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2603     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2604     RequiresAdjustment = true;
2605   }
2606 
2607   // Merge regparm attribute.
2608   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2609       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2610     if (NewTypeInfo.getHasRegParm()) {
2611       Diag(New->getLocation(), diag::err_regparm_mismatch)
2612         << NewType->getRegParmType()
2613         << OldType->getRegParmType();
2614       Diag(OldLocation, diag::note_previous_declaration);
2615       return true;
2616     }
2617 
2618     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2619     RequiresAdjustment = true;
2620   }
2621 
2622   // Merge ns_returns_retained attribute.
2623   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2624     if (NewTypeInfo.getProducesResult()) {
2625       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2626       Diag(OldLocation, diag::note_previous_declaration);
2627       return true;
2628     }
2629 
2630     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2631     RequiresAdjustment = true;
2632   }
2633 
2634   if (RequiresAdjustment) {
2635     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2636     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2637     New->setType(QualType(AdjustedType, 0));
2638     NewQType = Context.getCanonicalType(New->getType());
2639     NewType = cast<FunctionType>(NewQType);
2640   }
2641 
2642   // If this redeclaration makes the function inline, we may need to add it to
2643   // UndefinedButUsed.
2644   if (!Old->isInlined() && New->isInlined() &&
2645       !New->hasAttr<GNUInlineAttr>() &&
2646       (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2647       Old->isUsed(false) &&
2648       !Old->isDefined() && !New->isThisDeclarationADefinition())
2649     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2650                                            SourceLocation()));
2651 
2652   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2653   // about it.
2654   if (New->hasAttr<GNUInlineAttr>() &&
2655       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2656     UndefinedButUsed.erase(Old->getCanonicalDecl());
2657   }
2658 
2659   if (getLangOpts().CPlusPlus) {
2660     // (C++98 13.1p2):
2661     //   Certain function declarations cannot be overloaded:
2662     //     -- Function declarations that differ only in the return type
2663     //        cannot be overloaded.
2664 
2665     // Go back to the type source info to compare the declared return types,
2666     // per C++1y [dcl.type.auto]p13:
2667     //   Redeclarations or specializations of a function or function template
2668     //   with a declared return type that uses a placeholder type shall also
2669     //   use that placeholder, not a deduced type.
2670     QualType OldDeclaredReturnType =
2671         (Old->getTypeSourceInfo()
2672              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2673              : OldType)->getReturnType();
2674     QualType NewDeclaredReturnType =
2675         (New->getTypeSourceInfo()
2676              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2677              : NewType)->getReturnType();
2678     QualType ResQT;
2679     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2680         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2681           New->isLocalExternDecl())) {
2682       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2683           OldDeclaredReturnType->isObjCObjectPointerType())
2684         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2685       if (ResQT.isNull()) {
2686         if (New->isCXXClassMember() && New->isOutOfLine())
2687           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2688               << New << New->getReturnTypeSourceRange();
2689         else
2690           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2691               << New->getReturnTypeSourceRange();
2692         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2693                                     << Old->getReturnTypeSourceRange();
2694         return true;
2695       }
2696       else
2697         NewQType = ResQT;
2698     }
2699 
2700     QualType OldReturnType = OldType->getReturnType();
2701     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2702     if (OldReturnType != NewReturnType) {
2703       // If this function has a deduced return type and has already been
2704       // defined, copy the deduced value from the old declaration.
2705       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2706       if (OldAT && OldAT->isDeduced()) {
2707         New->setType(
2708             SubstAutoType(New->getType(),
2709                           OldAT->isDependentType() ? Context.DependentTy
2710                                                    : OldAT->getDeducedType()));
2711         NewQType = Context.getCanonicalType(
2712             SubstAutoType(NewQType,
2713                           OldAT->isDependentType() ? Context.DependentTy
2714                                                    : OldAT->getDeducedType()));
2715       }
2716     }
2717 
2718     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2719     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2720     if (OldMethod && NewMethod) {
2721       // Preserve triviality.
2722       NewMethod->setTrivial(OldMethod->isTrivial());
2723 
2724       // MSVC allows explicit template specialization at class scope:
2725       // 2 CXXMethodDecls referring to the same function will be injected.
2726       // We don't want a redeclaration error.
2727       bool IsClassScopeExplicitSpecialization =
2728                               OldMethod->isFunctionTemplateSpecialization() &&
2729                               NewMethod->isFunctionTemplateSpecialization();
2730       bool isFriend = NewMethod->getFriendObjectKind();
2731 
2732       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2733           !IsClassScopeExplicitSpecialization) {
2734         //    -- Member function declarations with the same name and the
2735         //       same parameter types cannot be overloaded if any of them
2736         //       is a static member function declaration.
2737         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2738           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2739           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2740           return true;
2741         }
2742 
2743         // C++ [class.mem]p1:
2744         //   [...] A member shall not be declared twice in the
2745         //   member-specification, except that a nested class or member
2746         //   class template can be declared and then later defined.
2747         if (ActiveTemplateInstantiations.empty()) {
2748           unsigned NewDiag;
2749           if (isa<CXXConstructorDecl>(OldMethod))
2750             NewDiag = diag::err_constructor_redeclared;
2751           else if (isa<CXXDestructorDecl>(NewMethod))
2752             NewDiag = diag::err_destructor_redeclared;
2753           else if (isa<CXXConversionDecl>(NewMethod))
2754             NewDiag = diag::err_conv_function_redeclared;
2755           else
2756             NewDiag = diag::err_member_redeclared;
2757 
2758           Diag(New->getLocation(), NewDiag);
2759         } else {
2760           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2761             << New << New->getType();
2762         }
2763         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2764         return true;
2765 
2766       // Complain if this is an explicit declaration of a special
2767       // member that was initially declared implicitly.
2768       //
2769       // As an exception, it's okay to befriend such methods in order
2770       // to permit the implicit constructor/destructor/operator calls.
2771       } else if (OldMethod->isImplicit()) {
2772         if (isFriend) {
2773           NewMethod->setImplicit();
2774         } else {
2775           Diag(NewMethod->getLocation(),
2776                diag::err_definition_of_implicitly_declared_member)
2777             << New << getSpecialMember(OldMethod);
2778           return true;
2779         }
2780       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2781         Diag(NewMethod->getLocation(),
2782              diag::err_definition_of_explicitly_defaulted_member)
2783           << getSpecialMember(OldMethod);
2784         return true;
2785       }
2786     }
2787 
2788     // C++11 [dcl.attr.noreturn]p1:
2789     //   The first declaration of a function shall specify the noreturn
2790     //   attribute if any declaration of that function specifies the noreturn
2791     //   attribute.
2792     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2793     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2794       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2795       Diag(Old->getFirstDecl()->getLocation(),
2796            diag::note_noreturn_missing_first_decl);
2797     }
2798 
2799     // C++11 [dcl.attr.depend]p2:
2800     //   The first declaration of a function shall specify the
2801     //   carries_dependency attribute for its declarator-id if any declaration
2802     //   of the function specifies the carries_dependency attribute.
2803     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2804     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2805       Diag(CDA->getLocation(),
2806            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2807       Diag(Old->getFirstDecl()->getLocation(),
2808            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2809     }
2810 
2811     // (C++98 8.3.5p3):
2812     //   All declarations for a function shall agree exactly in both the
2813     //   return type and the parameter-type-list.
2814     // We also want to respect all the extended bits except noreturn.
2815 
2816     // noreturn should now match unless the old type info didn't have it.
2817     QualType OldQTypeForComparison = OldQType;
2818     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2819       assert(OldQType == QualType(OldType, 0));
2820       const FunctionType *OldTypeForComparison
2821         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2822       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2823       assert(OldQTypeForComparison.isCanonical());
2824     }
2825 
2826     if (haveIncompatibleLanguageLinkages(Old, New)) {
2827       // As a special case, retain the language linkage from previous
2828       // declarations of a friend function as an extension.
2829       //
2830       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2831       // and is useful because there's otherwise no way to specify language
2832       // linkage within class scope.
2833       //
2834       // Check cautiously as the friend object kind isn't yet complete.
2835       if (New->getFriendObjectKind() != Decl::FOK_None) {
2836         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2837         Diag(OldLocation, PrevDiag);
2838       } else {
2839         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2840         Diag(OldLocation, PrevDiag);
2841         return true;
2842       }
2843     }
2844 
2845     if (OldQTypeForComparison == NewQType)
2846       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2847 
2848     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2849         New->isLocalExternDecl()) {
2850       // It's OK if we couldn't merge types for a local function declaraton
2851       // if either the old or new type is dependent. We'll merge the types
2852       // when we instantiate the function.
2853       return false;
2854     }
2855 
2856     // Fall through for conflicting redeclarations and redefinitions.
2857   }
2858 
2859   // C: Function types need to be compatible, not identical. This handles
2860   // duplicate function decls like "void f(int); void f(enum X);" properly.
2861   if (!getLangOpts().CPlusPlus &&
2862       Context.typesAreCompatible(OldQType, NewQType)) {
2863     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2864     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2865     const FunctionProtoType *OldProto = nullptr;
2866     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
2867         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2868       // The old declaration provided a function prototype, but the
2869       // new declaration does not. Merge in the prototype.
2870       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2871       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
2872       NewQType =
2873           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2874                                   OldProto->getExtProtoInfo());
2875       New->setType(NewQType);
2876       New->setHasInheritedPrototype();
2877 
2878       // Synthesize parameters with the same types.
2879       SmallVector<ParmVarDecl*, 16> Params;
2880       for (const auto &ParamType : OldProto->param_types()) {
2881         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
2882                                                  SourceLocation(), nullptr,
2883                                                  ParamType, /*TInfo=*/nullptr,
2884                                                  SC_None, nullptr);
2885         Param->setScopeInfo(0, Params.size());
2886         Param->setImplicit();
2887         Params.push_back(Param);
2888       }
2889 
2890       New->setParams(Params);
2891     }
2892 
2893     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2894   }
2895 
2896   // GNU C permits a K&R definition to follow a prototype declaration
2897   // if the declared types of the parameters in the K&R definition
2898   // match the types in the prototype declaration, even when the
2899   // promoted types of the parameters from the K&R definition differ
2900   // from the types in the prototype. GCC then keeps the types from
2901   // the prototype.
2902   //
2903   // If a variadic prototype is followed by a non-variadic K&R definition,
2904   // the K&R definition becomes variadic.  This is sort of an edge case, but
2905   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2906   // C99 6.9.1p8.
2907   if (!getLangOpts().CPlusPlus &&
2908       Old->hasPrototype() && !New->hasPrototype() &&
2909       New->getType()->getAs<FunctionProtoType>() &&
2910       Old->getNumParams() == New->getNumParams()) {
2911     SmallVector<QualType, 16> ArgTypes;
2912     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2913     const FunctionProtoType *OldProto
2914       = Old->getType()->getAs<FunctionProtoType>();
2915     const FunctionProtoType *NewProto
2916       = New->getType()->getAs<FunctionProtoType>();
2917 
2918     // Determine whether this is the GNU C extension.
2919     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2920                                                NewProto->getReturnType());
2921     bool LooseCompatible = !MergedReturn.isNull();
2922     for (unsigned Idx = 0, End = Old->getNumParams();
2923          LooseCompatible && Idx != End; ++Idx) {
2924       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2925       ParmVarDecl *NewParm = New->getParamDecl(Idx);
2926       if (Context.typesAreCompatible(OldParm->getType(),
2927                                      NewProto->getParamType(Idx))) {
2928         ArgTypes.push_back(NewParm->getType());
2929       } else if (Context.typesAreCompatible(OldParm->getType(),
2930                                             NewParm->getType(),
2931                                             /*CompareUnqualified=*/true)) {
2932         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2933                                            NewProto->getParamType(Idx) };
2934         Warnings.push_back(Warn);
2935         ArgTypes.push_back(NewParm->getType());
2936       } else
2937         LooseCompatible = false;
2938     }
2939 
2940     if (LooseCompatible) {
2941       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2942         Diag(Warnings[Warn].NewParm->getLocation(),
2943              diag::ext_param_promoted_not_compatible_with_prototype)
2944           << Warnings[Warn].PromotedType
2945           << Warnings[Warn].OldParm->getType();
2946         if (Warnings[Warn].OldParm->getLocation().isValid())
2947           Diag(Warnings[Warn].OldParm->getLocation(),
2948                diag::note_previous_declaration);
2949       }
2950 
2951       if (MergeTypeWithOld)
2952         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2953                                              OldProto->getExtProtoInfo()));
2954       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2955     }
2956 
2957     // Fall through to diagnose conflicting types.
2958   }
2959 
2960   // A function that has already been declared has been redeclared or
2961   // defined with a different type; show an appropriate diagnostic.
2962 
2963   // If the previous declaration was an implicitly-generated builtin
2964   // declaration, then at the very least we should use a specialized note.
2965   unsigned BuiltinID;
2966   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2967     // If it's actually a library-defined builtin function like 'malloc'
2968     // or 'printf', just warn about the incompatible redeclaration.
2969     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2970       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2971       Diag(OldLocation, diag::note_previous_builtin_declaration)
2972         << Old << Old->getType();
2973 
2974       // If this is a global redeclaration, just forget hereafter
2975       // about the "builtin-ness" of the function.
2976       //
2977       // Doing this for local extern declarations is problematic.  If
2978       // the builtin declaration remains visible, a second invalid
2979       // local declaration will produce a hard error; if it doesn't
2980       // remain visible, a single bogus local redeclaration (which is
2981       // actually only a warning) could break all the downstream code.
2982       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
2983         New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2984 
2985       return false;
2986     }
2987 
2988     PrevDiag = diag::note_previous_builtin_declaration;
2989   }
2990 
2991   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2992   Diag(OldLocation, PrevDiag) << Old << Old->getType();
2993   return true;
2994 }
2995 
2996 /// \brief Completes the merge of two function declarations that are
2997 /// known to be compatible.
2998 ///
2999 /// This routine handles the merging of attributes and other
3000 /// properties of function declarations from the old declaration to
3001 /// the new declaration, once we know that New is in fact a
3002 /// redeclaration of Old.
3003 ///
3004 /// \returns false
3005 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3006                                         Scope *S, bool MergeTypeWithOld) {
3007   // Merge the attributes
3008   mergeDeclAttributes(New, Old);
3009 
3010   // Merge "pure" flag.
3011   if (Old->isPure())
3012     New->setPure();
3013 
3014   // Merge "used" flag.
3015   if (Old->getMostRecentDecl()->isUsed(false))
3016     New->setIsUsed();
3017 
3018   // Merge attributes from the parameters.  These can mismatch with K&R
3019   // declarations.
3020   if (New->getNumParams() == Old->getNumParams())
3021     for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
3022       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
3023                                *this);
3024 
3025   if (getLangOpts().CPlusPlus)
3026     return MergeCXXFunctionDecl(New, Old, S);
3027 
3028   // Merge the function types so the we get the composite types for the return
3029   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3030   // was visible.
3031   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3032   if (!Merged.isNull() && MergeTypeWithOld)
3033     New->setType(Merged);
3034 
3035   return false;
3036 }
3037 
3038 
3039 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3040                                 ObjCMethodDecl *oldMethod) {
3041 
3042   // Merge the attributes, including deprecated/unavailable
3043   AvailabilityMergeKind MergeKind =
3044     isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3045                                                    : AMK_Override;
3046   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3047 
3048   // Merge attributes from the parameters.
3049   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3050                                        oe = oldMethod->param_end();
3051   for (ObjCMethodDecl::param_iterator
3052          ni = newMethod->param_begin(), ne = newMethod->param_end();
3053        ni != ne && oi != oe; ++ni, ++oi)
3054     mergeParamDeclAttributes(*ni, *oi, *this);
3055 
3056   CheckObjCMethodOverride(newMethod, oldMethod);
3057 }
3058 
3059 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3060 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3061 /// emitting diagnostics as appropriate.
3062 ///
3063 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3064 /// to here in AddInitializerToDecl. We can't check them before the initializer
3065 /// is attached.
3066 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3067                              bool MergeTypeWithOld) {
3068   if (New->isInvalidDecl() || Old->isInvalidDecl())
3069     return;
3070 
3071   QualType MergedT;
3072   if (getLangOpts().CPlusPlus) {
3073     if (New->getType()->isUndeducedType()) {
3074       // We don't know what the new type is until the initializer is attached.
3075       return;
3076     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3077       // These could still be something that needs exception specs checked.
3078       return MergeVarDeclExceptionSpecs(New, Old);
3079     }
3080     // C++ [basic.link]p10:
3081     //   [...] the types specified by all declarations referring to a given
3082     //   object or function shall be identical, except that declarations for an
3083     //   array object can specify array types that differ by the presence or
3084     //   absence of a major array bound (8.3.4).
3085     else if (Old->getType()->isIncompleteArrayType() &&
3086              New->getType()->isArrayType()) {
3087       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3088       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3089       if (Context.hasSameType(OldArray->getElementType(),
3090                               NewArray->getElementType()))
3091         MergedT = New->getType();
3092     } else if (Old->getType()->isArrayType() &&
3093                New->getType()->isIncompleteArrayType()) {
3094       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3095       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3096       if (Context.hasSameType(OldArray->getElementType(),
3097                               NewArray->getElementType()))
3098         MergedT = Old->getType();
3099     } else if (New->getType()->isObjCObjectPointerType() &&
3100                Old->getType()->isObjCObjectPointerType()) {
3101       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3102                                               Old->getType());
3103     }
3104   } else {
3105     // C 6.2.7p2:
3106     //   All declarations that refer to the same object or function shall have
3107     //   compatible type.
3108     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3109   }
3110   if (MergedT.isNull()) {
3111     // It's OK if we couldn't merge types if either type is dependent, for a
3112     // block-scope variable. In other cases (static data members of class
3113     // templates, variable templates, ...), we require the types to be
3114     // equivalent.
3115     // FIXME: The C++ standard doesn't say anything about this.
3116     if ((New->getType()->isDependentType() ||
3117          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3118       // If the old type was dependent, we can't merge with it, so the new type
3119       // becomes dependent for now. We'll reproduce the original type when we
3120       // instantiate the TypeSourceInfo for the variable.
3121       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3122         New->setType(Context.DependentTy);
3123       return;
3124     }
3125 
3126     // FIXME: Even if this merging succeeds, some other non-visible declaration
3127     // of this variable might have an incompatible type. For instance:
3128     //
3129     //   extern int arr[];
3130     //   void f() { extern int arr[2]; }
3131     //   void g() { extern int arr[3]; }
3132     //
3133     // Neither C nor C++ requires a diagnostic for this, but we should still try
3134     // to diagnose it.
3135     Diag(New->getLocation(), diag::err_redefinition_different_type)
3136       << New->getDeclName() << New->getType() << Old->getType();
3137     Diag(Old->getLocation(), diag::note_previous_definition);
3138     return New->setInvalidDecl();
3139   }
3140 
3141   // Don't actually update the type on the new declaration if the old
3142   // declaration was an extern declaration in a different scope.
3143   if (MergeTypeWithOld)
3144     New->setType(MergedT);
3145 }
3146 
3147 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3148                                   LookupResult &Previous) {
3149   // C11 6.2.7p4:
3150   //   For an identifier with internal or external linkage declared
3151   //   in a scope in which a prior declaration of that identifier is
3152   //   visible, if the prior declaration specifies internal or
3153   //   external linkage, the type of the identifier at the later
3154   //   declaration becomes the composite type.
3155   //
3156   // If the variable isn't visible, we do not merge with its type.
3157   if (Previous.isShadowed())
3158     return false;
3159 
3160   if (S.getLangOpts().CPlusPlus) {
3161     // C++11 [dcl.array]p3:
3162     //   If there is a preceding declaration of the entity in the same
3163     //   scope in which the bound was specified, an omitted array bound
3164     //   is taken to be the same as in that earlier declaration.
3165     return NewVD->isPreviousDeclInSameBlockScope() ||
3166            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3167             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3168   } else {
3169     // If the old declaration was function-local, don't merge with its
3170     // type unless we're in the same function.
3171     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3172            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3173   }
3174 }
3175 
3176 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3177 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3178 /// situation, merging decls or emitting diagnostics as appropriate.
3179 ///
3180 /// Tentative definition rules (C99 6.9.2p2) are checked by
3181 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3182 /// definitions here, since the initializer hasn't been attached.
3183 ///
3184 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3185   // If the new decl is already invalid, don't do any other checking.
3186   if (New->isInvalidDecl())
3187     return;
3188 
3189   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3190 
3191   // Verify the old decl was also a variable or variable template.
3192   VarDecl *Old = nullptr;
3193   VarTemplateDecl *OldTemplate = nullptr;
3194   if (Previous.isSingleResult()) {
3195     if (NewTemplate) {
3196       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3197       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3198     } else
3199       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3200   }
3201   if (!Old) {
3202     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3203       << New->getDeclName();
3204     Diag(Previous.getRepresentativeDecl()->getLocation(),
3205          diag::note_previous_definition);
3206     return New->setInvalidDecl();
3207   }
3208 
3209   if (!shouldLinkPossiblyHiddenDecl(Old, New))
3210     return;
3211 
3212   // Ensure the template parameters are compatible.
3213   if (NewTemplate &&
3214       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3215                                       OldTemplate->getTemplateParameters(),
3216                                       /*Complain=*/true, TPL_TemplateMatch))
3217     return;
3218 
3219   // C++ [class.mem]p1:
3220   //   A member shall not be declared twice in the member-specification [...]
3221   //
3222   // Here, we need only consider static data members.
3223   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3224     Diag(New->getLocation(), diag::err_duplicate_member)
3225       << New->getIdentifier();
3226     Diag(Old->getLocation(), diag::note_previous_declaration);
3227     New->setInvalidDecl();
3228   }
3229 
3230   mergeDeclAttributes(New, Old);
3231   // Warn if an already-declared variable is made a weak_import in a subsequent
3232   // declaration
3233   if (New->hasAttr<WeakImportAttr>() &&
3234       Old->getStorageClass() == SC_None &&
3235       !Old->hasAttr<WeakImportAttr>()) {
3236     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3237     Diag(Old->getLocation(), diag::note_previous_definition);
3238     // Remove weak_import attribute on new declaration.
3239     New->dropAttr<WeakImportAttr>();
3240   }
3241 
3242   // Merge the types.
3243   VarDecl *MostRecent = Old->getMostRecentDecl();
3244   if (MostRecent != Old) {
3245     MergeVarDeclTypes(New, MostRecent,
3246                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3247     if (New->isInvalidDecl())
3248       return;
3249   }
3250 
3251   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3252   if (New->isInvalidDecl())
3253     return;
3254 
3255   diag::kind PrevDiag;
3256   SourceLocation OldLocation;
3257   std::tie(PrevDiag, OldLocation) =
3258       getNoteDiagForInvalidRedeclaration(Old, New);
3259 
3260   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3261   if (New->getStorageClass() == SC_Static &&
3262       !New->isStaticDataMember() &&
3263       Old->hasExternalFormalLinkage()) {
3264     if (getLangOpts().MicrosoftExt) {
3265       Diag(New->getLocation(), diag::ext_static_non_static)
3266           << New->getDeclName();
3267       Diag(OldLocation, PrevDiag);
3268     } else {
3269       Diag(New->getLocation(), diag::err_static_non_static)
3270           << New->getDeclName();
3271       Diag(OldLocation, PrevDiag);
3272       return New->setInvalidDecl();
3273     }
3274   }
3275   // C99 6.2.2p4:
3276   //   For an identifier declared with the storage-class specifier
3277   //   extern in a scope in which a prior declaration of that
3278   //   identifier is visible,23) if the prior declaration specifies
3279   //   internal or external linkage, the linkage of the identifier at
3280   //   the later declaration is the same as the linkage specified at
3281   //   the prior declaration. If no prior declaration is visible, or
3282   //   if the prior declaration specifies no linkage, then the
3283   //   identifier has external linkage.
3284   if (New->hasExternalStorage() && Old->hasLinkage())
3285     /* Okay */;
3286   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3287            !New->isStaticDataMember() &&
3288            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3289     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3290     Diag(OldLocation, PrevDiag);
3291     return New->setInvalidDecl();
3292   }
3293 
3294   // Check if extern is followed by non-extern and vice-versa.
3295   if (New->hasExternalStorage() &&
3296       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3297     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3298     Diag(OldLocation, PrevDiag);
3299     return New->setInvalidDecl();
3300   }
3301   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3302       !New->hasExternalStorage()) {
3303     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3304     Diag(OldLocation, PrevDiag);
3305     return New->setInvalidDecl();
3306   }
3307 
3308   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3309 
3310   // FIXME: The test for external storage here seems wrong? We still
3311   // need to check for mismatches.
3312   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3313       // Don't complain about out-of-line definitions of static members.
3314       !(Old->getLexicalDeclContext()->isRecord() &&
3315         !New->getLexicalDeclContext()->isRecord())) {
3316     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3317     Diag(OldLocation, PrevDiag);
3318     return New->setInvalidDecl();
3319   }
3320 
3321   if (New->getTLSKind() != Old->getTLSKind()) {
3322     if (!Old->getTLSKind()) {
3323       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3324       Diag(OldLocation, PrevDiag);
3325     } else if (!New->getTLSKind()) {
3326       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3327       Diag(OldLocation, PrevDiag);
3328     } else {
3329       // Do not allow redeclaration to change the variable between requiring
3330       // static and dynamic initialization.
3331       // FIXME: GCC allows this, but uses the TLS keyword on the first
3332       // declaration to determine the kind. Do we need to be compatible here?
3333       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3334         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3335       Diag(OldLocation, PrevDiag);
3336     }
3337   }
3338 
3339   // C++ doesn't have tentative definitions, so go right ahead and check here.
3340   const VarDecl *Def;
3341   if (getLangOpts().CPlusPlus &&
3342       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3343       (Def = Old->getDefinition())) {
3344     Diag(New->getLocation(), diag::err_redefinition) << New;
3345     Diag(Def->getLocation(), diag::note_previous_definition);
3346     New->setInvalidDecl();
3347     return;
3348   }
3349 
3350   if (haveIncompatibleLanguageLinkages(Old, New)) {
3351     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3352     Diag(OldLocation, PrevDiag);
3353     New->setInvalidDecl();
3354     return;
3355   }
3356 
3357   // Merge "used" flag.
3358   if (Old->getMostRecentDecl()->isUsed(false))
3359     New->setIsUsed();
3360 
3361   // Keep a chain of previous declarations.
3362   New->setPreviousDecl(Old);
3363   if (NewTemplate)
3364     NewTemplate->setPreviousDecl(OldTemplate);
3365 
3366   // Inherit access appropriately.
3367   New->setAccess(Old->getAccess());
3368   if (NewTemplate)
3369     NewTemplate->setAccess(New->getAccess());
3370 }
3371 
3372 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3373 /// no declarator (e.g. "struct foo;") is parsed.
3374 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3375                                        DeclSpec &DS) {
3376   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3377 }
3378 
3379 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
3380   if (!S.Context.getLangOpts().CPlusPlus)
3381     return;
3382 
3383   if (isa<CXXRecordDecl>(Tag->getParent())) {
3384     // If this tag is the direct child of a class, number it if
3385     // it is anonymous.
3386     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3387       return;
3388     MangleNumberingContext &MCtx =
3389         S.Context.getManglingNumberContext(Tag->getParent());
3390     S.Context.setManglingNumber(
3391         Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
3392     return;
3393   }
3394 
3395   // If this tag isn't a direct child of a class, number it if it is local.
3396   Decl *ManglingContextDecl;
3397   if (MangleNumberingContext *MCtx =
3398           S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3399                                           ManglingContextDecl)) {
3400     S.Context.setManglingNumber(
3401         Tag,
3402         MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
3403   }
3404 }
3405 
3406 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3407 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3408 /// parameters to cope with template friend declarations.
3409 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3410                                        DeclSpec &DS,
3411                                        MultiTemplateParamsArg TemplateParams,
3412                                        bool IsExplicitInstantiation) {
3413   Decl *TagD = nullptr;
3414   TagDecl *Tag = nullptr;
3415   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3416       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3417       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3418       DS.getTypeSpecType() == DeclSpec::TST_union ||
3419       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3420     TagD = DS.getRepAsDecl();
3421 
3422     if (!TagD) // We probably had an error
3423       return nullptr;
3424 
3425     // Note that the above type specs guarantee that the
3426     // type rep is a Decl, whereas in many of the others
3427     // it's a Type.
3428     if (isa<TagDecl>(TagD))
3429       Tag = cast<TagDecl>(TagD);
3430     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3431       Tag = CTD->getTemplatedDecl();
3432   }
3433 
3434   if (Tag) {
3435     HandleTagNumbering(*this, Tag, S);
3436     Tag->setFreeStanding();
3437     if (Tag->isInvalidDecl())
3438       return Tag;
3439   }
3440 
3441   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3442     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3443     // or incomplete types shall not be restrict-qualified."
3444     if (TypeQuals & DeclSpec::TQ_restrict)
3445       Diag(DS.getRestrictSpecLoc(),
3446            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3447            << DS.getSourceRange();
3448   }
3449 
3450   if (DS.isConstexprSpecified()) {
3451     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3452     // and definitions of functions and variables.
3453     if (Tag)
3454       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3455         << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3456             DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3457             DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3458             DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
3459     else
3460       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3461     // Don't emit warnings after this error.
3462     return TagD;
3463   }
3464 
3465   DiagnoseFunctionSpecifiers(DS);
3466 
3467   if (DS.isFriendSpecified()) {
3468     // If we're dealing with a decl but not a TagDecl, assume that
3469     // whatever routines created it handled the friendship aspect.
3470     if (TagD && !Tag)
3471       return nullptr;
3472     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3473   }
3474 
3475   CXXScopeSpec &SS = DS.getTypeSpecScope();
3476   bool IsExplicitSpecialization =
3477     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3478   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3479       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3480     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3481     // nested-name-specifier unless it is an explicit instantiation
3482     // or an explicit specialization.
3483     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3484     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3485       << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3486           DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3487           DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3488           DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3489       << SS.getRange();
3490     return nullptr;
3491   }
3492 
3493   // Track whether this decl-specifier declares anything.
3494   bool DeclaresAnything = true;
3495 
3496   // Handle anonymous struct definitions.
3497   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3498     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3499         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3500       if (getLangOpts().CPlusPlus ||
3501           Record->getDeclContext()->isRecord())
3502         return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
3503 
3504       DeclaresAnything = false;
3505     }
3506   }
3507 
3508   // C11 6.7.2.1p2:
3509   //   A struct-declaration that does not declare an anonymous structure or
3510   //   anonymous union shall contain a struct-declarator-list.
3511   //
3512   // This rule also existed in C89 and C99; the grammar for struct-declaration
3513   // did not permit a struct-declaration without a struct-declarator-list.
3514   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3515       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3516     // Check for Microsoft C extension: anonymous struct/union member.
3517     // Handle 2 kinds of anonymous struct/union:
3518     //   struct STRUCT;
3519     //   union UNION;
3520     // and
3521     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3522     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3523     if ((Tag && Tag->getDeclName()) ||
3524         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3525       RecordDecl *Record = nullptr;
3526       if (Tag)
3527         Record = dyn_cast<RecordDecl>(Tag);
3528       else if (const RecordType *RT =
3529                    DS.getRepAsType().get()->getAsStructureType())
3530         Record = RT->getDecl();
3531       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3532         Record = UT->getDecl();
3533 
3534       if (Record && getLangOpts().MicrosoftExt) {
3535         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3536           << Record->isUnion() << DS.getSourceRange();
3537         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3538       }
3539 
3540       DeclaresAnything = false;
3541     }
3542   }
3543 
3544   // Skip all the checks below if we have a type error.
3545   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3546       (TagD && TagD->isInvalidDecl()))
3547     return TagD;
3548 
3549   if (getLangOpts().CPlusPlus &&
3550       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3551     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3552       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3553           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3554         DeclaresAnything = false;
3555 
3556   if (!DS.isMissingDeclaratorOk()) {
3557     // Customize diagnostic for a typedef missing a name.
3558     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3559       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3560         << DS.getSourceRange();
3561     else
3562       DeclaresAnything = false;
3563   }
3564 
3565   if (DS.isModulePrivateSpecified() &&
3566       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3567     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3568       << Tag->getTagKind()
3569       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3570 
3571   ActOnDocumentableDecl(TagD);
3572 
3573   // C 6.7/2:
3574   //   A declaration [...] shall declare at least a declarator [...], a tag,
3575   //   or the members of an enumeration.
3576   // C++ [dcl.dcl]p3:
3577   //   [If there are no declarators], and except for the declaration of an
3578   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3579   //   names into the program, or shall redeclare a name introduced by a
3580   //   previous declaration.
3581   if (!DeclaresAnything) {
3582     // In C, we allow this as a (popular) extension / bug. Don't bother
3583     // producing further diagnostics for redundant qualifiers after this.
3584     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3585     return TagD;
3586   }
3587 
3588   // C++ [dcl.stc]p1:
3589   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3590   //   init-declarator-list of the declaration shall not be empty.
3591   // C++ [dcl.fct.spec]p1:
3592   //   If a cv-qualifier appears in a decl-specifier-seq, the
3593   //   init-declarator-list of the declaration shall not be empty.
3594   //
3595   // Spurious qualifiers here appear to be valid in C.
3596   unsigned DiagID = diag::warn_standalone_specifier;
3597   if (getLangOpts().CPlusPlus)
3598     DiagID = diag::ext_standalone_specifier;
3599 
3600   // Note that a linkage-specification sets a storage class, but
3601   // 'extern "C" struct foo;' is actually valid and not theoretically
3602   // useless.
3603   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3604     if (SCS == DeclSpec::SCS_mutable)
3605       // Since mutable is not a viable storage class specifier in C, there is
3606       // no reason to treat it as an extension. Instead, diagnose as an error.
3607       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3608     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3609       Diag(DS.getStorageClassSpecLoc(), DiagID)
3610         << DeclSpec::getSpecifierName(SCS);
3611   }
3612 
3613   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3614     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3615       << DeclSpec::getSpecifierName(TSCS);
3616   if (DS.getTypeQualifiers()) {
3617     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3618       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3619     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3620       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3621     // Restrict is covered above.
3622     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3623       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3624   }
3625 
3626   // Warn about ignored type attributes, for example:
3627   // __attribute__((aligned)) struct A;
3628   // Attributes should be placed after tag to apply to type declaration.
3629   if (!DS.getAttributes().empty()) {
3630     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3631     if (TypeSpecType == DeclSpec::TST_class ||
3632         TypeSpecType == DeclSpec::TST_struct ||
3633         TypeSpecType == DeclSpec::TST_interface ||
3634         TypeSpecType == DeclSpec::TST_union ||
3635         TypeSpecType == DeclSpec::TST_enum) {
3636       AttributeList* attrs = DS.getAttributes().getList();
3637       while (attrs) {
3638         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3639         << attrs->getName()
3640         << (TypeSpecType == DeclSpec::TST_class ? 0 :
3641             TypeSpecType == DeclSpec::TST_struct ? 1 :
3642             TypeSpecType == DeclSpec::TST_union ? 2 :
3643             TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
3644         attrs = attrs->getNext();
3645       }
3646     }
3647   }
3648 
3649   return TagD;
3650 }
3651 
3652 /// We are trying to inject an anonymous member into the given scope;
3653 /// check if there's an existing declaration that can't be overloaded.
3654 ///
3655 /// \return true if this is a forbidden redeclaration
3656 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3657                                          Scope *S,
3658                                          DeclContext *Owner,
3659                                          DeclarationName Name,
3660                                          SourceLocation NameLoc,
3661                                          unsigned diagnostic) {
3662   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3663                  Sema::ForRedeclaration);
3664   if (!SemaRef.LookupName(R, S)) return false;
3665 
3666   if (R.getAsSingle<TagDecl>())
3667     return false;
3668 
3669   // Pick a representative declaration.
3670   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3671   assert(PrevDecl && "Expected a non-null Decl");
3672 
3673   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3674     return false;
3675 
3676   SemaRef.Diag(NameLoc, diagnostic) << Name;
3677   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3678 
3679   return true;
3680 }
3681 
3682 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3683 /// anonymous struct or union AnonRecord into the owning context Owner
3684 /// and scope S. This routine will be invoked just after we realize
3685 /// that an unnamed union or struct is actually an anonymous union or
3686 /// struct, e.g.,
3687 ///
3688 /// @code
3689 /// union {
3690 ///   int i;
3691 ///   float f;
3692 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3693 ///    // f into the surrounding scope.x
3694 /// @endcode
3695 ///
3696 /// This routine is recursive, injecting the names of nested anonymous
3697 /// structs/unions into the owning context and scope as well.
3698 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3699                                          DeclContext *Owner,
3700                                          RecordDecl *AnonRecord,
3701                                          AccessSpecifier AS,
3702                                          SmallVectorImpl<NamedDecl *> &Chaining,
3703                                          bool MSAnonStruct) {
3704   unsigned diagKind
3705     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3706                             : diag::err_anonymous_struct_member_redecl;
3707 
3708   bool Invalid = false;
3709 
3710   // Look every FieldDecl and IndirectFieldDecl with a name.
3711   for (auto *D : AnonRecord->decls()) {
3712     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3713         cast<NamedDecl>(D)->getDeclName()) {
3714       ValueDecl *VD = cast<ValueDecl>(D);
3715       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3716                                        VD->getLocation(), diagKind)) {
3717         // C++ [class.union]p2:
3718         //   The names of the members of an anonymous union shall be
3719         //   distinct from the names of any other entity in the
3720         //   scope in which the anonymous union is declared.
3721         Invalid = true;
3722       } else {
3723         // C++ [class.union]p2:
3724         //   For the purpose of name lookup, after the anonymous union
3725         //   definition, the members of the anonymous union are
3726         //   considered to have been defined in the scope in which the
3727         //   anonymous union is declared.
3728         unsigned OldChainingSize = Chaining.size();
3729         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3730           for (auto *PI : IF->chain())
3731             Chaining.push_back(PI);
3732         else
3733           Chaining.push_back(VD);
3734 
3735         assert(Chaining.size() >= 2);
3736         NamedDecl **NamedChain =
3737           new (SemaRef.Context)NamedDecl*[Chaining.size()];
3738         for (unsigned i = 0; i < Chaining.size(); i++)
3739           NamedChain[i] = Chaining[i];
3740 
3741         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
3742             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
3743             VD->getType(), NamedChain, Chaining.size());
3744 
3745         for (const auto *Attr : VD->attrs())
3746           IndirectField->addAttr(Attr->clone(SemaRef.Context));
3747 
3748         IndirectField->setAccess(AS);
3749         IndirectField->setImplicit();
3750         SemaRef.PushOnScopeChains(IndirectField, S);
3751 
3752         // That includes picking up the appropriate access specifier.
3753         if (AS != AS_none) IndirectField->setAccess(AS);
3754 
3755         Chaining.resize(OldChainingSize);
3756       }
3757     }
3758   }
3759 
3760   return Invalid;
3761 }
3762 
3763 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3764 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
3765 /// illegal input values are mapped to SC_None.
3766 static StorageClass
3767 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3768   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3769   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3770          "Parser allowed 'typedef' as storage class VarDecl.");
3771   switch (StorageClassSpec) {
3772   case DeclSpec::SCS_unspecified:    return SC_None;
3773   case DeclSpec::SCS_extern:
3774     if (DS.isExternInLinkageSpec())
3775       return SC_None;
3776     return SC_Extern;
3777   case DeclSpec::SCS_static:         return SC_Static;
3778   case DeclSpec::SCS_auto:           return SC_Auto;
3779   case DeclSpec::SCS_register:       return SC_Register;
3780   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3781     // Illegal SCSs map to None: error reporting is up to the caller.
3782   case DeclSpec::SCS_mutable:        // Fall through.
3783   case DeclSpec::SCS_typedef:        return SC_None;
3784   }
3785   llvm_unreachable("unknown storage class specifier");
3786 }
3787 
3788 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3789   assert(Record->hasInClassInitializer());
3790 
3791   for (const auto *I : Record->decls()) {
3792     const auto *FD = dyn_cast<FieldDecl>(I);
3793     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
3794       FD = IFD->getAnonField();
3795     if (FD && FD->hasInClassInitializer())
3796       return FD->getLocation();
3797   }
3798 
3799   llvm_unreachable("couldn't find in-class initializer");
3800 }
3801 
3802 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3803                                       SourceLocation DefaultInitLoc) {
3804   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3805     return;
3806 
3807   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3808   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3809 }
3810 
3811 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3812                                       CXXRecordDecl *AnonUnion) {
3813   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3814     return;
3815 
3816   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3817 }
3818 
3819 /// BuildAnonymousStructOrUnion - Handle the declaration of an
3820 /// anonymous structure or union. Anonymous unions are a C++ feature
3821 /// (C++ [class.union]) and a C11 feature; anonymous structures
3822 /// are a C11 feature and GNU C++ extension.
3823 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3824                                         AccessSpecifier AS,
3825                                         RecordDecl *Record,
3826                                         const PrintingPolicy &Policy) {
3827   DeclContext *Owner = Record->getDeclContext();
3828 
3829   // Diagnose whether this anonymous struct/union is an extension.
3830   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
3831     Diag(Record->getLocation(), diag::ext_anonymous_union);
3832   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
3833     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3834   else if (!Record->isUnion() && !getLangOpts().C11)
3835     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3836 
3837   // C and C++ require different kinds of checks for anonymous
3838   // structs/unions.
3839   bool Invalid = false;
3840   if (getLangOpts().CPlusPlus) {
3841     const char *PrevSpec = nullptr;
3842     unsigned DiagID;
3843     if (Record->isUnion()) {
3844       // C++ [class.union]p6:
3845       //   Anonymous unions declared in a named namespace or in the
3846       //   global namespace shall be declared static.
3847       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3848           (isa<TranslationUnitDecl>(Owner) ||
3849            (isa<NamespaceDecl>(Owner) &&
3850             cast<NamespaceDecl>(Owner)->getDeclName()))) {
3851         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3852           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3853 
3854         // Recover by adding 'static'.
3855         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3856                                PrevSpec, DiagID, Policy);
3857       }
3858       // C++ [class.union]p6:
3859       //   A storage class is not allowed in a declaration of an
3860       //   anonymous union in a class scope.
3861       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3862                isa<RecordDecl>(Owner)) {
3863         Diag(DS.getStorageClassSpecLoc(),
3864              diag::err_anonymous_union_with_storage_spec)
3865           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3866 
3867         // Recover by removing the storage specifier.
3868         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3869                                SourceLocation(),
3870                                PrevSpec, DiagID, Context.getPrintingPolicy());
3871       }
3872     }
3873 
3874     // Ignore const/volatile/restrict qualifiers.
3875     if (DS.getTypeQualifiers()) {
3876       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3877         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3878           << Record->isUnion() << "const"
3879           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3880       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3881         Diag(DS.getVolatileSpecLoc(),
3882              diag::ext_anonymous_struct_union_qualified)
3883           << Record->isUnion() << "volatile"
3884           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3885       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3886         Diag(DS.getRestrictSpecLoc(),
3887              diag::ext_anonymous_struct_union_qualified)
3888           << Record->isUnion() << "restrict"
3889           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3890       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3891         Diag(DS.getAtomicSpecLoc(),
3892              diag::ext_anonymous_struct_union_qualified)
3893           << Record->isUnion() << "_Atomic"
3894           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
3895 
3896       DS.ClearTypeQualifiers();
3897     }
3898 
3899     // C++ [class.union]p2:
3900     //   The member-specification of an anonymous union shall only
3901     //   define non-static data members. [Note: nested types and
3902     //   functions cannot be declared within an anonymous union. ]
3903     for (auto *Mem : Record->decls()) {
3904       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
3905         // C++ [class.union]p3:
3906         //   An anonymous union shall not have private or protected
3907         //   members (clause 11).
3908         assert(FD->getAccess() != AS_none);
3909         if (FD->getAccess() != AS_public) {
3910           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3911             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3912           Invalid = true;
3913         }
3914 
3915         // C++ [class.union]p1
3916         //   An object of a class with a non-trivial constructor, a non-trivial
3917         //   copy constructor, a non-trivial destructor, or a non-trivial copy
3918         //   assignment operator cannot be a member of a union, nor can an
3919         //   array of such objects.
3920         if (CheckNontrivialField(FD))
3921           Invalid = true;
3922       } else if (Mem->isImplicit()) {
3923         // Any implicit members are fine.
3924       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
3925         // This is a type that showed up in an
3926         // elaborated-type-specifier inside the anonymous struct or
3927         // union, but which actually declares a type outside of the
3928         // anonymous struct or union. It's okay.
3929       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
3930         if (!MemRecord->isAnonymousStructOrUnion() &&
3931             MemRecord->getDeclName()) {
3932           // Visual C++ allows type definition in anonymous struct or union.
3933           if (getLangOpts().MicrosoftExt)
3934             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3935               << (int)Record->isUnion();
3936           else {
3937             // This is a nested type declaration.
3938             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3939               << (int)Record->isUnion();
3940             Invalid = true;
3941           }
3942         } else {
3943           // This is an anonymous type definition within another anonymous type.
3944           // This is a popular extension, provided by Plan9, MSVC and GCC, but
3945           // not part of standard C++.
3946           Diag(MemRecord->getLocation(),
3947                diag::ext_anonymous_record_with_anonymous_type)
3948             << (int)Record->isUnion();
3949         }
3950       } else if (isa<AccessSpecDecl>(Mem)) {
3951         // Any access specifier is fine.
3952       } else if (isa<StaticAssertDecl>(Mem)) {
3953         // In C++1z, static_assert declarations are also fine.
3954       } else {
3955         // We have something that isn't a non-static data
3956         // member. Complain about it.
3957         unsigned DK = diag::err_anonymous_record_bad_member;
3958         if (isa<TypeDecl>(Mem))
3959           DK = diag::err_anonymous_record_with_type;
3960         else if (isa<FunctionDecl>(Mem))
3961           DK = diag::err_anonymous_record_with_function;
3962         else if (isa<VarDecl>(Mem))
3963           DK = diag::err_anonymous_record_with_static;
3964 
3965         // Visual C++ allows type definition in anonymous struct or union.
3966         if (getLangOpts().MicrosoftExt &&
3967             DK == diag::err_anonymous_record_with_type)
3968           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
3969             << (int)Record->isUnion();
3970         else {
3971           Diag(Mem->getLocation(), DK)
3972               << (int)Record->isUnion();
3973           Invalid = true;
3974         }
3975       }
3976     }
3977 
3978     // C++11 [class.union]p8 (DR1460):
3979     //   At most one variant member of a union may have a
3980     //   brace-or-equal-initializer.
3981     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3982         Owner->isRecord())
3983       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3984                                 cast<CXXRecordDecl>(Record));
3985   }
3986 
3987   if (!Record->isUnion() && !Owner->isRecord()) {
3988     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3989       << (int)getLangOpts().CPlusPlus;
3990     Invalid = true;
3991   }
3992 
3993   // Mock up a declarator.
3994   Declarator Dc(DS, Declarator::MemberContext);
3995   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3996   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3997 
3998   // Create a declaration for this anonymous struct/union.
3999   NamedDecl *Anon = nullptr;
4000   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4001     Anon = FieldDecl::Create(Context, OwningClass,
4002                              DS.getLocStart(),
4003                              Record->getLocation(),
4004                              /*IdentifierInfo=*/nullptr,
4005                              Context.getTypeDeclType(Record),
4006                              TInfo,
4007                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4008                              /*InitStyle=*/ICIS_NoInit);
4009     Anon->setAccess(AS);
4010     if (getLangOpts().CPlusPlus)
4011       FieldCollector->Add(cast<FieldDecl>(Anon));
4012   } else {
4013     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4014     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4015     if (SCSpec == DeclSpec::SCS_mutable) {
4016       // mutable can only appear on non-static class members, so it's always
4017       // an error here
4018       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4019       Invalid = true;
4020       SC = SC_None;
4021     }
4022 
4023     Anon = VarDecl::Create(Context, Owner,
4024                            DS.getLocStart(),
4025                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4026                            Context.getTypeDeclType(Record),
4027                            TInfo, SC);
4028 
4029     // Default-initialize the implicit variable. This initialization will be
4030     // trivial in almost all cases, except if a union member has an in-class
4031     // initializer:
4032     //   union { int n = 0; };
4033     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4034   }
4035   Anon->setImplicit();
4036 
4037   // Mark this as an anonymous struct/union type.
4038   Record->setAnonymousStructOrUnion(true);
4039 
4040   // Add the anonymous struct/union object to the current
4041   // context. We'll be referencing this object when we refer to one of
4042   // its members.
4043   Owner->addDecl(Anon);
4044 
4045   // Inject the members of the anonymous struct/union into the owning
4046   // context and into the identifier resolver chain for name lookup
4047   // purposes.
4048   SmallVector<NamedDecl*, 2> Chain;
4049   Chain.push_back(Anon);
4050 
4051   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
4052                                           Chain, false))
4053     Invalid = true;
4054 
4055   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4056     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4057       Decl *ManglingContextDecl;
4058       if (MangleNumberingContext *MCtx =
4059               getCurrentMangleNumberContext(NewVD->getDeclContext(),
4060                                             ManglingContextDecl)) {
4061         Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
4062         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4063       }
4064     }
4065   }
4066 
4067   if (Invalid)
4068     Anon->setInvalidDecl();
4069 
4070   return Anon;
4071 }
4072 
4073 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4074 /// Microsoft C anonymous structure.
4075 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4076 /// Example:
4077 ///
4078 /// struct A { int a; };
4079 /// struct B { struct A; int b; };
4080 ///
4081 /// void foo() {
4082 ///   B var;
4083 ///   var.a = 3;
4084 /// }
4085 ///
4086 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4087                                            RecordDecl *Record) {
4088   assert(Record && "expected a record!");
4089 
4090   // Mock up a declarator.
4091   Declarator Dc(DS, Declarator::TypeNameContext);
4092   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4093   assert(TInfo && "couldn't build declarator info for anonymous struct");
4094 
4095   auto *ParentDecl = cast<RecordDecl>(CurContext);
4096   QualType RecTy = Context.getTypeDeclType(Record);
4097 
4098   // Create a declaration for this anonymous struct.
4099   NamedDecl *Anon = FieldDecl::Create(Context,
4100                              ParentDecl,
4101                              DS.getLocStart(),
4102                              DS.getLocStart(),
4103                              /*IdentifierInfo=*/nullptr,
4104                              RecTy,
4105                              TInfo,
4106                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4107                              /*InitStyle=*/ICIS_NoInit);
4108   Anon->setImplicit();
4109 
4110   // Add the anonymous struct object to the current context.
4111   CurContext->addDecl(Anon);
4112 
4113   // Inject the members of the anonymous struct into the current
4114   // context and into the identifier resolver chain for name lookup
4115   // purposes.
4116   SmallVector<NamedDecl*, 2> Chain;
4117   Chain.push_back(Anon);
4118 
4119   RecordDecl *RecordDef = Record->getDefinition();
4120   if (RequireCompleteType(Anon->getLocation(), RecTy,
4121                           diag::err_field_incomplete) ||
4122       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4123                                           AS_none, Chain, true)) {
4124     Anon->setInvalidDecl();
4125     ParentDecl->setInvalidDecl();
4126   }
4127 
4128   return Anon;
4129 }
4130 
4131 /// GetNameForDeclarator - Determine the full declaration name for the
4132 /// given Declarator.
4133 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4134   return GetNameFromUnqualifiedId(D.getName());
4135 }
4136 
4137 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4138 DeclarationNameInfo
4139 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4140   DeclarationNameInfo NameInfo;
4141   NameInfo.setLoc(Name.StartLocation);
4142 
4143   switch (Name.getKind()) {
4144 
4145   case UnqualifiedId::IK_ImplicitSelfParam:
4146   case UnqualifiedId::IK_Identifier:
4147     NameInfo.setName(Name.Identifier);
4148     NameInfo.setLoc(Name.StartLocation);
4149     return NameInfo;
4150 
4151   case UnqualifiedId::IK_OperatorFunctionId:
4152     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4153                                            Name.OperatorFunctionId.Operator));
4154     NameInfo.setLoc(Name.StartLocation);
4155     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4156       = Name.OperatorFunctionId.SymbolLocations[0];
4157     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4158       = Name.EndLocation.getRawEncoding();
4159     return NameInfo;
4160 
4161   case UnqualifiedId::IK_LiteralOperatorId:
4162     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4163                                                            Name.Identifier));
4164     NameInfo.setLoc(Name.StartLocation);
4165     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4166     return NameInfo;
4167 
4168   case UnqualifiedId::IK_ConversionFunctionId: {
4169     TypeSourceInfo *TInfo;
4170     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4171     if (Ty.isNull())
4172       return DeclarationNameInfo();
4173     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4174                                                Context.getCanonicalType(Ty)));
4175     NameInfo.setLoc(Name.StartLocation);
4176     NameInfo.setNamedTypeInfo(TInfo);
4177     return NameInfo;
4178   }
4179 
4180   case UnqualifiedId::IK_ConstructorName: {
4181     TypeSourceInfo *TInfo;
4182     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4183     if (Ty.isNull())
4184       return DeclarationNameInfo();
4185     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4186                                               Context.getCanonicalType(Ty)));
4187     NameInfo.setLoc(Name.StartLocation);
4188     NameInfo.setNamedTypeInfo(TInfo);
4189     return NameInfo;
4190   }
4191 
4192   case UnqualifiedId::IK_ConstructorTemplateId: {
4193     // In well-formed code, we can only have a constructor
4194     // template-id that refers to the current context, so go there
4195     // to find the actual type being constructed.
4196     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4197     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4198       return DeclarationNameInfo();
4199 
4200     // Determine the type of the class being constructed.
4201     QualType CurClassType = Context.getTypeDeclType(CurClass);
4202 
4203     // FIXME: Check two things: that the template-id names the same type as
4204     // CurClassType, and that the template-id does not occur when the name
4205     // was qualified.
4206 
4207     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4208                                     Context.getCanonicalType(CurClassType)));
4209     NameInfo.setLoc(Name.StartLocation);
4210     // FIXME: should we retrieve TypeSourceInfo?
4211     NameInfo.setNamedTypeInfo(nullptr);
4212     return NameInfo;
4213   }
4214 
4215   case UnqualifiedId::IK_DestructorName: {
4216     TypeSourceInfo *TInfo;
4217     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4218     if (Ty.isNull())
4219       return DeclarationNameInfo();
4220     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4221                                               Context.getCanonicalType(Ty)));
4222     NameInfo.setLoc(Name.StartLocation);
4223     NameInfo.setNamedTypeInfo(TInfo);
4224     return NameInfo;
4225   }
4226 
4227   case UnqualifiedId::IK_TemplateId: {
4228     TemplateName TName = Name.TemplateId->Template.get();
4229     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4230     return Context.getNameForTemplate(TName, TNameLoc);
4231   }
4232 
4233   } // switch (Name.getKind())
4234 
4235   llvm_unreachable("Unknown name kind");
4236 }
4237 
4238 static QualType getCoreType(QualType Ty) {
4239   do {
4240     if (Ty->isPointerType() || Ty->isReferenceType())
4241       Ty = Ty->getPointeeType();
4242     else if (Ty->isArrayType())
4243       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4244     else
4245       return Ty.withoutLocalFastQualifiers();
4246   } while (true);
4247 }
4248 
4249 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4250 /// and Definition have "nearly" matching parameters. This heuristic is
4251 /// used to improve diagnostics in the case where an out-of-line function
4252 /// definition doesn't match any declaration within the class or namespace.
4253 /// Also sets Params to the list of indices to the parameters that differ
4254 /// between the declaration and the definition. If hasSimilarParameters
4255 /// returns true and Params is empty, then all of the parameters match.
4256 static bool hasSimilarParameters(ASTContext &Context,
4257                                      FunctionDecl *Declaration,
4258                                      FunctionDecl *Definition,
4259                                      SmallVectorImpl<unsigned> &Params) {
4260   Params.clear();
4261   if (Declaration->param_size() != Definition->param_size())
4262     return false;
4263   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4264     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4265     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4266 
4267     // The parameter types are identical
4268     if (Context.hasSameType(DefParamTy, DeclParamTy))
4269       continue;
4270 
4271     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4272     QualType DefParamBaseTy = getCoreType(DefParamTy);
4273     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4274     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4275 
4276     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4277         (DeclTyName && DeclTyName == DefTyName))
4278       Params.push_back(Idx);
4279     else  // The two parameters aren't even close
4280       return false;
4281   }
4282 
4283   return true;
4284 }
4285 
4286 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4287 /// declarator needs to be rebuilt in the current instantiation.
4288 /// Any bits of declarator which appear before the name are valid for
4289 /// consideration here.  That's specifically the type in the decl spec
4290 /// and the base type in any member-pointer chunks.
4291 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4292                                                     DeclarationName Name) {
4293   // The types we specifically need to rebuild are:
4294   //   - typenames, typeofs, and decltypes
4295   //   - types which will become injected class names
4296   // Of course, we also need to rebuild any type referencing such a
4297   // type.  It's safest to just say "dependent", but we call out a
4298   // few cases here.
4299 
4300   DeclSpec &DS = D.getMutableDeclSpec();
4301   switch (DS.getTypeSpecType()) {
4302   case DeclSpec::TST_typename:
4303   case DeclSpec::TST_typeofType:
4304   case DeclSpec::TST_underlyingType:
4305   case DeclSpec::TST_atomic: {
4306     // Grab the type from the parser.
4307     TypeSourceInfo *TSI = nullptr;
4308     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4309     if (T.isNull() || !T->isDependentType()) break;
4310 
4311     // Make sure there's a type source info.  This isn't really much
4312     // of a waste; most dependent types should have type source info
4313     // attached already.
4314     if (!TSI)
4315       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4316 
4317     // Rebuild the type in the current instantiation.
4318     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4319     if (!TSI) return true;
4320 
4321     // Store the new type back in the decl spec.
4322     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4323     DS.UpdateTypeRep(LocType);
4324     break;
4325   }
4326 
4327   case DeclSpec::TST_decltype:
4328   case DeclSpec::TST_typeofExpr: {
4329     Expr *E = DS.getRepAsExpr();
4330     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4331     if (Result.isInvalid()) return true;
4332     DS.UpdateExprRep(Result.get());
4333     break;
4334   }
4335 
4336   default:
4337     // Nothing to do for these decl specs.
4338     break;
4339   }
4340 
4341   // It doesn't matter what order we do this in.
4342   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4343     DeclaratorChunk &Chunk = D.getTypeObject(I);
4344 
4345     // The only type information in the declarator which can come
4346     // before the declaration name is the base type of a member
4347     // pointer.
4348     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4349       continue;
4350 
4351     // Rebuild the scope specifier in-place.
4352     CXXScopeSpec &SS = Chunk.Mem.Scope();
4353     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4354       return true;
4355   }
4356 
4357   return false;
4358 }
4359 
4360 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4361   D.setFunctionDefinitionKind(FDK_Declaration);
4362   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4363 
4364   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4365       Dcl && Dcl->getDeclContext()->isFileContext())
4366     Dcl->setTopLevelDeclInObjCContainer();
4367 
4368   return Dcl;
4369 }
4370 
4371 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4372 ///   If T is the name of a class, then each of the following shall have a
4373 ///   name different from T:
4374 ///     - every static data member of class T;
4375 ///     - every member function of class T
4376 ///     - every member of class T that is itself a type;
4377 /// \returns true if the declaration name violates these rules.
4378 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4379                                    DeclarationNameInfo NameInfo) {
4380   DeclarationName Name = NameInfo.getName();
4381 
4382   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4383     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4384       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4385       return true;
4386     }
4387 
4388   return false;
4389 }
4390 
4391 /// \brief Diagnose a declaration whose declarator-id has the given
4392 /// nested-name-specifier.
4393 ///
4394 /// \param SS The nested-name-specifier of the declarator-id.
4395 ///
4396 /// \param DC The declaration context to which the nested-name-specifier
4397 /// resolves.
4398 ///
4399 /// \param Name The name of the entity being declared.
4400 ///
4401 /// \param Loc The location of the name of the entity being declared.
4402 ///
4403 /// \returns true if we cannot safely recover from this error, false otherwise.
4404 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4405                                         DeclarationName Name,
4406                                         SourceLocation Loc) {
4407   DeclContext *Cur = CurContext;
4408   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4409     Cur = Cur->getParent();
4410 
4411   // If the user provided a superfluous scope specifier that refers back to the
4412   // class in which the entity is already declared, diagnose and ignore it.
4413   //
4414   // class X {
4415   //   void X::f();
4416   // };
4417   //
4418   // Note, it was once ill-formed to give redundant qualification in all
4419   // contexts, but that rule was removed by DR482.
4420   if (Cur->Equals(DC)) {
4421     if (Cur->isRecord()) {
4422       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4423                                       : diag::err_member_extra_qualification)
4424         << Name << FixItHint::CreateRemoval(SS.getRange());
4425       SS.clear();
4426     } else {
4427       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4428     }
4429     return false;
4430   }
4431 
4432   // Check whether the qualifying scope encloses the scope of the original
4433   // declaration.
4434   if (!Cur->Encloses(DC)) {
4435     if (Cur->isRecord())
4436       Diag(Loc, diag::err_member_qualification)
4437         << Name << SS.getRange();
4438     else if (isa<TranslationUnitDecl>(DC))
4439       Diag(Loc, diag::err_invalid_declarator_global_scope)
4440         << Name << SS.getRange();
4441     else if (isa<FunctionDecl>(Cur))
4442       Diag(Loc, diag::err_invalid_declarator_in_function)
4443         << Name << SS.getRange();
4444     else if (isa<BlockDecl>(Cur))
4445       Diag(Loc, diag::err_invalid_declarator_in_block)
4446         << Name << SS.getRange();
4447     else
4448       Diag(Loc, diag::err_invalid_declarator_scope)
4449       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4450 
4451     return true;
4452   }
4453 
4454   if (Cur->isRecord()) {
4455     // Cannot qualify members within a class.
4456     Diag(Loc, diag::err_member_qualification)
4457       << Name << SS.getRange();
4458     SS.clear();
4459 
4460     // C++ constructors and destructors with incorrect scopes can break
4461     // our AST invariants by having the wrong underlying types. If
4462     // that's the case, then drop this declaration entirely.
4463     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4464          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4465         !Context.hasSameType(Name.getCXXNameType(),
4466                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4467       return true;
4468 
4469     return false;
4470   }
4471 
4472   // C++11 [dcl.meaning]p1:
4473   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4474   //   not begin with a decltype-specifer"
4475   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4476   while (SpecLoc.getPrefix())
4477     SpecLoc = SpecLoc.getPrefix();
4478   if (dyn_cast_or_null<DecltypeType>(
4479         SpecLoc.getNestedNameSpecifier()->getAsType()))
4480     Diag(Loc, diag::err_decltype_in_declarator)
4481       << SpecLoc.getTypeLoc().getSourceRange();
4482 
4483   return false;
4484 }
4485 
4486 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4487                                   MultiTemplateParamsArg TemplateParamLists) {
4488   // TODO: consider using NameInfo for diagnostic.
4489   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4490   DeclarationName Name = NameInfo.getName();
4491 
4492   // All of these full declarators require an identifier.  If it doesn't have
4493   // one, the ParsedFreeStandingDeclSpec action should be used.
4494   if (!Name) {
4495     if (!D.isInvalidType())  // Reject this if we think it is valid.
4496       Diag(D.getDeclSpec().getLocStart(),
4497            diag::err_declarator_need_ident)
4498         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4499     return nullptr;
4500   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4501     return nullptr;
4502 
4503   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4504   // we find one that is.
4505   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4506          (S->getFlags() & Scope::TemplateParamScope) != 0)
4507     S = S->getParent();
4508 
4509   DeclContext *DC = CurContext;
4510   if (D.getCXXScopeSpec().isInvalid())
4511     D.setInvalidType();
4512   else if (D.getCXXScopeSpec().isSet()) {
4513     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4514                                         UPPC_DeclarationQualifier))
4515       return nullptr;
4516 
4517     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4518     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4519     if (!DC || isa<EnumDecl>(DC)) {
4520       // If we could not compute the declaration context, it's because the
4521       // declaration context is dependent but does not refer to a class,
4522       // class template, or class template partial specialization. Complain
4523       // and return early, to avoid the coming semantic disaster.
4524       Diag(D.getIdentifierLoc(),
4525            diag::err_template_qualified_declarator_no_match)
4526         << D.getCXXScopeSpec().getScopeRep()
4527         << D.getCXXScopeSpec().getRange();
4528       return nullptr;
4529     }
4530     bool IsDependentContext = DC->isDependentContext();
4531 
4532     if (!IsDependentContext &&
4533         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4534       return nullptr;
4535 
4536     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4537       Diag(D.getIdentifierLoc(),
4538            diag::err_member_def_undefined_record)
4539         << Name << DC << D.getCXXScopeSpec().getRange();
4540       D.setInvalidType();
4541     } else if (!D.getDeclSpec().isFriendSpecified()) {
4542       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4543                                       Name, D.getIdentifierLoc())) {
4544         if (DC->isRecord())
4545           return nullptr;
4546 
4547         D.setInvalidType();
4548       }
4549     }
4550 
4551     // Check whether we need to rebuild the type of the given
4552     // declaration in the current instantiation.
4553     if (EnteringContext && IsDependentContext &&
4554         TemplateParamLists.size() != 0) {
4555       ContextRAII SavedContext(*this, DC);
4556       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4557         D.setInvalidType();
4558     }
4559   }
4560 
4561   if (DiagnoseClassNameShadow(DC, NameInfo))
4562     // If this is a typedef, we'll end up spewing multiple diagnostics.
4563     // Just return early; it's safer.
4564     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4565       return nullptr;
4566 
4567   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4568   QualType R = TInfo->getType();
4569 
4570   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4571                                       UPPC_DeclarationType))
4572     D.setInvalidType();
4573 
4574   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4575                         ForRedeclaration);
4576 
4577   // See if this is a redefinition of a variable in the same scope.
4578   if (!D.getCXXScopeSpec().isSet()) {
4579     bool IsLinkageLookup = false;
4580     bool CreateBuiltins = false;
4581 
4582     // If the declaration we're planning to build will be a function
4583     // or object with linkage, then look for another declaration with
4584     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4585     //
4586     // If the declaration we're planning to build will be declared with
4587     // external linkage in the translation unit, create any builtin with
4588     // the same name.
4589     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4590       /* Do nothing*/;
4591     else if (CurContext->isFunctionOrMethod() &&
4592              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4593               R->isFunctionType())) {
4594       IsLinkageLookup = true;
4595       CreateBuiltins =
4596           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4597     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4598                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4599       CreateBuiltins = true;
4600 
4601     if (IsLinkageLookup)
4602       Previous.clear(LookupRedeclarationWithLinkage);
4603 
4604     LookupName(Previous, S, CreateBuiltins);
4605   } else { // Something like "int foo::x;"
4606     LookupQualifiedName(Previous, DC);
4607 
4608     // C++ [dcl.meaning]p1:
4609     //   When the declarator-id is qualified, the declaration shall refer to a
4610     //  previously declared member of the class or namespace to which the
4611     //  qualifier refers (or, in the case of a namespace, of an element of the
4612     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4613     //  thereof; [...]
4614     //
4615     // Note that we already checked the context above, and that we do not have
4616     // enough information to make sure that Previous contains the declaration
4617     // we want to match. For example, given:
4618     //
4619     //   class X {
4620     //     void f();
4621     //     void f(float);
4622     //   };
4623     //
4624     //   void X::f(int) { } // ill-formed
4625     //
4626     // In this case, Previous will point to the overload set
4627     // containing the two f's declared in X, but neither of them
4628     // matches.
4629 
4630     // C++ [dcl.meaning]p1:
4631     //   [...] the member shall not merely have been introduced by a
4632     //   using-declaration in the scope of the class or namespace nominated by
4633     //   the nested-name-specifier of the declarator-id.
4634     RemoveUsingDecls(Previous);
4635   }
4636 
4637   if (Previous.isSingleResult() &&
4638       Previous.getFoundDecl()->isTemplateParameter()) {
4639     // Maybe we will complain about the shadowed template parameter.
4640     if (!D.isInvalidType())
4641       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4642                                       Previous.getFoundDecl());
4643 
4644     // Just pretend that we didn't see the previous declaration.
4645     Previous.clear();
4646   }
4647 
4648   // In C++, the previous declaration we find might be a tag type
4649   // (class or enum). In this case, the new declaration will hide the
4650   // tag type. Note that this does does not apply if we're declaring a
4651   // typedef (C++ [dcl.typedef]p4).
4652   if (Previous.isSingleTagDecl() &&
4653       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4654     Previous.clear();
4655 
4656   // Check that there are no default arguments other than in the parameters
4657   // of a function declaration (C++ only).
4658   if (getLangOpts().CPlusPlus)
4659     CheckExtraCXXDefaultArguments(D);
4660 
4661   NamedDecl *New;
4662 
4663   bool AddToScope = true;
4664   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4665     if (TemplateParamLists.size()) {
4666       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4667       return nullptr;
4668     }
4669 
4670     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4671   } else if (R->isFunctionType()) {
4672     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4673                                   TemplateParamLists,
4674                                   AddToScope);
4675   } else {
4676     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4677                                   AddToScope);
4678   }
4679 
4680   if (!New)
4681     return nullptr;
4682 
4683   // If this has an identifier and is not an invalid redeclaration or
4684   // function template specialization, add it to the scope stack.
4685   if (New->getDeclName() && AddToScope &&
4686        !(D.isRedeclaration() && New->isInvalidDecl())) {
4687     // Only make a locally-scoped extern declaration visible if it is the first
4688     // declaration of this entity. Qualified lookup for such an entity should
4689     // only find this declaration if there is no visible declaration of it.
4690     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4691     PushOnScopeChains(New, S, AddToContext);
4692     if (!AddToContext)
4693       CurContext->addHiddenDecl(New);
4694   }
4695 
4696   return New;
4697 }
4698 
4699 /// Helper method to turn variable array types into constant array
4700 /// types in certain situations which would otherwise be errors (for
4701 /// GCC compatibility).
4702 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4703                                                     ASTContext &Context,
4704                                                     bool &SizeIsNegative,
4705                                                     llvm::APSInt &Oversized) {
4706   // This method tries to turn a variable array into a constant
4707   // array even when the size isn't an ICE.  This is necessary
4708   // for compatibility with code that depends on gcc's buggy
4709   // constant expression folding, like struct {char x[(int)(char*)2];}
4710   SizeIsNegative = false;
4711   Oversized = 0;
4712 
4713   if (T->isDependentType())
4714     return QualType();
4715 
4716   QualifierCollector Qs;
4717   const Type *Ty = Qs.strip(T);
4718 
4719   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4720     QualType Pointee = PTy->getPointeeType();
4721     QualType FixedType =
4722         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4723                                             Oversized);
4724     if (FixedType.isNull()) return FixedType;
4725     FixedType = Context.getPointerType(FixedType);
4726     return Qs.apply(Context, FixedType);
4727   }
4728   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4729     QualType Inner = PTy->getInnerType();
4730     QualType FixedType =
4731         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4732                                             Oversized);
4733     if (FixedType.isNull()) return FixedType;
4734     FixedType = Context.getParenType(FixedType);
4735     return Qs.apply(Context, FixedType);
4736   }
4737 
4738   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4739   if (!VLATy)
4740     return QualType();
4741   // FIXME: We should probably handle this case
4742   if (VLATy->getElementType()->isVariablyModifiedType())
4743     return QualType();
4744 
4745   llvm::APSInt Res;
4746   if (!VLATy->getSizeExpr() ||
4747       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4748     return QualType();
4749 
4750   // Check whether the array size is negative.
4751   if (Res.isSigned() && Res.isNegative()) {
4752     SizeIsNegative = true;
4753     return QualType();
4754   }
4755 
4756   // Check whether the array is too large to be addressed.
4757   unsigned ActiveSizeBits
4758     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4759                                               Res);
4760   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4761     Oversized = Res;
4762     return QualType();
4763   }
4764 
4765   return Context.getConstantArrayType(VLATy->getElementType(),
4766                                       Res, ArrayType::Normal, 0);
4767 }
4768 
4769 static void
4770 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
4771   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4772     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4773     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4774                                       DstPTL.getPointeeLoc());
4775     DstPTL.setStarLoc(SrcPTL.getStarLoc());
4776     return;
4777   }
4778   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4779     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4780     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4781                                       DstPTL.getInnerLoc());
4782     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4783     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
4784     return;
4785   }
4786   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4787   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4788   TypeLoc SrcElemTL = SrcATL.getElementLoc();
4789   TypeLoc DstElemTL = DstATL.getElementLoc();
4790   DstElemTL.initializeFullCopy(SrcElemTL);
4791   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4792   DstATL.setSizeExpr(SrcATL.getSizeExpr());
4793   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
4794 }
4795 
4796 /// Helper method to turn variable array types into constant array
4797 /// types in certain situations which would otherwise be errors (for
4798 /// GCC compatibility).
4799 static TypeSourceInfo*
4800 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4801                                               ASTContext &Context,
4802                                               bool &SizeIsNegative,
4803                                               llvm::APSInt &Oversized) {
4804   QualType FixedTy
4805     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4806                                           SizeIsNegative, Oversized);
4807   if (FixedTy.isNull())
4808     return nullptr;
4809   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4810   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4811                                     FixedTInfo->getTypeLoc());
4812   return FixedTInfo;
4813 }
4814 
4815 /// \brief Register the given locally-scoped extern "C" declaration so
4816 /// that it can be found later for redeclarations. We include any extern "C"
4817 /// declaration that is not visible in the translation unit here, not just
4818 /// function-scope declarations.
4819 void
4820 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
4821   if (!getLangOpts().CPlusPlus &&
4822       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4823     // Don't need to track declarations in the TU in C.
4824     return;
4825 
4826   // Note that we have a locally-scoped external with this name.
4827   // FIXME: There can be multiple such declarations if they are functions marked
4828   // __attribute__((overloadable)) declared in function scope in C.
4829   LocallyScopedExternCDecls[ND->getDeclName()] = ND;
4830 }
4831 
4832 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4833   if (ExternalSource) {
4834     // Load locally-scoped external decls from the external source.
4835     // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
4836     SmallVector<NamedDecl *, 4> Decls;
4837     ExternalSource->ReadLocallyScopedExternCDecls(Decls);
4838     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4839       llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4840         = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4841       if (Pos == LocallyScopedExternCDecls.end())
4842         LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
4843     }
4844   }
4845 
4846   NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
4847   return D ? D->getMostRecentDecl() : nullptr;
4848 }
4849 
4850 /// \brief Diagnose function specifiers on a declaration of an identifier that
4851 /// does not identify a function.
4852 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
4853   // FIXME: We should probably indicate the identifier in question to avoid
4854   // confusion for constructs like "inline int a(), b;"
4855   if (DS.isInlineSpecified())
4856     Diag(DS.getInlineSpecLoc(),
4857          diag::err_inline_non_function);
4858 
4859   if (DS.isVirtualSpecified())
4860     Diag(DS.getVirtualSpecLoc(),
4861          diag::err_virtual_non_function);
4862 
4863   if (DS.isExplicitSpecified())
4864     Diag(DS.getExplicitSpecLoc(),
4865          diag::err_explicit_non_function);
4866 
4867   if (DS.isNoreturnSpecified())
4868     Diag(DS.getNoreturnSpecLoc(),
4869          diag::err_noreturn_non_function);
4870 }
4871 
4872 NamedDecl*
4873 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4874                              TypeSourceInfo *TInfo, LookupResult &Previous) {
4875   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4876   if (D.getCXXScopeSpec().isSet()) {
4877     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4878       << D.getCXXScopeSpec().getRange();
4879     D.setInvalidType();
4880     // Pretend we didn't see the scope specifier.
4881     DC = CurContext;
4882     Previous.clear();
4883   }
4884 
4885   DiagnoseFunctionSpecifiers(D.getDeclSpec());
4886 
4887   if (D.getDeclSpec().isConstexprSpecified())
4888     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4889       << 1;
4890 
4891   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4892     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4893       << D.getName().getSourceRange();
4894     return nullptr;
4895   }
4896 
4897   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4898   if (!NewTD) return nullptr;
4899 
4900   // Handle attributes prior to checking for duplicates in MergeVarDecl
4901   ProcessDeclAttributes(S, NewTD, D);
4902 
4903   CheckTypedefForVariablyModifiedType(S, NewTD);
4904 
4905   bool Redeclaration = D.isRedeclaration();
4906   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4907   D.setRedeclaration(Redeclaration);
4908   return ND;
4909 }
4910 
4911 void
4912 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4913   // C99 6.7.7p2: If a typedef name specifies a variably modified type
4914   // then it shall have block scope.
4915   // Note that variably modified types must be fixed before merging the decl so
4916   // that redeclarations will match.
4917   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4918   QualType T = TInfo->getType();
4919   if (T->isVariablyModifiedType()) {
4920     getCurFunction()->setHasBranchProtectedScope();
4921 
4922     if (S->getFnParent() == nullptr) {
4923       bool SizeIsNegative;
4924       llvm::APSInt Oversized;
4925       TypeSourceInfo *FixedTInfo =
4926         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4927                                                       SizeIsNegative,
4928                                                       Oversized);
4929       if (FixedTInfo) {
4930         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4931         NewTD->setTypeSourceInfo(FixedTInfo);
4932       } else {
4933         if (SizeIsNegative)
4934           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4935         else if (T->isVariableArrayType())
4936           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4937         else if (Oversized.getBoolValue())
4938           Diag(NewTD->getLocation(), diag::err_array_too_large)
4939             << Oversized.toString(10);
4940         else
4941           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4942         NewTD->setInvalidDecl();
4943       }
4944     }
4945   }
4946 }
4947 
4948 
4949 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4950 /// declares a typedef-name, either using the 'typedef' type specifier or via
4951 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4952 NamedDecl*
4953 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4954                            LookupResult &Previous, bool &Redeclaration) {
4955   // Merge the decl with the existing one if appropriate. If the decl is
4956   // in an outer scope, it isn't the same thing.
4957   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4958                        /*AllowInlineNamespace*/false);
4959   filterNonConflictingPreviousTypedefDecls(Context, NewTD, Previous);
4960   if (!Previous.empty()) {
4961     Redeclaration = true;
4962     MergeTypedefNameDecl(NewTD, Previous);
4963   }
4964 
4965   // If this is the C FILE type, notify the AST context.
4966   if (IdentifierInfo *II = NewTD->getIdentifier())
4967     if (!NewTD->isInvalidDecl() &&
4968         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4969       if (II->isStr("FILE"))
4970         Context.setFILEDecl(NewTD);
4971       else if (II->isStr("jmp_buf"))
4972         Context.setjmp_bufDecl(NewTD);
4973       else if (II->isStr("sigjmp_buf"))
4974         Context.setsigjmp_bufDecl(NewTD);
4975       else if (II->isStr("ucontext_t"))
4976         Context.setucontext_tDecl(NewTD);
4977     }
4978 
4979   return NewTD;
4980 }
4981 
4982 /// \brief Determines whether the given declaration is an out-of-scope
4983 /// previous declaration.
4984 ///
4985 /// This routine should be invoked when name lookup has found a
4986 /// previous declaration (PrevDecl) that is not in the scope where a
4987 /// new declaration by the same name is being introduced. If the new
4988 /// declaration occurs in a local scope, previous declarations with
4989 /// linkage may still be considered previous declarations (C99
4990 /// 6.2.2p4-5, C++ [basic.link]p6).
4991 ///
4992 /// \param PrevDecl the previous declaration found by name
4993 /// lookup
4994 ///
4995 /// \param DC the context in which the new declaration is being
4996 /// declared.
4997 ///
4998 /// \returns true if PrevDecl is an out-of-scope previous declaration
4999 /// for a new delcaration with the same name.
5000 static bool
5001 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5002                                 ASTContext &Context) {
5003   if (!PrevDecl)
5004     return false;
5005 
5006   if (!PrevDecl->hasLinkage())
5007     return false;
5008 
5009   if (Context.getLangOpts().CPlusPlus) {
5010     // C++ [basic.link]p6:
5011     //   If there is a visible declaration of an entity with linkage
5012     //   having the same name and type, ignoring entities declared
5013     //   outside the innermost enclosing namespace scope, the block
5014     //   scope declaration declares that same entity and receives the
5015     //   linkage of the previous declaration.
5016     DeclContext *OuterContext = DC->getRedeclContext();
5017     if (!OuterContext->isFunctionOrMethod())
5018       // This rule only applies to block-scope declarations.
5019       return false;
5020 
5021     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5022     if (PrevOuterContext->isRecord())
5023       // We found a member function: ignore it.
5024       return false;
5025 
5026     // Find the innermost enclosing namespace for the new and
5027     // previous declarations.
5028     OuterContext = OuterContext->getEnclosingNamespaceContext();
5029     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5030 
5031     // The previous declaration is in a different namespace, so it
5032     // isn't the same function.
5033     if (!OuterContext->Equals(PrevOuterContext))
5034       return false;
5035   }
5036 
5037   return true;
5038 }
5039 
5040 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5041   CXXScopeSpec &SS = D.getCXXScopeSpec();
5042   if (!SS.isSet()) return;
5043   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5044 }
5045 
5046 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5047   QualType type = decl->getType();
5048   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5049   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5050     // Various kinds of declaration aren't allowed to be __autoreleasing.
5051     unsigned kind = -1U;
5052     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5053       if (var->hasAttr<BlocksAttr>())
5054         kind = 0; // __block
5055       else if (!var->hasLocalStorage())
5056         kind = 1; // global
5057     } else if (isa<ObjCIvarDecl>(decl)) {
5058       kind = 3; // ivar
5059     } else if (isa<FieldDecl>(decl)) {
5060       kind = 2; // field
5061     }
5062 
5063     if (kind != -1U) {
5064       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5065         << kind;
5066     }
5067   } else if (lifetime == Qualifiers::OCL_None) {
5068     // Try to infer lifetime.
5069     if (!type->isObjCLifetimeType())
5070       return false;
5071 
5072     lifetime = type->getObjCARCImplicitLifetime();
5073     type = Context.getLifetimeQualifiedType(type, lifetime);
5074     decl->setType(type);
5075   }
5076 
5077   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5078     // Thread-local variables cannot have lifetime.
5079     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5080         var->getTLSKind()) {
5081       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5082         << var->getType();
5083       return true;
5084     }
5085   }
5086 
5087   return false;
5088 }
5089 
5090 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5091   // Ensure that an auto decl is deduced otherwise the checks below might cache
5092   // the wrong linkage.
5093   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5094 
5095   // 'weak' only applies to declarations with external linkage.
5096   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5097     if (!ND.isExternallyVisible()) {
5098       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5099       ND.dropAttr<WeakAttr>();
5100     }
5101   }
5102   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5103     if (ND.isExternallyVisible()) {
5104       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5105       ND.dropAttr<WeakRefAttr>();
5106       ND.dropAttr<AliasAttr>();
5107     }
5108   }
5109 
5110   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5111     if (VD->hasInit()) {
5112       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5113         assert(VD->isThisDeclarationADefinition() &&
5114                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5115         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
5116         VD->dropAttr<AliasAttr>();
5117       }
5118     }
5119   }
5120 
5121   // 'selectany' only applies to externally visible varable declarations.
5122   // It does not apply to functions.
5123   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5124     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5125       S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
5126       ND.dropAttr<SelectAnyAttr>();
5127     }
5128   }
5129 
5130   // dll attributes require external linkage.
5131   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5132     if (!ND.isExternallyVisible()) {
5133       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5134         << &ND << Attr;
5135       ND.setInvalidDecl();
5136     }
5137   }
5138 }
5139 
5140 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5141                                            NamedDecl *NewDecl,
5142                                            bool IsSpecialization) {
5143   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5144     OldDecl = OldTD->getTemplatedDecl();
5145   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5146     NewDecl = NewTD->getTemplatedDecl();
5147 
5148   if (!OldDecl || !NewDecl)
5149     return;
5150 
5151   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5152   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5153   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5154   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5155 
5156   // dllimport and dllexport are inheritable attributes so we have to exclude
5157   // inherited attribute instances.
5158   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5159                     (NewExportAttr && !NewExportAttr->isInherited());
5160 
5161   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5162   // the only exception being explicit specializations.
5163   // Implicitly generated declarations are also excluded for now because there
5164   // is no other way to switch these to use dllimport or dllexport.
5165   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5166 
5167   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5168     // If the declaration hasn't been used yet, allow with a warning for
5169     // free functions and global variables.
5170     bool JustWarn = false;
5171     if (!OldDecl->isUsed() && !OldDecl->isCXXClassMember()) {
5172       auto *VD = dyn_cast<VarDecl>(OldDecl);
5173       if (VD && !VD->getDescribedVarTemplate())
5174         JustWarn = true;
5175       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5176       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5177         JustWarn = true;
5178     }
5179 
5180     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5181                                : diag::err_attribute_dll_redeclaration;
5182     S.Diag(NewDecl->getLocation(), DiagID)
5183         << NewDecl
5184         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5185     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5186     if (!JustWarn) {
5187       NewDecl->setInvalidDecl();
5188       return;
5189     }
5190   }
5191 
5192   // A redeclaration is not allowed to drop a dllimport attribute, the only
5193   // exceptions being inline function definitions, local extern declarations,
5194   // and qualified friend declarations.
5195   // NB: MSVC converts such a declaration to dllexport.
5196   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5197   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5198     // Ignore static data because out-of-line definitions are diagnosed
5199     // separately.
5200     IsStaticDataMember = VD->isStaticDataMember();
5201   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5202     IsInline = FD->isInlined();
5203     IsQualifiedFriend = FD->getQualifier() &&
5204                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5205   }
5206 
5207   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5208       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5209     S.Diag(NewDecl->getLocation(),
5210            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5211       << NewDecl << OldImportAttr;
5212     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5213     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5214     OldDecl->dropAttr<DLLImportAttr>();
5215     NewDecl->dropAttr<DLLImportAttr>();
5216   } else if (IsInline && OldImportAttr &&
5217              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5218     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5219     OldDecl->dropAttr<DLLImportAttr>();
5220     NewDecl->dropAttr<DLLImportAttr>();
5221     S.Diag(NewDecl->getLocation(),
5222            diag::warn_dllimport_dropped_from_inline_function)
5223         << NewDecl << OldImportAttr;
5224   }
5225 }
5226 
5227 /// Given that we are within the definition of the given function,
5228 /// will that definition behave like C99's 'inline', where the
5229 /// definition is discarded except for optimization purposes?
5230 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5231   // Try to avoid calling GetGVALinkageForFunction.
5232 
5233   // All cases of this require the 'inline' keyword.
5234   if (!FD->isInlined()) return false;
5235 
5236   // This is only possible in C++ with the gnu_inline attribute.
5237   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5238     return false;
5239 
5240   // Okay, go ahead and call the relatively-more-expensive function.
5241 
5242 #ifndef NDEBUG
5243   // AST quite reasonably asserts that it's working on a function
5244   // definition.  We don't really have a way to tell it that we're
5245   // currently defining the function, so just lie to it in +Asserts
5246   // builds.  This is an awful hack.
5247   FD->setLazyBody(1);
5248 #endif
5249 
5250   bool isC99Inline =
5251       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5252 
5253 #ifndef NDEBUG
5254   FD->setLazyBody(0);
5255 #endif
5256 
5257   return isC99Inline;
5258 }
5259 
5260 /// Determine whether a variable is extern "C" prior to attaching
5261 /// an initializer. We can't just call isExternC() here, because that
5262 /// will also compute and cache whether the declaration is externally
5263 /// visible, which might change when we attach the initializer.
5264 ///
5265 /// This can only be used if the declaration is known to not be a
5266 /// redeclaration of an internal linkage declaration.
5267 ///
5268 /// For instance:
5269 ///
5270 ///   auto x = []{};
5271 ///
5272 /// Attaching the initializer here makes this declaration not externally
5273 /// visible, because its type has internal linkage.
5274 ///
5275 /// FIXME: This is a hack.
5276 template<typename T>
5277 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5278   if (S.getLangOpts().CPlusPlus) {
5279     // In C++, the overloadable attribute negates the effects of extern "C".
5280     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5281       return false;
5282   }
5283   return D->isExternC();
5284 }
5285 
5286 static bool shouldConsiderLinkage(const VarDecl *VD) {
5287   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5288   if (DC->isFunctionOrMethod())
5289     return VD->hasExternalStorage();
5290   if (DC->isFileContext())
5291     return true;
5292   if (DC->isRecord())
5293     return false;
5294   llvm_unreachable("Unexpected context");
5295 }
5296 
5297 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5298   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5299   if (DC->isFileContext() || DC->isFunctionOrMethod())
5300     return true;
5301   if (DC->isRecord())
5302     return false;
5303   llvm_unreachable("Unexpected context");
5304 }
5305 
5306 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5307                           AttributeList::Kind Kind) {
5308   for (const AttributeList *L = AttrList; L; L = L->getNext())
5309     if (L->getKind() == Kind)
5310       return true;
5311   return false;
5312 }
5313 
5314 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5315                           AttributeList::Kind Kind) {
5316   // Check decl attributes on the DeclSpec.
5317   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5318     return true;
5319 
5320   // Walk the declarator structure, checking decl attributes that were in a type
5321   // position to the decl itself.
5322   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5323     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5324       return true;
5325   }
5326 
5327   // Finally, check attributes on the decl itself.
5328   return hasParsedAttr(S, PD.getAttributes(), Kind);
5329 }
5330 
5331 /// Adjust the \c DeclContext for a function or variable that might be a
5332 /// function-local external declaration.
5333 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5334   if (!DC->isFunctionOrMethod())
5335     return false;
5336 
5337   // If this is a local extern function or variable declared within a function
5338   // template, don't add it into the enclosing namespace scope until it is
5339   // instantiated; it might have a dependent type right now.
5340   if (DC->isDependentContext())
5341     return true;
5342 
5343   // C++11 [basic.link]p7:
5344   //   When a block scope declaration of an entity with linkage is not found to
5345   //   refer to some other declaration, then that entity is a member of the
5346   //   innermost enclosing namespace.
5347   //
5348   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5349   // semantically-enclosing namespace, not a lexically-enclosing one.
5350   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5351     DC = DC->getParent();
5352   return true;
5353 }
5354 
5355 NamedDecl *
5356 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5357                               TypeSourceInfo *TInfo, LookupResult &Previous,
5358                               MultiTemplateParamsArg TemplateParamLists,
5359                               bool &AddToScope) {
5360   QualType R = TInfo->getType();
5361   DeclarationName Name = GetNameForDeclarator(D).getName();
5362 
5363   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5364   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5365 
5366   // dllimport globals without explicit storage class are treated as extern. We
5367   // have to change the storage class this early to get the right DeclContext.
5368   if (SC == SC_None && !DC->isRecord() &&
5369       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5370       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5371     SC = SC_Extern;
5372 
5373   DeclContext *OriginalDC = DC;
5374   bool IsLocalExternDecl = SC == SC_Extern &&
5375                            adjustContextForLocalExternDecl(DC);
5376 
5377   if (getLangOpts().OpenCL) {
5378     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5379     QualType NR = R;
5380     while (NR->isPointerType()) {
5381       if (NR->isFunctionPointerType()) {
5382         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5383         D.setInvalidType();
5384         break;
5385       }
5386       NR = NR->getPointeeType();
5387     }
5388 
5389     if (!getOpenCLOptions().cl_khr_fp16) {
5390       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5391       // half array type (unless the cl_khr_fp16 extension is enabled).
5392       if (Context.getBaseElementType(R)->isHalfType()) {
5393         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5394         D.setInvalidType();
5395       }
5396     }
5397   }
5398 
5399   if (SCSpec == DeclSpec::SCS_mutable) {
5400     // mutable can only appear on non-static class members, so it's always
5401     // an error here
5402     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5403     D.setInvalidType();
5404     SC = SC_None;
5405   }
5406 
5407   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5408       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5409                               D.getDeclSpec().getStorageClassSpecLoc())) {
5410     // In C++11, the 'register' storage class specifier is deprecated.
5411     // Suppress the warning in system macros, it's used in macros in some
5412     // popular C system headers, such as in glibc's htonl() macro.
5413     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5414          diag::warn_deprecated_register)
5415       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5416   }
5417 
5418   IdentifierInfo *II = Name.getAsIdentifierInfo();
5419   if (!II) {
5420     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5421       << Name;
5422     return nullptr;
5423   }
5424 
5425   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5426 
5427   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5428     // C99 6.9p2: The storage-class specifiers auto and register shall not
5429     // appear in the declaration specifiers in an external declaration.
5430     // Global Register+Asm is a GNU extension we support.
5431     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5432       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5433       D.setInvalidType();
5434     }
5435   }
5436 
5437   if (getLangOpts().OpenCL) {
5438     // Set up the special work-group-local storage class for variables in the
5439     // OpenCL __local address space.
5440     if (R.getAddressSpace() == LangAS::opencl_local) {
5441       SC = SC_OpenCLWorkGroupLocal;
5442     }
5443 
5444     // OpenCL v1.2 s6.9.b p4:
5445     // The sampler type cannot be used with the __local and __global address
5446     // space qualifiers.
5447     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5448       R.getAddressSpace() == LangAS::opencl_global)) {
5449       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5450     }
5451 
5452     // OpenCL 1.2 spec, p6.9 r:
5453     // The event type cannot be used to declare a program scope variable.
5454     // The event type cannot be used with the __local, __constant and __global
5455     // address space qualifiers.
5456     if (R->isEventT()) {
5457       if (S->getParent() == nullptr) {
5458         Diag(D.getLocStart(), diag::err_event_t_global_var);
5459         D.setInvalidType();
5460       }
5461 
5462       if (R.getAddressSpace()) {
5463         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5464         D.setInvalidType();
5465       }
5466     }
5467   }
5468 
5469   bool IsExplicitSpecialization = false;
5470   bool IsVariableTemplateSpecialization = false;
5471   bool IsPartialSpecialization = false;
5472   bool IsVariableTemplate = false;
5473   VarDecl *NewVD = nullptr;
5474   VarTemplateDecl *NewTemplate = nullptr;
5475   TemplateParameterList *TemplateParams = nullptr;
5476   if (!getLangOpts().CPlusPlus) {
5477     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5478                             D.getIdentifierLoc(), II,
5479                             R, TInfo, SC);
5480 
5481     if (D.isInvalidType())
5482       NewVD->setInvalidDecl();
5483   } else {
5484     bool Invalid = false;
5485 
5486     if (DC->isRecord() && !CurContext->isRecord()) {
5487       // This is an out-of-line definition of a static data member.
5488       switch (SC) {
5489       case SC_None:
5490         break;
5491       case SC_Static:
5492         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5493              diag::err_static_out_of_line)
5494           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5495         break;
5496       case SC_Auto:
5497       case SC_Register:
5498       case SC_Extern:
5499         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5500         // to names of variables declared in a block or to function parameters.
5501         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5502         // of class members
5503 
5504         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5505              diag::err_storage_class_for_static_member)
5506           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5507         break;
5508       case SC_PrivateExtern:
5509         llvm_unreachable("C storage class in c++!");
5510       case SC_OpenCLWorkGroupLocal:
5511         llvm_unreachable("OpenCL storage class in c++!");
5512       }
5513     }
5514 
5515     if (SC == SC_Static && CurContext->isRecord()) {
5516       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5517         if (RD->isLocalClass())
5518           Diag(D.getIdentifierLoc(),
5519                diag::err_static_data_member_not_allowed_in_local_class)
5520             << Name << RD->getDeclName();
5521 
5522         // C++98 [class.union]p1: If a union contains a static data member,
5523         // the program is ill-formed. C++11 drops this restriction.
5524         if (RD->isUnion())
5525           Diag(D.getIdentifierLoc(),
5526                getLangOpts().CPlusPlus11
5527                  ? diag::warn_cxx98_compat_static_data_member_in_union
5528                  : diag::ext_static_data_member_in_union) << Name;
5529         // We conservatively disallow static data members in anonymous structs.
5530         else if (!RD->getDeclName())
5531           Diag(D.getIdentifierLoc(),
5532                diag::err_static_data_member_not_allowed_in_anon_struct)
5533             << Name << RD->isUnion();
5534       }
5535     }
5536 
5537     // Match up the template parameter lists with the scope specifier, then
5538     // determine whether we have a template or a template specialization.
5539     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5540         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5541         D.getCXXScopeSpec(),
5542         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5543             ? D.getName().TemplateId
5544             : nullptr,
5545         TemplateParamLists,
5546         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5547 
5548     if (TemplateParams) {
5549       if (!TemplateParams->size() &&
5550           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5551         // There is an extraneous 'template<>' for this variable. Complain
5552         // about it, but allow the declaration of the variable.
5553         Diag(TemplateParams->getTemplateLoc(),
5554              diag::err_template_variable_noparams)
5555           << II
5556           << SourceRange(TemplateParams->getTemplateLoc(),
5557                          TemplateParams->getRAngleLoc());
5558         TemplateParams = nullptr;
5559       } else {
5560         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5561           // This is an explicit specialization or a partial specialization.
5562           // FIXME: Check that we can declare a specialization here.
5563           IsVariableTemplateSpecialization = true;
5564           IsPartialSpecialization = TemplateParams->size() > 0;
5565         } else { // if (TemplateParams->size() > 0)
5566           // This is a template declaration.
5567           IsVariableTemplate = true;
5568 
5569           // Check that we can declare a template here.
5570           if (CheckTemplateDeclScope(S, TemplateParams))
5571             return nullptr;
5572 
5573           // Only C++1y supports variable templates (N3651).
5574           Diag(D.getIdentifierLoc(),
5575                getLangOpts().CPlusPlus14
5576                    ? diag::warn_cxx11_compat_variable_template
5577                    : diag::ext_variable_template);
5578         }
5579       }
5580     } else {
5581       assert(
5582           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5583           "should have a 'template<>' for this decl");
5584     }
5585 
5586     if (IsVariableTemplateSpecialization) {
5587       SourceLocation TemplateKWLoc =
5588           TemplateParamLists.size() > 0
5589               ? TemplateParamLists[0]->getTemplateLoc()
5590               : SourceLocation();
5591       DeclResult Res = ActOnVarTemplateSpecialization(
5592           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5593           IsPartialSpecialization);
5594       if (Res.isInvalid())
5595         return nullptr;
5596       NewVD = cast<VarDecl>(Res.get());
5597       AddToScope = false;
5598     } else
5599       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5600                               D.getIdentifierLoc(), II, R, TInfo, SC);
5601 
5602     // If this is supposed to be a variable template, create it as such.
5603     if (IsVariableTemplate) {
5604       NewTemplate =
5605           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5606                                   TemplateParams, NewVD);
5607       NewVD->setDescribedVarTemplate(NewTemplate);
5608     }
5609 
5610     // If this decl has an auto type in need of deduction, make a note of the
5611     // Decl so we can diagnose uses of it in its own initializer.
5612     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5613       ParsingInitForAutoVars.insert(NewVD);
5614 
5615     if (D.isInvalidType() || Invalid) {
5616       NewVD->setInvalidDecl();
5617       if (NewTemplate)
5618         NewTemplate->setInvalidDecl();
5619     }
5620 
5621     SetNestedNameSpecifier(NewVD, D);
5622 
5623     // If we have any template parameter lists that don't directly belong to
5624     // the variable (matching the scope specifier), store them.
5625     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5626     if (TemplateParamLists.size() > VDTemplateParamLists)
5627       NewVD->setTemplateParameterListsInfo(
5628           Context, TemplateParamLists.size() - VDTemplateParamLists,
5629           TemplateParamLists.data());
5630 
5631     if (D.getDeclSpec().isConstexprSpecified())
5632       NewVD->setConstexpr(true);
5633   }
5634 
5635   // Set the lexical context. If the declarator has a C++ scope specifier, the
5636   // lexical context will be different from the semantic context.
5637   NewVD->setLexicalDeclContext(CurContext);
5638   if (NewTemplate)
5639     NewTemplate->setLexicalDeclContext(CurContext);
5640 
5641   if (IsLocalExternDecl)
5642     NewVD->setLocalExternDecl();
5643 
5644   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5645     // C++11 [dcl.stc]p4:
5646     //   When thread_local is applied to a variable of block scope the
5647     //   storage-class-specifier static is implied if it does not appear
5648     //   explicitly.
5649     // Core issue: 'static' is not implied if the variable is declared
5650     //   'extern'.
5651     if (NewVD->hasLocalStorage() &&
5652         (SCSpec != DeclSpec::SCS_unspecified ||
5653          TSCS != DeclSpec::TSCS_thread_local ||
5654          !DC->isFunctionOrMethod()))
5655       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5656            diag::err_thread_non_global)
5657         << DeclSpec::getSpecifierName(TSCS);
5658     else if (!Context.getTargetInfo().isTLSSupported())
5659       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5660            diag::err_thread_unsupported);
5661     else
5662       NewVD->setTSCSpec(TSCS);
5663   }
5664 
5665   // C99 6.7.4p3
5666   //   An inline definition of a function with external linkage shall
5667   //   not contain a definition of a modifiable object with static or
5668   //   thread storage duration...
5669   // We only apply this when the function is required to be defined
5670   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5671   // that a local variable with thread storage duration still has to
5672   // be marked 'static'.  Also note that it's possible to get these
5673   // semantics in C++ using __attribute__((gnu_inline)).
5674   if (SC == SC_Static && S->getFnParent() != nullptr &&
5675       !NewVD->getType().isConstQualified()) {
5676     FunctionDecl *CurFD = getCurFunctionDecl();
5677     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5678       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5679            diag::warn_static_local_in_extern_inline);
5680       MaybeSuggestAddingStaticToDecl(CurFD);
5681     }
5682   }
5683 
5684   if (D.getDeclSpec().isModulePrivateSpecified()) {
5685     if (IsVariableTemplateSpecialization)
5686       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5687           << (IsPartialSpecialization ? 1 : 0)
5688           << FixItHint::CreateRemoval(
5689                  D.getDeclSpec().getModulePrivateSpecLoc());
5690     else if (IsExplicitSpecialization)
5691       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5692         << 2
5693         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5694     else if (NewVD->hasLocalStorage())
5695       Diag(NewVD->getLocation(), diag::err_module_private_local)
5696         << 0 << NewVD->getDeclName()
5697         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5698         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5699     else {
5700       NewVD->setModulePrivate();
5701       if (NewTemplate)
5702         NewTemplate->setModulePrivate();
5703     }
5704   }
5705 
5706   // Handle attributes prior to checking for duplicates in MergeVarDecl
5707   ProcessDeclAttributes(S, NewVD, D);
5708 
5709   if (getLangOpts().CUDA) {
5710     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5711     // storage [duration]."
5712     if (SC == SC_None && S->getFnParent() != nullptr &&
5713         (NewVD->hasAttr<CUDASharedAttr>() ||
5714          NewVD->hasAttr<CUDAConstantAttr>())) {
5715       NewVD->setStorageClass(SC_Static);
5716     }
5717   }
5718 
5719   // Ensure that dllimport globals without explicit storage class are treated as
5720   // extern. The storage class is set above using parsed attributes. Now we can
5721   // check the VarDecl itself.
5722   assert(!NewVD->hasAttr<DLLImportAttr>() ||
5723          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5724          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5725 
5726   // In auto-retain/release, infer strong retension for variables of
5727   // retainable type.
5728   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5729     NewVD->setInvalidDecl();
5730 
5731   // Handle GNU asm-label extension (encoded as an attribute).
5732   if (Expr *E = (Expr*)D.getAsmLabel()) {
5733     // The parser guarantees this is a string.
5734     StringLiteral *SE = cast<StringLiteral>(E);
5735     StringRef Label = SE->getString();
5736     if (S->getFnParent() != nullptr) {
5737       switch (SC) {
5738       case SC_None:
5739       case SC_Auto:
5740         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5741         break;
5742       case SC_Register:
5743         // Local Named register
5744         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5745           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5746         break;
5747       case SC_Static:
5748       case SC_Extern:
5749       case SC_PrivateExtern:
5750       case SC_OpenCLWorkGroupLocal:
5751         break;
5752       }
5753     } else if (SC == SC_Register) {
5754       // Global Named register
5755       if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5756         Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5757       if (!R->isIntegralType(Context) && !R->isPointerType()) {
5758         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
5759         NewVD->setInvalidDecl(true);
5760       }
5761     }
5762 
5763     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
5764                                                 Context, Label, 0));
5765   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5766     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5767       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5768     if (I != ExtnameUndeclaredIdentifiers.end()) {
5769       NewVD->addAttr(I->second);
5770       ExtnameUndeclaredIdentifiers.erase(I);
5771     }
5772   }
5773 
5774   // Diagnose shadowed variables before filtering for scope.
5775   if (D.getCXXScopeSpec().isEmpty())
5776     CheckShadow(S, NewVD, Previous);
5777 
5778   // Don't consider existing declarations that are in a different
5779   // scope and are out-of-semantic-context declarations (if the new
5780   // declaration has linkage).
5781   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5782                        D.getCXXScopeSpec().isNotEmpty() ||
5783                        IsExplicitSpecialization ||
5784                        IsVariableTemplateSpecialization);
5785 
5786   // Check whether the previous declaration is in the same block scope. This
5787   // affects whether we merge types with it, per C++11 [dcl.array]p3.
5788   if (getLangOpts().CPlusPlus &&
5789       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5790     NewVD->setPreviousDeclInSameBlockScope(
5791         Previous.isSingleResult() && !Previous.isShadowed() &&
5792         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
5793 
5794   if (!getLangOpts().CPlusPlus) {
5795     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5796   } else {
5797     // If this is an explicit specialization of a static data member, check it.
5798     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5799         CheckMemberSpecialization(NewVD, Previous))
5800       NewVD->setInvalidDecl();
5801 
5802     // Merge the decl with the existing one if appropriate.
5803     if (!Previous.empty()) {
5804       if (Previous.isSingleResult() &&
5805           isa<FieldDecl>(Previous.getFoundDecl()) &&
5806           D.getCXXScopeSpec().isSet()) {
5807         // The user tried to define a non-static data member
5808         // out-of-line (C++ [dcl.meaning]p1).
5809         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5810           << D.getCXXScopeSpec().getRange();
5811         Previous.clear();
5812         NewVD->setInvalidDecl();
5813       }
5814     } else if (D.getCXXScopeSpec().isSet()) {
5815       // No previous declaration in the qualifying scope.
5816       Diag(D.getIdentifierLoc(), diag::err_no_member)
5817         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
5818         << D.getCXXScopeSpec().getRange();
5819       NewVD->setInvalidDecl();
5820     }
5821 
5822     if (!IsVariableTemplateSpecialization)
5823       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5824 
5825     if (NewTemplate) {
5826       VarTemplateDecl *PrevVarTemplate =
5827           NewVD->getPreviousDecl()
5828               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5829               : nullptr;
5830 
5831       // Check the template parameter list of this declaration, possibly
5832       // merging in the template parameter list from the previous variable
5833       // template declaration.
5834       if (CheckTemplateParameterList(
5835               TemplateParams,
5836               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5837                               : nullptr,
5838               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5839                DC->isDependentContext())
5840                   ? TPC_ClassTemplateMember
5841                   : TPC_VarTemplate))
5842         NewVD->setInvalidDecl();
5843 
5844       // If we are providing an explicit specialization of a static variable
5845       // template, make a note of that.
5846       if (PrevVarTemplate &&
5847           PrevVarTemplate->getInstantiatedFromMemberTemplate())
5848         PrevVarTemplate->setMemberSpecialization();
5849     }
5850   }
5851 
5852   ProcessPragmaWeak(S, NewVD);
5853 
5854   // If this is the first declaration of an extern C variable, update
5855   // the map of such variables.
5856   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
5857       isIncompleteDeclExternC(*this, NewVD))
5858     RegisterLocallyScopedExternCDecl(NewVD, S);
5859 
5860   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5861     Decl *ManglingContextDecl;
5862     if (MangleNumberingContext *MCtx =
5863             getCurrentMangleNumberContext(NewVD->getDeclContext(),
5864                                           ManglingContextDecl)) {
5865       Context.setManglingNumber(
5866           NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
5867       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5868     }
5869   }
5870 
5871   if (D.isRedeclaration() && !Previous.empty()) {
5872     checkDLLAttributeRedeclaration(
5873         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
5874         IsExplicitSpecialization);
5875   }
5876 
5877   if (NewTemplate) {
5878     if (NewVD->isInvalidDecl())
5879       NewTemplate->setInvalidDecl();
5880     ActOnDocumentableDecl(NewTemplate);
5881     return NewTemplate;
5882   }
5883 
5884   return NewVD;
5885 }
5886 
5887 /// \brief Diagnose variable or built-in function shadowing.  Implements
5888 /// -Wshadow.
5889 ///
5890 /// This method is called whenever a VarDecl is added to a "useful"
5891 /// scope.
5892 ///
5893 /// \param S the scope in which the shadowing name is being declared
5894 /// \param R the lookup of the name
5895 ///
5896 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
5897   // Return if warning is ignored.
5898   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
5899     return;
5900 
5901   // Don't diagnose declarations at file scope.
5902   if (D->hasGlobalStorage())
5903     return;
5904 
5905   DeclContext *NewDC = D->getDeclContext();
5906 
5907   // Only diagnose if we're shadowing an unambiguous field or variable.
5908   if (R.getResultKind() != LookupResult::Found)
5909     return;
5910 
5911   NamedDecl* ShadowedDecl = R.getFoundDecl();
5912   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5913     return;
5914 
5915   // Fields are not shadowed by variables in C++ static methods.
5916   if (isa<FieldDecl>(ShadowedDecl))
5917     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5918       if (MD->isStatic())
5919         return;
5920 
5921   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5922     if (shadowedVar->isExternC()) {
5923       // For shadowing external vars, make sure that we point to the global
5924       // declaration, not a locally scoped extern declaration.
5925       for (auto I : shadowedVar->redecls())
5926         if (I->isFileVarDecl()) {
5927           ShadowedDecl = I;
5928           break;
5929         }
5930     }
5931 
5932   DeclContext *OldDC = ShadowedDecl->getDeclContext();
5933 
5934   // Only warn about certain kinds of shadowing for class members.
5935   if (NewDC && NewDC->isRecord()) {
5936     // In particular, don't warn about shadowing non-class members.
5937     if (!OldDC->isRecord())
5938       return;
5939 
5940     // TODO: should we warn about static data members shadowing
5941     // static data members from base classes?
5942 
5943     // TODO: don't diagnose for inaccessible shadowed members.
5944     // This is hard to do perfectly because we might friend the
5945     // shadowing context, but that's just a false negative.
5946   }
5947 
5948   // Determine what kind of declaration we're shadowing.
5949   unsigned Kind;
5950   if (isa<RecordDecl>(OldDC)) {
5951     if (isa<FieldDecl>(ShadowedDecl))
5952       Kind = 3; // field
5953     else
5954       Kind = 2; // static data member
5955   } else if (OldDC->isFileContext())
5956     Kind = 1; // global
5957   else
5958     Kind = 0; // local
5959 
5960   DeclarationName Name = R.getLookupName();
5961 
5962   // Emit warning and note.
5963   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5964     return;
5965   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
5966   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5967 }
5968 
5969 /// \brief Check -Wshadow without the advantage of a previous lookup.
5970 void Sema::CheckShadow(Scope *S, VarDecl *D) {
5971   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
5972     return;
5973 
5974   LookupResult R(*this, D->getDeclName(), D->getLocation(),
5975                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5976   LookupName(R, S);
5977   CheckShadow(S, D, R);
5978 }
5979 
5980 /// Check for conflict between this global or extern "C" declaration and
5981 /// previous global or extern "C" declarations. This is only used in C++.
5982 template<typename T>
5983 static bool checkGlobalOrExternCConflict(
5984     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5985   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5986   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
5987 
5988   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5989     // The common case: this global doesn't conflict with any extern "C"
5990     // declaration.
5991     return false;
5992   }
5993 
5994   if (Prev) {
5995     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5996       // Both the old and new declarations have C language linkage. This is a
5997       // redeclaration.
5998       Previous.clear();
5999       Previous.addDecl(Prev);
6000       return true;
6001     }
6002 
6003     // This is a global, non-extern "C" declaration, and there is a previous
6004     // non-global extern "C" declaration. Diagnose if this is a variable
6005     // declaration.
6006     if (!isa<VarDecl>(ND))
6007       return false;
6008   } else {
6009     // The declaration is extern "C". Check for any declaration in the
6010     // translation unit which might conflict.
6011     if (IsGlobal) {
6012       // We have already performed the lookup into the translation unit.
6013       IsGlobal = false;
6014       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6015            I != E; ++I) {
6016         if (isa<VarDecl>(*I)) {
6017           Prev = *I;
6018           break;
6019         }
6020       }
6021     } else {
6022       DeclContext::lookup_result R =
6023           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6024       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6025            I != E; ++I) {
6026         if (isa<VarDecl>(*I)) {
6027           Prev = *I;
6028           break;
6029         }
6030         // FIXME: If we have any other entity with this name in global scope,
6031         // the declaration is ill-formed, but that is a defect: it breaks the
6032         // 'stat' hack, for instance. Only variables can have mangled name
6033         // clashes with extern "C" declarations, so only they deserve a
6034         // diagnostic.
6035       }
6036     }
6037 
6038     if (!Prev)
6039       return false;
6040   }
6041 
6042   // Use the first declaration's location to ensure we point at something which
6043   // is lexically inside an extern "C" linkage-spec.
6044   assert(Prev && "should have found a previous declaration to diagnose");
6045   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6046     Prev = FD->getFirstDecl();
6047   else
6048     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6049 
6050   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6051     << IsGlobal << ND;
6052   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6053     << IsGlobal;
6054   return false;
6055 }
6056 
6057 /// Apply special rules for handling extern "C" declarations. Returns \c true
6058 /// if we have found that this is a redeclaration of some prior entity.
6059 ///
6060 /// Per C++ [dcl.link]p6:
6061 ///   Two declarations [for a function or variable] with C language linkage
6062 ///   with the same name that appear in different scopes refer to the same
6063 ///   [entity]. An entity with C language linkage shall not be declared with
6064 ///   the same name as an entity in global scope.
6065 template<typename T>
6066 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6067                                                   LookupResult &Previous) {
6068   if (!S.getLangOpts().CPlusPlus) {
6069     // In C, when declaring a global variable, look for a corresponding 'extern'
6070     // variable declared in function scope. We don't need this in C++, because
6071     // we find local extern decls in the surrounding file-scope DeclContext.
6072     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6073       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6074         Previous.clear();
6075         Previous.addDecl(Prev);
6076         return true;
6077       }
6078     }
6079     return false;
6080   }
6081 
6082   // A declaration in the translation unit can conflict with an extern "C"
6083   // declaration.
6084   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6085     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6086 
6087   // An extern "C" declaration can conflict with a declaration in the
6088   // translation unit or can be a redeclaration of an extern "C" declaration
6089   // in another scope.
6090   if (isIncompleteDeclExternC(S,ND))
6091     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6092 
6093   // Neither global nor extern "C": nothing to do.
6094   return false;
6095 }
6096 
6097 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6098   // If the decl is already known invalid, don't check it.
6099   if (NewVD->isInvalidDecl())
6100     return;
6101 
6102   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6103   QualType T = TInfo->getType();
6104 
6105   // Defer checking an 'auto' type until its initializer is attached.
6106   if (T->isUndeducedType())
6107     return;
6108 
6109   if (NewVD->hasAttrs())
6110     CheckAlignasUnderalignment(NewVD);
6111 
6112   if (T->isObjCObjectType()) {
6113     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6114       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6115     T = Context.getObjCObjectPointerType(T);
6116     NewVD->setType(T);
6117   }
6118 
6119   // Emit an error if an address space was applied to decl with local storage.
6120   // This includes arrays of objects with address space qualifiers, but not
6121   // automatic variables that point to other address spaces.
6122   // ISO/IEC TR 18037 S5.1.2
6123   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6124     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6125     NewVD->setInvalidDecl();
6126     return;
6127   }
6128 
6129   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6130   // __constant address space.
6131   if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
6132       && T.getAddressSpace() != LangAS::opencl_constant
6133       && !T->isSamplerT()){
6134     Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
6135     NewVD->setInvalidDecl();
6136     return;
6137   }
6138 
6139   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6140   // scope.
6141   if ((getLangOpts().OpenCLVersion >= 120)
6142       && NewVD->isStaticLocal()) {
6143     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6144     NewVD->setInvalidDecl();
6145     return;
6146   }
6147 
6148   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6149       && !NewVD->hasAttr<BlocksAttr>()) {
6150     if (getLangOpts().getGC() != LangOptions::NonGC)
6151       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6152     else {
6153       assert(!getLangOpts().ObjCAutoRefCount);
6154       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6155     }
6156   }
6157 
6158   bool isVM = T->isVariablyModifiedType();
6159   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6160       NewVD->hasAttr<BlocksAttr>())
6161     getCurFunction()->setHasBranchProtectedScope();
6162 
6163   if ((isVM && NewVD->hasLinkage()) ||
6164       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6165     bool SizeIsNegative;
6166     llvm::APSInt Oversized;
6167     TypeSourceInfo *FixedTInfo =
6168       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6169                                                     SizeIsNegative, Oversized);
6170     if (!FixedTInfo && T->isVariableArrayType()) {
6171       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6172       // FIXME: This won't give the correct result for
6173       // int a[10][n];
6174       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6175 
6176       if (NewVD->isFileVarDecl())
6177         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6178         << SizeRange;
6179       else if (NewVD->isStaticLocal())
6180         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6181         << SizeRange;
6182       else
6183         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6184         << SizeRange;
6185       NewVD->setInvalidDecl();
6186       return;
6187     }
6188 
6189     if (!FixedTInfo) {
6190       if (NewVD->isFileVarDecl())
6191         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6192       else
6193         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6194       NewVD->setInvalidDecl();
6195       return;
6196     }
6197 
6198     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6199     NewVD->setType(FixedTInfo->getType());
6200     NewVD->setTypeSourceInfo(FixedTInfo);
6201   }
6202 
6203   if (T->isVoidType()) {
6204     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6205     //                    of objects and functions.
6206     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6207       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6208         << T;
6209       NewVD->setInvalidDecl();
6210       return;
6211     }
6212   }
6213 
6214   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6215     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6216     NewVD->setInvalidDecl();
6217     return;
6218   }
6219 
6220   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6221     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6222     NewVD->setInvalidDecl();
6223     return;
6224   }
6225 
6226   if (NewVD->isConstexpr() && !T->isDependentType() &&
6227       RequireLiteralType(NewVD->getLocation(), T,
6228                          diag::err_constexpr_var_non_literal)) {
6229     NewVD->setInvalidDecl();
6230     return;
6231   }
6232 }
6233 
6234 /// \brief Perform semantic checking on a newly-created variable
6235 /// declaration.
6236 ///
6237 /// This routine performs all of the type-checking required for a
6238 /// variable declaration once it has been built. It is used both to
6239 /// check variables after they have been parsed and their declarators
6240 /// have been translated into a declaration, and to check variables
6241 /// that have been instantiated from a template.
6242 ///
6243 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6244 ///
6245 /// Returns true if the variable declaration is a redeclaration.
6246 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6247   CheckVariableDeclarationType(NewVD);
6248 
6249   // If the decl is already known invalid, don't check it.
6250   if (NewVD->isInvalidDecl())
6251     return false;
6252 
6253   // If we did not find anything by this name, look for a non-visible
6254   // extern "C" declaration with the same name.
6255   if (Previous.empty() &&
6256       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6257     Previous.setShadowed();
6258 
6259   // Filter out any non-conflicting previous declarations.
6260   filterNonConflictingPreviousDecls(Context, NewVD, Previous);
6261 
6262   if (!Previous.empty()) {
6263     MergeVarDecl(NewVD, Previous);
6264     return true;
6265   }
6266   return false;
6267 }
6268 
6269 /// \brief Data used with FindOverriddenMethod
6270 struct FindOverriddenMethodData {
6271   Sema *S;
6272   CXXMethodDecl *Method;
6273 };
6274 
6275 /// \brief Member lookup function that determines whether a given C++
6276 /// method overrides a method in a base class, to be used with
6277 /// CXXRecordDecl::lookupInBases().
6278 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
6279                                  CXXBasePath &Path,
6280                                  void *UserData) {
6281   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6282 
6283   FindOverriddenMethodData *Data
6284     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
6285 
6286   DeclarationName Name = Data->Method->getDeclName();
6287 
6288   // FIXME: Do we care about other names here too?
6289   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6290     // We really want to find the base class destructor here.
6291     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
6292     CanQualType CT = Data->S->Context.getCanonicalType(T);
6293 
6294     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
6295   }
6296 
6297   for (Path.Decls = BaseRecord->lookup(Name);
6298        !Path.Decls.empty();
6299        Path.Decls = Path.Decls.slice(1)) {
6300     NamedDecl *D = Path.Decls.front();
6301     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6302       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
6303         return true;
6304     }
6305   }
6306 
6307   return false;
6308 }
6309 
6310 namespace {
6311   enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6312 }
6313 /// \brief Report an error regarding overriding, along with any relevant
6314 /// overriden methods.
6315 ///
6316 /// \param DiagID the primary error to report.
6317 /// \param MD the overriding method.
6318 /// \param OEK which overrides to include as notes.
6319 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6320                             OverrideErrorKind OEK = OEK_All) {
6321   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6322   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6323                                       E = MD->end_overridden_methods();
6324        I != E; ++I) {
6325     // This check (& the OEK parameter) could be replaced by a predicate, but
6326     // without lambdas that would be overkill. This is still nicer than writing
6327     // out the diag loop 3 times.
6328     if ((OEK == OEK_All) ||
6329         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6330         (OEK == OEK_Deleted && (*I)->isDeleted()))
6331       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6332   }
6333 }
6334 
6335 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6336 /// and if so, check that it's a valid override and remember it.
6337 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6338   // Look for methods in base classes that this method might override.
6339   CXXBasePaths Paths;
6340   FindOverriddenMethodData Data;
6341   Data.Method = MD;
6342   Data.S = this;
6343   bool hasDeletedOverridenMethods = false;
6344   bool hasNonDeletedOverridenMethods = false;
6345   bool AddedAny = false;
6346   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
6347     for (auto *I : Paths.found_decls()) {
6348       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6349         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6350         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6351             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6352             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6353             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6354           hasDeletedOverridenMethods |= OldMD->isDeleted();
6355           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6356           AddedAny = true;
6357         }
6358       }
6359     }
6360   }
6361 
6362   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6363     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6364   }
6365   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6366     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6367   }
6368 
6369   return AddedAny;
6370 }
6371 
6372 namespace {
6373   // Struct for holding all of the extra arguments needed by
6374   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6375   struct ActOnFDArgs {
6376     Scope *S;
6377     Declarator &D;
6378     MultiTemplateParamsArg TemplateParamLists;
6379     bool AddToScope;
6380   };
6381 }
6382 
6383 namespace {
6384 
6385 // Callback to only accept typo corrections that have a non-zero edit distance.
6386 // Also only accept corrections that have the same parent decl.
6387 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6388  public:
6389   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6390                             CXXRecordDecl *Parent)
6391       : Context(Context), OriginalFD(TypoFD),
6392         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6393 
6394   bool ValidateCandidate(const TypoCorrection &candidate) override {
6395     if (candidate.getEditDistance() == 0)
6396       return false;
6397 
6398     SmallVector<unsigned, 1> MismatchedParams;
6399     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6400                                           CDeclEnd = candidate.end();
6401          CDecl != CDeclEnd; ++CDecl) {
6402       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6403 
6404       if (FD && !FD->hasBody() &&
6405           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6406         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6407           CXXRecordDecl *Parent = MD->getParent();
6408           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6409             return true;
6410         } else if (!ExpectedParent) {
6411           return true;
6412         }
6413       }
6414     }
6415 
6416     return false;
6417   }
6418 
6419  private:
6420   ASTContext &Context;
6421   FunctionDecl *OriginalFD;
6422   CXXRecordDecl *ExpectedParent;
6423 };
6424 
6425 }
6426 
6427 /// \brief Generate diagnostics for an invalid function redeclaration.
6428 ///
6429 /// This routine handles generating the diagnostic messages for an invalid
6430 /// function redeclaration, including finding possible similar declarations
6431 /// or performing typo correction if there are no previous declarations with
6432 /// the same name.
6433 ///
6434 /// Returns a NamedDecl iff typo correction was performed and substituting in
6435 /// the new declaration name does not cause new errors.
6436 static NamedDecl *DiagnoseInvalidRedeclaration(
6437     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6438     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6439   DeclarationName Name = NewFD->getDeclName();
6440   DeclContext *NewDC = NewFD->getDeclContext();
6441   SmallVector<unsigned, 1> MismatchedParams;
6442   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6443   TypoCorrection Correction;
6444   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6445   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6446                                    : diag::err_member_decl_does_not_match;
6447   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6448                     IsLocalFriend ? Sema::LookupLocalFriendName
6449                                   : Sema::LookupOrdinaryName,
6450                     Sema::ForRedeclaration);
6451 
6452   NewFD->setInvalidDecl();
6453   if (IsLocalFriend)
6454     SemaRef.LookupName(Prev, S);
6455   else
6456     SemaRef.LookupQualifiedName(Prev, NewDC);
6457   assert(!Prev.isAmbiguous() &&
6458          "Cannot have an ambiguity in previous-declaration lookup");
6459   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6460   if (!Prev.empty()) {
6461     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6462          Func != FuncEnd; ++Func) {
6463       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6464       if (FD &&
6465           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6466         // Add 1 to the index so that 0 can mean the mismatch didn't
6467         // involve a parameter
6468         unsigned ParamNum =
6469             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6470         NearMatches.push_back(std::make_pair(FD, ParamNum));
6471       }
6472     }
6473   // If the qualified name lookup yielded nothing, try typo correction
6474   } else if ((Correction = SemaRef.CorrectTypo(
6475                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6476                   &ExtraArgs.D.getCXXScopeSpec(),
6477                   llvm::make_unique<DifferentNameValidatorCCC>(
6478                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6479                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6480     // Set up everything for the call to ActOnFunctionDeclarator
6481     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6482                               ExtraArgs.D.getIdentifierLoc());
6483     Previous.clear();
6484     Previous.setLookupName(Correction.getCorrection());
6485     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6486                                     CDeclEnd = Correction.end();
6487          CDecl != CDeclEnd; ++CDecl) {
6488       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6489       if (FD && !FD->hasBody() &&
6490           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6491         Previous.addDecl(FD);
6492       }
6493     }
6494     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6495 
6496     NamedDecl *Result;
6497     // Retry building the function declaration with the new previous
6498     // declarations, and with errors suppressed.
6499     {
6500       // Trap errors.
6501       Sema::SFINAETrap Trap(SemaRef);
6502 
6503       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6504       // pieces need to verify the typo-corrected C++ declaration and hopefully
6505       // eliminate the need for the parameter pack ExtraArgs.
6506       Result = SemaRef.ActOnFunctionDeclarator(
6507           ExtraArgs.S, ExtraArgs.D,
6508           Correction.getCorrectionDecl()->getDeclContext(),
6509           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6510           ExtraArgs.AddToScope);
6511 
6512       if (Trap.hasErrorOccurred())
6513         Result = nullptr;
6514     }
6515 
6516     if (Result) {
6517       // Determine which correction we picked.
6518       Decl *Canonical = Result->getCanonicalDecl();
6519       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6520            I != E; ++I)
6521         if ((*I)->getCanonicalDecl() == Canonical)
6522           Correction.setCorrectionDecl(*I);
6523 
6524       SemaRef.diagnoseTypo(
6525           Correction,
6526           SemaRef.PDiag(IsLocalFriend
6527                           ? diag::err_no_matching_local_friend_suggest
6528                           : diag::err_member_decl_does_not_match_suggest)
6529             << Name << NewDC << IsDefinition);
6530       return Result;
6531     }
6532 
6533     // Pretend the typo correction never occurred
6534     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6535                               ExtraArgs.D.getIdentifierLoc());
6536     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6537     Previous.clear();
6538     Previous.setLookupName(Name);
6539   }
6540 
6541   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6542       << Name << NewDC << IsDefinition << NewFD->getLocation();
6543 
6544   bool NewFDisConst = false;
6545   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6546     NewFDisConst = NewMD->isConst();
6547 
6548   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6549        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6550        NearMatch != NearMatchEnd; ++NearMatch) {
6551     FunctionDecl *FD = NearMatch->first;
6552     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6553     bool FDisConst = MD && MD->isConst();
6554     bool IsMember = MD || !IsLocalFriend;
6555 
6556     // FIXME: These notes are poorly worded for the local friend case.
6557     if (unsigned Idx = NearMatch->second) {
6558       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6559       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6560       if (Loc.isInvalid()) Loc = FD->getLocation();
6561       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6562                                  : diag::note_local_decl_close_param_match)
6563         << Idx << FDParam->getType()
6564         << NewFD->getParamDecl(Idx - 1)->getType();
6565     } else if (FDisConst != NewFDisConst) {
6566       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6567           << NewFDisConst << FD->getSourceRange().getEnd();
6568     } else
6569       SemaRef.Diag(FD->getLocation(),
6570                    IsMember ? diag::note_member_def_close_match
6571                             : diag::note_local_decl_close_match);
6572   }
6573   return nullptr;
6574 }
6575 
6576 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
6577   switch (D.getDeclSpec().getStorageClassSpec()) {
6578   default: llvm_unreachable("Unknown storage class!");
6579   case DeclSpec::SCS_auto:
6580   case DeclSpec::SCS_register:
6581   case DeclSpec::SCS_mutable:
6582     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6583                  diag::err_typecheck_sclass_func);
6584     D.setInvalidType();
6585     break;
6586   case DeclSpec::SCS_unspecified: break;
6587   case DeclSpec::SCS_extern:
6588     if (D.getDeclSpec().isExternInLinkageSpec())
6589       return SC_None;
6590     return SC_Extern;
6591   case DeclSpec::SCS_static: {
6592     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6593       // C99 6.7.1p5:
6594       //   The declaration of an identifier for a function that has
6595       //   block scope shall have no explicit storage-class specifier
6596       //   other than extern
6597       // See also (C++ [dcl.stc]p4).
6598       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6599                    diag::err_static_block_func);
6600       break;
6601     } else
6602       return SC_Static;
6603   }
6604   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6605   }
6606 
6607   // No explicit storage class has already been returned
6608   return SC_None;
6609 }
6610 
6611 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6612                                            DeclContext *DC, QualType &R,
6613                                            TypeSourceInfo *TInfo,
6614                                            StorageClass SC,
6615                                            bool &IsVirtualOkay) {
6616   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6617   DeclarationName Name = NameInfo.getName();
6618 
6619   FunctionDecl *NewFD = nullptr;
6620   bool isInline = D.getDeclSpec().isInlineSpecified();
6621 
6622   if (!SemaRef.getLangOpts().CPlusPlus) {
6623     // Determine whether the function was written with a
6624     // prototype. This true when:
6625     //   - there is a prototype in the declarator, or
6626     //   - the type R of the function is some kind of typedef or other reference
6627     //     to a type name (which eventually refers to a function type).
6628     bool HasPrototype =
6629       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6630       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6631 
6632     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6633                                  D.getLocStart(), NameInfo, R,
6634                                  TInfo, SC, isInline,
6635                                  HasPrototype, false);
6636     if (D.isInvalidType())
6637       NewFD->setInvalidDecl();
6638 
6639     return NewFD;
6640   }
6641 
6642   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6643   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6644 
6645   // Check that the return type is not an abstract class type.
6646   // For record types, this is done by the AbstractClassUsageDiagnoser once
6647   // the class has been completely parsed.
6648   if (!DC->isRecord() &&
6649       SemaRef.RequireNonAbstractType(
6650           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6651           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
6652     D.setInvalidType();
6653 
6654   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6655     // This is a C++ constructor declaration.
6656     assert(DC->isRecord() &&
6657            "Constructors can only be declared in a member context");
6658 
6659     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6660     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6661                                       D.getLocStart(), NameInfo,
6662                                       R, TInfo, isExplicit, isInline,
6663                                       /*isImplicitlyDeclared=*/false,
6664                                       isConstexpr);
6665 
6666   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6667     // This is a C++ destructor declaration.
6668     if (DC->isRecord()) {
6669       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6670       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6671       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6672                                         SemaRef.Context, Record,
6673                                         D.getLocStart(),
6674                                         NameInfo, R, TInfo, isInline,
6675                                         /*isImplicitlyDeclared=*/false);
6676 
6677       // If the class is complete, then we now create the implicit exception
6678       // specification. If the class is incomplete or dependent, we can't do
6679       // it yet.
6680       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6681           Record->getDefinition() && !Record->isBeingDefined() &&
6682           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6683         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6684       }
6685 
6686       IsVirtualOkay = true;
6687       return NewDD;
6688 
6689     } else {
6690       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6691       D.setInvalidType();
6692 
6693       // Create a FunctionDecl to satisfy the function definition parsing
6694       // code path.
6695       return FunctionDecl::Create(SemaRef.Context, DC,
6696                                   D.getLocStart(),
6697                                   D.getIdentifierLoc(), Name, R, TInfo,
6698                                   SC, isInline,
6699                                   /*hasPrototype=*/true, isConstexpr);
6700     }
6701 
6702   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6703     if (!DC->isRecord()) {
6704       SemaRef.Diag(D.getIdentifierLoc(),
6705            diag::err_conv_function_not_member);
6706       return nullptr;
6707     }
6708 
6709     SemaRef.CheckConversionDeclarator(D, R, SC);
6710     IsVirtualOkay = true;
6711     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6712                                      D.getLocStart(), NameInfo,
6713                                      R, TInfo, isInline, isExplicit,
6714                                      isConstexpr, SourceLocation());
6715 
6716   } else if (DC->isRecord()) {
6717     // If the name of the function is the same as the name of the record,
6718     // then this must be an invalid constructor that has a return type.
6719     // (The parser checks for a return type and makes the declarator a
6720     // constructor if it has no return type).
6721     if (Name.getAsIdentifierInfo() &&
6722         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6723       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6724         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6725         << SourceRange(D.getIdentifierLoc());
6726       return nullptr;
6727     }
6728 
6729     // This is a C++ method declaration.
6730     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6731                                                cast<CXXRecordDecl>(DC),
6732                                                D.getLocStart(), NameInfo, R,
6733                                                TInfo, SC, isInline,
6734                                                isConstexpr, SourceLocation());
6735     IsVirtualOkay = !Ret->isStatic();
6736     return Ret;
6737   } else {
6738     bool isFriend =
6739         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
6740     if (!isFriend && SemaRef.CurContext->isRecord())
6741       return nullptr;
6742 
6743     // Determine whether the function was written with a
6744     // prototype. This true when:
6745     //   - we're in C++ (where every function has a prototype),
6746     return FunctionDecl::Create(SemaRef.Context, DC,
6747                                 D.getLocStart(),
6748                                 NameInfo, R, TInfo, SC, isInline,
6749                                 true/*HasPrototype*/, isConstexpr);
6750   }
6751 }
6752 
6753 enum OpenCLParamType {
6754   ValidKernelParam,
6755   PtrPtrKernelParam,
6756   PtrKernelParam,
6757   PrivatePtrKernelParam,
6758   InvalidKernelParam,
6759   RecordKernelParam
6760 };
6761 
6762 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6763   if (PT->isPointerType()) {
6764     QualType PointeeType = PT->getPointeeType();
6765     if (PointeeType->isPointerType())
6766       return PtrPtrKernelParam;
6767     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
6768                                               : PtrKernelParam;
6769   }
6770 
6771   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6772   // be used as builtin types.
6773 
6774   if (PT->isImageType())
6775     return PtrKernelParam;
6776 
6777   if (PT->isBooleanType())
6778     return InvalidKernelParam;
6779 
6780   if (PT->isEventT())
6781     return InvalidKernelParam;
6782 
6783   if (PT->isHalfType())
6784     return InvalidKernelParam;
6785 
6786   if (PT->isRecordType())
6787     return RecordKernelParam;
6788 
6789   return ValidKernelParam;
6790 }
6791 
6792 static void checkIsValidOpenCLKernelParameter(
6793   Sema &S,
6794   Declarator &D,
6795   ParmVarDecl *Param,
6796   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
6797   QualType PT = Param->getType();
6798 
6799   // Cache the valid types we encounter to avoid rechecking structs that are
6800   // used again
6801   if (ValidTypes.count(PT.getTypePtr()))
6802     return;
6803 
6804   switch (getOpenCLKernelParameterType(PT)) {
6805   case PtrPtrKernelParam:
6806     // OpenCL v1.2 s6.9.a:
6807     // A kernel function argument cannot be declared as a
6808     // pointer to a pointer type.
6809     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6810     D.setInvalidType();
6811     return;
6812 
6813   case PrivatePtrKernelParam:
6814     // OpenCL v1.2 s6.9.a:
6815     // A kernel function argument cannot be declared as a
6816     // pointer to the private address space.
6817     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
6818     D.setInvalidType();
6819     return;
6820 
6821     // OpenCL v1.2 s6.9.k:
6822     // Arguments to kernel functions in a program cannot be declared with the
6823     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6824     // uintptr_t or a struct and/or union that contain fields declared to be
6825     // one of these built-in scalar types.
6826 
6827   case InvalidKernelParam:
6828     // OpenCL v1.2 s6.8 n:
6829     // A kernel function argument cannot be declared
6830     // of event_t type.
6831     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6832     D.setInvalidType();
6833     return;
6834 
6835   case PtrKernelParam:
6836   case ValidKernelParam:
6837     ValidTypes.insert(PT.getTypePtr());
6838     return;
6839 
6840   case RecordKernelParam:
6841     break;
6842   }
6843 
6844   // Track nested structs we will inspect
6845   SmallVector<const Decl *, 4> VisitStack;
6846 
6847   // Track where we are in the nested structs. Items will migrate from
6848   // VisitStack to HistoryStack as we do the DFS for bad field.
6849   SmallVector<const FieldDecl *, 4> HistoryStack;
6850   HistoryStack.push_back(nullptr);
6851 
6852   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6853   VisitStack.push_back(PD);
6854 
6855   assert(VisitStack.back() && "First decl null?");
6856 
6857   do {
6858     const Decl *Next = VisitStack.pop_back_val();
6859     if (!Next) {
6860       assert(!HistoryStack.empty());
6861       // Found a marker, we have gone up a level
6862       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6863         ValidTypes.insert(Hist->getType().getTypePtr());
6864 
6865       continue;
6866     }
6867 
6868     // Adds everything except the original parameter declaration (which is not a
6869     // field itself) to the history stack.
6870     const RecordDecl *RD;
6871     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6872       HistoryStack.push_back(Field);
6873       RD = Field->getType()->castAs<RecordType>()->getDecl();
6874     } else {
6875       RD = cast<RecordDecl>(Next);
6876     }
6877 
6878     // Add a null marker so we know when we've gone back up a level
6879     VisitStack.push_back(nullptr);
6880 
6881     for (const auto *FD : RD->fields()) {
6882       QualType QT = FD->getType();
6883 
6884       if (ValidTypes.count(QT.getTypePtr()))
6885         continue;
6886 
6887       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6888       if (ParamType == ValidKernelParam)
6889         continue;
6890 
6891       if (ParamType == RecordKernelParam) {
6892         VisitStack.push_back(FD);
6893         continue;
6894       }
6895 
6896       // OpenCL v1.2 s6.9.p:
6897       // Arguments to kernel functions that are declared to be a struct or union
6898       // do not allow OpenCL objects to be passed as elements of the struct or
6899       // union.
6900       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
6901           ParamType == PrivatePtrKernelParam) {
6902         S.Diag(Param->getLocation(),
6903                diag::err_record_with_pointers_kernel_param)
6904           << PT->isUnionType()
6905           << PT;
6906       } else {
6907         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6908       }
6909 
6910       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6911         << PD->getDeclName();
6912 
6913       // We have an error, now let's go back up through history and show where
6914       // the offending field came from
6915       for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6916              E = HistoryStack.end(); I != E; ++I) {
6917         const FieldDecl *OuterField = *I;
6918         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6919           << OuterField->getType();
6920       }
6921 
6922       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6923         << QT->isPointerType()
6924         << QT;
6925       D.setInvalidType();
6926       return;
6927     }
6928   } while (!VisitStack.empty());
6929 }
6930 
6931 NamedDecl*
6932 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
6933                               TypeSourceInfo *TInfo, LookupResult &Previous,
6934                               MultiTemplateParamsArg TemplateParamLists,
6935                               bool &AddToScope) {
6936   QualType R = TInfo->getType();
6937 
6938   assert(R.getTypePtr()->isFunctionType());
6939 
6940   // TODO: consider using NameInfo for diagnostic.
6941   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6942   DeclarationName Name = NameInfo.getName();
6943   StorageClass SC = getFunctionStorageClass(*this, D);
6944 
6945   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6946     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6947          diag::err_invalid_thread)
6948       << DeclSpec::getSpecifierName(TSCS);
6949 
6950   if (D.isFirstDeclarationOfMember())
6951     adjustMemberFunctionCC(R, D.isStaticMember());
6952 
6953   bool isFriend = false;
6954   FunctionTemplateDecl *FunctionTemplate = nullptr;
6955   bool isExplicitSpecialization = false;
6956   bool isFunctionTemplateSpecialization = false;
6957 
6958   bool isDependentClassScopeExplicitSpecialization = false;
6959   bool HasExplicitTemplateArgs = false;
6960   TemplateArgumentListInfo TemplateArgs;
6961 
6962   bool isVirtualOkay = false;
6963 
6964   DeclContext *OriginalDC = DC;
6965   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6966 
6967   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6968                                               isVirtualOkay);
6969   if (!NewFD) return nullptr;
6970 
6971   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6972     NewFD->setTopLevelDeclInObjCContainer();
6973 
6974   // Set the lexical context. If this is a function-scope declaration, or has a
6975   // C++ scope specifier, or is the object of a friend declaration, the lexical
6976   // context will be different from the semantic context.
6977   NewFD->setLexicalDeclContext(CurContext);
6978 
6979   if (IsLocalExternDecl)
6980     NewFD->setLocalExternDecl();
6981 
6982   if (getLangOpts().CPlusPlus) {
6983     bool isInline = D.getDeclSpec().isInlineSpecified();
6984     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6985     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6986     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6987     isFriend = D.getDeclSpec().isFriendSpecified();
6988     if (isFriend && !isInline && D.isFunctionDefinition()) {
6989       // C++ [class.friend]p5
6990       //   A function can be defined in a friend declaration of a
6991       //   class . . . . Such a function is implicitly inline.
6992       NewFD->setImplicitlyInline();
6993     }
6994 
6995     // If this is a method defined in an __interface, and is not a constructor
6996     // or an overloaded operator, then set the pure flag (isVirtual will already
6997     // return true).
6998     if (const CXXRecordDecl *Parent =
6999           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7000       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7001         NewFD->setPure(true);
7002     }
7003 
7004     SetNestedNameSpecifier(NewFD, D);
7005     isExplicitSpecialization = false;
7006     isFunctionTemplateSpecialization = false;
7007     if (D.isInvalidType())
7008       NewFD->setInvalidDecl();
7009 
7010     // Match up the template parameter lists with the scope specifier, then
7011     // determine whether we have a template or a template specialization.
7012     bool Invalid = false;
7013     if (TemplateParameterList *TemplateParams =
7014             MatchTemplateParametersToScopeSpecifier(
7015                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7016                 D.getCXXScopeSpec(),
7017                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7018                     ? D.getName().TemplateId
7019                     : nullptr,
7020                 TemplateParamLists, isFriend, isExplicitSpecialization,
7021                 Invalid)) {
7022       if (TemplateParams->size() > 0) {
7023         // This is a function template
7024 
7025         // Check that we can declare a template here.
7026         if (CheckTemplateDeclScope(S, TemplateParams))
7027           NewFD->setInvalidDecl();
7028 
7029         // A destructor cannot be a template.
7030         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7031           Diag(NewFD->getLocation(), diag::err_destructor_template);
7032           NewFD->setInvalidDecl();
7033         }
7034 
7035         // If we're adding a template to a dependent context, we may need to
7036         // rebuilding some of the types used within the template parameter list,
7037         // now that we know what the current instantiation is.
7038         if (DC->isDependentContext()) {
7039           ContextRAII SavedContext(*this, DC);
7040           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7041             Invalid = true;
7042         }
7043 
7044 
7045         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7046                                                         NewFD->getLocation(),
7047                                                         Name, TemplateParams,
7048                                                         NewFD);
7049         FunctionTemplate->setLexicalDeclContext(CurContext);
7050         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7051 
7052         // For source fidelity, store the other template param lists.
7053         if (TemplateParamLists.size() > 1) {
7054           NewFD->setTemplateParameterListsInfo(Context,
7055                                                TemplateParamLists.size() - 1,
7056                                                TemplateParamLists.data());
7057         }
7058       } else {
7059         // This is a function template specialization.
7060         isFunctionTemplateSpecialization = true;
7061         // For source fidelity, store all the template param lists.
7062         if (TemplateParamLists.size() > 0)
7063           NewFD->setTemplateParameterListsInfo(Context,
7064                                                TemplateParamLists.size(),
7065                                                TemplateParamLists.data());
7066 
7067         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7068         if (isFriend) {
7069           // We want to remove the "template<>", found here.
7070           SourceRange RemoveRange = TemplateParams->getSourceRange();
7071 
7072           // If we remove the template<> and the name is not a
7073           // template-id, we're actually silently creating a problem:
7074           // the friend declaration will refer to an untemplated decl,
7075           // and clearly the user wants a template specialization.  So
7076           // we need to insert '<>' after the name.
7077           SourceLocation InsertLoc;
7078           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7079             InsertLoc = D.getName().getSourceRange().getEnd();
7080             InsertLoc = getLocForEndOfToken(InsertLoc);
7081           }
7082 
7083           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7084             << Name << RemoveRange
7085             << FixItHint::CreateRemoval(RemoveRange)
7086             << FixItHint::CreateInsertion(InsertLoc, "<>");
7087         }
7088       }
7089     }
7090     else {
7091       // All template param lists were matched against the scope specifier:
7092       // this is NOT (an explicit specialization of) a template.
7093       if (TemplateParamLists.size() > 0)
7094         // For source fidelity, store all the template param lists.
7095         NewFD->setTemplateParameterListsInfo(Context,
7096                                              TemplateParamLists.size(),
7097                                              TemplateParamLists.data());
7098     }
7099 
7100     if (Invalid) {
7101       NewFD->setInvalidDecl();
7102       if (FunctionTemplate)
7103         FunctionTemplate->setInvalidDecl();
7104     }
7105 
7106     // C++ [dcl.fct.spec]p5:
7107     //   The virtual specifier shall only be used in declarations of
7108     //   nonstatic class member functions that appear within a
7109     //   member-specification of a class declaration; see 10.3.
7110     //
7111     if (isVirtual && !NewFD->isInvalidDecl()) {
7112       if (!isVirtualOkay) {
7113         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7114              diag::err_virtual_non_function);
7115       } else if (!CurContext->isRecord()) {
7116         // 'virtual' was specified outside of the class.
7117         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7118              diag::err_virtual_out_of_class)
7119           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7120       } else if (NewFD->getDescribedFunctionTemplate()) {
7121         // C++ [temp.mem]p3:
7122         //  A member function template shall not be virtual.
7123         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7124              diag::err_virtual_member_function_template)
7125           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7126       } else {
7127         // Okay: Add virtual to the method.
7128         NewFD->setVirtualAsWritten(true);
7129       }
7130 
7131       if (getLangOpts().CPlusPlus14 &&
7132           NewFD->getReturnType()->isUndeducedType())
7133         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7134     }
7135 
7136     if (getLangOpts().CPlusPlus14 &&
7137         (NewFD->isDependentContext() ||
7138          (isFriend && CurContext->isDependentContext())) &&
7139         NewFD->getReturnType()->isUndeducedType()) {
7140       // If the function template is referenced directly (for instance, as a
7141       // member of the current instantiation), pretend it has a dependent type.
7142       // This is not really justified by the standard, but is the only sane
7143       // thing to do.
7144       // FIXME: For a friend function, we have not marked the function as being
7145       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7146       const FunctionProtoType *FPT =
7147           NewFD->getType()->castAs<FunctionProtoType>();
7148       QualType Result =
7149           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7150       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7151                                              FPT->getExtProtoInfo()));
7152     }
7153 
7154     // C++ [dcl.fct.spec]p3:
7155     //  The inline specifier shall not appear on a block scope function
7156     //  declaration.
7157     if (isInline && !NewFD->isInvalidDecl()) {
7158       if (CurContext->isFunctionOrMethod()) {
7159         // 'inline' is not allowed on block scope function declaration.
7160         Diag(D.getDeclSpec().getInlineSpecLoc(),
7161              diag::err_inline_declaration_block_scope) << Name
7162           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7163       }
7164     }
7165 
7166     // C++ [dcl.fct.spec]p6:
7167     //  The explicit specifier shall be used only in the declaration of a
7168     //  constructor or conversion function within its class definition;
7169     //  see 12.3.1 and 12.3.2.
7170     if (isExplicit && !NewFD->isInvalidDecl()) {
7171       if (!CurContext->isRecord()) {
7172         // 'explicit' was specified outside of the class.
7173         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7174              diag::err_explicit_out_of_class)
7175           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7176       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7177                  !isa<CXXConversionDecl>(NewFD)) {
7178         // 'explicit' was specified on a function that wasn't a constructor
7179         // or conversion function.
7180         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7181              diag::err_explicit_non_ctor_or_conv_function)
7182           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7183       }
7184     }
7185 
7186     if (isConstexpr) {
7187       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7188       // are implicitly inline.
7189       NewFD->setImplicitlyInline();
7190 
7191       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7192       // be either constructors or to return a literal type. Therefore,
7193       // destructors cannot be declared constexpr.
7194       if (isa<CXXDestructorDecl>(NewFD))
7195         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7196     }
7197 
7198     // If __module_private__ was specified, mark the function accordingly.
7199     if (D.getDeclSpec().isModulePrivateSpecified()) {
7200       if (isFunctionTemplateSpecialization) {
7201         SourceLocation ModulePrivateLoc
7202           = D.getDeclSpec().getModulePrivateSpecLoc();
7203         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7204           << 0
7205           << FixItHint::CreateRemoval(ModulePrivateLoc);
7206       } else {
7207         NewFD->setModulePrivate();
7208         if (FunctionTemplate)
7209           FunctionTemplate->setModulePrivate();
7210       }
7211     }
7212 
7213     if (isFriend) {
7214       if (FunctionTemplate) {
7215         FunctionTemplate->setObjectOfFriendDecl();
7216         FunctionTemplate->setAccess(AS_public);
7217       }
7218       NewFD->setObjectOfFriendDecl();
7219       NewFD->setAccess(AS_public);
7220     }
7221 
7222     // If a function is defined as defaulted or deleted, mark it as such now.
7223     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7224     // definition kind to FDK_Definition.
7225     switch (D.getFunctionDefinitionKind()) {
7226       case FDK_Declaration:
7227       case FDK_Definition:
7228         break;
7229 
7230       case FDK_Defaulted:
7231         NewFD->setDefaulted();
7232         break;
7233 
7234       case FDK_Deleted:
7235         NewFD->setDeletedAsWritten();
7236         break;
7237     }
7238 
7239     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7240         D.isFunctionDefinition()) {
7241       // C++ [class.mfct]p2:
7242       //   A member function may be defined (8.4) in its class definition, in
7243       //   which case it is an inline member function (7.1.2)
7244       NewFD->setImplicitlyInline();
7245     }
7246 
7247     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7248         !CurContext->isRecord()) {
7249       // C++ [class.static]p1:
7250       //   A data or function member of a class may be declared static
7251       //   in a class definition, in which case it is a static member of
7252       //   the class.
7253 
7254       // Complain about the 'static' specifier if it's on an out-of-line
7255       // member function definition.
7256       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7257            diag::err_static_out_of_line)
7258         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7259     }
7260 
7261     // C++11 [except.spec]p15:
7262     //   A deallocation function with no exception-specification is treated
7263     //   as if it were specified with noexcept(true).
7264     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7265     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7266          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7267         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7268       NewFD->setType(Context.getFunctionType(
7269           FPT->getReturnType(), FPT->getParamTypes(),
7270           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7271   }
7272 
7273   // Filter out previous declarations that don't match the scope.
7274   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7275                        D.getCXXScopeSpec().isNotEmpty() ||
7276                        isExplicitSpecialization ||
7277                        isFunctionTemplateSpecialization);
7278 
7279   // Handle GNU asm-label extension (encoded as an attribute).
7280   if (Expr *E = (Expr*) D.getAsmLabel()) {
7281     // The parser guarantees this is a string.
7282     StringLiteral *SE = cast<StringLiteral>(E);
7283     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7284                                                 SE->getString(), 0));
7285   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7286     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7287       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7288     if (I != ExtnameUndeclaredIdentifiers.end()) {
7289       NewFD->addAttr(I->second);
7290       ExtnameUndeclaredIdentifiers.erase(I);
7291     }
7292   }
7293 
7294   // Copy the parameter declarations from the declarator D to the function
7295   // declaration NewFD, if they are available.  First scavenge them into Params.
7296   SmallVector<ParmVarDecl*, 16> Params;
7297   if (D.isFunctionDeclarator()) {
7298     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7299 
7300     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7301     // function that takes no arguments, not a function that takes a
7302     // single void argument.
7303     // We let through "const void" here because Sema::GetTypeForDeclarator
7304     // already checks for that case.
7305     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7306       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7307         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7308         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7309         Param->setDeclContext(NewFD);
7310         Params.push_back(Param);
7311 
7312         if (Param->isInvalidDecl())
7313           NewFD->setInvalidDecl();
7314       }
7315     }
7316 
7317   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7318     // When we're declaring a function with a typedef, typeof, etc as in the
7319     // following example, we'll need to synthesize (unnamed)
7320     // parameters for use in the declaration.
7321     //
7322     // @code
7323     // typedef void fn(int);
7324     // fn f;
7325     // @endcode
7326 
7327     // Synthesize a parameter for each argument type.
7328     for (const auto &AI : FT->param_types()) {
7329       ParmVarDecl *Param =
7330           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7331       Param->setScopeInfo(0, Params.size());
7332       Params.push_back(Param);
7333     }
7334   } else {
7335     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7336            "Should not need args for typedef of non-prototype fn");
7337   }
7338 
7339   // Finally, we know we have the right number of parameters, install them.
7340   NewFD->setParams(Params);
7341 
7342   // Find all anonymous symbols defined during the declaration of this function
7343   // and add to NewFD. This lets us track decls such 'enum Y' in:
7344   //
7345   //   void f(enum Y {AA} x) {}
7346   //
7347   // which would otherwise incorrectly end up in the translation unit scope.
7348   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7349   DeclsInPrototypeScope.clear();
7350 
7351   if (D.getDeclSpec().isNoreturnSpecified())
7352     NewFD->addAttr(
7353         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7354                                        Context, 0));
7355 
7356   // Functions returning a variably modified type violate C99 6.7.5.2p2
7357   // because all functions have linkage.
7358   if (!NewFD->isInvalidDecl() &&
7359       NewFD->getReturnType()->isVariablyModifiedType()) {
7360     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7361     NewFD->setInvalidDecl();
7362   }
7363 
7364   if (D.isFunctionDefinition() && CodeSegStack.CurrentValue &&
7365       !NewFD->hasAttr<SectionAttr>()) {
7366     NewFD->addAttr(
7367         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7368                                     CodeSegStack.CurrentValue->getString(),
7369                                     CodeSegStack.CurrentPragmaLocation));
7370     if (UnifySection(CodeSegStack.CurrentValue->getString(),
7371                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
7372                          ASTContext::PSF_Read,
7373                      NewFD))
7374       NewFD->dropAttr<SectionAttr>();
7375   }
7376 
7377   // Handle attributes.
7378   ProcessDeclAttributes(S, NewFD, D);
7379 
7380   QualType RetType = NewFD->getReturnType();
7381   const CXXRecordDecl *Ret = RetType->isRecordType() ?
7382       RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
7383   if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
7384       Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
7385     const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7386     // Attach WarnUnusedResult to functions returning types with that attribute.
7387     // Don't apply the attribute to that type's own non-static member functions
7388     // (to avoid warning on things like assignment operators)
7389     if (!MD || MD->getParent() != Ret)
7390       NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
7391   }
7392 
7393   if (getLangOpts().OpenCL) {
7394     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7395     // type declaration will generate a compilation error.
7396     unsigned AddressSpace = RetType.getAddressSpace();
7397     if (AddressSpace == LangAS::opencl_local ||
7398         AddressSpace == LangAS::opencl_global ||
7399         AddressSpace == LangAS::opencl_constant) {
7400       Diag(NewFD->getLocation(),
7401            diag::err_opencl_return_value_with_address_space);
7402       NewFD->setInvalidDecl();
7403     }
7404   }
7405 
7406   if (!getLangOpts().CPlusPlus) {
7407     // Perform semantic checking on the function declaration.
7408     bool isExplicitSpecialization=false;
7409     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7410       CheckMain(NewFD, D.getDeclSpec());
7411 
7412     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7413       CheckMSVCRTEntryPoint(NewFD);
7414 
7415     if (!NewFD->isInvalidDecl())
7416       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7417                                                   isExplicitSpecialization));
7418     else if (!Previous.empty())
7419       // Make graceful recovery from an invalid redeclaration.
7420       D.setRedeclaration(true);
7421     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7422             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7423            "previous declaration set still overloaded");
7424 
7425     // Diagnose no-prototype function declarations with calling conventions that
7426     // don't support variadic calls. Only do this in C and do it after merging
7427     // possibly prototyped redeclarations.
7428     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
7429     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
7430       CallingConv CC = FT->getExtInfo().getCC();
7431       if (!supportsVariadicCall(CC)) {
7432         // Windows system headers sometimes accidentally use stdcall without
7433         // (void) parameters, so we relax this to a warning.
7434         int DiagID =
7435             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
7436         Diag(NewFD->getLocation(), DiagID)
7437             << FunctionType::getNameForCallConv(CC);
7438       }
7439     }
7440   } else {
7441     // C++11 [replacement.functions]p3:
7442     //  The program's definitions shall not be specified as inline.
7443     //
7444     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7445     //
7446     // Suppress the diagnostic if the function is __attribute__((used)), since
7447     // that forces an external definition to be emitted.
7448     if (D.getDeclSpec().isInlineSpecified() &&
7449         NewFD->isReplaceableGlobalAllocationFunction() &&
7450         !NewFD->hasAttr<UsedAttr>())
7451       Diag(D.getDeclSpec().getInlineSpecLoc(),
7452            diag::ext_operator_new_delete_declared_inline)
7453         << NewFD->getDeclName();
7454 
7455     // If the declarator is a template-id, translate the parser's template
7456     // argument list into our AST format.
7457     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7458       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7459       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7460       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7461       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7462                                          TemplateId->NumArgs);
7463       translateTemplateArguments(TemplateArgsPtr,
7464                                  TemplateArgs);
7465 
7466       HasExplicitTemplateArgs = true;
7467 
7468       if (NewFD->isInvalidDecl()) {
7469         HasExplicitTemplateArgs = false;
7470       } else if (FunctionTemplate) {
7471         // Function template with explicit template arguments.
7472         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7473           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7474 
7475         HasExplicitTemplateArgs = false;
7476       } else {
7477         assert((isFunctionTemplateSpecialization ||
7478                 D.getDeclSpec().isFriendSpecified()) &&
7479                "should have a 'template<>' for this decl");
7480         // "friend void foo<>(int);" is an implicit specialization decl.
7481         isFunctionTemplateSpecialization = true;
7482       }
7483     } else if (isFriend && isFunctionTemplateSpecialization) {
7484       // This combination is only possible in a recovery case;  the user
7485       // wrote something like:
7486       //   template <> friend void foo(int);
7487       // which we're recovering from as if the user had written:
7488       //   friend void foo<>(int);
7489       // Go ahead and fake up a template id.
7490       HasExplicitTemplateArgs = true;
7491       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7492       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7493     }
7494 
7495     // If it's a friend (and only if it's a friend), it's possible
7496     // that either the specialized function type or the specialized
7497     // template is dependent, and therefore matching will fail.  In
7498     // this case, don't check the specialization yet.
7499     bool InstantiationDependent = false;
7500     if (isFunctionTemplateSpecialization && isFriend &&
7501         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7502          TemplateSpecializationType::anyDependentTemplateArguments(
7503             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7504             InstantiationDependent))) {
7505       assert(HasExplicitTemplateArgs &&
7506              "friend function specialization without template args");
7507       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7508                                                        Previous))
7509         NewFD->setInvalidDecl();
7510     } else if (isFunctionTemplateSpecialization) {
7511       if (CurContext->isDependentContext() && CurContext->isRecord()
7512           && !isFriend) {
7513         isDependentClassScopeExplicitSpecialization = true;
7514         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7515           diag::ext_function_specialization_in_class :
7516           diag::err_function_specialization_in_class)
7517           << NewFD->getDeclName();
7518       } else if (CheckFunctionTemplateSpecialization(NewFD,
7519                                   (HasExplicitTemplateArgs ? &TemplateArgs
7520                                                            : nullptr),
7521                                                      Previous))
7522         NewFD->setInvalidDecl();
7523 
7524       // C++ [dcl.stc]p1:
7525       //   A storage-class-specifier shall not be specified in an explicit
7526       //   specialization (14.7.3)
7527       FunctionTemplateSpecializationInfo *Info =
7528           NewFD->getTemplateSpecializationInfo();
7529       if (Info && SC != SC_None) {
7530         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7531           Diag(NewFD->getLocation(),
7532                diag::err_explicit_specialization_inconsistent_storage_class)
7533             << SC
7534             << FixItHint::CreateRemoval(
7535                                       D.getDeclSpec().getStorageClassSpecLoc());
7536 
7537         else
7538           Diag(NewFD->getLocation(),
7539                diag::ext_explicit_specialization_storage_class)
7540             << FixItHint::CreateRemoval(
7541                                       D.getDeclSpec().getStorageClassSpecLoc());
7542       }
7543 
7544     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7545       if (CheckMemberSpecialization(NewFD, Previous))
7546           NewFD->setInvalidDecl();
7547     }
7548 
7549     // Perform semantic checking on the function declaration.
7550     if (!isDependentClassScopeExplicitSpecialization) {
7551       if (!NewFD->isInvalidDecl() && NewFD->isMain())
7552         CheckMain(NewFD, D.getDeclSpec());
7553 
7554       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7555         CheckMSVCRTEntryPoint(NewFD);
7556 
7557       if (!NewFD->isInvalidDecl())
7558         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7559                                                     isExplicitSpecialization));
7560     }
7561 
7562     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7563             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7564            "previous declaration set still overloaded");
7565 
7566     NamedDecl *PrincipalDecl = (FunctionTemplate
7567                                 ? cast<NamedDecl>(FunctionTemplate)
7568                                 : NewFD);
7569 
7570     if (isFriend && D.isRedeclaration()) {
7571       AccessSpecifier Access = AS_public;
7572       if (!NewFD->isInvalidDecl())
7573         Access = NewFD->getPreviousDecl()->getAccess();
7574 
7575       NewFD->setAccess(Access);
7576       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7577     }
7578 
7579     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7580         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7581       PrincipalDecl->setNonMemberOperator();
7582 
7583     // If we have a function template, check the template parameter
7584     // list. This will check and merge default template arguments.
7585     if (FunctionTemplate) {
7586       FunctionTemplateDecl *PrevTemplate =
7587                                      FunctionTemplate->getPreviousDecl();
7588       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7589                        PrevTemplate ? PrevTemplate->getTemplateParameters()
7590                                     : nullptr,
7591                             D.getDeclSpec().isFriendSpecified()
7592                               ? (D.isFunctionDefinition()
7593                                    ? TPC_FriendFunctionTemplateDefinition
7594                                    : TPC_FriendFunctionTemplate)
7595                               : (D.getCXXScopeSpec().isSet() &&
7596                                  DC && DC->isRecord() &&
7597                                  DC->isDependentContext())
7598                                   ? TPC_ClassTemplateMember
7599                                   : TPC_FunctionTemplate);
7600     }
7601 
7602     if (NewFD->isInvalidDecl()) {
7603       // Ignore all the rest of this.
7604     } else if (!D.isRedeclaration()) {
7605       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7606                                        AddToScope };
7607       // Fake up an access specifier if it's supposed to be a class member.
7608       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7609         NewFD->setAccess(AS_public);
7610 
7611       // Qualified decls generally require a previous declaration.
7612       if (D.getCXXScopeSpec().isSet()) {
7613         // ...with the major exception of templated-scope or
7614         // dependent-scope friend declarations.
7615 
7616         // TODO: we currently also suppress this check in dependent
7617         // contexts because (1) the parameter depth will be off when
7618         // matching friend templates and (2) we might actually be
7619         // selecting a friend based on a dependent factor.  But there
7620         // are situations where these conditions don't apply and we
7621         // can actually do this check immediately.
7622         if (isFriend &&
7623             (TemplateParamLists.size() ||
7624              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7625              CurContext->isDependentContext())) {
7626           // ignore these
7627         } else {
7628           // The user tried to provide an out-of-line definition for a
7629           // function that is a member of a class or namespace, but there
7630           // was no such member function declared (C++ [class.mfct]p2,
7631           // C++ [namespace.memdef]p2). For example:
7632           //
7633           // class X {
7634           //   void f() const;
7635           // };
7636           //
7637           // void X::f() { } // ill-formed
7638           //
7639           // Complain about this problem, and attempt to suggest close
7640           // matches (e.g., those that differ only in cv-qualifiers and
7641           // whether the parameter types are references).
7642 
7643           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7644                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
7645             AddToScope = ExtraArgs.AddToScope;
7646             return Result;
7647           }
7648         }
7649 
7650         // Unqualified local friend declarations are required to resolve
7651         // to something.
7652       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7653         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7654                 *this, Previous, NewFD, ExtraArgs, true, S)) {
7655           AddToScope = ExtraArgs.AddToScope;
7656           return Result;
7657         }
7658       }
7659 
7660     } else if (!D.isFunctionDefinition() &&
7661                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
7662                !isFriend && !isFunctionTemplateSpecialization &&
7663                !isExplicitSpecialization) {
7664       // An out-of-line member function declaration must also be a
7665       // definition (C++ [class.mfct]p2).
7666       // Note that this is not the case for explicit specializations of
7667       // function templates or member functions of class templates, per
7668       // C++ [temp.expl.spec]p2. We also allow these declarations as an
7669       // extension for compatibility with old SWIG code which likes to
7670       // generate them.
7671       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7672         << D.getCXXScopeSpec().getRange();
7673     }
7674   }
7675 
7676   ProcessPragmaWeak(S, NewFD);
7677   checkAttributesAfterMerging(*this, *NewFD);
7678 
7679   AddKnownFunctionAttributes(NewFD);
7680 
7681   if (NewFD->hasAttr<OverloadableAttr>() &&
7682       !NewFD->getType()->getAs<FunctionProtoType>()) {
7683     Diag(NewFD->getLocation(),
7684          diag::err_attribute_overloadable_no_prototype)
7685       << NewFD;
7686 
7687     // Turn this into a variadic function with no parameters.
7688     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7689     FunctionProtoType::ExtProtoInfo EPI(
7690         Context.getDefaultCallingConvention(true, false));
7691     EPI.Variadic = true;
7692     EPI.ExtInfo = FT->getExtInfo();
7693 
7694     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
7695     NewFD->setType(R);
7696   }
7697 
7698   // If there's a #pragma GCC visibility in scope, and this isn't a class
7699   // member, set the visibility of this function.
7700   if (!DC->isRecord() && NewFD->isExternallyVisible())
7701     AddPushedVisibilityAttribute(NewFD);
7702 
7703   // If there's a #pragma clang arc_cf_code_audited in scope, consider
7704   // marking the function.
7705   AddCFAuditedAttribute(NewFD);
7706 
7707   // If this is a function definition, check if we have to apply optnone due to
7708   // a pragma.
7709   if(D.isFunctionDefinition())
7710     AddRangeBasedOptnone(NewFD);
7711 
7712   // If this is the first declaration of an extern C variable, update
7713   // the map of such variables.
7714   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7715       isIncompleteDeclExternC(*this, NewFD))
7716     RegisterLocallyScopedExternCDecl(NewFD, S);
7717 
7718   // Set this FunctionDecl's range up to the right paren.
7719   NewFD->setRangeEnd(D.getSourceRange().getEnd());
7720 
7721   if (D.isRedeclaration() && !Previous.empty()) {
7722     checkDLLAttributeRedeclaration(
7723         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
7724         isExplicitSpecialization || isFunctionTemplateSpecialization);
7725   }
7726 
7727   if (getLangOpts().CPlusPlus) {
7728     if (FunctionTemplate) {
7729       if (NewFD->isInvalidDecl())
7730         FunctionTemplate->setInvalidDecl();
7731       return FunctionTemplate;
7732     }
7733   }
7734 
7735   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7736     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7737     if ((getLangOpts().OpenCLVersion >= 120)
7738         && (SC == SC_Static)) {
7739       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7740       D.setInvalidType();
7741     }
7742 
7743     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7744     if (!NewFD->getReturnType()->isVoidType()) {
7745       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
7746       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
7747           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
7748                                 : FixItHint());
7749       D.setInvalidType();
7750     }
7751 
7752     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
7753     for (auto Param : NewFD->params())
7754       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
7755   }
7756 
7757   MarkUnusedFileScopedDecl(NewFD);
7758 
7759   if (getLangOpts().CUDA)
7760     if (IdentifierInfo *II = NewFD->getIdentifier())
7761       if (!NewFD->isInvalidDecl() &&
7762           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7763         if (II->isStr("cudaConfigureCall")) {
7764           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
7765             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7766 
7767           Context.setcudaConfigureCallDecl(NewFD);
7768         }
7769       }
7770 
7771   // Here we have an function template explicit specialization at class scope.
7772   // The actually specialization will be postponed to template instatiation
7773   // time via the ClassScopeFunctionSpecializationDecl node.
7774   if (isDependentClassScopeExplicitSpecialization) {
7775     ClassScopeFunctionSpecializationDecl *NewSpec =
7776                          ClassScopeFunctionSpecializationDecl::Create(
7777                                 Context, CurContext, SourceLocation(),
7778                                 cast<CXXMethodDecl>(NewFD),
7779                                 HasExplicitTemplateArgs, TemplateArgs);
7780     CurContext->addDecl(NewSpec);
7781     AddToScope = false;
7782   }
7783 
7784   return NewFD;
7785 }
7786 
7787 /// \brief Perform semantic checking of a new function declaration.
7788 ///
7789 /// Performs semantic analysis of the new function declaration
7790 /// NewFD. This routine performs all semantic checking that does not
7791 /// require the actual declarator involved in the declaration, and is
7792 /// used both for the declaration of functions as they are parsed
7793 /// (called via ActOnDeclarator) and for the declaration of functions
7794 /// that have been instantiated via C++ template instantiation (called
7795 /// via InstantiateDecl).
7796 ///
7797 /// \param IsExplicitSpecialization whether this new function declaration is
7798 /// an explicit specialization of the previous declaration.
7799 ///
7800 /// This sets NewFD->isInvalidDecl() to true if there was an error.
7801 ///
7802 /// \returns true if the function declaration is a redeclaration.
7803 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
7804                                     LookupResult &Previous,
7805                                     bool IsExplicitSpecialization) {
7806   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7807          "Variably modified return types are not handled here");
7808 
7809   // Determine whether the type of this function should be merged with
7810   // a previous visible declaration. This never happens for functions in C++,
7811   // and always happens in C if the previous declaration was visible.
7812   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7813                                !Previous.isShadowed();
7814 
7815   // Filter out any non-conflicting previous declarations.
7816   filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7817 
7818   bool Redeclaration = false;
7819   NamedDecl *OldDecl = nullptr;
7820 
7821   // Merge or overload the declaration with an existing declaration of
7822   // the same name, if appropriate.
7823   if (!Previous.empty()) {
7824     // Determine whether NewFD is an overload of PrevDecl or
7825     // a declaration that requires merging. If it's an overload,
7826     // there's no more work to do here; we'll just add the new
7827     // function to the scope.
7828     if (!AllowOverloadingOfFunction(Previous, Context)) {
7829       NamedDecl *Candidate = Previous.getFoundDecl();
7830       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7831         Redeclaration = true;
7832         OldDecl = Candidate;
7833       }
7834     } else {
7835       switch (CheckOverload(S, NewFD, Previous, OldDecl,
7836                             /*NewIsUsingDecl*/ false)) {
7837       case Ovl_Match:
7838         Redeclaration = true;
7839         break;
7840 
7841       case Ovl_NonFunction:
7842         Redeclaration = true;
7843         break;
7844 
7845       case Ovl_Overload:
7846         Redeclaration = false;
7847         break;
7848       }
7849 
7850       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7851         // If a function name is overloadable in C, then every function
7852         // with that name must be marked "overloadable".
7853         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7854           << Redeclaration << NewFD;
7855         NamedDecl *OverloadedDecl = nullptr;
7856         if (Redeclaration)
7857           OverloadedDecl = OldDecl;
7858         else if (!Previous.empty())
7859           OverloadedDecl = Previous.getRepresentativeDecl();
7860         if (OverloadedDecl)
7861           Diag(OverloadedDecl->getLocation(),
7862                diag::note_attribute_overloadable_prev_overload);
7863         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7864       }
7865     }
7866   }
7867 
7868   // Check for a previous extern "C" declaration with this name.
7869   if (!Redeclaration &&
7870       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7871     filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7872     if (!Previous.empty()) {
7873       // This is an extern "C" declaration with the same name as a previous
7874       // declaration, and thus redeclares that entity...
7875       Redeclaration = true;
7876       OldDecl = Previous.getFoundDecl();
7877       MergeTypeWithPrevious = false;
7878 
7879       // ... except in the presence of __attribute__((overloadable)).
7880       if (OldDecl->hasAttr<OverloadableAttr>()) {
7881         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7882           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7883             << Redeclaration << NewFD;
7884           Diag(Previous.getFoundDecl()->getLocation(),
7885                diag::note_attribute_overloadable_prev_overload);
7886           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7887         }
7888         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7889           Redeclaration = false;
7890           OldDecl = nullptr;
7891         }
7892       }
7893     }
7894   }
7895 
7896   // C++11 [dcl.constexpr]p8:
7897   //   A constexpr specifier for a non-static member function that is not
7898   //   a constructor declares that member function to be const.
7899   //
7900   // This needs to be delayed until we know whether this is an out-of-line
7901   // definition of a static member function.
7902   //
7903   // This rule is not present in C++1y, so we produce a backwards
7904   // compatibility warning whenever it happens in C++11.
7905   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7906   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
7907       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
7908       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7909     CXXMethodDecl *OldMD = nullptr;
7910     if (OldDecl)
7911       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
7912     if (!OldMD || !OldMD->isStatic()) {
7913       const FunctionProtoType *FPT =
7914         MD->getType()->castAs<FunctionProtoType>();
7915       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7916       EPI.TypeQuals |= Qualifiers::Const;
7917       MD->setType(Context.getFunctionType(FPT->getReturnType(),
7918                                           FPT->getParamTypes(), EPI));
7919 
7920       // Warn that we did this, if we're not performing template instantiation.
7921       // In that case, we'll have warned already when the template was defined.
7922       if (ActiveTemplateInstantiations.empty()) {
7923         SourceLocation AddConstLoc;
7924         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7925                 .IgnoreParens().getAs<FunctionTypeLoc>())
7926           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
7927 
7928         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
7929           << FixItHint::CreateInsertion(AddConstLoc, " const");
7930       }
7931     }
7932   }
7933 
7934   if (Redeclaration) {
7935     // NewFD and OldDecl represent declarations that need to be
7936     // merged.
7937     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
7938       NewFD->setInvalidDecl();
7939       return Redeclaration;
7940     }
7941 
7942     Previous.clear();
7943     Previous.addDecl(OldDecl);
7944 
7945     if (FunctionTemplateDecl *OldTemplateDecl
7946                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7947       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7948       FunctionTemplateDecl *NewTemplateDecl
7949         = NewFD->getDescribedFunctionTemplate();
7950       assert(NewTemplateDecl && "Template/non-template mismatch");
7951       if (CXXMethodDecl *Method
7952             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7953         Method->setAccess(OldTemplateDecl->getAccess());
7954         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
7955       }
7956 
7957       // If this is an explicit specialization of a member that is a function
7958       // template, mark it as a member specialization.
7959       if (IsExplicitSpecialization &&
7960           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7961         NewTemplateDecl->setMemberSpecialization();
7962         assert(OldTemplateDecl->isMemberSpecialization());
7963       }
7964 
7965     } else {
7966       // This needs to happen first so that 'inline' propagates.
7967       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
7968 
7969       if (isa<CXXMethodDecl>(NewFD)) {
7970         // A valid redeclaration of a C++ method must be out-of-line,
7971         // but (unfortunately) it's not necessarily a definition
7972         // because of templates, which means that the previous
7973         // declaration is not necessarily from the class definition.
7974 
7975         // For just setting the access, that doesn't matter.
7976         CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7977         NewFD->setAccess(oldMethod->getAccess());
7978 
7979         // Update the key-function state if necessary for this ABI.
7980         if (NewFD->isInlined() &&
7981             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7982           // setNonKeyFunction needs to work with the original
7983           // declaration from the class definition, and isVirtual() is
7984           // just faster in that case, so map back to that now.
7985           oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
7986           if (oldMethod->isVirtual()) {
7987             Context.setNonKeyFunction(oldMethod);
7988           }
7989         }
7990       }
7991     }
7992   }
7993 
7994   // Semantic checking for this function declaration (in isolation).
7995 
7996   if (getLangOpts().CPlusPlus) {
7997     // C++-specific checks.
7998     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7999       CheckConstructor(Constructor);
8000     } else if (CXXDestructorDecl *Destructor =
8001                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8002       CXXRecordDecl *Record = Destructor->getParent();
8003       QualType ClassType = Context.getTypeDeclType(Record);
8004 
8005       // FIXME: Shouldn't we be able to perform this check even when the class
8006       // type is dependent? Both gcc and edg can handle that.
8007       if (!ClassType->isDependentType()) {
8008         DeclarationName Name
8009           = Context.DeclarationNames.getCXXDestructorName(
8010                                         Context.getCanonicalType(ClassType));
8011         if (NewFD->getDeclName() != Name) {
8012           Diag(NewFD->getLocation(), diag::err_destructor_name);
8013           NewFD->setInvalidDecl();
8014           return Redeclaration;
8015         }
8016       }
8017     } else if (CXXConversionDecl *Conversion
8018                = dyn_cast<CXXConversionDecl>(NewFD)) {
8019       ActOnConversionDeclarator(Conversion);
8020     }
8021 
8022     // Find any virtual functions that this function overrides.
8023     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8024       if (!Method->isFunctionTemplateSpecialization() &&
8025           !Method->getDescribedFunctionTemplate() &&
8026           Method->isCanonicalDecl()) {
8027         if (AddOverriddenMethods(Method->getParent(), Method)) {
8028           // If the function was marked as "static", we have a problem.
8029           if (NewFD->getStorageClass() == SC_Static) {
8030             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8031           }
8032         }
8033       }
8034 
8035       if (Method->isStatic())
8036         checkThisInStaticMemberFunctionType(Method);
8037     }
8038 
8039     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8040     if (NewFD->isOverloadedOperator() &&
8041         CheckOverloadedOperatorDeclaration(NewFD)) {
8042       NewFD->setInvalidDecl();
8043       return Redeclaration;
8044     }
8045 
8046     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8047     if (NewFD->getLiteralIdentifier() &&
8048         CheckLiteralOperatorDeclaration(NewFD)) {
8049       NewFD->setInvalidDecl();
8050       return Redeclaration;
8051     }
8052 
8053     // In C++, check default arguments now that we have merged decls. Unless
8054     // the lexical context is the class, because in this case this is done
8055     // during delayed parsing anyway.
8056     if (!CurContext->isRecord())
8057       CheckCXXDefaultArguments(NewFD);
8058 
8059     // If this function declares a builtin function, check the type of this
8060     // declaration against the expected type for the builtin.
8061     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8062       ASTContext::GetBuiltinTypeError Error;
8063       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8064       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8065       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8066         // The type of this function differs from the type of the builtin,
8067         // so forget about the builtin entirely.
8068         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
8069       }
8070     }
8071 
8072     // If this function is declared as being extern "C", then check to see if
8073     // the function returns a UDT (class, struct, or union type) that is not C
8074     // compatible, and if it does, warn the user.
8075     // But, issue any diagnostic on the first declaration only.
8076     if (Previous.empty() && NewFD->isExternC()) {
8077       QualType R = NewFD->getReturnType();
8078       if (R->isIncompleteType() && !R->isVoidType())
8079         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8080             << NewFD << R;
8081       else if (!R.isPODType(Context) && !R->isVoidType() &&
8082                !R->isObjCObjectPointerType())
8083         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8084     }
8085   }
8086   return Redeclaration;
8087 }
8088 
8089 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8090   // C++11 [basic.start.main]p3:
8091   //   A program that [...] declares main to be inline, static or
8092   //   constexpr is ill-formed.
8093   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8094   //   appear in a declaration of main.
8095   // static main is not an error under C99, but we should warn about it.
8096   // We accept _Noreturn main as an extension.
8097   if (FD->getStorageClass() == SC_Static)
8098     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8099          ? diag::err_static_main : diag::warn_static_main)
8100       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8101   if (FD->isInlineSpecified())
8102     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8103       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8104   if (DS.isNoreturnSpecified()) {
8105     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8106     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8107     Diag(NoreturnLoc, diag::ext_noreturn_main);
8108     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8109       << FixItHint::CreateRemoval(NoreturnRange);
8110   }
8111   if (FD->isConstexpr()) {
8112     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8113       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8114     FD->setConstexpr(false);
8115   }
8116 
8117   if (getLangOpts().OpenCL) {
8118     Diag(FD->getLocation(), diag::err_opencl_no_main)
8119         << FD->hasAttr<OpenCLKernelAttr>();
8120     FD->setInvalidDecl();
8121     return;
8122   }
8123 
8124   QualType T = FD->getType();
8125   assert(T->isFunctionType() && "function decl is not of function type");
8126   const FunctionType* FT = T->castAs<FunctionType>();
8127 
8128   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8129     // In C with GNU extensions we allow main() to have non-integer return
8130     // type, but we should warn about the extension, and we disable the
8131     // implicit-return-zero rule.
8132 
8133     // GCC in C mode accepts qualified 'int'.
8134     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8135       FD->setHasImplicitReturnZero(true);
8136     else {
8137       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8138       SourceRange RTRange = FD->getReturnTypeSourceRange();
8139       if (RTRange.isValid())
8140         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8141             << FixItHint::CreateReplacement(RTRange, "int");
8142     }
8143   } else {
8144     // In C and C++, main magically returns 0 if you fall off the end;
8145     // set the flag which tells us that.
8146     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8147 
8148     // All the standards say that main() should return 'int'.
8149     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8150       FD->setHasImplicitReturnZero(true);
8151     else {
8152       // Otherwise, this is just a flat-out error.
8153       SourceRange RTRange = FD->getReturnTypeSourceRange();
8154       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8155           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8156                                 : FixItHint());
8157       FD->setInvalidDecl(true);
8158     }
8159   }
8160 
8161   // Treat protoless main() as nullary.
8162   if (isa<FunctionNoProtoType>(FT)) return;
8163 
8164   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8165   unsigned nparams = FTP->getNumParams();
8166   assert(FD->getNumParams() == nparams);
8167 
8168   bool HasExtraParameters = (nparams > 3);
8169 
8170   // Darwin passes an undocumented fourth argument of type char**.  If
8171   // other platforms start sprouting these, the logic below will start
8172   // getting shifty.
8173   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8174     HasExtraParameters = false;
8175 
8176   if (HasExtraParameters) {
8177     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8178     FD->setInvalidDecl(true);
8179     nparams = 3;
8180   }
8181 
8182   // FIXME: a lot of the following diagnostics would be improved
8183   // if we had some location information about types.
8184 
8185   QualType CharPP =
8186     Context.getPointerType(Context.getPointerType(Context.CharTy));
8187   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8188 
8189   for (unsigned i = 0; i < nparams; ++i) {
8190     QualType AT = FTP->getParamType(i);
8191 
8192     bool mismatch = true;
8193 
8194     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8195       mismatch = false;
8196     else if (Expected[i] == CharPP) {
8197       // As an extension, the following forms are okay:
8198       //   char const **
8199       //   char const * const *
8200       //   char * const *
8201 
8202       QualifierCollector qs;
8203       const PointerType* PT;
8204       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8205           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8206           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8207                               Context.CharTy)) {
8208         qs.removeConst();
8209         mismatch = !qs.empty();
8210       }
8211     }
8212 
8213     if (mismatch) {
8214       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8215       // TODO: suggest replacing given type with expected type
8216       FD->setInvalidDecl(true);
8217     }
8218   }
8219 
8220   if (nparams == 1 && !FD->isInvalidDecl()) {
8221     Diag(FD->getLocation(), diag::warn_main_one_arg);
8222   }
8223 
8224   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8225     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8226     FD->setInvalidDecl();
8227   }
8228 }
8229 
8230 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8231   QualType T = FD->getType();
8232   assert(T->isFunctionType() && "function decl is not of function type");
8233   const FunctionType *FT = T->castAs<FunctionType>();
8234 
8235   // Set an implicit return of 'zero' if the function can return some integral,
8236   // enumeration, pointer or nullptr type.
8237   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8238       FT->getReturnType()->isAnyPointerType() ||
8239       FT->getReturnType()->isNullPtrType())
8240     // DllMain is exempt because a return value of zero means it failed.
8241     if (FD->getName() != "DllMain")
8242       FD->setHasImplicitReturnZero(true);
8243 
8244   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8245     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8246     FD->setInvalidDecl();
8247   }
8248 }
8249 
8250 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8251   // FIXME: Need strict checking.  In C89, we need to check for
8252   // any assignment, increment, decrement, function-calls, or
8253   // commas outside of a sizeof.  In C99, it's the same list,
8254   // except that the aforementioned are allowed in unevaluated
8255   // expressions.  Everything else falls under the
8256   // "may accept other forms of constant expressions" exception.
8257   // (We never end up here for C++, so the constant expression
8258   // rules there don't matter.)
8259   const Expr *Culprit;
8260   if (Init->isConstantInitializer(Context, false, &Culprit))
8261     return false;
8262   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8263     << Culprit->getSourceRange();
8264   return true;
8265 }
8266 
8267 namespace {
8268   // Visits an initialization expression to see if OrigDecl is evaluated in
8269   // its own initialization and throws a warning if it does.
8270   class SelfReferenceChecker
8271       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8272     Sema &S;
8273     Decl *OrigDecl;
8274     bool isRecordType;
8275     bool isPODType;
8276     bool isReferenceType;
8277 
8278     bool isInitList;
8279     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8280   public:
8281     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8282 
8283     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8284                                                     S(S), OrigDecl(OrigDecl) {
8285       isPODType = false;
8286       isRecordType = false;
8287       isReferenceType = false;
8288       isInitList = false;
8289       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8290         isPODType = VD->getType().isPODType(S.Context);
8291         isRecordType = VD->getType()->isRecordType();
8292         isReferenceType = VD->getType()->isReferenceType();
8293       }
8294     }
8295 
8296     // For most expressions, just call the visitor.  For initializer lists,
8297     // track the index of the field being initialized since fields are
8298     // initialized in order allowing use of previously initialized fields.
8299     void CheckExpr(Expr *E) {
8300       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8301       if (!InitList) {
8302         Visit(E);
8303         return;
8304       }
8305 
8306       // Track and increment the index here.
8307       isInitList = true;
8308       InitFieldIndex.push_back(0);
8309       for (auto Child : InitList->children()) {
8310         CheckExpr(cast<Expr>(Child));
8311         ++InitFieldIndex.back();
8312       }
8313       InitFieldIndex.pop_back();
8314     }
8315 
8316     // Returns true if MemberExpr is checked and no futher checking is needed.
8317     // Returns false if additional checking is required.
8318     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8319       llvm::SmallVector<FieldDecl*, 4> Fields;
8320       Expr *Base = E;
8321       bool ReferenceField = false;
8322 
8323       // Get the field memebers used.
8324       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8325         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8326         if (!FD)
8327           return false;
8328         Fields.push_back(FD);
8329         if (FD->getType()->isReferenceType())
8330           ReferenceField = true;
8331         Base = ME->getBase()->IgnoreParenImpCasts();
8332       }
8333 
8334       // Keep checking only if the base Decl is the same.
8335       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8336       if (!DRE || DRE->getDecl() != OrigDecl)
8337         return false;
8338 
8339       // A reference field can be bound to an unininitialized field.
8340       if (CheckReference && !ReferenceField)
8341         return true;
8342 
8343       // Convert FieldDecls to their index number.
8344       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8345       for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) {
8346         UsedFieldIndex.push_back((*I)->getFieldIndex());
8347       }
8348 
8349       // See if a warning is needed by checking the first difference in index
8350       // numbers.  If field being used has index less than the field being
8351       // initialized, then the use is safe.
8352       for (auto UsedIter = UsedFieldIndex.begin(),
8353                 UsedEnd = UsedFieldIndex.end(),
8354                 OrigIter = InitFieldIndex.begin(),
8355                 OrigEnd = InitFieldIndex.end();
8356            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8357         if (*UsedIter < *OrigIter)
8358           return true;
8359         if (*UsedIter > *OrigIter)
8360           break;
8361       }
8362 
8363       // TODO: Add a different warning which will print the field names.
8364       HandleDeclRefExpr(DRE);
8365       return true;
8366     }
8367 
8368     // For most expressions, the cast is directly above the DeclRefExpr.
8369     // For conditional operators, the cast can be outside the conditional
8370     // operator if both expressions are DeclRefExpr's.
8371     void HandleValue(Expr *E) {
8372       E = E->IgnoreParens();
8373       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8374         HandleDeclRefExpr(DRE);
8375         return;
8376       }
8377 
8378       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8379         Visit(CO->getCond());
8380         HandleValue(CO->getTrueExpr());
8381         HandleValue(CO->getFalseExpr());
8382         return;
8383       }
8384 
8385       if (BinaryConditionalOperator *BCO =
8386               dyn_cast<BinaryConditionalOperator>(E)) {
8387         Visit(BCO->getCond());
8388         HandleValue(BCO->getFalseExpr());
8389         return;
8390       }
8391 
8392       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8393         HandleValue(OVE->getSourceExpr());
8394         return;
8395       }
8396 
8397       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8398         if (BO->getOpcode() == BO_Comma) {
8399           Visit(BO->getLHS());
8400           HandleValue(BO->getRHS());
8401           return;
8402         }
8403       }
8404 
8405       if (isa<MemberExpr>(E)) {
8406         if (isInitList) {
8407           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8408                                       false /*CheckReference*/))
8409             return;
8410         }
8411 
8412         Expr *Base = E->IgnoreParenImpCasts();
8413         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8414           // Check for static member variables and don't warn on them.
8415           if (!isa<FieldDecl>(ME->getMemberDecl()))
8416             return;
8417           Base = ME->getBase()->IgnoreParenImpCasts();
8418         }
8419         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8420           HandleDeclRefExpr(DRE);
8421         return;
8422       }
8423 
8424       Visit(E);
8425     }
8426 
8427     // Reference types not handled in HandleValue are handled here since all
8428     // uses of references are bad, not just r-value uses.
8429     void VisitDeclRefExpr(DeclRefExpr *E) {
8430       if (isReferenceType)
8431         HandleDeclRefExpr(E);
8432     }
8433 
8434     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8435       if (E->getCastKind() == CK_LValueToRValue) {
8436         HandleValue(E->getSubExpr());
8437         return;
8438       }
8439 
8440       Inherited::VisitImplicitCastExpr(E);
8441     }
8442 
8443     void VisitMemberExpr(MemberExpr *E) {
8444       if (isInitList) {
8445         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8446           return;
8447       }
8448 
8449       // Don't warn on arrays since they can be treated as pointers.
8450       if (E->getType()->canDecayToPointerType()) return;
8451 
8452       // Warn when a non-static method call is followed by non-static member
8453       // field accesses, which is followed by a DeclRefExpr.
8454       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8455       bool Warn = (MD && !MD->isStatic());
8456       Expr *Base = E->getBase()->IgnoreParenImpCasts();
8457       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8458         if (!isa<FieldDecl>(ME->getMemberDecl()))
8459           Warn = false;
8460         Base = ME->getBase()->IgnoreParenImpCasts();
8461       }
8462 
8463       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8464         if (Warn)
8465           HandleDeclRefExpr(DRE);
8466         return;
8467       }
8468 
8469       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8470       // Visit that expression.
8471       Visit(Base);
8472     }
8473 
8474     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8475       Expr *Callee = E->getCallee();
8476 
8477       if (isa<UnresolvedLookupExpr>(Callee))
8478         return Inherited::VisitCXXOperatorCallExpr(E);
8479 
8480       Visit(Callee);
8481       for (auto Arg: E->arguments())
8482         HandleValue(Arg->IgnoreParenImpCasts());
8483     }
8484 
8485     void VisitUnaryOperator(UnaryOperator *E) {
8486       // For POD record types, addresses of its own members are well-defined.
8487       if (E->getOpcode() == UO_AddrOf && isRecordType &&
8488           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8489         if (!isPODType)
8490           HandleValue(E->getSubExpr());
8491         return;
8492       }
8493 
8494       if (E->isIncrementDecrementOp()) {
8495         HandleValue(E->getSubExpr());
8496         return;
8497       }
8498 
8499       Inherited::VisitUnaryOperator(E);
8500     }
8501 
8502     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8503 
8504     void VisitCXXConstructExpr(CXXConstructExpr *E) {
8505       if (E->getConstructor()->isCopyConstructor()) {
8506         Expr *ArgExpr = E->getArg(0);
8507         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
8508           if (ILE->getNumInits() == 1)
8509             ArgExpr = ILE->getInit(0);
8510         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8511           if (ICE->getCastKind() == CK_NoOp)
8512             ArgExpr = ICE->getSubExpr();
8513         HandleValue(ArgExpr);
8514         return;
8515       }
8516       Inherited::VisitCXXConstructExpr(E);
8517     }
8518 
8519     void VisitCallExpr(CallExpr *E) {
8520       // Treat std::move as a use.
8521       if (E->getNumArgs() == 1) {
8522         if (FunctionDecl *FD = E->getDirectCallee()) {
8523           if (FD->isInStdNamespace() && FD->getIdentifier() &&
8524               FD->getIdentifier()->isStr("move")) {
8525             HandleValue(E->getArg(0));
8526             return;
8527           }
8528         }
8529       }
8530 
8531       Inherited::VisitCallExpr(E);
8532     }
8533 
8534     void VisitBinaryOperator(BinaryOperator *E) {
8535       if (E->isCompoundAssignmentOp()) {
8536         HandleValue(E->getLHS());
8537         Visit(E->getRHS());
8538         return;
8539       }
8540 
8541       Inherited::VisitBinaryOperator(E);
8542     }
8543 
8544     // A custom visitor for BinaryConditionalOperator is needed because the
8545     // regular visitor would check the condition and true expression separately
8546     // but both point to the same place giving duplicate diagnostics.
8547     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
8548       Visit(E->getCond());
8549       Visit(E->getFalseExpr());
8550     }
8551 
8552     void HandleDeclRefExpr(DeclRefExpr *DRE) {
8553       Decl* ReferenceDecl = DRE->getDecl();
8554       if (OrigDecl != ReferenceDecl) return;
8555       unsigned diag;
8556       if (isReferenceType) {
8557         diag = diag::warn_uninit_self_reference_in_reference_init;
8558       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8559         diag = diag::warn_static_self_reference_in_init;
8560       } else {
8561         diag = diag::warn_uninit_self_reference_in_init;
8562       }
8563 
8564       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
8565                             S.PDiag(diag)
8566                               << DRE->getNameInfo().getName()
8567                               << OrigDecl->getLocation()
8568                               << DRE->getSourceRange());
8569     }
8570   };
8571 
8572   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8573   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8574                                  bool DirectInit) {
8575     // Parameters arguments are occassionially constructed with itself,
8576     // for instance, in recursive functions.  Skip them.
8577     if (isa<ParmVarDecl>(OrigDecl))
8578       return;
8579 
8580     E = E->IgnoreParens();
8581 
8582     // Skip checking T a = a where T is not a record or reference type.
8583     // Doing so is a way to silence uninitialized warnings.
8584     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8585       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8586         if (ICE->getCastKind() == CK_LValueToRValue)
8587           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8588             if (DRE->getDecl() == OrigDecl)
8589               return;
8590 
8591     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
8592   }
8593 }
8594 
8595 /// AddInitializerToDecl - Adds the initializer Init to the
8596 /// declaration dcl. If DirectInit is true, this is C++ direct
8597 /// initialization rather than copy initialization.
8598 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8599                                 bool DirectInit, bool TypeMayContainAuto) {
8600   // If there is no declaration, there was an error parsing it.  Just ignore
8601   // the initializer.
8602   if (!RealDecl || RealDecl->isInvalidDecl()) {
8603     CorrectDelayedTyposInExpr(Init);
8604     return;
8605   }
8606 
8607   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8608     // With declarators parsed the way they are, the parser cannot
8609     // distinguish between a normal initializer and a pure-specifier.
8610     // Thus this grotesque test.
8611     IntegerLiteral *IL;
8612     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
8613         Context.getCanonicalType(IL->getType()) == Context.IntTy)
8614       CheckPureMethod(Method, Init->getSourceRange());
8615     else {
8616       Diag(Method->getLocation(), diag::err_member_function_initialization)
8617         << Method->getDeclName() << Init->getSourceRange();
8618       Method->setInvalidDecl();
8619     }
8620     return;
8621   }
8622 
8623   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8624   if (!VDecl) {
8625     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8626     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8627     RealDecl->setInvalidDecl();
8628     return;
8629   }
8630   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8631 
8632   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8633   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8634     Expr *DeduceInit = Init;
8635     // Initializer could be a C++ direct-initializer. Deduction only works if it
8636     // contains exactly one expression.
8637     if (CXXDirectInit) {
8638       if (CXXDirectInit->getNumExprs() == 0) {
8639         // It isn't possible to write this directly, but it is possible to
8640         // end up in this situation with "auto x(some_pack...);"
8641         Diag(CXXDirectInit->getLocStart(),
8642              VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8643                                     : diag::err_auto_var_init_no_expression)
8644           << VDecl->getDeclName() << VDecl->getType()
8645           << VDecl->getSourceRange();
8646         RealDecl->setInvalidDecl();
8647         return;
8648       } else if (CXXDirectInit->getNumExprs() > 1) {
8649         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8650              VDecl->isInitCapture()
8651                  ? diag::err_init_capture_multiple_expressions
8652                  : diag::err_auto_var_init_multiple_expressions)
8653           << VDecl->getDeclName() << VDecl->getType()
8654           << VDecl->getSourceRange();
8655         RealDecl->setInvalidDecl();
8656         return;
8657       } else {
8658         DeduceInit = CXXDirectInit->getExpr(0);
8659         if (isa<InitListExpr>(DeduceInit))
8660           Diag(CXXDirectInit->getLocStart(),
8661                diag::err_auto_var_init_paren_braces)
8662             << VDecl->getDeclName() << VDecl->getType()
8663             << VDecl->getSourceRange();
8664       }
8665     }
8666 
8667     // Expressions default to 'id' when we're in a debugger.
8668     bool DefaultedToAuto = false;
8669     if (getLangOpts().DebuggerCastResultToId &&
8670         Init->getType() == Context.UnknownAnyTy) {
8671       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8672       if (Result.isInvalid()) {
8673         VDecl->setInvalidDecl();
8674         return;
8675       }
8676       Init = Result.get();
8677       DefaultedToAuto = true;
8678     }
8679 
8680     QualType DeducedType;
8681     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8682             DAR_Failed)
8683       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8684     if (DeducedType.isNull()) {
8685       RealDecl->setInvalidDecl();
8686       return;
8687     }
8688     VDecl->setType(DeducedType);
8689     assert(VDecl->isLinkageValid());
8690 
8691     // In ARC, infer lifetime.
8692     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8693       VDecl->setInvalidDecl();
8694 
8695     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8696     // 'id' instead of a specific object type prevents most of our usual checks.
8697     // We only want to warn outside of template instantiations, though:
8698     // inside a template, the 'id' could have come from a parameter.
8699     if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8700         DeducedType->isObjCIdType()) {
8701       SourceLocation Loc =
8702           VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8703       Diag(Loc, diag::warn_auto_var_is_id)
8704         << VDecl->getDeclName() << DeduceInit->getSourceRange();
8705     }
8706 
8707     // If this is a redeclaration, check that the type we just deduced matches
8708     // the previously declared type.
8709     if (VarDecl *Old = VDecl->getPreviousDecl()) {
8710       // We never need to merge the type, because we cannot form an incomplete
8711       // array of auto, nor deduce such a type.
8712       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8713     }
8714 
8715     // Check the deduced type is valid for a variable declaration.
8716     CheckVariableDeclarationType(VDecl);
8717     if (VDecl->isInvalidDecl())
8718       return;
8719 
8720     // If all looks well, warn if this is a case that will change meaning when
8721     // we implement N3922.
8722     if (DirectInit && !CXXDirectInit && isa<InitListExpr>(Init)) {
8723       Diag(Init->getLocStart(),
8724            diag::warn_auto_var_direct_list_init)
8725         << FixItHint::CreateInsertion(Init->getLocStart(), "=");
8726     }
8727   }
8728 
8729   // dllimport cannot be used on variable definitions.
8730   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8731     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8732     VDecl->setInvalidDecl();
8733     return;
8734   }
8735 
8736   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8737     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8738     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8739     VDecl->setInvalidDecl();
8740     return;
8741   }
8742 
8743   if (!VDecl->getType()->isDependentType()) {
8744     // A definition must end up with a complete type, which means it must be
8745     // complete with the restriction that an array type might be completed by
8746     // the initializer; note that later code assumes this restriction.
8747     QualType BaseDeclType = VDecl->getType();
8748     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8749       BaseDeclType = Array->getElementType();
8750     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8751                             diag::err_typecheck_decl_incomplete_type)) {
8752       RealDecl->setInvalidDecl();
8753       return;
8754     }
8755 
8756     // The variable can not have an abstract class type.
8757     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8758                                diag::err_abstract_type_in_decl,
8759                                AbstractVariableType))
8760       VDecl->setInvalidDecl();
8761   }
8762 
8763   const VarDecl *Def;
8764   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8765     Diag(VDecl->getLocation(), diag::err_redefinition)
8766       << VDecl->getDeclName();
8767     Diag(Def->getLocation(), diag::note_previous_definition);
8768     VDecl->setInvalidDecl();
8769     return;
8770   }
8771 
8772   const VarDecl *PrevInit = nullptr;
8773   if (getLangOpts().CPlusPlus) {
8774     // C++ [class.static.data]p4
8775     //   If a static data member is of const integral or const
8776     //   enumeration type, its declaration in the class definition can
8777     //   specify a constant-initializer which shall be an integral
8778     //   constant expression (5.19). In that case, the member can appear
8779     //   in integral constant expressions. The member shall still be
8780     //   defined in a namespace scope if it is used in the program and the
8781     //   namespace scope definition shall not contain an initializer.
8782     //
8783     // We already performed a redefinition check above, but for static
8784     // data members we also need to check whether there was an in-class
8785     // declaration with an initializer.
8786     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8787       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8788           << VDecl->getDeclName();
8789       Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
8790       return;
8791     }
8792 
8793     if (VDecl->hasLocalStorage())
8794       getCurFunction()->setHasBranchProtectedScope();
8795 
8796     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8797       VDecl->setInvalidDecl();
8798       return;
8799     }
8800   }
8801 
8802   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8803   // a kernel function cannot be initialized."
8804   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8805     Diag(VDecl->getLocation(), diag::err_local_cant_init);
8806     VDecl->setInvalidDecl();
8807     return;
8808   }
8809 
8810   // Get the decls type and save a reference for later, since
8811   // CheckInitializerTypes may change it.
8812   QualType DclT = VDecl->getType(), SavT = DclT;
8813 
8814   // Expressions default to 'id' when we're in a debugger
8815   // and we are assigning it to a variable of Objective-C pointer type.
8816   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8817       Init->getType() == Context.UnknownAnyTy) {
8818     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8819     if (Result.isInvalid()) {
8820       VDecl->setInvalidDecl();
8821       return;
8822     }
8823     Init = Result.get();
8824   }
8825 
8826   // Perform the initialization.
8827   if (!VDecl->isInvalidDecl()) {
8828     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8829     InitializationKind Kind
8830       = DirectInit ?
8831           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8832                                                            Init->getLocStart(),
8833                                                            Init->getLocEnd())
8834                         : InitializationKind::CreateDirectList(
8835                                                           VDecl->getLocation())
8836                    : InitializationKind::CreateCopy(VDecl->getLocation(),
8837                                                     Init->getLocStart());
8838 
8839     MultiExprArg Args = Init;
8840     if (CXXDirectInit)
8841       Args = MultiExprArg(CXXDirectInit->getExprs(),
8842                           CXXDirectInit->getNumExprs());
8843 
8844     // Try to correct any TypoExprs in the initialization arguments.
8845     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
8846       ExprResult Res =
8847           CorrectDelayedTyposInExpr(Args[Idx], [this, Entity, Kind](Expr *E) {
8848             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
8849             return Init.Failed() ? ExprError() : E;
8850           });
8851       if (Res.isInvalid()) {
8852         VDecl->setInvalidDecl();
8853       } else if (Res.get() != Args[Idx]) {
8854         Args[Idx] = Res.get();
8855       }
8856     }
8857     if (VDecl->isInvalidDecl())
8858       return;
8859 
8860     InitializationSequence InitSeq(*this, Entity, Kind, Args);
8861     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8862     if (Result.isInvalid()) {
8863       VDecl->setInvalidDecl();
8864       return;
8865     }
8866 
8867     Init = Result.getAs<Expr>();
8868   }
8869 
8870   // Check for self-references within variable initializers.
8871   // Variables declared within a function/method body (except for references)
8872   // are handled by a dataflow analysis.
8873   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8874       VDecl->getType()->isReferenceType()) {
8875     CheckSelfReference(*this, RealDecl, Init, DirectInit);
8876   }
8877 
8878   // If the type changed, it means we had an incomplete type that was
8879   // completed by the initializer. For example:
8880   //   int ary[] = { 1, 3, 5 };
8881   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
8882   if (!VDecl->isInvalidDecl() && (DclT != SavT))
8883     VDecl->setType(DclT);
8884 
8885   if (!VDecl->isInvalidDecl()) {
8886     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8887 
8888     if (VDecl->hasAttr<BlocksAttr>())
8889       checkRetainCycles(VDecl, Init);
8890 
8891     // It is safe to assign a weak reference into a strong variable.
8892     // Although this code can still have problems:
8893     //   id x = self.weakProp;
8894     //   id y = self.weakProp;
8895     // we do not warn to warn spuriously when 'x' and 'y' are on separate
8896     // paths through the function. This should be revisited if
8897     // -Wrepeated-use-of-weak is made flow-sensitive.
8898     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
8899         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8900                          Init->getLocStart()))
8901         getCurFunction()->markSafeWeakUse(Init);
8902   }
8903 
8904   // The initialization is usually a full-expression.
8905   //
8906   // FIXME: If this is a braced initialization of an aggregate, it is not
8907   // an expression, and each individual field initializer is a separate
8908   // full-expression. For instance, in:
8909   //
8910   //   struct Temp { ~Temp(); };
8911   //   struct S { S(Temp); };
8912   //   struct T { S a, b; } t = { Temp(), Temp() }
8913   //
8914   // we should destroy the first Temp before constructing the second.
8915   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8916                                           false,
8917                                           VDecl->isConstexpr());
8918   if (Result.isInvalid()) {
8919     VDecl->setInvalidDecl();
8920     return;
8921   }
8922   Init = Result.get();
8923 
8924   // Attach the initializer to the decl.
8925   VDecl->setInit(Init);
8926 
8927   if (VDecl->isLocalVarDecl()) {
8928     // C99 6.7.8p4: All the expressions in an initializer for an object that has
8929     // static storage duration shall be constant expressions or string literals.
8930     // C++ does not have this restriction.
8931     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8932       const Expr *Culprit;
8933       if (VDecl->getStorageClass() == SC_Static)
8934         CheckForConstantInitializer(Init, DclT);
8935       // C89 is stricter than C99 for non-static aggregate types.
8936       // C89 6.5.7p3: All the expressions [...] in an initializer list
8937       // for an object that has aggregate or union type shall be
8938       // constant expressions.
8939       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
8940                isa<InitListExpr>(Init) &&
8941                !Init->isConstantInitializer(Context, false, &Culprit))
8942         Diag(Culprit->getExprLoc(),
8943              diag::ext_aggregate_init_not_constant)
8944           << Culprit->getSourceRange();
8945     }
8946   } else if (VDecl->isStaticDataMember() &&
8947              VDecl->getLexicalDeclContext()->isRecord()) {
8948     // This is an in-class initialization for a static data member, e.g.,
8949     //
8950     // struct S {
8951     //   static const int value = 17;
8952     // };
8953 
8954     // C++ [class.mem]p4:
8955     //   A member-declarator can contain a constant-initializer only
8956     //   if it declares a static member (9.4) of const integral or
8957     //   const enumeration type, see 9.4.2.
8958     //
8959     // C++11 [class.static.data]p3:
8960     //   If a non-volatile const static data member is of integral or
8961     //   enumeration type, its declaration in the class definition can
8962     //   specify a brace-or-equal-initializer in which every initalizer-clause
8963     //   that is an assignment-expression is a constant expression. A static
8964     //   data member of literal type can be declared in the class definition
8965     //   with the constexpr specifier; if so, its declaration shall specify a
8966     //   brace-or-equal-initializer in which every initializer-clause that is
8967     //   an assignment-expression is a constant expression.
8968 
8969     // Do nothing on dependent types.
8970     if (DclT->isDependentType()) {
8971 
8972     // Allow any 'static constexpr' members, whether or not they are of literal
8973     // type. We separately check that every constexpr variable is of literal
8974     // type.
8975     } else if (VDecl->isConstexpr()) {
8976 
8977     // Require constness.
8978     } else if (!DclT.isConstQualified()) {
8979       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8980         << Init->getSourceRange();
8981       VDecl->setInvalidDecl();
8982 
8983     // We allow integer constant expressions in all cases.
8984     } else if (DclT->isIntegralOrEnumerationType()) {
8985       // Check whether the expression is a constant expression.
8986       SourceLocation Loc;
8987       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
8988         // In C++11, a non-constexpr const static data member with an
8989         // in-class initializer cannot be volatile.
8990         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8991       else if (Init->isValueDependent())
8992         ; // Nothing to check.
8993       else if (Init->isIntegerConstantExpr(Context, &Loc))
8994         ; // Ok, it's an ICE!
8995       else if (Init->isEvaluatable(Context)) {
8996         // If we can constant fold the initializer through heroics, accept it,
8997         // but report this as a use of an extension for -pedantic.
8998         Diag(Loc, diag::ext_in_class_initializer_non_constant)
8999           << Init->getSourceRange();
9000       } else {
9001         // Otherwise, this is some crazy unknown case.  Report the issue at the
9002         // location provided by the isIntegerConstantExpr failed check.
9003         Diag(Loc, diag::err_in_class_initializer_non_constant)
9004           << Init->getSourceRange();
9005         VDecl->setInvalidDecl();
9006       }
9007 
9008     // We allow foldable floating-point constants as an extension.
9009     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9010       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9011       // it anyway and provide a fixit to add the 'constexpr'.
9012       if (getLangOpts().CPlusPlus11) {
9013         Diag(VDecl->getLocation(),
9014              diag::ext_in_class_initializer_float_type_cxx11)
9015             << DclT << Init->getSourceRange();
9016         Diag(VDecl->getLocStart(),
9017              diag::note_in_class_initializer_float_type_cxx11)
9018             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9019       } else {
9020         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9021           << DclT << Init->getSourceRange();
9022 
9023         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9024           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9025             << Init->getSourceRange();
9026           VDecl->setInvalidDecl();
9027         }
9028       }
9029 
9030     // Suggest adding 'constexpr' in C++11 for literal types.
9031     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9032       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9033         << DclT << Init->getSourceRange()
9034         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9035       VDecl->setConstexpr(true);
9036 
9037     } else {
9038       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9039         << DclT << Init->getSourceRange();
9040       VDecl->setInvalidDecl();
9041     }
9042   } else if (VDecl->isFileVarDecl()) {
9043     if (VDecl->getStorageClass() == SC_Extern &&
9044         (!getLangOpts().CPlusPlus ||
9045          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9046            VDecl->isExternC())) &&
9047         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9048       Diag(VDecl->getLocation(), diag::warn_extern_init);
9049 
9050     // C99 6.7.8p4. All file scoped initializers need to be constant.
9051     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9052       CheckForConstantInitializer(Init, DclT);
9053   }
9054 
9055   // We will represent direct-initialization similarly to copy-initialization:
9056   //    int x(1);  -as-> int x = 1;
9057   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9058   //
9059   // Clients that want to distinguish between the two forms, can check for
9060   // direct initializer using VarDecl::getInitStyle().
9061   // A major benefit is that clients that don't particularly care about which
9062   // exactly form was it (like the CodeGen) can handle both cases without
9063   // special case code.
9064 
9065   // C++ 8.5p11:
9066   // The form of initialization (using parentheses or '=') is generally
9067   // insignificant, but does matter when the entity being initialized has a
9068   // class type.
9069   if (CXXDirectInit) {
9070     assert(DirectInit && "Call-style initializer must be direct init.");
9071     VDecl->setInitStyle(VarDecl::CallInit);
9072   } else if (DirectInit) {
9073     // This must be list-initialization. No other way is direct-initialization.
9074     VDecl->setInitStyle(VarDecl::ListInit);
9075   }
9076 
9077   CheckCompleteVariableDeclaration(VDecl);
9078 }
9079 
9080 /// ActOnInitializerError - Given that there was an error parsing an
9081 /// initializer for the given declaration, try to return to some form
9082 /// of sanity.
9083 void Sema::ActOnInitializerError(Decl *D) {
9084   // Our main concern here is re-establishing invariants like "a
9085   // variable's type is either dependent or complete".
9086   if (!D || D->isInvalidDecl()) return;
9087 
9088   VarDecl *VD = dyn_cast<VarDecl>(D);
9089   if (!VD) return;
9090 
9091   // Auto types are meaningless if we can't make sense of the initializer.
9092   if (ParsingInitForAutoVars.count(D)) {
9093     D->setInvalidDecl();
9094     return;
9095   }
9096 
9097   QualType Ty = VD->getType();
9098   if (Ty->isDependentType()) return;
9099 
9100   // Require a complete type.
9101   if (RequireCompleteType(VD->getLocation(),
9102                           Context.getBaseElementType(Ty),
9103                           diag::err_typecheck_decl_incomplete_type)) {
9104     VD->setInvalidDecl();
9105     return;
9106   }
9107 
9108   // Require a non-abstract type.
9109   if (RequireNonAbstractType(VD->getLocation(), Ty,
9110                              diag::err_abstract_type_in_decl,
9111                              AbstractVariableType)) {
9112     VD->setInvalidDecl();
9113     return;
9114   }
9115 
9116   // Don't bother complaining about constructors or destructors,
9117   // though.
9118 }
9119 
9120 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9121                                   bool TypeMayContainAuto) {
9122   // If there is no declaration, there was an error parsing it. Just ignore it.
9123   if (!RealDecl)
9124     return;
9125 
9126   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9127     QualType Type = Var->getType();
9128 
9129     // C++11 [dcl.spec.auto]p3
9130     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9131       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9132         << Var->getDeclName() << Type;
9133       Var->setInvalidDecl();
9134       return;
9135     }
9136 
9137     // C++11 [class.static.data]p3: A static data member can be declared with
9138     // the constexpr specifier; if so, its declaration shall specify
9139     // a brace-or-equal-initializer.
9140     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9141     // the definition of a variable [...] or the declaration of a static data
9142     // member.
9143     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9144       if (Var->isStaticDataMember())
9145         Diag(Var->getLocation(),
9146              diag::err_constexpr_static_mem_var_requires_init)
9147           << Var->getDeclName();
9148       else
9149         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9150       Var->setInvalidDecl();
9151       return;
9152     }
9153 
9154     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9155     // be initialized.
9156     if (!Var->isInvalidDecl() &&
9157         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9158         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9159       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9160       Var->setInvalidDecl();
9161       return;
9162     }
9163 
9164     switch (Var->isThisDeclarationADefinition()) {
9165     case VarDecl::Definition:
9166       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9167         break;
9168 
9169       // We have an out-of-line definition of a static data member
9170       // that has an in-class initializer, so we type-check this like
9171       // a declaration.
9172       //
9173       // Fall through
9174 
9175     case VarDecl::DeclarationOnly:
9176       // It's only a declaration.
9177 
9178       // Block scope. C99 6.7p7: If an identifier for an object is
9179       // declared with no linkage (C99 6.2.2p6), the type for the
9180       // object shall be complete.
9181       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9182           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9183           RequireCompleteType(Var->getLocation(), Type,
9184                               diag::err_typecheck_decl_incomplete_type))
9185         Var->setInvalidDecl();
9186 
9187       // Make sure that the type is not abstract.
9188       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9189           RequireNonAbstractType(Var->getLocation(), Type,
9190                                  diag::err_abstract_type_in_decl,
9191                                  AbstractVariableType))
9192         Var->setInvalidDecl();
9193       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9194           Var->getStorageClass() == SC_PrivateExtern) {
9195         Diag(Var->getLocation(), diag::warn_private_extern);
9196         Diag(Var->getLocation(), diag::note_private_extern);
9197       }
9198 
9199       return;
9200 
9201     case VarDecl::TentativeDefinition:
9202       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9203       // object that has file scope without an initializer, and without a
9204       // storage-class specifier or with the storage-class specifier "static",
9205       // constitutes a tentative definition. Note: A tentative definition with
9206       // external linkage is valid (C99 6.2.2p5).
9207       if (!Var->isInvalidDecl()) {
9208         if (const IncompleteArrayType *ArrayT
9209                                     = Context.getAsIncompleteArrayType(Type)) {
9210           if (RequireCompleteType(Var->getLocation(),
9211                                   ArrayT->getElementType(),
9212                                   diag::err_illegal_decl_array_incomplete_type))
9213             Var->setInvalidDecl();
9214         } else if (Var->getStorageClass() == SC_Static) {
9215           // C99 6.9.2p3: If the declaration of an identifier for an object is
9216           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9217           // declared type shall not be an incomplete type.
9218           // NOTE: code such as the following
9219           //     static struct s;
9220           //     struct s { int a; };
9221           // is accepted by gcc. Hence here we issue a warning instead of
9222           // an error and we do not invalidate the static declaration.
9223           // NOTE: to avoid multiple warnings, only check the first declaration.
9224           if (Var->isFirstDecl())
9225             RequireCompleteType(Var->getLocation(), Type,
9226                                 diag::ext_typecheck_decl_incomplete_type);
9227         }
9228       }
9229 
9230       // Record the tentative definition; we're done.
9231       if (!Var->isInvalidDecl())
9232         TentativeDefinitions.push_back(Var);
9233       return;
9234     }
9235 
9236     // Provide a specific diagnostic for uninitialized variable
9237     // definitions with incomplete array type.
9238     if (Type->isIncompleteArrayType()) {
9239       Diag(Var->getLocation(),
9240            diag::err_typecheck_incomplete_array_needs_initializer);
9241       Var->setInvalidDecl();
9242       return;
9243     }
9244 
9245     // Provide a specific diagnostic for uninitialized variable
9246     // definitions with reference type.
9247     if (Type->isReferenceType()) {
9248       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9249         << Var->getDeclName()
9250         << SourceRange(Var->getLocation(), Var->getLocation());
9251       Var->setInvalidDecl();
9252       return;
9253     }
9254 
9255     // Do not attempt to type-check the default initializer for a
9256     // variable with dependent type.
9257     if (Type->isDependentType())
9258       return;
9259 
9260     if (Var->isInvalidDecl())
9261       return;
9262 
9263     if (!Var->hasAttr<AliasAttr>()) {
9264       if (RequireCompleteType(Var->getLocation(),
9265                               Context.getBaseElementType(Type),
9266                               diag::err_typecheck_decl_incomplete_type)) {
9267         Var->setInvalidDecl();
9268         return;
9269       }
9270     } else {
9271       return;
9272     }
9273 
9274     // The variable can not have an abstract class type.
9275     if (RequireNonAbstractType(Var->getLocation(), Type,
9276                                diag::err_abstract_type_in_decl,
9277                                AbstractVariableType)) {
9278       Var->setInvalidDecl();
9279       return;
9280     }
9281 
9282     // Check for jumps past the implicit initializer.  C++0x
9283     // clarifies that this applies to a "variable with automatic
9284     // storage duration", not a "local variable".
9285     // C++11 [stmt.dcl]p3
9286     //   A program that jumps from a point where a variable with automatic
9287     //   storage duration is not in scope to a point where it is in scope is
9288     //   ill-formed unless the variable has scalar type, class type with a
9289     //   trivial default constructor and a trivial destructor, a cv-qualified
9290     //   version of one of these types, or an array of one of the preceding
9291     //   types and is declared without an initializer.
9292     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9293       if (const RecordType *Record
9294             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9295         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9296         // Mark the function for further checking even if the looser rules of
9297         // C++11 do not require such checks, so that we can diagnose
9298         // incompatibilities with C++98.
9299         if (!CXXRecord->isPOD())
9300           getCurFunction()->setHasBranchProtectedScope();
9301       }
9302     }
9303 
9304     // C++03 [dcl.init]p9:
9305     //   If no initializer is specified for an object, and the
9306     //   object is of (possibly cv-qualified) non-POD class type (or
9307     //   array thereof), the object shall be default-initialized; if
9308     //   the object is of const-qualified type, the underlying class
9309     //   type shall have a user-declared default
9310     //   constructor. Otherwise, if no initializer is specified for
9311     //   a non- static object, the object and its subobjects, if
9312     //   any, have an indeterminate initial value); if the object
9313     //   or any of its subobjects are of const-qualified type, the
9314     //   program is ill-formed.
9315     // C++0x [dcl.init]p11:
9316     //   If no initializer is specified for an object, the object is
9317     //   default-initialized; [...].
9318     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9319     InitializationKind Kind
9320       = InitializationKind::CreateDefault(Var->getLocation());
9321 
9322     InitializationSequence InitSeq(*this, Entity, Kind, None);
9323     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9324     if (Init.isInvalid())
9325       Var->setInvalidDecl();
9326     else if (Init.get()) {
9327       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9328       // This is important for template substitution.
9329       Var->setInitStyle(VarDecl::CallInit);
9330     }
9331 
9332     CheckCompleteVariableDeclaration(Var);
9333   }
9334 }
9335 
9336 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9337   VarDecl *VD = dyn_cast<VarDecl>(D);
9338   if (!VD) {
9339     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9340     D->setInvalidDecl();
9341     return;
9342   }
9343 
9344   VD->setCXXForRangeDecl(true);
9345 
9346   // for-range-declaration cannot be given a storage class specifier.
9347   int Error = -1;
9348   switch (VD->getStorageClass()) {
9349   case SC_None:
9350     break;
9351   case SC_Extern:
9352     Error = 0;
9353     break;
9354   case SC_Static:
9355     Error = 1;
9356     break;
9357   case SC_PrivateExtern:
9358     Error = 2;
9359     break;
9360   case SC_Auto:
9361     Error = 3;
9362     break;
9363   case SC_Register:
9364     Error = 4;
9365     break;
9366   case SC_OpenCLWorkGroupLocal:
9367     llvm_unreachable("Unexpected storage class");
9368   }
9369   if (VD->isConstexpr())
9370     Error = 5;
9371   if (Error != -1) {
9372     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9373       << VD->getDeclName() << Error;
9374     D->setInvalidDecl();
9375   }
9376 }
9377 
9378 StmtResult
9379 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9380                                  IdentifierInfo *Ident,
9381                                  ParsedAttributes &Attrs,
9382                                  SourceLocation AttrEnd) {
9383   // C++1y [stmt.iter]p1:
9384   //   A range-based for statement of the form
9385   //      for ( for-range-identifier : for-range-initializer ) statement
9386   //   is equivalent to
9387   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
9388   DeclSpec DS(Attrs.getPool().getFactory());
9389 
9390   const char *PrevSpec;
9391   unsigned DiagID;
9392   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9393                      getPrintingPolicy());
9394 
9395   Declarator D(DS, Declarator::ForContext);
9396   D.SetIdentifier(Ident, IdentLoc);
9397   D.takeAttributes(Attrs, AttrEnd);
9398 
9399   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9400   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9401                 EmptyAttrs, IdentLoc);
9402   Decl *Var = ActOnDeclarator(S, D);
9403   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9404   FinalizeDeclaration(Var);
9405   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9406                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
9407 }
9408 
9409 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9410   if (var->isInvalidDecl()) return;
9411 
9412   // In ARC, don't allow jumps past the implicit initialization of a
9413   // local retaining variable.
9414   if (getLangOpts().ObjCAutoRefCount &&
9415       var->hasLocalStorage()) {
9416     switch (var->getType().getObjCLifetime()) {
9417     case Qualifiers::OCL_None:
9418     case Qualifiers::OCL_ExplicitNone:
9419     case Qualifiers::OCL_Autoreleasing:
9420       break;
9421 
9422     case Qualifiers::OCL_Weak:
9423     case Qualifiers::OCL_Strong:
9424       getCurFunction()->setHasBranchProtectedScope();
9425       break;
9426     }
9427   }
9428 
9429   // Warn about externally-visible variables being defined without a
9430   // prior declaration.  We only want to do this for global
9431   // declarations, but we also specifically need to avoid doing it for
9432   // class members because the linkage of an anonymous class can
9433   // change if it's later given a typedef name.
9434   if (var->isThisDeclarationADefinition() &&
9435       var->getDeclContext()->getRedeclContext()->isFileContext() &&
9436       var->isExternallyVisible() && var->hasLinkage() &&
9437       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9438                                   var->getLocation())) {
9439     // Find a previous declaration that's not a definition.
9440     VarDecl *prev = var->getPreviousDecl();
9441     while (prev && prev->isThisDeclarationADefinition())
9442       prev = prev->getPreviousDecl();
9443 
9444     if (!prev)
9445       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9446   }
9447 
9448   if (var->getTLSKind() == VarDecl::TLS_Static) {
9449     const Expr *Culprit;
9450     if (var->getType().isDestructedType()) {
9451       // GNU C++98 edits for __thread, [basic.start.term]p3:
9452       //   The type of an object with thread storage duration shall not
9453       //   have a non-trivial destructor.
9454       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9455       if (getLangOpts().CPlusPlus11)
9456         Diag(var->getLocation(), diag::note_use_thread_local);
9457     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9458                !var->getInit()->isConstantInitializer(
9459                    Context, var->getType()->isReferenceType(), &Culprit)) {
9460       // GNU C++98 edits for __thread, [basic.start.init]p4:
9461       //   An object of thread storage duration shall not require dynamic
9462       //   initialization.
9463       // FIXME: Need strict checking here.
9464       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9465         << Culprit->getSourceRange();
9466       if (getLangOpts().CPlusPlus11)
9467         Diag(var->getLocation(), diag::note_use_thread_local);
9468     }
9469 
9470   }
9471 
9472   if (var->isThisDeclarationADefinition() &&
9473       ActiveTemplateInstantiations.empty()) {
9474     PragmaStack<StringLiteral *> *Stack = nullptr;
9475     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
9476     if (var->getType().isConstQualified())
9477       Stack = &ConstSegStack;
9478     else if (!var->getInit()) {
9479       Stack = &BSSSegStack;
9480       SectionFlags |= ASTContext::PSF_Write;
9481     } else {
9482       Stack = &DataSegStack;
9483       SectionFlags |= ASTContext::PSF_Write;
9484     }
9485     if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue)
9486       var->addAttr(
9487           SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
9488                                       Stack->CurrentValue->getString(),
9489                                       Stack->CurrentPragmaLocation));
9490     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
9491       if (UnifySection(SA->getName(), SectionFlags, var))
9492         var->dropAttr<SectionAttr>();
9493 
9494     // Apply the init_seg attribute if this has an initializer.  If the
9495     // initializer turns out to not be dynamic, we'll end up ignoring this
9496     // attribute.
9497     if (CurInitSeg && var->getInit())
9498       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
9499                                                CurInitSegLoc));
9500   }
9501 
9502   // All the following checks are C++ only.
9503   if (!getLangOpts().CPlusPlus) return;
9504 
9505   QualType type = var->getType();
9506   if (type->isDependentType()) return;
9507 
9508   // __block variables might require us to capture a copy-initializer.
9509   if (var->hasAttr<BlocksAttr>()) {
9510     // It's currently invalid to ever have a __block variable with an
9511     // array type; should we diagnose that here?
9512 
9513     // Regardless, we don't want to ignore array nesting when
9514     // constructing this copy.
9515     if (type->isStructureOrClassType()) {
9516       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
9517       SourceLocation poi = var->getLocation();
9518       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
9519       ExprResult result
9520         = PerformMoveOrCopyInitialization(
9521             InitializedEntity::InitializeBlock(poi, type, false),
9522             var, var->getType(), varRef, /*AllowNRVO=*/true);
9523       if (!result.isInvalid()) {
9524         result = MaybeCreateExprWithCleanups(result);
9525         Expr *init = result.getAs<Expr>();
9526         Context.setBlockVarCopyInits(var, init);
9527       }
9528     }
9529   }
9530 
9531   Expr *Init = var->getInit();
9532   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
9533   QualType baseType = Context.getBaseElementType(type);
9534 
9535   if (!var->getDeclContext()->isDependentContext() &&
9536       Init && !Init->isValueDependent()) {
9537     if (IsGlobal && !var->isConstexpr() &&
9538         !getDiagnostics().isIgnored(diag::warn_global_constructor,
9539                                     var->getLocation())) {
9540       // Warn about globals which don't have a constant initializer.  Don't
9541       // warn about globals with a non-trivial destructor because we already
9542       // warned about them.
9543       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
9544       if (!(RD && !RD->hasTrivialDestructor()) &&
9545           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
9546         Diag(var->getLocation(), diag::warn_global_constructor)
9547           << Init->getSourceRange();
9548     }
9549 
9550     if (var->isConstexpr()) {
9551       SmallVector<PartialDiagnosticAt, 8> Notes;
9552       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
9553         SourceLocation DiagLoc = var->getLocation();
9554         // If the note doesn't add any useful information other than a source
9555         // location, fold it into the primary diagnostic.
9556         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9557               diag::note_invalid_subexpr_in_const_expr) {
9558           DiagLoc = Notes[0].first;
9559           Notes.clear();
9560         }
9561         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
9562           << var << Init->getSourceRange();
9563         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9564           Diag(Notes[I].first, Notes[I].second);
9565       }
9566     } else if (var->isUsableInConstantExpressions(Context)) {
9567       // Check whether the initializer of a const variable of integral or
9568       // enumeration type is an ICE now, since we can't tell whether it was
9569       // initialized by a constant expression if we check later.
9570       var->checkInitIsICE();
9571     }
9572   }
9573 
9574   // Require the destructor.
9575   if (const RecordType *recordType = baseType->getAs<RecordType>())
9576     FinalizeVarWithDestructor(var, recordType);
9577 }
9578 
9579 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9580 /// any semantic actions necessary after any initializer has been attached.
9581 void
9582 Sema::FinalizeDeclaration(Decl *ThisDecl) {
9583   // Note that we are no longer parsing the initializer for this declaration.
9584   ParsingInitForAutoVars.erase(ThisDecl);
9585 
9586   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
9587   if (!VD)
9588     return;
9589 
9590   checkAttributesAfterMerging(*this, *VD);
9591 
9592   // Static locals inherit dll attributes from their function.
9593   if (VD->isStaticLocal()) {
9594     if (FunctionDecl *FD =
9595             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
9596       if (Attr *A = getDLLAttr(FD)) {
9597         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
9598         NewAttr->setInherited(true);
9599         VD->addAttr(NewAttr);
9600       }
9601     }
9602   }
9603 
9604   // Grab the dllimport or dllexport attribute off of the VarDecl.
9605   const InheritableAttr *DLLAttr = getDLLAttr(VD);
9606 
9607   // Imported static data members cannot be defined out-of-line.
9608   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
9609     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
9610         VD->isThisDeclarationADefinition()) {
9611       // We allow definitions of dllimport class template static data members
9612       // with a warning.
9613       CXXRecordDecl *Context =
9614         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
9615       bool IsClassTemplateMember =
9616           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
9617           Context->getDescribedClassTemplate();
9618 
9619       Diag(VD->getLocation(),
9620            IsClassTemplateMember
9621                ? diag::warn_attribute_dllimport_static_field_definition
9622                : diag::err_attribute_dllimport_static_field_definition);
9623       Diag(IA->getLocation(), diag::note_attribute);
9624       if (!IsClassTemplateMember)
9625         VD->setInvalidDecl();
9626     }
9627   }
9628 
9629   // dllimport/dllexport variables cannot be thread local, their TLS index
9630   // isn't exported with the variable.
9631   if (DLLAttr && VD->getTLSKind()) {
9632     Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
9633                                                                   << DLLAttr;
9634     VD->setInvalidDecl();
9635   }
9636 
9637   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9638     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
9639       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
9640       VD->dropAttr<UsedAttr>();
9641     }
9642   }
9643 
9644   const DeclContext *DC = VD->getDeclContext();
9645   // If there's a #pragma GCC visibility in scope, and this isn't a class
9646   // member, set the visibility of this variable.
9647   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
9648     AddPushedVisibilityAttribute(VD);
9649 
9650   // FIXME: Warn on unused templates.
9651   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
9652       !isa<VarTemplatePartialSpecializationDecl>(VD))
9653     MarkUnusedFileScopedDecl(VD);
9654 
9655   // Now we have parsed the initializer and can update the table of magic
9656   // tag values.
9657   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
9658       !VD->getType()->isIntegralOrEnumerationType())
9659     return;
9660 
9661   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
9662     const Expr *MagicValueExpr = VD->getInit();
9663     if (!MagicValueExpr) {
9664       continue;
9665     }
9666     llvm::APSInt MagicValueInt;
9667     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9668       Diag(I->getRange().getBegin(),
9669            diag::err_type_tag_for_datatype_not_ice)
9670         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9671       continue;
9672     }
9673     if (MagicValueInt.getActiveBits() > 64) {
9674       Diag(I->getRange().getBegin(),
9675            diag::err_type_tag_for_datatype_too_large)
9676         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9677       continue;
9678     }
9679     uint64_t MagicValue = MagicValueInt.getZExtValue();
9680     RegisterTypeTagForDatatype(I->getArgumentKind(),
9681                                MagicValue,
9682                                I->getMatchingCType(),
9683                                I->getLayoutCompatible(),
9684                                I->getMustBeNull());
9685   }
9686 }
9687 
9688 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
9689                                                    ArrayRef<Decl *> Group) {
9690   SmallVector<Decl*, 8> Decls;
9691 
9692   if (DS.isTypeSpecOwned())
9693     Decls.push_back(DS.getRepAsDecl());
9694 
9695   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
9696   for (unsigned i = 0, e = Group.size(); i != e; ++i)
9697     if (Decl *D = Group[i]) {
9698       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9699         if (!FirstDeclaratorInGroup)
9700           FirstDeclaratorInGroup = DD;
9701       Decls.push_back(D);
9702     }
9703 
9704   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
9705     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
9706       HandleTagNumbering(*this, Tag, S);
9707       if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9708         Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9709     }
9710   }
9711 
9712   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
9713 }
9714 
9715 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
9716 /// group, performing any necessary semantic checking.
9717 Sema::DeclGroupPtrTy
9718 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
9719                            bool TypeMayContainAuto) {
9720   // C++0x [dcl.spec.auto]p7:
9721   //   If the type deduced for the template parameter U is not the same in each
9722   //   deduction, the program is ill-formed.
9723   // FIXME: When initializer-list support is added, a distinction is needed
9724   // between the deduced type U and the deduced type which 'auto' stands for.
9725   //   auto a = 0, b = { 1, 2, 3 };
9726   // is legal because the deduced type U is 'int' in both cases.
9727   if (TypeMayContainAuto && Group.size() > 1) {
9728     QualType Deduced;
9729     CanQualType DeducedCanon;
9730     VarDecl *DeducedDecl = nullptr;
9731     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
9732       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9733         AutoType *AT = D->getType()->getContainedAutoType();
9734         // Don't reissue diagnostics when instantiating a template.
9735         if (AT && D->isInvalidDecl())
9736           break;
9737         QualType U = AT ? AT->getDeducedType() : QualType();
9738         if (!U.isNull()) {
9739           CanQualType UCanon = Context.getCanonicalType(U);
9740           if (Deduced.isNull()) {
9741             Deduced = U;
9742             DeducedCanon = UCanon;
9743             DeducedDecl = D;
9744           } else if (DeducedCanon != UCanon) {
9745             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9746                  diag::err_auto_different_deductions)
9747               << (AT->isDecltypeAuto() ? 1 : 0)
9748               << Deduced << DeducedDecl->getDeclName()
9749               << U << D->getDeclName()
9750               << DeducedDecl->getInit()->getSourceRange()
9751               << D->getInit()->getSourceRange();
9752             D->setInvalidDecl();
9753             break;
9754           }
9755         }
9756       }
9757     }
9758   }
9759 
9760   ActOnDocumentableDecls(Group);
9761 
9762   return DeclGroupPtrTy::make(
9763       DeclGroupRef::Create(Context, Group.data(), Group.size()));
9764 }
9765 
9766 void Sema::ActOnDocumentableDecl(Decl *D) {
9767   ActOnDocumentableDecls(D);
9768 }
9769 
9770 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
9771   // Don't parse the comment if Doxygen diagnostics are ignored.
9772   if (Group.empty() || !Group[0])
9773    return;
9774 
9775   if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation()))
9776     return;
9777 
9778   if (Group.size() >= 2) {
9779     // This is a decl group.  Normally it will contain only declarations
9780     // produced from declarator list.  But in case we have any definitions or
9781     // additional declaration references:
9782     //   'typedef struct S {} S;'
9783     //   'typedef struct S *S;'
9784     //   'struct S *pS;'
9785     // FinalizeDeclaratorGroup adds these as separate declarations.
9786     Decl *MaybeTagDecl = Group[0];
9787     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
9788       Group = Group.slice(1);
9789     }
9790   }
9791 
9792   // See if there are any new comments that are not attached to a decl.
9793   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9794   if (!Comments.empty() &&
9795       !Comments.back()->isAttached()) {
9796     // There is at least one comment that not attached to a decl.
9797     // Maybe it should be attached to one of these decls?
9798     //
9799     // Note that this way we pick up not only comments that precede the
9800     // declaration, but also comments that *follow* the declaration -- thanks to
9801     // the lookahead in the lexer: we've consumed the semicolon and looked
9802     // ahead through comments.
9803     for (unsigned i = 0, e = Group.size(); i != e; ++i)
9804       Context.getCommentForDecl(Group[i], &PP);
9805   }
9806 }
9807 
9808 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9809 /// to introduce parameters into function prototype scope.
9810 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
9811   const DeclSpec &DS = D.getDeclSpec();
9812 
9813   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
9814 
9815   // C++03 [dcl.stc]p2 also permits 'auto'.
9816   StorageClass SC = SC_None;
9817   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
9818     SC = SC_Register;
9819   } else if (getLangOpts().CPlusPlus &&
9820              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9821     SC = SC_Auto;
9822   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
9823     Diag(DS.getStorageClassSpecLoc(),
9824          diag::err_invalid_storage_class_in_func_decl);
9825     D.getMutableDeclSpec().ClearStorageClassSpecs();
9826   }
9827 
9828   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9829     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9830       << DeclSpec::getSpecifierName(TSCS);
9831   if (DS.isConstexprSpecified())
9832     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
9833       << 0;
9834 
9835   DiagnoseFunctionSpecifiers(DS);
9836 
9837   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9838   QualType parmDeclType = TInfo->getType();
9839 
9840   if (getLangOpts().CPlusPlus) {
9841     // Check that there are no default arguments inside the type of this
9842     // parameter.
9843     CheckExtraCXXDefaultArguments(D);
9844 
9845     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9846     if (D.getCXXScopeSpec().isSet()) {
9847       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9848         << D.getCXXScopeSpec().getRange();
9849       D.getCXXScopeSpec().clear();
9850     }
9851   }
9852 
9853   // Ensure we have a valid name
9854   IdentifierInfo *II = nullptr;
9855   if (D.hasName()) {
9856     II = D.getIdentifier();
9857     if (!II) {
9858       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9859         << GetNameForDeclarator(D).getName();
9860       D.setInvalidType(true);
9861     }
9862   }
9863 
9864   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
9865   if (II) {
9866     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9867                    ForRedeclaration);
9868     LookupName(R, S);
9869     if (R.isSingleResult()) {
9870       NamedDecl *PrevDecl = R.getFoundDecl();
9871       if (PrevDecl->isTemplateParameter()) {
9872         // Maybe we will complain about the shadowed template parameter.
9873         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9874         // Just pretend that we didn't see the previous declaration.
9875         PrevDecl = nullptr;
9876       } else if (S->isDeclScope(PrevDecl)) {
9877         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
9878         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9879 
9880         // Recover by removing the name
9881         II = nullptr;
9882         D.SetIdentifier(nullptr, D.getIdentifierLoc());
9883         D.setInvalidType(true);
9884       }
9885     }
9886   }
9887 
9888   // Temporarily put parameter variables in the translation unit, not
9889   // the enclosing context.  This prevents them from accidentally
9890   // looking like class members in C++.
9891   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
9892                                     D.getLocStart(),
9893                                     D.getIdentifierLoc(), II,
9894                                     parmDeclType, TInfo,
9895                                     SC);
9896 
9897   if (D.isInvalidType())
9898     New->setInvalidDecl();
9899 
9900   assert(S->isFunctionPrototypeScope());
9901   assert(S->getFunctionPrototypeDepth() >= 1);
9902   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9903                     S->getNextFunctionPrototypeIndex());
9904 
9905   // Add the parameter declaration into this scope.
9906   S->AddDecl(New);
9907   if (II)
9908     IdResolver.AddDecl(New);
9909 
9910   ProcessDeclAttributes(S, New, D);
9911 
9912   if (D.getDeclSpec().isModulePrivateSpecified())
9913     Diag(New->getLocation(), diag::err_module_private_local)
9914       << 1 << New->getDeclName()
9915       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9916       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9917 
9918   if (New->hasAttr<BlocksAttr>()) {
9919     Diag(New->getLocation(), diag::err_block_on_nonlocal);
9920   }
9921   return New;
9922 }
9923 
9924 /// \brief Synthesizes a variable for a parameter arising from a
9925 /// typedef.
9926 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9927                                               SourceLocation Loc,
9928                                               QualType T) {
9929   /* FIXME: setting StartLoc == Loc.
9930      Would it be worth to modify callers so as to provide proper source
9931      location for the unnamed parameters, embedding the parameter's type? */
9932   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
9933                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
9934                                            SC_None, nullptr);
9935   Param->setImplicit();
9936   return Param;
9937 }
9938 
9939 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9940                                     ParmVarDecl * const *ParamEnd) {
9941   // Don't diagnose unused-parameter errors in template instantiations; we
9942   // will already have done so in the template itself.
9943   if (!ActiveTemplateInstantiations.empty())
9944     return;
9945 
9946   for (; Param != ParamEnd; ++Param) {
9947     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
9948         !(*Param)->hasAttr<UnusedAttr>()) {
9949       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9950         << (*Param)->getDeclName();
9951     }
9952   }
9953 }
9954 
9955 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9956                                                   ParmVarDecl * const *ParamEnd,
9957                                                   QualType ReturnTy,
9958                                                   NamedDecl *D) {
9959   if (LangOpts.NumLargeByValueCopy == 0) // No check.
9960     return;
9961 
9962   // Warn if the return value is pass-by-value and larger than the specified
9963   // threshold.
9964   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
9965     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
9966     if (Size > LangOpts.NumLargeByValueCopy)
9967       Diag(D->getLocation(), diag::warn_return_value_size)
9968           << D->getDeclName() << Size;
9969   }
9970 
9971   // Warn if any parameter is pass-by-value and larger than the specified
9972   // threshold.
9973   for (; Param != ParamEnd; ++Param) {
9974     QualType T = (*Param)->getType();
9975     if (T->isDependentType() || !T.isPODType(Context))
9976       continue;
9977     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
9978     if (Size > LangOpts.NumLargeByValueCopy)
9979       Diag((*Param)->getLocation(), diag::warn_parameter_size)
9980           << (*Param)->getDeclName() << Size;
9981   }
9982 }
9983 
9984 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9985                                   SourceLocation NameLoc, IdentifierInfo *Name,
9986                                   QualType T, TypeSourceInfo *TSInfo,
9987                                   StorageClass SC) {
9988   // In ARC, infer a lifetime qualifier for appropriate parameter types.
9989   if (getLangOpts().ObjCAutoRefCount &&
9990       T.getObjCLifetime() == Qualifiers::OCL_None &&
9991       T->isObjCLifetimeType()) {
9992 
9993     Qualifiers::ObjCLifetime lifetime;
9994 
9995     // Special cases for arrays:
9996     //   - if it's const, use __unsafe_unretained
9997     //   - otherwise, it's an error
9998     if (T->isArrayType()) {
9999       if (!T.isConstQualified()) {
10000         DelayedDiagnostics.add(
10001             sema::DelayedDiagnostic::makeForbiddenType(
10002             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10003       }
10004       lifetime = Qualifiers::OCL_ExplicitNone;
10005     } else {
10006       lifetime = T->getObjCARCImplicitLifetime();
10007     }
10008     T = Context.getLifetimeQualifiedType(T, lifetime);
10009   }
10010 
10011   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10012                                          Context.getAdjustedParameterType(T),
10013                                          TSInfo, SC, nullptr);
10014 
10015   // Parameters can not be abstract class types.
10016   // For record types, this is done by the AbstractClassUsageDiagnoser once
10017   // the class has been completely parsed.
10018   if (!CurContext->isRecord() &&
10019       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10020                              AbstractParamType))
10021     New->setInvalidDecl();
10022 
10023   // Parameter declarators cannot be interface types. All ObjC objects are
10024   // passed by reference.
10025   if (T->isObjCObjectType()) {
10026     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10027     Diag(NameLoc,
10028          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10029       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10030     T = Context.getObjCObjectPointerType(T);
10031     New->setType(T);
10032   }
10033 
10034   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10035   // duration shall not be qualified by an address-space qualifier."
10036   // Since all parameters have automatic store duration, they can not have
10037   // an address space.
10038   if (T.getAddressSpace() != 0) {
10039     // OpenCL allows function arguments declared to be an array of a type
10040     // to be qualified with an address space.
10041     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10042       Diag(NameLoc, diag::err_arg_with_address_space);
10043       New->setInvalidDecl();
10044     }
10045   }
10046 
10047   return New;
10048 }
10049 
10050 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10051                                            SourceLocation LocAfterDecls) {
10052   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10053 
10054   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10055   // for a K&R function.
10056   if (!FTI.hasPrototype) {
10057     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10058       --i;
10059       if (FTI.Params[i].Param == nullptr) {
10060         SmallString<256> Code;
10061         llvm::raw_svector_ostream(Code)
10062             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10063         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10064             << FTI.Params[i].Ident
10065             << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
10066 
10067         // Implicitly declare the argument as type 'int' for lack of a better
10068         // type.
10069         AttributeFactory attrs;
10070         DeclSpec DS(attrs);
10071         const char* PrevSpec; // unused
10072         unsigned DiagID; // unused
10073         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10074                            DiagID, Context.getPrintingPolicy());
10075         // Use the identifier location for the type source range.
10076         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10077         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10078         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10079         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10080         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10081       }
10082     }
10083   }
10084 }
10085 
10086 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
10087   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10088   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10089   Scope *ParentScope = FnBodyScope->getParent();
10090 
10091   D.setFunctionDefinitionKind(FDK_Definition);
10092   Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
10093   return ActOnStartOfFunctionDef(FnBodyScope, DP);
10094 }
10095 
10096 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10097   Consumer.HandleInlineMethodDefinition(D);
10098 }
10099 
10100 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10101                              const FunctionDecl*& PossibleZeroParamPrototype) {
10102   // Don't warn about invalid declarations.
10103   if (FD->isInvalidDecl())
10104     return false;
10105 
10106   // Or declarations that aren't global.
10107   if (!FD->isGlobal())
10108     return false;
10109 
10110   // Don't warn about C++ member functions.
10111   if (isa<CXXMethodDecl>(FD))
10112     return false;
10113 
10114   // Don't warn about 'main'.
10115   if (FD->isMain())
10116     return false;
10117 
10118   // Don't warn about inline functions.
10119   if (FD->isInlined())
10120     return false;
10121 
10122   // Don't warn about function templates.
10123   if (FD->getDescribedFunctionTemplate())
10124     return false;
10125 
10126   // Don't warn about function template specializations.
10127   if (FD->isFunctionTemplateSpecialization())
10128     return false;
10129 
10130   // Don't warn for OpenCL kernels.
10131   if (FD->hasAttr<OpenCLKernelAttr>())
10132     return false;
10133 
10134   bool MissingPrototype = true;
10135   for (const FunctionDecl *Prev = FD->getPreviousDecl();
10136        Prev; Prev = Prev->getPreviousDecl()) {
10137     // Ignore any declarations that occur in function or method
10138     // scope, because they aren't visible from the header.
10139     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10140       continue;
10141 
10142     MissingPrototype = !Prev->getType()->isFunctionProtoType();
10143     if (FD->getNumParams() == 0)
10144       PossibleZeroParamPrototype = Prev;
10145     break;
10146   }
10147 
10148   return MissingPrototype;
10149 }
10150 
10151 void
10152 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10153                                    const FunctionDecl *EffectiveDefinition) {
10154   // Don't complain if we're in GNU89 mode and the previous definition
10155   // was an extern inline function.
10156   const FunctionDecl *Definition = EffectiveDefinition;
10157   if (!Definition)
10158     if (!FD->isDefined(Definition))
10159       return;
10160 
10161   if (canRedefineFunction(Definition, getLangOpts()))
10162     return;
10163 
10164   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10165       Definition->getStorageClass() == SC_Extern)
10166     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10167         << FD->getDeclName() << getLangOpts().CPlusPlus;
10168   else
10169     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10170 
10171   Diag(Definition->getLocation(), diag::note_previous_definition);
10172   FD->setInvalidDecl();
10173 }
10174 
10175 
10176 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10177                                    Sema &S) {
10178   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10179 
10180   LambdaScopeInfo *LSI = S.PushLambdaScope();
10181   LSI->CallOperator = CallOperator;
10182   LSI->Lambda = LambdaClass;
10183   LSI->ReturnType = CallOperator->getReturnType();
10184   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10185 
10186   if (LCD == LCD_None)
10187     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10188   else if (LCD == LCD_ByCopy)
10189     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10190   else if (LCD == LCD_ByRef)
10191     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10192   DeclarationNameInfo DNI = CallOperator->getNameInfo();
10193 
10194   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10195   LSI->Mutable = !CallOperator->isConst();
10196 
10197   // Add the captures to the LSI so they can be noted as already
10198   // captured within tryCaptureVar.
10199   auto I = LambdaClass->field_begin();
10200   for (const auto &C : LambdaClass->captures()) {
10201     if (C.capturesVariable()) {
10202       VarDecl *VD = C.getCapturedVar();
10203       if (VD->isInitCapture())
10204         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10205       QualType CaptureType = VD->getType();
10206       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10207       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10208           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
10209           /*EllipsisLoc*/C.isPackExpansion()
10210                          ? C.getEllipsisLoc() : SourceLocation(),
10211           CaptureType, /*Expr*/ nullptr);
10212 
10213     } else if (C.capturesThis()) {
10214       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10215                               S.getCurrentThisType(), /*Expr*/ nullptr);
10216     } else {
10217       LSI->addVLATypeCapture(C.getLocation(), I->getType());
10218     }
10219     ++I;
10220   }
10221 }
10222 
10223 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
10224   // Clear the last template instantiation error context.
10225   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10226 
10227   if (!D)
10228     return D;
10229   FunctionDecl *FD = nullptr;
10230 
10231   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10232     FD = FunTmpl->getTemplatedDecl();
10233   else
10234     FD = cast<FunctionDecl>(D);
10235   // If we are instantiating a generic lambda call operator, push
10236   // a LambdaScopeInfo onto the function stack.  But use the information
10237   // that's already been calculated (ActOnLambdaExpr) to prime the current
10238   // LambdaScopeInfo.
10239   // When the template operator is being specialized, the LambdaScopeInfo,
10240   // has to be properly restored so that tryCaptureVariable doesn't try
10241   // and capture any new variables. In addition when calculating potential
10242   // captures during transformation of nested lambdas, it is necessary to
10243   // have the LSI properly restored.
10244   if (isGenericLambdaCallOperatorSpecialization(FD)) {
10245     assert(ActiveTemplateInstantiations.size() &&
10246       "There should be an active template instantiation on the stack "
10247       "when instantiating a generic lambda!");
10248     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10249   }
10250   else
10251     // Enter a new function scope
10252     PushFunctionScope();
10253 
10254   // See if this is a redefinition.
10255   if (!FD->isLateTemplateParsed())
10256     CheckForFunctionRedefinition(FD);
10257 
10258   // Builtin functions cannot be defined.
10259   if (unsigned BuiltinID = FD->getBuiltinID()) {
10260     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10261         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10262       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10263       FD->setInvalidDecl();
10264     }
10265   }
10266 
10267   // The return type of a function definition must be complete
10268   // (C99 6.9.1p3, C++ [dcl.fct]p6).
10269   QualType ResultType = FD->getReturnType();
10270   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10271       !FD->isInvalidDecl() &&
10272       RequireCompleteType(FD->getLocation(), ResultType,
10273                           diag::err_func_def_incomplete_result))
10274     FD->setInvalidDecl();
10275 
10276   // GNU warning -Wmissing-prototypes:
10277   //   Warn if a global function is defined without a previous
10278   //   prototype declaration. This warning is issued even if the
10279   //   definition itself provides a prototype. The aim is to detect
10280   //   global functions that fail to be declared in header files.
10281   const FunctionDecl *PossibleZeroParamPrototype = nullptr;
10282   if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
10283     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
10284 
10285     if (PossibleZeroParamPrototype) {
10286       // We found a declaration that is not a prototype,
10287       // but that could be a zero-parameter prototype
10288       if (TypeSourceInfo *TI =
10289               PossibleZeroParamPrototype->getTypeSourceInfo()) {
10290         TypeLoc TL = TI->getTypeLoc();
10291         if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
10292           Diag(PossibleZeroParamPrototype->getLocation(),
10293                diag::note_declaration_not_a_prototype)
10294             << PossibleZeroParamPrototype
10295             << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
10296       }
10297     }
10298   }
10299 
10300   if (FnBodyScope)
10301     PushDeclContext(FnBodyScope, FD);
10302 
10303   // Check the validity of our function parameters
10304   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10305                            /*CheckParameterNames=*/true);
10306 
10307   // Introduce our parameters into the function scope
10308   for (auto Param : FD->params()) {
10309     Param->setOwningFunction(FD);
10310 
10311     // If this has an identifier, add it to the scope stack.
10312     if (Param->getIdentifier() && FnBodyScope) {
10313       CheckShadow(FnBodyScope, Param);
10314 
10315       PushOnScopeChains(Param, FnBodyScope);
10316     }
10317   }
10318 
10319   // If we had any tags defined in the function prototype,
10320   // introduce them into the function scope.
10321   if (FnBodyScope) {
10322     for (ArrayRef<NamedDecl *>::iterator
10323              I = FD->getDeclsInPrototypeScope().begin(),
10324              E = FD->getDeclsInPrototypeScope().end();
10325          I != E; ++I) {
10326       NamedDecl *D = *I;
10327 
10328       // Some of these decls (like enums) may have been pinned to the translation unit
10329       // for lack of a real context earlier. If so, remove from the translation unit
10330       // and reattach to the current context.
10331       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10332         // Is the decl actually in the context?
10333         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10334           if (DI == D) {
10335             Context.getTranslationUnitDecl()->removeDecl(D);
10336             break;
10337           }
10338         }
10339         // Either way, reassign the lexical decl context to our FunctionDecl.
10340         D->setLexicalDeclContext(CurContext);
10341       }
10342 
10343       // If the decl has a non-null name, make accessible in the current scope.
10344       if (!D->getName().empty())
10345         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10346 
10347       // Similarly, dive into enums and fish their constants out, making them
10348       // accessible in this scope.
10349       if (auto *ED = dyn_cast<EnumDecl>(D)) {
10350         for (auto *EI : ED->enumerators())
10351           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10352       }
10353     }
10354   }
10355 
10356   // Ensure that the function's exception specification is instantiated.
10357   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10358     ResolveExceptionSpec(D->getLocation(), FPT);
10359 
10360   // dllimport cannot be applied to non-inline function definitions.
10361   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10362       !FD->isTemplateInstantiation()) {
10363     assert(!FD->hasAttr<DLLExportAttr>());
10364     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10365     FD->setInvalidDecl();
10366     return D;
10367   }
10368   // We want to attach documentation to original Decl (which might be
10369   // a function template).
10370   ActOnDocumentableDecl(D);
10371   if (getCurLexicalContext()->isObjCContainer() &&
10372       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10373       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10374     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10375 
10376   return D;
10377 }
10378 
10379 /// \brief Given the set of return statements within a function body,
10380 /// compute the variables that are subject to the named return value
10381 /// optimization.
10382 ///
10383 /// Each of the variables that is subject to the named return value
10384 /// optimization will be marked as NRVO variables in the AST, and any
10385 /// return statement that has a marked NRVO variable as its NRVO candidate can
10386 /// use the named return value optimization.
10387 ///
10388 /// This function applies a very simplistic algorithm for NRVO: if every return
10389 /// statement in the scope of a variable has the same NRVO candidate, that
10390 /// candidate is an NRVO variable.
10391 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
10392   ReturnStmt **Returns = Scope->Returns.data();
10393 
10394   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10395     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10396       if (!NRVOCandidate->isNRVOVariable())
10397         Returns[I]->setNRVOCandidate(nullptr);
10398     }
10399   }
10400 }
10401 
10402 bool Sema::canDelayFunctionBody(const Declarator &D) {
10403   // We can't delay parsing the body of a constexpr function template (yet).
10404   if (D.getDeclSpec().isConstexprSpecified())
10405     return false;
10406 
10407   // We can't delay parsing the body of a function template with a deduced
10408   // return type (yet).
10409   if (D.getDeclSpec().containsPlaceholderType()) {
10410     // If the placeholder introduces a non-deduced trailing return type,
10411     // we can still delay parsing it.
10412     if (D.getNumTypeObjects()) {
10413       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10414       if (Outer.Kind == DeclaratorChunk::Function &&
10415           Outer.Fun.hasTrailingReturnType()) {
10416         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10417         return Ty.isNull() || !Ty->isUndeducedType();
10418       }
10419     }
10420     return false;
10421   }
10422 
10423   return true;
10424 }
10425 
10426 bool Sema::canSkipFunctionBody(Decl *D) {
10427   // We cannot skip the body of a function (or function template) which is
10428   // constexpr, since we may need to evaluate its body in order to parse the
10429   // rest of the file.
10430   // We cannot skip the body of a function with an undeduced return type,
10431   // because any callers of that function need to know the type.
10432   if (const FunctionDecl *FD = D->getAsFunction())
10433     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
10434       return false;
10435   return Consumer.shouldSkipFunctionBody(D);
10436 }
10437 
10438 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
10439   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
10440     FD->setHasSkippedBody();
10441   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
10442     MD->setHasSkippedBody();
10443   return ActOnFinishFunctionBody(Decl, nullptr);
10444 }
10445 
10446 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
10447   return ActOnFinishFunctionBody(D, BodyArg, false);
10448 }
10449 
10450 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
10451                                     bool IsInstantiation) {
10452   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
10453 
10454   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10455   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
10456 
10457   if (FD) {
10458     FD->setBody(Body);
10459 
10460     if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
10461         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
10462       // If the function has a deduced result type but contains no 'return'
10463       // statements, the result type as written must be exactly 'auto', and
10464       // the deduced result type is 'void'.
10465       if (!FD->getReturnType()->getAs<AutoType>()) {
10466         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
10467             << FD->getReturnType();
10468         FD->setInvalidDecl();
10469       } else {
10470         // Substitute 'void' for the 'auto' in the type.
10471         TypeLoc ResultType = getReturnTypeLoc(FD);
10472         Context.adjustDeducedFunctionResultType(
10473             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
10474       }
10475     }
10476 
10477     // The only way to be included in UndefinedButUsed is if there is an
10478     // ODR use before the definition. Avoid the expensive map lookup if this
10479     // is the first declaration.
10480     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
10481       if (!FD->isExternallyVisible())
10482         UndefinedButUsed.erase(FD);
10483       else if (FD->isInlined() &&
10484                (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10485                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
10486         UndefinedButUsed.erase(FD);
10487     }
10488 
10489     // If the function implicitly returns zero (like 'main') or is naked,
10490     // don't complain about missing return statements.
10491     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
10492       WP.disableCheckFallThrough();
10493 
10494     // MSVC permits the use of pure specifier (=0) on function definition,
10495     // defined at class scope, warn about this non-standard construct.
10496     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
10497       Diag(FD->getLocation(), diag::ext_pure_function_definition);
10498 
10499     if (!FD->isInvalidDecl()) {
10500       // Don't diagnose unused parameters of defaulted or deleted functions.
10501       if (Body)
10502         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
10503       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
10504                                              FD->getReturnType(), FD);
10505 
10506       // If this is a structor, we need a vtable.
10507       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
10508         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
10509       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
10510         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
10511 
10512       // Try to apply the named return value optimization. We have to check
10513       // if we can do this here because lambdas keep return statements around
10514       // to deduce an implicit return type.
10515       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
10516           !FD->isDependentContext())
10517         computeNRVO(Body, getCurFunction());
10518     }
10519 
10520     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
10521            "Function parsing confused");
10522   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
10523     assert(MD == getCurMethodDecl() && "Method parsing confused");
10524     MD->setBody(Body);
10525     if (!MD->isInvalidDecl()) {
10526       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
10527       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
10528                                              MD->getReturnType(), MD);
10529 
10530       if (Body)
10531         computeNRVO(Body, getCurFunction());
10532     }
10533     if (getCurFunction()->ObjCShouldCallSuper) {
10534       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
10535         << MD->getSelector().getAsString();
10536       getCurFunction()->ObjCShouldCallSuper = false;
10537     }
10538     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
10539       const ObjCMethodDecl *InitMethod = nullptr;
10540       bool isDesignated =
10541           MD->isDesignatedInitializerForTheInterface(&InitMethod);
10542       assert(isDesignated && InitMethod);
10543       (void)isDesignated;
10544 
10545       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
10546         auto IFace = MD->getClassInterface();
10547         if (!IFace)
10548           return false;
10549         auto SuperD = IFace->getSuperClass();
10550         if (!SuperD)
10551           return false;
10552         return SuperD->getIdentifier() ==
10553             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
10554       };
10555       // Don't issue this warning for unavailable inits or direct subclasses
10556       // of NSObject.
10557       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
10558         Diag(MD->getLocation(),
10559              diag::warn_objc_designated_init_missing_super_call);
10560         Diag(InitMethod->getLocation(),
10561              diag::note_objc_designated_init_marked_here);
10562       }
10563       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
10564     }
10565     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
10566       // Don't issue this warning for unavaialable inits.
10567       if (!MD->isUnavailable())
10568         Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
10569       getCurFunction()->ObjCWarnForNoInitDelegation = false;
10570     }
10571   } else {
10572     return nullptr;
10573   }
10574 
10575   assert(!getCurFunction()->ObjCShouldCallSuper &&
10576          "This should only be set for ObjC methods, which should have been "
10577          "handled in the block above.");
10578 
10579   // Verify and clean out per-function state.
10580   if (Body) {
10581     // C++ constructors that have function-try-blocks can't have return
10582     // statements in the handlers of that block. (C++ [except.handle]p14)
10583     // Verify this.
10584     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
10585       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
10586 
10587     // Verify that gotos and switch cases don't jump into scopes illegally.
10588     if (getCurFunction()->NeedsScopeChecking() &&
10589         !PP.isCodeCompletionEnabled())
10590       DiagnoseInvalidJumps(Body);
10591 
10592     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
10593       if (!Destructor->getParent()->isDependentType())
10594         CheckDestructor(Destructor);
10595 
10596       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10597                                              Destructor->getParent());
10598     }
10599 
10600     // If any errors have occurred, clear out any temporaries that may have
10601     // been leftover. This ensures that these temporaries won't be picked up for
10602     // deletion in some later function.
10603     if (getDiagnostics().hasErrorOccurred() ||
10604         getDiagnostics().getSuppressAllDiagnostics()) {
10605       DiscardCleanupsInEvaluationContext();
10606     }
10607     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
10608         !isa<FunctionTemplateDecl>(dcl)) {
10609       // Since the body is valid, issue any analysis-based warnings that are
10610       // enabled.
10611       ActivePolicy = &WP;
10612     }
10613 
10614     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10615         (!CheckConstexprFunctionDecl(FD) ||
10616          !CheckConstexprFunctionBody(FD, Body)))
10617       FD->setInvalidDecl();
10618 
10619     if (FD && FD->hasAttr<NakedAttr>()) {
10620       for (const Stmt *S : Body->children()) {
10621         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
10622           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
10623           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
10624           FD->setInvalidDecl();
10625           break;
10626         }
10627       }
10628     }
10629 
10630     assert(ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
10631            && "Leftover temporaries in function");
10632     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
10633     assert(MaybeODRUseExprs.empty() &&
10634            "Leftover expressions for odr-use checking");
10635   }
10636 
10637   if (!IsInstantiation)
10638     PopDeclContext();
10639 
10640   PopFunctionScopeInfo(ActivePolicy, dcl);
10641   // If any errors have occurred, clear out any temporaries that may have
10642   // been leftover. This ensures that these temporaries won't be picked up for
10643   // deletion in some later function.
10644   if (getDiagnostics().hasErrorOccurred()) {
10645     DiscardCleanupsInEvaluationContext();
10646   }
10647 
10648   return dcl;
10649 }
10650 
10651 
10652 /// When we finish delayed parsing of an attribute, we must attach it to the
10653 /// relevant Decl.
10654 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
10655                                        ParsedAttributes &Attrs) {
10656   // Always attach attributes to the underlying decl.
10657   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
10658     D = TD->getTemplatedDecl();
10659   ProcessDeclAttributeList(S, D, Attrs.getList());
10660 
10661   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
10662     if (Method->isStatic())
10663       checkThisInStaticMemberFunctionAttributes(Method);
10664 }
10665 
10666 
10667 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
10668 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
10669 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
10670                                           IdentifierInfo &II, Scope *S) {
10671   // Before we produce a declaration for an implicitly defined
10672   // function, see whether there was a locally-scoped declaration of
10673   // this name as a function or variable. If so, use that
10674   // (non-visible) declaration, and complain about it.
10675   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
10676     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
10677     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
10678     return ExternCPrev;
10679   }
10680 
10681   // Extension in C99.  Legal in C90, but warn about it.
10682   unsigned diag_id;
10683   if (II.getName().startswith("__builtin_"))
10684     diag_id = diag::warn_builtin_unknown;
10685   else if (getLangOpts().C99)
10686     diag_id = diag::ext_implicit_function_decl;
10687   else
10688     diag_id = diag::warn_implicit_function_decl;
10689   Diag(Loc, diag_id) << &II;
10690 
10691   // Because typo correction is expensive, only do it if the implicit
10692   // function declaration is going to be treated as an error.
10693   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
10694     TypoCorrection Corrected;
10695     if (S &&
10696         (Corrected = CorrectTypo(
10697              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
10698              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
10699       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
10700                    /*ErrorRecovery*/false);
10701   }
10702 
10703   // Set a Declarator for the implicit definition: int foo();
10704   const char *Dummy;
10705   AttributeFactory attrFactory;
10706   DeclSpec DS(attrFactory);
10707   unsigned DiagID;
10708   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
10709                                   Context.getPrintingPolicy());
10710   (void)Error; // Silence warning.
10711   assert(!Error && "Error setting up implicit decl!");
10712   SourceLocation NoLoc;
10713   Declarator D(DS, Declarator::BlockContext);
10714   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
10715                                              /*IsAmbiguous=*/false,
10716                                              /*LParenLoc=*/NoLoc,
10717                                              /*Params=*/nullptr,
10718                                              /*NumParams=*/0,
10719                                              /*EllipsisLoc=*/NoLoc,
10720                                              /*RParenLoc=*/NoLoc,
10721                                              /*TypeQuals=*/0,
10722                                              /*RefQualifierIsLvalueRef=*/true,
10723                                              /*RefQualifierLoc=*/NoLoc,
10724                                              /*ConstQualifierLoc=*/NoLoc,
10725                                              /*VolatileQualifierLoc=*/NoLoc,
10726                                              /*RestrictQualifierLoc=*/NoLoc,
10727                                              /*MutableLoc=*/NoLoc,
10728                                              EST_None,
10729                                              /*ESpecLoc=*/NoLoc,
10730                                              /*Exceptions=*/nullptr,
10731                                              /*ExceptionRanges=*/nullptr,
10732                                              /*NumExceptions=*/0,
10733                                              /*NoexceptExpr=*/nullptr,
10734                                              /*ExceptionSpecTokens=*/nullptr,
10735                                              Loc, Loc, D),
10736                 DS.getAttributes(),
10737                 SourceLocation());
10738   D.SetIdentifier(&II, Loc);
10739 
10740   // Insert this function into translation-unit scope.
10741 
10742   DeclContext *PrevDC = CurContext;
10743   CurContext = Context.getTranslationUnitDecl();
10744 
10745   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
10746   FD->setImplicit();
10747 
10748   CurContext = PrevDC;
10749 
10750   AddKnownFunctionAttributes(FD);
10751 
10752   return FD;
10753 }
10754 
10755 /// \brief Adds any function attributes that we know a priori based on
10756 /// the declaration of this function.
10757 ///
10758 /// These attributes can apply both to implicitly-declared builtins
10759 /// (like __builtin___printf_chk) or to library-declared functions
10760 /// like NSLog or printf.
10761 ///
10762 /// We need to check for duplicate attributes both here and where user-written
10763 /// attributes are applied to declarations.
10764 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10765   if (FD->isInvalidDecl())
10766     return;
10767 
10768   // If this is a built-in function, map its builtin attributes to
10769   // actual attributes.
10770   if (unsigned BuiltinID = FD->getBuiltinID()) {
10771     // Handle printf-formatting attributes.
10772     unsigned FormatIdx;
10773     bool HasVAListArg;
10774     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
10775       if (!FD->hasAttr<FormatAttr>()) {
10776         const char *fmt = "printf";
10777         unsigned int NumParams = FD->getNumParams();
10778         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10779             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10780           fmt = "NSString";
10781         FD->addAttr(FormatAttr::CreateImplicit(Context,
10782                                                &Context.Idents.get(fmt),
10783                                                FormatIdx+1,
10784                                                HasVAListArg ? 0 : FormatIdx+2,
10785                                                FD->getLocation()));
10786       }
10787     }
10788     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10789                                              HasVAListArg)) {
10790      if (!FD->hasAttr<FormatAttr>())
10791        FD->addAttr(FormatAttr::CreateImplicit(Context,
10792                                               &Context.Idents.get("scanf"),
10793                                               FormatIdx+1,
10794                                               HasVAListArg ? 0 : FormatIdx+2,
10795                                               FD->getLocation()));
10796     }
10797 
10798     // Mark const if we don't care about errno and that is the only
10799     // thing preventing the function from being const. This allows
10800     // IRgen to use LLVM intrinsics for such functions.
10801     if (!getLangOpts().MathErrno &&
10802         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
10803       if (!FD->hasAttr<ConstAttr>())
10804         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10805     }
10806 
10807     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10808         !FD->hasAttr<ReturnsTwiceAttr>())
10809       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10810                                          FD->getLocation()));
10811     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
10812       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
10813     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
10814       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10815   }
10816 
10817   IdentifierInfo *Name = FD->getIdentifier();
10818   if (!Name)
10819     return;
10820   if ((!getLangOpts().CPlusPlus &&
10821        FD->getDeclContext()->isTranslationUnit()) ||
10822       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
10823        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
10824        LinkageSpecDecl::lang_c)) {
10825     // Okay: this could be a libc/libm/Objective-C function we know
10826     // about.
10827   } else
10828     return;
10829 
10830   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
10831     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
10832     // target-specific builtins, perhaps?
10833     if (!FD->hasAttr<FormatAttr>())
10834       FD->addAttr(FormatAttr::CreateImplicit(Context,
10835                                              &Context.Idents.get("printf"), 2,
10836                                              Name->isStr("vasprintf") ? 0 : 3,
10837                                              FD->getLocation()));
10838   }
10839 
10840   if (Name->isStr("__CFStringMakeConstantString")) {
10841     // We already have a __builtin___CFStringMakeConstantString,
10842     // but builds that use -fno-constant-cfstrings don't go through that.
10843     if (!FD->hasAttr<FormatArgAttr>())
10844       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10845                                                 FD->getLocation()));
10846   }
10847 }
10848 
10849 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
10850                                     TypeSourceInfo *TInfo) {
10851   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
10852   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
10853 
10854   if (!TInfo) {
10855     assert(D.isInvalidType() && "no declarator info for valid type");
10856     TInfo = Context.getTrivialTypeSourceInfo(T);
10857   }
10858 
10859   // Scope manipulation handled by caller.
10860   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
10861                                            D.getLocStart(),
10862                                            D.getIdentifierLoc(),
10863                                            D.getIdentifier(),
10864                                            TInfo);
10865 
10866   // Bail out immediately if we have an invalid declaration.
10867   if (D.isInvalidType()) {
10868     NewTD->setInvalidDecl();
10869     return NewTD;
10870   }
10871 
10872   if (D.getDeclSpec().isModulePrivateSpecified()) {
10873     if (CurContext->isFunctionOrMethod())
10874       Diag(NewTD->getLocation(), diag::err_module_private_local)
10875         << 2 << NewTD->getDeclName()
10876         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10877         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10878     else
10879       NewTD->setModulePrivate();
10880   }
10881 
10882   // C++ [dcl.typedef]p8:
10883   //   If the typedef declaration defines an unnamed class (or
10884   //   enum), the first typedef-name declared by the declaration
10885   //   to be that class type (or enum type) is used to denote the
10886   //   class type (or enum type) for linkage purposes only.
10887   // We need to check whether the type was declared in the declaration.
10888   switch (D.getDeclSpec().getTypeSpecType()) {
10889   case TST_enum:
10890   case TST_struct:
10891   case TST_interface:
10892   case TST_union:
10893   case TST_class: {
10894     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10895 
10896     // Do nothing if the tag is not anonymous or already has an
10897     // associated typedef (from an earlier typedef in this decl group).
10898     if (tagFromDeclSpec->getIdentifier()) break;
10899     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
10900 
10901     // A well-formed anonymous tag must always be a TUK_Definition.
10902     assert(tagFromDeclSpec->isThisDeclarationADefinition());
10903 
10904     // The type must match the tag exactly;  no qualifiers allowed.
10905     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10906       break;
10907 
10908     // If we've already computed linkage for the anonymous tag, then
10909     // adding a typedef name for the anonymous decl can change that
10910     // linkage, which might be a serious problem.  Diagnose this as
10911     // unsupported and ignore the typedef name.  TODO: we should
10912     // pursue this as a language defect and establish a formal rule
10913     // for how to handle it.
10914     if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10915       Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10916 
10917       SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
10918       tagLoc = getLocForEndOfToken(tagLoc);
10919 
10920       llvm::SmallString<40> textToInsert;
10921       textToInsert += ' ';
10922       textToInsert += D.getIdentifier()->getName();
10923       Diag(tagLoc, diag::note_typedef_changes_linkage)
10924         << FixItHint::CreateInsertion(tagLoc, textToInsert);
10925       break;
10926     }
10927 
10928     // Otherwise, set this is the anon-decl typedef for the tag.
10929     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
10930     break;
10931   }
10932 
10933   default:
10934     break;
10935   }
10936 
10937   return NewTD;
10938 }
10939 
10940 
10941 /// \brief Check that this is a valid underlying type for an enum declaration.
10942 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10943   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10944   QualType T = TI->getType();
10945 
10946   if (T->isDependentType())
10947     return false;
10948 
10949   if (const BuiltinType *BT = T->getAs<BuiltinType>())
10950     if (BT->isInteger())
10951       return false;
10952 
10953   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10954   return true;
10955 }
10956 
10957 /// Check whether this is a valid redeclaration of a previous enumeration.
10958 /// \return true if the redeclaration was invalid.
10959 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10960                                   QualType EnumUnderlyingTy,
10961                                   const EnumDecl *Prev) {
10962   bool IsFixed = !EnumUnderlyingTy.isNull();
10963 
10964   if (IsScoped != Prev->isScoped()) {
10965     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10966       << Prev->isScoped();
10967     Diag(Prev->getLocation(), diag::note_previous_declaration);
10968     return true;
10969   }
10970 
10971   if (IsFixed && Prev->isFixed()) {
10972     if (!EnumUnderlyingTy->isDependentType() &&
10973         !Prev->getIntegerType()->isDependentType() &&
10974         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
10975                                         Prev->getIntegerType())) {
10976       // TODO: Highlight the underlying type of the redeclaration.
10977       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10978         << EnumUnderlyingTy << Prev->getIntegerType();
10979       Diag(Prev->getLocation(), diag::note_previous_declaration)
10980           << Prev->getIntegerTypeRange();
10981       return true;
10982     }
10983   } else if (IsFixed != Prev->isFixed()) {
10984     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10985       << Prev->isFixed();
10986     Diag(Prev->getLocation(), diag::note_previous_declaration);
10987     return true;
10988   }
10989 
10990   return false;
10991 }
10992 
10993 /// \brief Get diagnostic %select index for tag kind for
10994 /// redeclaration diagnostic message.
10995 /// WARNING: Indexes apply to particular diagnostics only!
10996 ///
10997 /// \returns diagnostic %select index.
10998 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
10999   switch (Tag) {
11000   case TTK_Struct: return 0;
11001   case TTK_Interface: return 1;
11002   case TTK_Class:  return 2;
11003   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11004   }
11005 }
11006 
11007 /// \brief Determine if tag kind is a class-key compatible with
11008 /// class for redeclaration (class, struct, or __interface).
11009 ///
11010 /// \returns true iff the tag kind is compatible.
11011 static bool isClassCompatTagKind(TagTypeKind Tag)
11012 {
11013   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11014 }
11015 
11016 /// \brief Determine whether a tag with a given kind is acceptable
11017 /// as a redeclaration of the given tag declaration.
11018 ///
11019 /// \returns true if the new tag kind is acceptable, false otherwise.
11020 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11021                                         TagTypeKind NewTag, bool isDefinition,
11022                                         SourceLocation NewTagLoc,
11023                                         const IdentifierInfo &Name) {
11024   // C++ [dcl.type.elab]p3:
11025   //   The class-key or enum keyword present in the
11026   //   elaborated-type-specifier shall agree in kind with the
11027   //   declaration to which the name in the elaborated-type-specifier
11028   //   refers. This rule also applies to the form of
11029   //   elaborated-type-specifier that declares a class-name or
11030   //   friend class since it can be construed as referring to the
11031   //   definition of the class. Thus, in any
11032   //   elaborated-type-specifier, the enum keyword shall be used to
11033   //   refer to an enumeration (7.2), the union class-key shall be
11034   //   used to refer to a union (clause 9), and either the class or
11035   //   struct class-key shall be used to refer to a class (clause 9)
11036   //   declared using the class or struct class-key.
11037   TagTypeKind OldTag = Previous->getTagKind();
11038   if (!isDefinition || !isClassCompatTagKind(NewTag))
11039     if (OldTag == NewTag)
11040       return true;
11041 
11042   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11043     // Warn about the struct/class tag mismatch.
11044     bool isTemplate = false;
11045     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11046       isTemplate = Record->getDescribedClassTemplate();
11047 
11048     if (!ActiveTemplateInstantiations.empty()) {
11049       // In a template instantiation, do not offer fix-its for tag mismatches
11050       // since they usually mess up the template instead of fixing the problem.
11051       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11052         << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11053         << getRedeclDiagFromTagKind(OldTag);
11054       return true;
11055     }
11056 
11057     if (isDefinition) {
11058       // On definitions, check previous tags and issue a fix-it for each
11059       // one that doesn't match the current tag.
11060       if (Previous->getDefinition()) {
11061         // Don't suggest fix-its for redefinitions.
11062         return true;
11063       }
11064 
11065       bool previousMismatch = false;
11066       for (auto I : Previous->redecls()) {
11067         if (I->getTagKind() != NewTag) {
11068           if (!previousMismatch) {
11069             previousMismatch = true;
11070             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11071               << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11072               << getRedeclDiagFromTagKind(I->getTagKind());
11073           }
11074           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11075             << getRedeclDiagFromTagKind(NewTag)
11076             << FixItHint::CreateReplacement(I->getInnerLocStart(),
11077                  TypeWithKeyword::getTagTypeKindName(NewTag));
11078         }
11079       }
11080       return true;
11081     }
11082 
11083     // Check for a previous definition.  If current tag and definition
11084     // are same type, do nothing.  If no definition, but disagree with
11085     // with previous tag type, give a warning, but no fix-it.
11086     const TagDecl *Redecl = Previous->getDefinition() ?
11087                             Previous->getDefinition() : Previous;
11088     if (Redecl->getTagKind() == NewTag) {
11089       return true;
11090     }
11091 
11092     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11093       << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11094       << getRedeclDiagFromTagKind(OldTag);
11095     Diag(Redecl->getLocation(), diag::note_previous_use);
11096 
11097     // If there is a previous definition, suggest a fix-it.
11098     if (Previous->getDefinition()) {
11099         Diag(NewTagLoc, diag::note_struct_class_suggestion)
11100           << getRedeclDiagFromTagKind(Redecl->getTagKind())
11101           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11102                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11103     }
11104 
11105     return true;
11106   }
11107   return false;
11108 }
11109 
11110 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11111 /// from an outer enclosing namespace or file scope inside a friend declaration.
11112 /// This should provide the commented out code in the following snippet:
11113 ///   namespace N {
11114 ///     struct X;
11115 ///     namespace M {
11116 ///       struct Y { friend struct /*N::*/ X; };
11117 ///     }
11118 ///   }
11119 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11120                                          SourceLocation NameLoc) {
11121   // While the decl is in a namespace, do repeated lookup of that name and see
11122   // if we get the same namespace back.  If we do not, continue until
11123   // translation unit scope, at which point we have a fully qualified NNS.
11124   SmallVector<IdentifierInfo *, 4> Namespaces;
11125   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11126   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11127     // This tag should be declared in a namespace, which can only be enclosed by
11128     // other namespaces.  Bail if there's an anonymous namespace in the chain.
11129     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11130     if (!Namespace || Namespace->isAnonymousNamespace())
11131       return FixItHint();
11132     IdentifierInfo *II = Namespace->getIdentifier();
11133     Namespaces.push_back(II);
11134     NamedDecl *Lookup = SemaRef.LookupSingleName(
11135         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11136     if (Lookup == Namespace)
11137       break;
11138   }
11139 
11140   // Once we have all the namespaces, reverse them to go outermost first, and
11141   // build an NNS.
11142   SmallString<64> Insertion;
11143   llvm::raw_svector_ostream OS(Insertion);
11144   if (DC->isTranslationUnit())
11145     OS << "::";
11146   std::reverse(Namespaces.begin(), Namespaces.end());
11147   for (auto *II : Namespaces)
11148     OS << II->getName() << "::";
11149   OS.flush();
11150   return FixItHint::CreateInsertion(NameLoc, Insertion);
11151 }
11152 
11153 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
11154 /// former case, Name will be non-null.  In the later case, Name will be null.
11155 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11156 /// reference/declaration/definition of a tag.
11157 ///
11158 /// IsTypeSpecifier is true if this is a type-specifier (or
11159 /// trailing-type-specifier) other than one in an alias-declaration.
11160 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11161                      SourceLocation KWLoc, CXXScopeSpec &SS,
11162                      IdentifierInfo *Name, SourceLocation NameLoc,
11163                      AttributeList *Attr, AccessSpecifier AS,
11164                      SourceLocation ModulePrivateLoc,
11165                      MultiTemplateParamsArg TemplateParameterLists,
11166                      bool &OwnedDecl, bool &IsDependent,
11167                      SourceLocation ScopedEnumKWLoc,
11168                      bool ScopedEnumUsesClassTag,
11169                      TypeResult UnderlyingType,
11170                      bool IsTypeSpecifier) {
11171   // If this is not a definition, it must have a name.
11172   IdentifierInfo *OrigName = Name;
11173   assert((Name != nullptr || TUK == TUK_Definition) &&
11174          "Nameless record must be a definition!");
11175   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11176 
11177   OwnedDecl = false;
11178   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11179   bool ScopedEnum = ScopedEnumKWLoc.isValid();
11180 
11181   // FIXME: Check explicit specializations more carefully.
11182   bool isExplicitSpecialization = false;
11183   bool Invalid = false;
11184 
11185   // We only need to do this matching if we have template parameters
11186   // or a scope specifier, which also conveniently avoids this work
11187   // for non-C++ cases.
11188   if (TemplateParameterLists.size() > 0 ||
11189       (SS.isNotEmpty() && TUK != TUK_Reference)) {
11190     if (TemplateParameterList *TemplateParams =
11191             MatchTemplateParametersToScopeSpecifier(
11192                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11193                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11194       if (Kind == TTK_Enum) {
11195         Diag(KWLoc, diag::err_enum_template);
11196         return nullptr;
11197       }
11198 
11199       if (TemplateParams->size() > 0) {
11200         // This is a declaration or definition of a class template (which may
11201         // be a member of another template).
11202 
11203         if (Invalid)
11204           return nullptr;
11205 
11206         OwnedDecl = false;
11207         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11208                                                SS, Name, NameLoc, Attr,
11209                                                TemplateParams, AS,
11210                                                ModulePrivateLoc,
11211                                                /*FriendLoc*/SourceLocation(),
11212                                                TemplateParameterLists.size()-1,
11213                                                TemplateParameterLists.data());
11214         return Result.get();
11215       } else {
11216         // The "template<>" header is extraneous.
11217         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11218           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11219         isExplicitSpecialization = true;
11220       }
11221     }
11222   }
11223 
11224   // Figure out the underlying type if this a enum declaration. We need to do
11225   // this early, because it's needed to detect if this is an incompatible
11226   // redeclaration.
11227   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11228 
11229   if (Kind == TTK_Enum) {
11230     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11231       // No underlying type explicitly specified, or we failed to parse the
11232       // type, default to int.
11233       EnumUnderlying = Context.IntTy.getTypePtr();
11234     else if (UnderlyingType.get()) {
11235       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11236       // integral type; any cv-qualification is ignored.
11237       TypeSourceInfo *TI = nullptr;
11238       GetTypeFromParser(UnderlyingType.get(), &TI);
11239       EnumUnderlying = TI;
11240 
11241       if (CheckEnumUnderlyingType(TI))
11242         // Recover by falling back to int.
11243         EnumUnderlying = Context.IntTy.getTypePtr();
11244 
11245       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11246                                           UPPC_FixedUnderlyingType))
11247         EnumUnderlying = Context.IntTy.getTypePtr();
11248 
11249     } else if (getLangOpts().MSVCCompat)
11250       // Microsoft enums are always of int type.
11251       EnumUnderlying = Context.IntTy.getTypePtr();
11252   }
11253 
11254   DeclContext *SearchDC = CurContext;
11255   DeclContext *DC = CurContext;
11256   bool isStdBadAlloc = false;
11257 
11258   RedeclarationKind Redecl = ForRedeclaration;
11259   if (TUK == TUK_Friend || TUK == TUK_Reference)
11260     Redecl = NotForRedeclaration;
11261 
11262   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11263   if (Name && SS.isNotEmpty()) {
11264     // We have a nested-name tag ('struct foo::bar').
11265 
11266     // Check for invalid 'foo::'.
11267     if (SS.isInvalid()) {
11268       Name = nullptr;
11269       goto CreateNewDecl;
11270     }
11271 
11272     // If this is a friend or a reference to a class in a dependent
11273     // context, don't try to make a decl for it.
11274     if (TUK == TUK_Friend || TUK == TUK_Reference) {
11275       DC = computeDeclContext(SS, false);
11276       if (!DC) {
11277         IsDependent = true;
11278         return nullptr;
11279       }
11280     } else {
11281       DC = computeDeclContext(SS, true);
11282       if (!DC) {
11283         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11284           << SS.getRange();
11285         return nullptr;
11286       }
11287     }
11288 
11289     if (RequireCompleteDeclContext(SS, DC))
11290       return nullptr;
11291 
11292     SearchDC = DC;
11293     // Look-up name inside 'foo::'.
11294     LookupQualifiedName(Previous, DC);
11295 
11296     if (Previous.isAmbiguous())
11297       return nullptr;
11298 
11299     if (Previous.empty()) {
11300       // Name lookup did not find anything. However, if the
11301       // nested-name-specifier refers to the current instantiation,
11302       // and that current instantiation has any dependent base
11303       // classes, we might find something at instantiation time: treat
11304       // this as a dependent elaborated-type-specifier.
11305       // But this only makes any sense for reference-like lookups.
11306       if (Previous.wasNotFoundInCurrentInstantiation() &&
11307           (TUK == TUK_Reference || TUK == TUK_Friend)) {
11308         IsDependent = true;
11309         return nullptr;
11310       }
11311 
11312       // A tag 'foo::bar' must already exist.
11313       Diag(NameLoc, diag::err_not_tag_in_scope)
11314         << Kind << Name << DC << SS.getRange();
11315       Name = nullptr;
11316       Invalid = true;
11317       goto CreateNewDecl;
11318     }
11319   } else if (Name) {
11320     // If this is a named struct, check to see if there was a previous forward
11321     // declaration or definition.
11322     // FIXME: We're looking into outer scopes here, even when we
11323     // shouldn't be. Doing so can result in ambiguities that we
11324     // shouldn't be diagnosing.
11325     LookupName(Previous, S);
11326 
11327     // When declaring or defining a tag, ignore ambiguities introduced
11328     // by types using'ed into this scope.
11329     if (Previous.isAmbiguous() &&
11330         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
11331       LookupResult::Filter F = Previous.makeFilter();
11332       while (F.hasNext()) {
11333         NamedDecl *ND = F.next();
11334         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
11335           F.erase();
11336       }
11337       F.done();
11338     }
11339 
11340     // C++11 [namespace.memdef]p3:
11341     //   If the name in a friend declaration is neither qualified nor
11342     //   a template-id and the declaration is a function or an
11343     //   elaborated-type-specifier, the lookup to determine whether
11344     //   the entity has been previously declared shall not consider
11345     //   any scopes outside the innermost enclosing namespace.
11346     //
11347     // MSVC doesn't implement the above rule for types, so a friend tag
11348     // declaration may be a redeclaration of a type declared in an enclosing
11349     // scope.  They do implement this rule for friend functions.
11350     //
11351     // Does it matter that this should be by scope instead of by
11352     // semantic context?
11353     if (!Previous.empty() && TUK == TUK_Friend) {
11354       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
11355       LookupResult::Filter F = Previous.makeFilter();
11356       bool FriendSawTagOutsideEnclosingNamespace = false;
11357       while (F.hasNext()) {
11358         NamedDecl *ND = F.next();
11359         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11360         if (DC->isFileContext() &&
11361             !EnclosingNS->Encloses(ND->getDeclContext())) {
11362           if (getLangOpts().MSVCCompat)
11363             FriendSawTagOutsideEnclosingNamespace = true;
11364           else
11365             F.erase();
11366         }
11367       }
11368       F.done();
11369 
11370       // Diagnose this MSVC extension in the easy case where lookup would have
11371       // unambiguously found something outside the enclosing namespace.
11372       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
11373         NamedDecl *ND = Previous.getFoundDecl();
11374         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
11375             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
11376       }
11377     }
11378 
11379     // Note:  there used to be some attempt at recovery here.
11380     if (Previous.isAmbiguous())
11381       return nullptr;
11382 
11383     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
11384       // FIXME: This makes sure that we ignore the contexts associated
11385       // with C structs, unions, and enums when looking for a matching
11386       // tag declaration or definition. See the similar lookup tweak
11387       // in Sema::LookupName; is there a better way to deal with this?
11388       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
11389         SearchDC = SearchDC->getParent();
11390     }
11391   }
11392 
11393   if (Previous.isSingleResult() &&
11394       Previous.getFoundDecl()->isTemplateParameter()) {
11395     // Maybe we will complain about the shadowed template parameter.
11396     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
11397     // Just pretend that we didn't see the previous declaration.
11398     Previous.clear();
11399   }
11400 
11401   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
11402       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
11403     // This is a declaration of or a reference to "std::bad_alloc".
11404     isStdBadAlloc = true;
11405 
11406     if (Previous.empty() && StdBadAlloc) {
11407       // std::bad_alloc has been implicitly declared (but made invisible to
11408       // name lookup). Fill in this implicit declaration as the previous
11409       // declaration, so that the declarations get chained appropriately.
11410       Previous.addDecl(getStdBadAlloc());
11411     }
11412   }
11413 
11414   // If we didn't find a previous declaration, and this is a reference
11415   // (or friend reference), move to the correct scope.  In C++, we
11416   // also need to do a redeclaration lookup there, just in case
11417   // there's a shadow friend decl.
11418   if (Name && Previous.empty() &&
11419       (TUK == TUK_Reference || TUK == TUK_Friend)) {
11420     if (Invalid) goto CreateNewDecl;
11421     assert(SS.isEmpty());
11422 
11423     if (TUK == TUK_Reference) {
11424       // C++ [basic.scope.pdecl]p5:
11425       //   -- for an elaborated-type-specifier of the form
11426       //
11427       //          class-key identifier
11428       //
11429       //      if the elaborated-type-specifier is used in the
11430       //      decl-specifier-seq or parameter-declaration-clause of a
11431       //      function defined in namespace scope, the identifier is
11432       //      declared as a class-name in the namespace that contains
11433       //      the declaration; otherwise, except as a friend
11434       //      declaration, the identifier is declared in the smallest
11435       //      non-class, non-function-prototype scope that contains the
11436       //      declaration.
11437       //
11438       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
11439       // C structs and unions.
11440       //
11441       // It is an error in C++ to declare (rather than define) an enum
11442       // type, including via an elaborated type specifier.  We'll
11443       // diagnose that later; for now, declare the enum in the same
11444       // scope as we would have picked for any other tag type.
11445       //
11446       // GNU C also supports this behavior as part of its incomplete
11447       // enum types extension, while GNU C++ does not.
11448       //
11449       // Find the context where we'll be declaring the tag.
11450       // FIXME: We would like to maintain the current DeclContext as the
11451       // lexical context,
11452       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
11453         SearchDC = SearchDC->getParent();
11454 
11455       // Find the scope where we'll be declaring the tag.
11456       while (S->isClassScope() ||
11457              (getLangOpts().CPlusPlus &&
11458               S->isFunctionPrototypeScope()) ||
11459              ((S->getFlags() & Scope::DeclScope) == 0) ||
11460              (S->getEntity() && S->getEntity()->isTransparentContext()))
11461         S = S->getParent();
11462     } else {
11463       assert(TUK == TUK_Friend);
11464       // C++ [namespace.memdef]p3:
11465       //   If a friend declaration in a non-local class first declares a
11466       //   class or function, the friend class or function is a member of
11467       //   the innermost enclosing namespace.
11468       SearchDC = SearchDC->getEnclosingNamespaceContext();
11469     }
11470 
11471     // In C++, we need to do a redeclaration lookup to properly
11472     // diagnose some problems.
11473     if (getLangOpts().CPlusPlus) {
11474       Previous.setRedeclarationKind(ForRedeclaration);
11475       LookupQualifiedName(Previous, SearchDC);
11476     }
11477   }
11478 
11479   if (!Previous.empty()) {
11480     NamedDecl *PrevDecl = Previous.getFoundDecl();
11481     NamedDecl *DirectPrevDecl =
11482         getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
11483 
11484     // It's okay to have a tag decl in the same scope as a typedef
11485     // which hides a tag decl in the same scope.  Finding this
11486     // insanity with a redeclaration lookup can only actually happen
11487     // in C++.
11488     //
11489     // This is also okay for elaborated-type-specifiers, which is
11490     // technically forbidden by the current standard but which is
11491     // okay according to the likely resolution of an open issue;
11492     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
11493     if (getLangOpts().CPlusPlus) {
11494       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11495         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
11496           TagDecl *Tag = TT->getDecl();
11497           if (Tag->getDeclName() == Name &&
11498               Tag->getDeclContext()->getRedeclContext()
11499                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
11500             PrevDecl = Tag;
11501             Previous.clear();
11502             Previous.addDecl(Tag);
11503             Previous.resolveKind();
11504           }
11505         }
11506       }
11507     }
11508 
11509     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
11510       // If this is a use of a previous tag, or if the tag is already declared
11511       // in the same scope (so that the definition/declaration completes or
11512       // rementions the tag), reuse the decl.
11513       if (TUK == TUK_Reference || TUK == TUK_Friend ||
11514           isDeclInScope(DirectPrevDecl, SearchDC, S,
11515                         SS.isNotEmpty() || isExplicitSpecialization)) {
11516         // Make sure that this wasn't declared as an enum and now used as a
11517         // struct or something similar.
11518         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
11519                                           TUK == TUK_Definition, KWLoc,
11520                                           *Name)) {
11521           bool SafeToContinue
11522             = (PrevTagDecl->getTagKind() != TTK_Enum &&
11523                Kind != TTK_Enum);
11524           if (SafeToContinue)
11525             Diag(KWLoc, diag::err_use_with_wrong_tag)
11526               << Name
11527               << FixItHint::CreateReplacement(SourceRange(KWLoc),
11528                                               PrevTagDecl->getKindName());
11529           else
11530             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
11531           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
11532 
11533           if (SafeToContinue)
11534             Kind = PrevTagDecl->getTagKind();
11535           else {
11536             // Recover by making this an anonymous redefinition.
11537             Name = nullptr;
11538             Previous.clear();
11539             Invalid = true;
11540           }
11541         }
11542 
11543         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
11544           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
11545 
11546           // If this is an elaborated-type-specifier for a scoped enumeration,
11547           // the 'class' keyword is not necessary and not permitted.
11548           if (TUK == TUK_Reference || TUK == TUK_Friend) {
11549             if (ScopedEnum)
11550               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
11551                 << PrevEnum->isScoped()
11552                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
11553             return PrevTagDecl;
11554           }
11555 
11556           QualType EnumUnderlyingTy;
11557           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11558             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
11559           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
11560             EnumUnderlyingTy = QualType(T, 0);
11561 
11562           // All conflicts with previous declarations are recovered by
11563           // returning the previous declaration, unless this is a definition,
11564           // in which case we want the caller to bail out.
11565           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
11566                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
11567             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
11568         }
11569 
11570         // C++11 [class.mem]p1:
11571         //   A member shall not be declared twice in the member-specification,
11572         //   except that a nested class or member class template can be declared
11573         //   and then later defined.
11574         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
11575             S->isDeclScope(PrevDecl)) {
11576           Diag(NameLoc, diag::ext_member_redeclared);
11577           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
11578         }
11579 
11580         if (!Invalid) {
11581           // If this is a use, just return the declaration we found, unless
11582           // we have attributes.
11583 
11584           // FIXME: In the future, return a variant or some other clue
11585           // for the consumer of this Decl to know it doesn't own it.
11586           // For our current ASTs this shouldn't be a problem, but will
11587           // need to be changed with DeclGroups.
11588           if (!Attr &&
11589               ((TUK == TUK_Reference &&
11590                 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
11591                || TUK == TUK_Friend))
11592             return PrevTagDecl;
11593 
11594           // Diagnose attempts to redefine a tag.
11595           if (TUK == TUK_Definition) {
11596             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
11597               // If we're defining a specialization and the previous definition
11598               // is from an implicit instantiation, don't emit an error
11599               // here; we'll catch this in the general case below.
11600               bool IsExplicitSpecializationAfterInstantiation = false;
11601               if (isExplicitSpecialization) {
11602                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
11603                   IsExplicitSpecializationAfterInstantiation =
11604                     RD->getTemplateSpecializationKind() !=
11605                     TSK_ExplicitSpecialization;
11606                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
11607                   IsExplicitSpecializationAfterInstantiation =
11608                     ED->getTemplateSpecializationKind() !=
11609                     TSK_ExplicitSpecialization;
11610               }
11611 
11612               if (!IsExplicitSpecializationAfterInstantiation) {
11613                 // A redeclaration in function prototype scope in C isn't
11614                 // visible elsewhere, so merely issue a warning.
11615                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
11616                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
11617                 else
11618                   Diag(NameLoc, diag::err_redefinition) << Name;
11619                 Diag(Def->getLocation(), diag::note_previous_definition);
11620                 // If this is a redefinition, recover by making this
11621                 // struct be anonymous, which will make any later
11622                 // references get the previous definition.
11623                 Name = nullptr;
11624                 Previous.clear();
11625                 Invalid = true;
11626               }
11627             } else {
11628               // If the type is currently being defined, complain
11629               // about a nested redefinition.
11630               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
11631               if (TD->isBeingDefined()) {
11632                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
11633                 Diag(PrevTagDecl->getLocation(),
11634                      diag::note_previous_definition);
11635                 Name = nullptr;
11636                 Previous.clear();
11637                 Invalid = true;
11638               }
11639             }
11640 
11641             // Okay, this is definition of a previously declared or referenced
11642             // tag. We're going to create a new Decl for it.
11643           }
11644 
11645           // Okay, we're going to make a redeclaration.  If this is some kind
11646           // of reference, make sure we build the redeclaration in the same DC
11647           // as the original, and ignore the current access specifier.
11648           if (TUK == TUK_Friend || TUK == TUK_Reference) {
11649             SearchDC = PrevTagDecl->getDeclContext();
11650             AS = AS_none;
11651           }
11652         }
11653         // If we get here we have (another) forward declaration or we
11654         // have a definition.  Just create a new decl.
11655 
11656       } else {
11657         // If we get here, this is a definition of a new tag type in a nested
11658         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
11659         // new decl/type.  We set PrevDecl to NULL so that the entities
11660         // have distinct types.
11661         Previous.clear();
11662       }
11663       // If we get here, we're going to create a new Decl. If PrevDecl
11664       // is non-NULL, it's a definition of the tag declared by
11665       // PrevDecl. If it's NULL, we have a new definition.
11666 
11667 
11668     // Otherwise, PrevDecl is not a tag, but was found with tag
11669     // lookup.  This is only actually possible in C++, where a few
11670     // things like templates still live in the tag namespace.
11671     } else {
11672       // Use a better diagnostic if an elaborated-type-specifier
11673       // found the wrong kind of type on the first
11674       // (non-redeclaration) lookup.
11675       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
11676           !Previous.isForRedeclaration()) {
11677         unsigned Kind = 0;
11678         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11679         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11680         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11681         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
11682         Diag(PrevDecl->getLocation(), diag::note_declared_at);
11683         Invalid = true;
11684 
11685       // Otherwise, only diagnose if the declaration is in scope.
11686       } else if (!isDeclInScope(PrevDecl, SearchDC, S,
11687                                 SS.isNotEmpty() || isExplicitSpecialization)) {
11688         // do nothing
11689 
11690       // Diagnose implicit declarations introduced by elaborated types.
11691       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
11692         unsigned Kind = 0;
11693         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11694         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11695         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11696         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
11697         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11698         Invalid = true;
11699 
11700       // Otherwise it's a declaration.  Call out a particularly common
11701       // case here.
11702       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11703         unsigned Kind = 0;
11704         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
11705         Diag(NameLoc, diag::err_tag_definition_of_typedef)
11706           << Name << Kind << TND->getUnderlyingType();
11707         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11708         Invalid = true;
11709 
11710       // Otherwise, diagnose.
11711       } else {
11712         // The tag name clashes with something else in the target scope,
11713         // issue an error and recover by making this tag be anonymous.
11714         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
11715         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11716         Name = nullptr;
11717         Invalid = true;
11718       }
11719 
11720       // The existing declaration isn't relevant to us; we're in a
11721       // new scope, so clear out the previous declaration.
11722       Previous.clear();
11723     }
11724   }
11725 
11726 CreateNewDecl:
11727 
11728   TagDecl *PrevDecl = nullptr;
11729   if (Previous.isSingleResult())
11730     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
11731 
11732   // If there is an identifier, use the location of the identifier as the
11733   // location of the decl, otherwise use the location of the struct/union
11734   // keyword.
11735   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
11736 
11737   // Otherwise, create a new declaration. If there is a previous
11738   // declaration of the same entity, the two will be linked via
11739   // PrevDecl.
11740   TagDecl *New;
11741 
11742   bool IsForwardReference = false;
11743   if (Kind == TTK_Enum) {
11744     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11745     // enum X { A, B, C } D;    D should chain to X.
11746     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
11747                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
11748                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
11749     // If this is an undefined enum, warn.
11750     if (TUK != TUK_Definition && !Invalid) {
11751       TagDecl *Def;
11752       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
11753           cast<EnumDecl>(New)->isFixed()) {
11754         // C++0x: 7.2p2: opaque-enum-declaration.
11755         // Conflicts are diagnosed above. Do nothing.
11756       }
11757       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
11758         Diag(Loc, diag::ext_forward_ref_enum_def)
11759           << New;
11760         Diag(Def->getLocation(), diag::note_previous_definition);
11761       } else {
11762         unsigned DiagID = diag::ext_forward_ref_enum;
11763         if (getLangOpts().MSVCCompat)
11764           DiagID = diag::ext_ms_forward_ref_enum;
11765         else if (getLangOpts().CPlusPlus)
11766           DiagID = diag::err_forward_ref_enum;
11767         Diag(Loc, DiagID);
11768 
11769         // If this is a forward-declared reference to an enumeration, make a
11770         // note of it; we won't actually be introducing the declaration into
11771         // the declaration context.
11772         if (TUK == TUK_Reference)
11773           IsForwardReference = true;
11774       }
11775     }
11776 
11777     if (EnumUnderlying) {
11778       EnumDecl *ED = cast<EnumDecl>(New);
11779       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11780         ED->setIntegerTypeSourceInfo(TI);
11781       else
11782         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
11783       ED->setPromotionType(ED->getIntegerType());
11784     }
11785 
11786   } else {
11787     // struct/union/class
11788 
11789     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11790     // struct X { int A; } D;    D should chain to X.
11791     if (getLangOpts().CPlusPlus) {
11792       // FIXME: Look for a way to use RecordDecl for simple structs.
11793       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11794                                   cast_or_null<CXXRecordDecl>(PrevDecl));
11795 
11796       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
11797         StdBadAlloc = cast<CXXRecordDecl>(New);
11798     } else
11799       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11800                                cast_or_null<RecordDecl>(PrevDecl));
11801   }
11802 
11803   // C++11 [dcl.type]p3:
11804   //   A type-specifier-seq shall not define a class or enumeration [...].
11805   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11806     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11807       << Context.getTagDeclType(New);
11808     Invalid = true;
11809   }
11810 
11811   // Maybe add qualifier info.
11812   if (SS.isNotEmpty()) {
11813     if (SS.isSet()) {
11814       // If this is either a declaration or a definition, check the
11815       // nested-name-specifier against the current context. We don't do this
11816       // for explicit specializations, because they have similar checking
11817       // (with more specific diagnostics) in the call to
11818       // CheckMemberSpecialization, below.
11819       if (!isExplicitSpecialization &&
11820           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11821           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
11822         Invalid = true;
11823 
11824       New->setQualifierInfo(SS.getWithLocInContext(Context));
11825       if (TemplateParameterLists.size() > 0) {
11826         New->setTemplateParameterListsInfo(Context,
11827                                            TemplateParameterLists.size(),
11828                                            TemplateParameterLists.data());
11829       }
11830     }
11831     else
11832       Invalid = true;
11833   }
11834 
11835   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11836     // Add alignment attributes if necessary; these attributes are checked when
11837     // the ASTContext lays out the structure.
11838     //
11839     // It is important for implementing the correct semantics that this
11840     // happen here (in act on tag decl). The #pragma pack stack is
11841     // maintained as a result of parser callbacks which can occur at
11842     // many points during the parsing of a struct declaration (because
11843     // the #pragma tokens are effectively skipped over during the
11844     // parsing of the struct).
11845     if (TUK == TUK_Definition) {
11846       AddAlignmentAttributesForRecord(RD);
11847       AddMsStructLayoutForRecord(RD);
11848     }
11849   }
11850 
11851   if (ModulePrivateLoc.isValid()) {
11852     if (isExplicitSpecialization)
11853       Diag(New->getLocation(), diag::err_module_private_specialization)
11854         << 2
11855         << FixItHint::CreateRemoval(ModulePrivateLoc);
11856     // __module_private__ does not apply to local classes. However, we only
11857     // diagnose this as an error when the declaration specifiers are
11858     // freestanding. Here, we just ignore the __module_private__.
11859     else if (!SearchDC->isFunctionOrMethod())
11860       New->setModulePrivate();
11861   }
11862 
11863   // If this is a specialization of a member class (of a class template),
11864   // check the specialization.
11865   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
11866     Invalid = true;
11867 
11868   // If we're declaring or defining a tag in function prototype scope in C,
11869   // note that this type can only be used within the function and add it to
11870   // the list of decls to inject into the function definition scope.
11871   if ((Name || Kind == TTK_Enum) &&
11872       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
11873     if (getLangOpts().CPlusPlus) {
11874       // C++ [dcl.fct]p6:
11875       //   Types shall not be defined in return or parameter types.
11876       if (TUK == TUK_Definition && !IsTypeSpecifier) {
11877         Diag(Loc, diag::err_type_defined_in_param_type)
11878             << Name;
11879         Invalid = true;
11880       }
11881     } else {
11882       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11883     }
11884     DeclsInPrototypeScope.push_back(New);
11885   }
11886 
11887   if (Invalid)
11888     New->setInvalidDecl();
11889 
11890   if (Attr)
11891     ProcessDeclAttributeList(S, New, Attr);
11892 
11893   // Set the lexical context. If the tag has a C++ scope specifier, the
11894   // lexical context will be different from the semantic context.
11895   New->setLexicalDeclContext(CurContext);
11896 
11897   // Mark this as a friend decl if applicable.
11898   // In Microsoft mode, a friend declaration also acts as a forward
11899   // declaration so we always pass true to setObjectOfFriendDecl to make
11900   // the tag name visible.
11901   if (TUK == TUK_Friend)
11902     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
11903 
11904   // Set the access specifier.
11905   if (!Invalid && SearchDC->isRecord())
11906     SetMemberAccessSpecifier(New, PrevDecl, AS);
11907 
11908   if (TUK == TUK_Definition)
11909     New->startDefinition();
11910 
11911   // If this has an identifier, add it to the scope stack.
11912   if (TUK == TUK_Friend) {
11913     // We might be replacing an existing declaration in the lookup tables;
11914     // if so, borrow its access specifier.
11915     if (PrevDecl)
11916       New->setAccess(PrevDecl->getAccess());
11917 
11918     DeclContext *DC = New->getDeclContext()->getRedeclContext();
11919     DC->makeDeclVisibleInContext(New);
11920     if (Name) // can be null along some error paths
11921       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11922         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
11923   } else if (Name) {
11924     S = getNonFieldDeclScope(S);
11925     PushOnScopeChains(New, S, !IsForwardReference);
11926     if (IsForwardReference)
11927       SearchDC->makeDeclVisibleInContext(New);
11928 
11929   } else {
11930     CurContext->addDecl(New);
11931   }
11932 
11933   // If this is the C FILE type, notify the AST context.
11934   if (IdentifierInfo *II = New->getIdentifier())
11935     if (!New->isInvalidDecl() &&
11936         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
11937         II->isStr("FILE"))
11938       Context.setFILEDecl(New);
11939 
11940   if (PrevDecl)
11941     mergeDeclAttributes(New, PrevDecl);
11942 
11943   // If there's a #pragma GCC visibility in scope, set the visibility of this
11944   // record.
11945   AddPushedVisibilityAttribute(New);
11946 
11947   OwnedDecl = true;
11948   // In C++, don't return an invalid declaration. We can't recover well from
11949   // the cases where we make the type anonymous.
11950   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
11951 }
11952 
11953 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
11954   AdjustDeclIfTemplate(TagD);
11955   TagDecl *Tag = cast<TagDecl>(TagD);
11956 
11957   // Enter the tag context.
11958   PushDeclContext(S, Tag);
11959 
11960   ActOnDocumentableDecl(TagD);
11961 
11962   // If there's a #pragma GCC visibility in scope, set the visibility of this
11963   // record.
11964   AddPushedVisibilityAttribute(Tag);
11965 }
11966 
11967 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
11968   assert(isa<ObjCContainerDecl>(IDecl) &&
11969          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11970   DeclContext *OCD = cast<DeclContext>(IDecl);
11971   assert(getContainingDC(OCD) == CurContext &&
11972       "The next DeclContext should be lexically contained in the current one.");
11973   CurContext = OCD;
11974   return IDecl;
11975 }
11976 
11977 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
11978                                            SourceLocation FinalLoc,
11979                                            bool IsFinalSpelledSealed,
11980                                            SourceLocation LBraceLoc) {
11981   AdjustDeclIfTemplate(TagD);
11982   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
11983 
11984   FieldCollector->StartClass();
11985 
11986   if (!Record->getIdentifier())
11987     return;
11988 
11989   if (FinalLoc.isValid())
11990     Record->addAttr(new (Context)
11991                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11992 
11993   // C++ [class]p2:
11994   //   [...] The class-name is also inserted into the scope of the
11995   //   class itself; this is known as the injected-class-name. For
11996   //   purposes of access checking, the injected-class-name is treated
11997   //   as if it were a public member name.
11998   CXXRecordDecl *InjectedClassName
11999     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
12000                             Record->getLocStart(), Record->getLocation(),
12001                             Record->getIdentifier(),
12002                             /*PrevDecl=*/nullptr,
12003                             /*DelayTypeCreation=*/true);
12004   Context.getTypeDeclType(InjectedClassName, Record);
12005   InjectedClassName->setImplicit();
12006   InjectedClassName->setAccess(AS_public);
12007   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
12008       InjectedClassName->setDescribedClassTemplate(Template);
12009   PushOnScopeChains(InjectedClassName, S);
12010   assert(InjectedClassName->isInjectedClassName() &&
12011          "Broken injected-class-name");
12012 }
12013 
12014 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
12015                                     SourceLocation RBraceLoc) {
12016   AdjustDeclIfTemplate(TagD);
12017   TagDecl *Tag = cast<TagDecl>(TagD);
12018   Tag->setRBraceLoc(RBraceLoc);
12019 
12020   // Make sure we "complete" the definition even it is invalid.
12021   if (Tag->isBeingDefined()) {
12022     assert(Tag->isInvalidDecl() && "We should already have completed it");
12023     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12024       RD->completeDefinition();
12025   }
12026 
12027   if (isa<CXXRecordDecl>(Tag))
12028     FieldCollector->FinishClass();
12029 
12030   // Exit this scope of this tag's definition.
12031   PopDeclContext();
12032 
12033   if (getCurLexicalContext()->isObjCContainer() &&
12034       Tag->getDeclContext()->isFileContext())
12035     Tag->setTopLevelDeclInObjCContainer();
12036 
12037   // Notify the consumer that we've defined a tag.
12038   if (!Tag->isInvalidDecl())
12039     Consumer.HandleTagDeclDefinition(Tag);
12040 }
12041 
12042 void Sema::ActOnObjCContainerFinishDefinition() {
12043   // Exit this scope of this interface definition.
12044   PopDeclContext();
12045 }
12046 
12047 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12048   assert(DC == CurContext && "Mismatch of container contexts");
12049   OriginalLexicalContext = DC;
12050   ActOnObjCContainerFinishDefinition();
12051 }
12052 
12053 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12054   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12055   OriginalLexicalContext = nullptr;
12056 }
12057 
12058 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12059   AdjustDeclIfTemplate(TagD);
12060   TagDecl *Tag = cast<TagDecl>(TagD);
12061   Tag->setInvalidDecl();
12062 
12063   // Make sure we "complete" the definition even it is invalid.
12064   if (Tag->isBeingDefined()) {
12065     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12066       RD->completeDefinition();
12067   }
12068 
12069   // We're undoing ActOnTagStartDefinition here, not
12070   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12071   // the FieldCollector.
12072 
12073   PopDeclContext();
12074 }
12075 
12076 // Note that FieldName may be null for anonymous bitfields.
12077 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12078                                 IdentifierInfo *FieldName,
12079                                 QualType FieldTy, bool IsMsStruct,
12080                                 Expr *BitWidth, bool *ZeroWidth) {
12081   // Default to true; that shouldn't confuse checks for emptiness
12082   if (ZeroWidth)
12083     *ZeroWidth = true;
12084 
12085   // C99 6.7.2.1p4 - verify the field type.
12086   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12087   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12088     // Handle incomplete types with specific error.
12089     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12090       return ExprError();
12091     if (FieldName)
12092       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12093         << FieldName << FieldTy << BitWidth->getSourceRange();
12094     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12095       << FieldTy << BitWidth->getSourceRange();
12096   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12097                                              UPPC_BitFieldWidth))
12098     return ExprError();
12099 
12100   // If the bit-width is type- or value-dependent, don't try to check
12101   // it now.
12102   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12103     return BitWidth;
12104 
12105   llvm::APSInt Value;
12106   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12107   if (ICE.isInvalid())
12108     return ICE;
12109   BitWidth = ICE.get();
12110 
12111   if (Value != 0 && ZeroWidth)
12112     *ZeroWidth = false;
12113 
12114   // Zero-width bitfield is ok for anonymous field.
12115   if (Value == 0 && FieldName)
12116     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12117 
12118   if (Value.isSigned() && Value.isNegative()) {
12119     if (FieldName)
12120       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12121                << FieldName << Value.toString(10);
12122     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12123       << Value.toString(10);
12124   }
12125 
12126   if (!FieldTy->isDependentType()) {
12127     uint64_t TypeSize = Context.getTypeSize(FieldTy);
12128     if (Value.getZExtValue() > TypeSize) {
12129       if (!getLangOpts().CPlusPlus || IsMsStruct ||
12130           Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12131         if (FieldName)
12132           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
12133             << FieldName << (unsigned)Value.getZExtValue()
12134             << (unsigned)TypeSize;
12135 
12136         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
12137           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12138       }
12139 
12140       if (FieldName)
12141         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
12142           << FieldName << (unsigned)Value.getZExtValue()
12143           << (unsigned)TypeSize;
12144       else
12145         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
12146           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12147     }
12148   }
12149 
12150   return BitWidth;
12151 }
12152 
12153 /// ActOnField - Each field of a C struct/union is passed into this in order
12154 /// to create a FieldDecl object for it.
12155 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
12156                        Declarator &D, Expr *BitfieldWidth) {
12157   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12158                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12159                                /*InitStyle=*/ICIS_NoInit, AS_public);
12160   return Res;
12161 }
12162 
12163 /// HandleField - Analyze a field of a C struct or a C++ data member.
12164 ///
12165 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12166                              SourceLocation DeclStart,
12167                              Declarator &D, Expr *BitWidth,
12168                              InClassInitStyle InitStyle,
12169                              AccessSpecifier AS) {
12170   IdentifierInfo *II = D.getIdentifier();
12171   SourceLocation Loc = DeclStart;
12172   if (II) Loc = D.getIdentifierLoc();
12173 
12174   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12175   QualType T = TInfo->getType();
12176   if (getLangOpts().CPlusPlus) {
12177     CheckExtraCXXDefaultArguments(D);
12178 
12179     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12180                                         UPPC_DataMemberType)) {
12181       D.setInvalidType();
12182       T = Context.IntTy;
12183       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12184     }
12185   }
12186 
12187   // TR 18037 does not allow fields to be declared with address spaces.
12188   if (T.getQualifiers().hasAddressSpace()) {
12189     Diag(Loc, diag::err_field_with_address_space);
12190     D.setInvalidType();
12191   }
12192 
12193   // OpenCL 1.2 spec, s6.9 r:
12194   // The event type cannot be used to declare a structure or union field.
12195   if (LangOpts.OpenCL && T->isEventT()) {
12196     Diag(Loc, diag::err_event_t_struct_field);
12197     D.setInvalidType();
12198   }
12199 
12200   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12201 
12202   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12203     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12204          diag::err_invalid_thread)
12205       << DeclSpec::getSpecifierName(TSCS);
12206 
12207   // Check to see if this name was declared as a member previously
12208   NamedDecl *PrevDecl = nullptr;
12209   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12210   LookupName(Previous, S);
12211   switch (Previous.getResultKind()) {
12212     case LookupResult::Found:
12213     case LookupResult::FoundUnresolvedValue:
12214       PrevDecl = Previous.getAsSingle<NamedDecl>();
12215       break;
12216 
12217     case LookupResult::FoundOverloaded:
12218       PrevDecl = Previous.getRepresentativeDecl();
12219       break;
12220 
12221     case LookupResult::NotFound:
12222     case LookupResult::NotFoundInCurrentInstantiation:
12223     case LookupResult::Ambiguous:
12224       break;
12225   }
12226   Previous.suppressDiagnostics();
12227 
12228   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12229     // Maybe we will complain about the shadowed template parameter.
12230     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12231     // Just pretend that we didn't see the previous declaration.
12232     PrevDecl = nullptr;
12233   }
12234 
12235   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12236     PrevDecl = nullptr;
12237 
12238   bool Mutable
12239     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
12240   SourceLocation TSSL = D.getLocStart();
12241   FieldDecl *NewFD
12242     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
12243                      TSSL, AS, PrevDecl, &D);
12244 
12245   if (NewFD->isInvalidDecl())
12246     Record->setInvalidDecl();
12247 
12248   if (D.getDeclSpec().isModulePrivateSpecified())
12249     NewFD->setModulePrivate();
12250 
12251   if (NewFD->isInvalidDecl() && PrevDecl) {
12252     // Don't introduce NewFD into scope; there's already something
12253     // with the same name in the same scope.
12254   } else if (II) {
12255     PushOnScopeChains(NewFD, S);
12256   } else
12257     Record->addDecl(NewFD);
12258 
12259   return NewFD;
12260 }
12261 
12262 /// \brief Build a new FieldDecl and check its well-formedness.
12263 ///
12264 /// This routine builds a new FieldDecl given the fields name, type,
12265 /// record, etc. \p PrevDecl should refer to any previous declaration
12266 /// with the same name and in the same scope as the field to be
12267 /// created.
12268 ///
12269 /// \returns a new FieldDecl.
12270 ///
12271 /// \todo The Declarator argument is a hack. It will be removed once
12272 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
12273                                 TypeSourceInfo *TInfo,
12274                                 RecordDecl *Record, SourceLocation Loc,
12275                                 bool Mutable, Expr *BitWidth,
12276                                 InClassInitStyle InitStyle,
12277                                 SourceLocation TSSL,
12278                                 AccessSpecifier AS, NamedDecl *PrevDecl,
12279                                 Declarator *D) {
12280   IdentifierInfo *II = Name.getAsIdentifierInfo();
12281   bool InvalidDecl = false;
12282   if (D) InvalidDecl = D->isInvalidType();
12283 
12284   // If we receive a broken type, recover by assuming 'int' and
12285   // marking this declaration as invalid.
12286   if (T.isNull()) {
12287     InvalidDecl = true;
12288     T = Context.IntTy;
12289   }
12290 
12291   QualType EltTy = Context.getBaseElementType(T);
12292   if (!EltTy->isDependentType()) {
12293     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
12294       // Fields of incomplete type force their record to be invalid.
12295       Record->setInvalidDecl();
12296       InvalidDecl = true;
12297     } else {
12298       NamedDecl *Def;
12299       EltTy->isIncompleteType(&Def);
12300       if (Def && Def->isInvalidDecl()) {
12301         Record->setInvalidDecl();
12302         InvalidDecl = true;
12303       }
12304     }
12305   }
12306 
12307   // OpenCL v1.2 s6.9.c: bitfields are not supported.
12308   if (BitWidth && getLangOpts().OpenCL) {
12309     Diag(Loc, diag::err_opencl_bitfields);
12310     InvalidDecl = true;
12311   }
12312 
12313   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12314   // than a variably modified type.
12315   if (!InvalidDecl && T->isVariablyModifiedType()) {
12316     bool SizeIsNegative;
12317     llvm::APSInt Oversized;
12318 
12319     TypeSourceInfo *FixedTInfo =
12320       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
12321                                                     SizeIsNegative,
12322                                                     Oversized);
12323     if (FixedTInfo) {
12324       Diag(Loc, diag::warn_illegal_constant_array_size);
12325       TInfo = FixedTInfo;
12326       T = FixedTInfo->getType();
12327     } else {
12328       if (SizeIsNegative)
12329         Diag(Loc, diag::err_typecheck_negative_array_size);
12330       else if (Oversized.getBoolValue())
12331         Diag(Loc, diag::err_array_too_large)
12332           << Oversized.toString(10);
12333       else
12334         Diag(Loc, diag::err_typecheck_field_variable_size);
12335       InvalidDecl = true;
12336     }
12337   }
12338 
12339   // Fields can not have abstract class types
12340   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
12341                                              diag::err_abstract_type_in_decl,
12342                                              AbstractFieldType))
12343     InvalidDecl = true;
12344 
12345   bool ZeroWidth = false;
12346   // If this is declared as a bit-field, check the bit-field.
12347   if (!InvalidDecl && BitWidth) {
12348     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
12349                               &ZeroWidth).get();
12350     if (!BitWidth) {
12351       InvalidDecl = true;
12352       BitWidth = nullptr;
12353       ZeroWidth = false;
12354     }
12355   }
12356 
12357   // Check that 'mutable' is consistent with the type of the declaration.
12358   if (!InvalidDecl && Mutable) {
12359     unsigned DiagID = 0;
12360     if (T->isReferenceType())
12361       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
12362                                         : diag::err_mutable_reference;
12363     else if (T.isConstQualified())
12364       DiagID = diag::err_mutable_const;
12365 
12366     if (DiagID) {
12367       SourceLocation ErrLoc = Loc;
12368       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
12369         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
12370       Diag(ErrLoc, DiagID);
12371       if (DiagID != diag::ext_mutable_reference) {
12372         Mutable = false;
12373         InvalidDecl = true;
12374       }
12375     }
12376   }
12377 
12378   // C++11 [class.union]p8 (DR1460):
12379   //   At most one variant member of a union may have a
12380   //   brace-or-equal-initializer.
12381   if (InitStyle != ICIS_NoInit)
12382     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
12383 
12384   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
12385                                        BitWidth, Mutable, InitStyle);
12386   if (InvalidDecl)
12387     NewFD->setInvalidDecl();
12388 
12389   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
12390     Diag(Loc, diag::err_duplicate_member) << II;
12391     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12392     NewFD->setInvalidDecl();
12393   }
12394 
12395   if (!InvalidDecl && getLangOpts().CPlusPlus) {
12396     if (Record->isUnion()) {
12397       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12398         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
12399         if (RDecl->getDefinition()) {
12400           // C++ [class.union]p1: An object of a class with a non-trivial
12401           // constructor, a non-trivial copy constructor, a non-trivial
12402           // destructor, or a non-trivial copy assignment operator
12403           // cannot be a member of a union, nor can an array of such
12404           // objects.
12405           if (CheckNontrivialField(NewFD))
12406             NewFD->setInvalidDecl();
12407         }
12408       }
12409 
12410       // C++ [class.union]p1: If a union contains a member of reference type,
12411       // the program is ill-formed, except when compiling with MSVC extensions
12412       // enabled.
12413       if (EltTy->isReferenceType()) {
12414         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
12415                                     diag::ext_union_member_of_reference_type :
12416                                     diag::err_union_member_of_reference_type)
12417           << NewFD->getDeclName() << EltTy;
12418         if (!getLangOpts().MicrosoftExt)
12419           NewFD->setInvalidDecl();
12420       }
12421     }
12422   }
12423 
12424   // FIXME: We need to pass in the attributes given an AST
12425   // representation, not a parser representation.
12426   if (D) {
12427     // FIXME: The current scope is almost... but not entirely... correct here.
12428     ProcessDeclAttributes(getCurScope(), NewFD, *D);
12429 
12430     if (NewFD->hasAttrs())
12431       CheckAlignasUnderalignment(NewFD);
12432   }
12433 
12434   // In auto-retain/release, infer strong retension for fields of
12435   // retainable type.
12436   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
12437     NewFD->setInvalidDecl();
12438 
12439   if (T.isObjCGCWeak())
12440     Diag(Loc, diag::warn_attribute_weak_on_field);
12441 
12442   NewFD->setAccess(AS);
12443   return NewFD;
12444 }
12445 
12446 bool Sema::CheckNontrivialField(FieldDecl *FD) {
12447   assert(FD);
12448   assert(getLangOpts().CPlusPlus && "valid check only for C++");
12449 
12450   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
12451     return false;
12452 
12453   QualType EltTy = Context.getBaseElementType(FD->getType());
12454   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12455     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
12456     if (RDecl->getDefinition()) {
12457       // We check for copy constructors before constructors
12458       // because otherwise we'll never get complaints about
12459       // copy constructors.
12460 
12461       CXXSpecialMember member = CXXInvalid;
12462       // We're required to check for any non-trivial constructors. Since the
12463       // implicit default constructor is suppressed if there are any
12464       // user-declared constructors, we just need to check that there is a
12465       // trivial default constructor and a trivial copy constructor. (We don't
12466       // worry about move constructors here, since this is a C++98 check.)
12467       if (RDecl->hasNonTrivialCopyConstructor())
12468         member = CXXCopyConstructor;
12469       else if (!RDecl->hasTrivialDefaultConstructor())
12470         member = CXXDefaultConstructor;
12471       else if (RDecl->hasNonTrivialCopyAssignment())
12472         member = CXXCopyAssignment;
12473       else if (RDecl->hasNonTrivialDestructor())
12474         member = CXXDestructor;
12475 
12476       if (member != CXXInvalid) {
12477         if (!getLangOpts().CPlusPlus11 &&
12478             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
12479           // Objective-C++ ARC: it is an error to have a non-trivial field of
12480           // a union. However, system headers in Objective-C programs
12481           // occasionally have Objective-C lifetime objects within unions,
12482           // and rather than cause the program to fail, we make those
12483           // members unavailable.
12484           SourceLocation Loc = FD->getLocation();
12485           if (getSourceManager().isInSystemHeader(Loc)) {
12486             if (!FD->hasAttr<UnavailableAttr>())
12487               FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12488                                   "this system field has retaining ownership",
12489                                   Loc));
12490             return false;
12491           }
12492         }
12493 
12494         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
12495                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
12496                diag::err_illegal_union_or_anon_struct_member)
12497           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
12498         DiagnoseNontrivial(RDecl, member);
12499         return !getLangOpts().CPlusPlus11;
12500       }
12501     }
12502   }
12503 
12504   return false;
12505 }
12506 
12507 /// TranslateIvarVisibility - Translate visibility from a token ID to an
12508 ///  AST enum value.
12509 static ObjCIvarDecl::AccessControl
12510 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
12511   switch (ivarVisibility) {
12512   default: llvm_unreachable("Unknown visitibility kind");
12513   case tok::objc_private: return ObjCIvarDecl::Private;
12514   case tok::objc_public: return ObjCIvarDecl::Public;
12515   case tok::objc_protected: return ObjCIvarDecl::Protected;
12516   case tok::objc_package: return ObjCIvarDecl::Package;
12517   }
12518 }
12519 
12520 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
12521 /// in order to create an IvarDecl object for it.
12522 Decl *Sema::ActOnIvar(Scope *S,
12523                                 SourceLocation DeclStart,
12524                                 Declarator &D, Expr *BitfieldWidth,
12525                                 tok::ObjCKeywordKind Visibility) {
12526 
12527   IdentifierInfo *II = D.getIdentifier();
12528   Expr *BitWidth = (Expr*)BitfieldWidth;
12529   SourceLocation Loc = DeclStart;
12530   if (II) Loc = D.getIdentifierLoc();
12531 
12532   // FIXME: Unnamed fields can be handled in various different ways, for
12533   // example, unnamed unions inject all members into the struct namespace!
12534 
12535   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12536   QualType T = TInfo->getType();
12537 
12538   if (BitWidth) {
12539     // 6.7.2.1p3, 6.7.2.1p4
12540     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
12541     if (!BitWidth)
12542       D.setInvalidType();
12543   } else {
12544     // Not a bitfield.
12545 
12546     // validate II.
12547 
12548   }
12549   if (T->isReferenceType()) {
12550     Diag(Loc, diag::err_ivar_reference_type);
12551     D.setInvalidType();
12552   }
12553   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12554   // than a variably modified type.
12555   else if (T->isVariablyModifiedType()) {
12556     Diag(Loc, diag::err_typecheck_ivar_variable_size);
12557     D.setInvalidType();
12558   }
12559 
12560   // Get the visibility (access control) for this ivar.
12561   ObjCIvarDecl::AccessControl ac =
12562     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
12563                                         : ObjCIvarDecl::None;
12564   // Must set ivar's DeclContext to its enclosing interface.
12565   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
12566   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
12567     return nullptr;
12568   ObjCContainerDecl *EnclosingContext;
12569   if (ObjCImplementationDecl *IMPDecl =
12570       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12571     if (LangOpts.ObjCRuntime.isFragile()) {
12572     // Case of ivar declared in an implementation. Context is that of its class.
12573       EnclosingContext = IMPDecl->getClassInterface();
12574       assert(EnclosingContext && "Implementation has no class interface!");
12575     }
12576     else
12577       EnclosingContext = EnclosingDecl;
12578   } else {
12579     if (ObjCCategoryDecl *CDecl =
12580         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12581       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
12582         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
12583         return nullptr;
12584       }
12585     }
12586     EnclosingContext = EnclosingDecl;
12587   }
12588 
12589   // Construct the decl.
12590   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
12591                                              DeclStart, Loc, II, T,
12592                                              TInfo, ac, (Expr *)BitfieldWidth);
12593 
12594   if (II) {
12595     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
12596                                            ForRedeclaration);
12597     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
12598         && !isa<TagDecl>(PrevDecl)) {
12599       Diag(Loc, diag::err_duplicate_member) << II;
12600       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12601       NewID->setInvalidDecl();
12602     }
12603   }
12604 
12605   // Process attributes attached to the ivar.
12606   ProcessDeclAttributes(S, NewID, D);
12607 
12608   if (D.isInvalidType())
12609     NewID->setInvalidDecl();
12610 
12611   // In ARC, infer 'retaining' for ivars of retainable type.
12612   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
12613     NewID->setInvalidDecl();
12614 
12615   if (D.getDeclSpec().isModulePrivateSpecified())
12616     NewID->setModulePrivate();
12617 
12618   if (II) {
12619     // FIXME: When interfaces are DeclContexts, we'll need to add
12620     // these to the interface.
12621     S->AddDecl(NewID);
12622     IdResolver.AddDecl(NewID);
12623   }
12624 
12625   if (LangOpts.ObjCRuntime.isNonFragile() &&
12626       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
12627     Diag(Loc, diag::warn_ivars_in_interface);
12628 
12629   return NewID;
12630 }
12631 
12632 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
12633 /// class and class extensions. For every class \@interface and class
12634 /// extension \@interface, if the last ivar is a bitfield of any type,
12635 /// then add an implicit `char :0` ivar to the end of that interface.
12636 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
12637                              SmallVectorImpl<Decl *> &AllIvarDecls) {
12638   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
12639     return;
12640 
12641   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
12642   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
12643 
12644   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
12645     return;
12646   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
12647   if (!ID) {
12648     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
12649       if (!CD->IsClassExtension())
12650         return;
12651     }
12652     // No need to add this to end of @implementation.
12653     else
12654       return;
12655   }
12656   // All conditions are met. Add a new bitfield to the tail end of ivars.
12657   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
12658   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
12659 
12660   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
12661                               DeclLoc, DeclLoc, nullptr,
12662                               Context.CharTy,
12663                               Context.getTrivialTypeSourceInfo(Context.CharTy,
12664                                                                DeclLoc),
12665                               ObjCIvarDecl::Private, BW,
12666                               true);
12667   AllIvarDecls.push_back(Ivar);
12668 }
12669 
12670 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
12671                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
12672                        SourceLocation RBrac, AttributeList *Attr) {
12673   assert(EnclosingDecl && "missing record or interface decl");
12674 
12675   // If this is an Objective-C @implementation or category and we have
12676   // new fields here we should reset the layout of the interface since
12677   // it will now change.
12678   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
12679     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
12680     switch (DC->getKind()) {
12681     default: break;
12682     case Decl::ObjCCategory:
12683       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
12684       break;
12685     case Decl::ObjCImplementation:
12686       Context.
12687         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
12688       break;
12689     }
12690   }
12691 
12692   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
12693 
12694   // Start counting up the number of named members; make sure to include
12695   // members of anonymous structs and unions in the total.
12696   unsigned NumNamedMembers = 0;
12697   if (Record) {
12698     for (const auto *I : Record->decls()) {
12699       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
12700         if (IFD->getDeclName())
12701           ++NumNamedMembers;
12702     }
12703   }
12704 
12705   // Verify that all the fields are okay.
12706   SmallVector<FieldDecl*, 32> RecFields;
12707 
12708   bool ARCErrReported = false;
12709   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
12710        i != end; ++i) {
12711     FieldDecl *FD = cast<FieldDecl>(*i);
12712 
12713     // Get the type for the field.
12714     const Type *FDTy = FD->getType().getTypePtr();
12715 
12716     if (!FD->isAnonymousStructOrUnion()) {
12717       // Remember all fields written by the user.
12718       RecFields.push_back(FD);
12719     }
12720 
12721     // If the field is already invalid for some reason, don't emit more
12722     // diagnostics about it.
12723     if (FD->isInvalidDecl()) {
12724       EnclosingDecl->setInvalidDecl();
12725       continue;
12726     }
12727 
12728     // C99 6.7.2.1p2:
12729     //   A structure or union shall not contain a member with
12730     //   incomplete or function type (hence, a structure shall not
12731     //   contain an instance of itself, but may contain a pointer to
12732     //   an instance of itself), except that the last member of a
12733     //   structure with more than one named member may have incomplete
12734     //   array type; such a structure (and any union containing,
12735     //   possibly recursively, a member that is such a structure)
12736     //   shall not be a member of a structure or an element of an
12737     //   array.
12738     if (FDTy->isFunctionType()) {
12739       // Field declared as a function.
12740       Diag(FD->getLocation(), diag::err_field_declared_as_function)
12741         << FD->getDeclName();
12742       FD->setInvalidDecl();
12743       EnclosingDecl->setInvalidDecl();
12744       continue;
12745     } else if (FDTy->isIncompleteArrayType() && Record &&
12746                ((i + 1 == Fields.end() && !Record->isUnion()) ||
12747                 ((getLangOpts().MicrosoftExt ||
12748                   getLangOpts().CPlusPlus) &&
12749                  (i + 1 == Fields.end() || Record->isUnion())))) {
12750       // Flexible array member.
12751       // Microsoft and g++ is more permissive regarding flexible array.
12752       // It will accept flexible array in union and also
12753       // as the sole element of a struct/class.
12754       unsigned DiagID = 0;
12755       if (Record->isUnion())
12756         DiagID = getLangOpts().MicrosoftExt
12757                      ? diag::ext_flexible_array_union_ms
12758                      : getLangOpts().CPlusPlus
12759                            ? diag::ext_flexible_array_union_gnu
12760                            : diag::err_flexible_array_union;
12761       else if (Fields.size() == 1)
12762         DiagID = getLangOpts().MicrosoftExt
12763                      ? diag::ext_flexible_array_empty_aggregate_ms
12764                      : getLangOpts().CPlusPlus
12765                            ? diag::ext_flexible_array_empty_aggregate_gnu
12766                            : NumNamedMembers < 1
12767                                  ? diag::err_flexible_array_empty_aggregate
12768                                  : 0;
12769 
12770       if (DiagID)
12771         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
12772                                         << Record->getTagKind();
12773       // While the layout of types that contain virtual bases is not specified
12774       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
12775       // virtual bases after the derived members.  This would make a flexible
12776       // array member declared at the end of an object not adjacent to the end
12777       // of the type.
12778       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
12779         if (RD->getNumVBases() != 0)
12780           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
12781             << FD->getDeclName() << Record->getTagKind();
12782       if (!getLangOpts().C99)
12783         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
12784           << FD->getDeclName() << Record->getTagKind();
12785 
12786       // If the element type has a non-trivial destructor, we would not
12787       // implicitly destroy the elements, so disallow it for now.
12788       //
12789       // FIXME: GCC allows this. We should probably either implicitly delete
12790       // the destructor of the containing class, or just allow this.
12791       QualType BaseElem = Context.getBaseElementType(FD->getType());
12792       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
12793         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
12794           << FD->getDeclName() << FD->getType();
12795         FD->setInvalidDecl();
12796         EnclosingDecl->setInvalidDecl();
12797         continue;
12798       }
12799       // Okay, we have a legal flexible array member at the end of the struct.
12800       Record->setHasFlexibleArrayMember(true);
12801     } else if (!FDTy->isDependentType() &&
12802                RequireCompleteType(FD->getLocation(), FD->getType(),
12803                                    diag::err_field_incomplete)) {
12804       // Incomplete type
12805       FD->setInvalidDecl();
12806       EnclosingDecl->setInvalidDecl();
12807       continue;
12808     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
12809       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
12810         // A type which contains a flexible array member is considered to be a
12811         // flexible array member.
12812         Record->setHasFlexibleArrayMember(true);
12813         if (!Record->isUnion()) {
12814           // If this is a struct/class and this is not the last element, reject
12815           // it.  Note that GCC supports variable sized arrays in the middle of
12816           // structures.
12817           if (i + 1 != Fields.end())
12818             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
12819               << FD->getDeclName() << FD->getType();
12820           else {
12821             // We support flexible arrays at the end of structs in
12822             // other structs as an extension.
12823             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12824               << FD->getDeclName();
12825           }
12826         }
12827       }
12828       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12829           RequireNonAbstractType(FD->getLocation(), FD->getType(),
12830                                  diag::err_abstract_type_in_decl,
12831                                  AbstractIvarType)) {
12832         // Ivars can not have abstract class types
12833         FD->setInvalidDecl();
12834       }
12835       if (Record && FDTTy->getDecl()->hasObjectMember())
12836         Record->setHasObjectMember(true);
12837       if (Record && FDTTy->getDecl()->hasVolatileMember())
12838         Record->setHasVolatileMember(true);
12839     } else if (FDTy->isObjCObjectType()) {
12840       /// A field cannot be an Objective-c object
12841       Diag(FD->getLocation(), diag::err_statically_allocated_object)
12842         << FixItHint::CreateInsertion(FD->getLocation(), "*");
12843       QualType T = Context.getObjCObjectPointerType(FD->getType());
12844       FD->setType(T);
12845     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12846                (!getLangOpts().CPlusPlus || Record->isUnion())) {
12847       // It's an error in ARC if a field has lifetime.
12848       // We don't want to report this in a system header, though,
12849       // so we just make the field unavailable.
12850       // FIXME: that's really not sufficient; we need to make the type
12851       // itself invalid to, say, initialize or copy.
12852       QualType T = FD->getType();
12853       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12854       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12855         SourceLocation loc = FD->getLocation();
12856         if (getSourceManager().isInSystemHeader(loc)) {
12857           if (!FD->hasAttr<UnavailableAttr>()) {
12858             FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12859                               "this system field has retaining ownership",
12860                               loc));
12861           }
12862         } else {
12863           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
12864             << T->isBlockPointerType() << Record->getTagKind();
12865         }
12866         ARCErrReported = true;
12867       }
12868     } else if (getLangOpts().ObjC1 &&
12869                getLangOpts().getGC() != LangOptions::NonGC &&
12870                Record && !Record->hasObjectMember()) {
12871       if (FD->getType()->isObjCObjectPointerType() ||
12872           FD->getType().isObjCGCStrong())
12873         Record->setHasObjectMember(true);
12874       else if (Context.getAsArrayType(FD->getType())) {
12875         QualType BaseType = Context.getBaseElementType(FD->getType());
12876         if (BaseType->isRecordType() &&
12877             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
12878           Record->setHasObjectMember(true);
12879         else if (BaseType->isObjCObjectPointerType() ||
12880                  BaseType.isObjCGCStrong())
12881                Record->setHasObjectMember(true);
12882       }
12883     }
12884     if (Record && FD->getType().isVolatileQualified())
12885       Record->setHasVolatileMember(true);
12886     // Keep track of the number of named members.
12887     if (FD->getIdentifier())
12888       ++NumNamedMembers;
12889   }
12890 
12891   // Okay, we successfully defined 'Record'.
12892   if (Record) {
12893     bool Completed = false;
12894     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12895       if (!CXXRecord->isInvalidDecl()) {
12896         // Set access bits correctly on the directly-declared conversions.
12897         for (CXXRecordDecl::conversion_iterator
12898                I = CXXRecord->conversion_begin(),
12899                E = CXXRecord->conversion_end(); I != E; ++I)
12900           I.setAccess((*I)->getAccess());
12901 
12902         if (!CXXRecord->isDependentType()) {
12903           if (CXXRecord->hasUserDeclaredDestructor()) {
12904             // Adjust user-defined destructor exception spec.
12905             if (getLangOpts().CPlusPlus11)
12906               AdjustDestructorExceptionSpec(CXXRecord,
12907                                             CXXRecord->getDestructor());
12908           }
12909 
12910           // Add any implicitly-declared members to this class.
12911           AddImplicitlyDeclaredMembersToClass(CXXRecord);
12912 
12913           // If we have virtual base classes, we may end up finding multiple
12914           // final overriders for a given virtual function. Check for this
12915           // problem now.
12916           if (CXXRecord->getNumVBases()) {
12917             CXXFinalOverriderMap FinalOverriders;
12918             CXXRecord->getFinalOverriders(FinalOverriders);
12919 
12920             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12921                                              MEnd = FinalOverriders.end();
12922                  M != MEnd; ++M) {
12923               for (OverridingMethods::iterator SO = M->second.begin(),
12924                                             SOEnd = M->second.end();
12925                    SO != SOEnd; ++SO) {
12926                 assert(SO->second.size() > 0 &&
12927                        "Virtual function without overridding functions?");
12928                 if (SO->second.size() == 1)
12929                   continue;
12930 
12931                 // C++ [class.virtual]p2:
12932                 //   In a derived class, if a virtual member function of a base
12933                 //   class subobject has more than one final overrider the
12934                 //   program is ill-formed.
12935                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
12936                   << (const NamedDecl *)M->first << Record;
12937                 Diag(M->first->getLocation(),
12938                      diag::note_overridden_virtual_function);
12939                 for (OverridingMethods::overriding_iterator
12940                           OM = SO->second.begin(),
12941                        OMEnd = SO->second.end();
12942                      OM != OMEnd; ++OM)
12943                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
12944                     << (const NamedDecl *)M->first << OM->Method->getParent();
12945 
12946                 Record->setInvalidDecl();
12947               }
12948             }
12949             CXXRecord->completeDefinition(&FinalOverriders);
12950             Completed = true;
12951           }
12952         }
12953       }
12954     }
12955 
12956     if (!Completed)
12957       Record->completeDefinition();
12958 
12959     if (Record->hasAttrs()) {
12960       CheckAlignasUnderalignment(Record);
12961 
12962       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
12963         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
12964                                            IA->getRange(), IA->getBestCase(),
12965                                            IA->getSemanticSpelling());
12966     }
12967 
12968     // Check if the structure/union declaration is a type that can have zero
12969     // size in C. For C this is a language extension, for C++ it may cause
12970     // compatibility problems.
12971     bool CheckForZeroSize;
12972     if (!getLangOpts().CPlusPlus) {
12973       CheckForZeroSize = true;
12974     } else {
12975       // For C++ filter out types that cannot be referenced in C code.
12976       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12977       CheckForZeroSize =
12978           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12979           !CXXRecord->isDependentType() &&
12980           CXXRecord->isCLike();
12981     }
12982     if (CheckForZeroSize) {
12983       bool ZeroSize = true;
12984       bool IsEmpty = true;
12985       unsigned NonBitFields = 0;
12986       for (RecordDecl::field_iterator I = Record->field_begin(),
12987                                       E = Record->field_end();
12988            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12989         IsEmpty = false;
12990         if (I->isUnnamedBitfield()) {
12991           if (I->getBitWidthValue(Context) > 0)
12992             ZeroSize = false;
12993         } else {
12994           ++NonBitFields;
12995           QualType FieldType = I->getType();
12996           if (FieldType->isIncompleteType() ||
12997               !Context.getTypeSizeInChars(FieldType).isZero())
12998             ZeroSize = false;
12999         }
13000       }
13001 
13002       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
13003       // allowed in C++, but warn if its declaration is inside
13004       // extern "C" block.
13005       if (ZeroSize) {
13006         Diag(RecLoc, getLangOpts().CPlusPlus ?
13007                          diag::warn_zero_size_struct_union_in_extern_c :
13008                          diag::warn_zero_size_struct_union_compat)
13009           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
13010       }
13011 
13012       // Structs without named members are extension in C (C99 6.7.2.1p7),
13013       // but are accepted by GCC.
13014       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
13015         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
13016                                diag::ext_no_named_members_in_struct_union)
13017           << Record->isUnion();
13018       }
13019     }
13020   } else {
13021     ObjCIvarDecl **ClsFields =
13022       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
13023     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
13024       ID->setEndOfDefinitionLoc(RBrac);
13025       // Add ivar's to class's DeclContext.
13026       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13027         ClsFields[i]->setLexicalDeclContext(ID);
13028         ID->addDecl(ClsFields[i]);
13029       }
13030       // Must enforce the rule that ivars in the base classes may not be
13031       // duplicates.
13032       if (ID->getSuperClass())
13033         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13034     } else if (ObjCImplementationDecl *IMPDecl =
13035                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13036       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13037       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13038         // Ivar declared in @implementation never belongs to the implementation.
13039         // Only it is in implementation's lexical context.
13040         ClsFields[I]->setLexicalDeclContext(IMPDecl);
13041       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13042       IMPDecl->setIvarLBraceLoc(LBrac);
13043       IMPDecl->setIvarRBraceLoc(RBrac);
13044     } else if (ObjCCategoryDecl *CDecl =
13045                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13046       // case of ivars in class extension; all other cases have been
13047       // reported as errors elsewhere.
13048       // FIXME. Class extension does not have a LocEnd field.
13049       // CDecl->setLocEnd(RBrac);
13050       // Add ivar's to class extension's DeclContext.
13051       // Diagnose redeclaration of private ivars.
13052       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13053       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13054         if (IDecl) {
13055           if (const ObjCIvarDecl *ClsIvar =
13056               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13057             Diag(ClsFields[i]->getLocation(),
13058                  diag::err_duplicate_ivar_declaration);
13059             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13060             continue;
13061           }
13062           for (const auto *Ext : IDecl->known_extensions()) {
13063             if (const ObjCIvarDecl *ClsExtIvar
13064                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13065               Diag(ClsFields[i]->getLocation(),
13066                    diag::err_duplicate_ivar_declaration);
13067               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13068               continue;
13069             }
13070           }
13071         }
13072         ClsFields[i]->setLexicalDeclContext(CDecl);
13073         CDecl->addDecl(ClsFields[i]);
13074       }
13075       CDecl->setIvarLBraceLoc(LBrac);
13076       CDecl->setIvarRBraceLoc(RBrac);
13077     }
13078   }
13079 
13080   if (Attr)
13081     ProcessDeclAttributeList(S, Record, Attr);
13082 }
13083 
13084 /// \brief Determine whether the given integral value is representable within
13085 /// the given type T.
13086 static bool isRepresentableIntegerValue(ASTContext &Context,
13087                                         llvm::APSInt &Value,
13088                                         QualType T) {
13089   assert(T->isIntegralType(Context) && "Integral type required!");
13090   unsigned BitWidth = Context.getIntWidth(T);
13091 
13092   if (Value.isUnsigned() || Value.isNonNegative()) {
13093     if (T->isSignedIntegerOrEnumerationType())
13094       --BitWidth;
13095     return Value.getActiveBits() <= BitWidth;
13096   }
13097   return Value.getMinSignedBits() <= BitWidth;
13098 }
13099 
13100 // \brief Given an integral type, return the next larger integral type
13101 // (or a NULL type of no such type exists).
13102 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13103   // FIXME: Int128/UInt128 support, which also needs to be introduced into
13104   // enum checking below.
13105   assert(T->isIntegralType(Context) && "Integral type required!");
13106   const unsigned NumTypes = 4;
13107   QualType SignedIntegralTypes[NumTypes] = {
13108     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13109   };
13110   QualType UnsignedIntegralTypes[NumTypes] = {
13111     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
13112     Context.UnsignedLongLongTy
13113   };
13114 
13115   unsigned BitWidth = Context.getTypeSize(T);
13116   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13117                                                         : UnsignedIntegralTypes;
13118   for (unsigned I = 0; I != NumTypes; ++I)
13119     if (Context.getTypeSize(Types[I]) > BitWidth)
13120       return Types[I];
13121 
13122   return QualType();
13123 }
13124 
13125 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13126                                           EnumConstantDecl *LastEnumConst,
13127                                           SourceLocation IdLoc,
13128                                           IdentifierInfo *Id,
13129                                           Expr *Val) {
13130   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13131   llvm::APSInt EnumVal(IntWidth);
13132   QualType EltTy;
13133 
13134   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13135     Val = nullptr;
13136 
13137   if (Val)
13138     Val = DefaultLvalueConversion(Val).get();
13139 
13140   if (Val) {
13141     if (Enum->isDependentType() || Val->isTypeDependent())
13142       EltTy = Context.DependentTy;
13143     else {
13144       SourceLocation ExpLoc;
13145       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13146           !getLangOpts().MSVCCompat) {
13147         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13148         // constant-expression in the enumerator-definition shall be a converted
13149         // constant expression of the underlying type.
13150         EltTy = Enum->getIntegerType();
13151         ExprResult Converted =
13152           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13153                                            CCEK_Enumerator);
13154         if (Converted.isInvalid())
13155           Val = nullptr;
13156         else
13157           Val = Converted.get();
13158       } else if (!Val->isValueDependent() &&
13159                  !(Val = VerifyIntegerConstantExpression(Val,
13160                                                          &EnumVal).get())) {
13161         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13162       } else {
13163         if (Enum->isFixed()) {
13164           EltTy = Enum->getIntegerType();
13165 
13166           // In Obj-C and Microsoft mode, require the enumeration value to be
13167           // representable in the underlying type of the enumeration. In C++11,
13168           // we perform a non-narrowing conversion as part of converted constant
13169           // expression checking.
13170           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13171             if (getLangOpts().MSVCCompat) {
13172               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13173               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13174             } else
13175               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13176           } else
13177             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13178         } else if (getLangOpts().CPlusPlus) {
13179           // C++11 [dcl.enum]p5:
13180           //   If the underlying type is not fixed, the type of each enumerator
13181           //   is the type of its initializing value:
13182           //     - If an initializer is specified for an enumerator, the
13183           //       initializing value has the same type as the expression.
13184           EltTy = Val->getType();
13185         } else {
13186           // C99 6.7.2.2p2:
13187           //   The expression that defines the value of an enumeration constant
13188           //   shall be an integer constant expression that has a value
13189           //   representable as an int.
13190 
13191           // Complain if the value is not representable in an int.
13192           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13193             Diag(IdLoc, diag::ext_enum_value_not_int)
13194               << EnumVal.toString(10) << Val->getSourceRange()
13195               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13196           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13197             // Force the type of the expression to 'int'.
13198             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13199           }
13200           EltTy = Val->getType();
13201         }
13202       }
13203     }
13204   }
13205 
13206   if (!Val) {
13207     if (Enum->isDependentType())
13208       EltTy = Context.DependentTy;
13209     else if (!LastEnumConst) {
13210       // C++0x [dcl.enum]p5:
13211       //   If the underlying type is not fixed, the type of each enumerator
13212       //   is the type of its initializing value:
13213       //     - If no initializer is specified for the first enumerator, the
13214       //       initializing value has an unspecified integral type.
13215       //
13216       // GCC uses 'int' for its unspecified integral type, as does
13217       // C99 6.7.2.2p3.
13218       if (Enum->isFixed()) {
13219         EltTy = Enum->getIntegerType();
13220       }
13221       else {
13222         EltTy = Context.IntTy;
13223       }
13224     } else {
13225       // Assign the last value + 1.
13226       EnumVal = LastEnumConst->getInitVal();
13227       ++EnumVal;
13228       EltTy = LastEnumConst->getType();
13229 
13230       // Check for overflow on increment.
13231       if (EnumVal < LastEnumConst->getInitVal()) {
13232         // C++0x [dcl.enum]p5:
13233         //   If the underlying type is not fixed, the type of each enumerator
13234         //   is the type of its initializing value:
13235         //
13236         //     - Otherwise the type of the initializing value is the same as
13237         //       the type of the initializing value of the preceding enumerator
13238         //       unless the incremented value is not representable in that type,
13239         //       in which case the type is an unspecified integral type
13240         //       sufficient to contain the incremented value. If no such type
13241         //       exists, the program is ill-formed.
13242         QualType T = getNextLargerIntegralType(Context, EltTy);
13243         if (T.isNull() || Enum->isFixed()) {
13244           // There is no integral type larger enough to represent this
13245           // value. Complain, then allow the value to wrap around.
13246           EnumVal = LastEnumConst->getInitVal();
13247           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
13248           ++EnumVal;
13249           if (Enum->isFixed())
13250             // When the underlying type is fixed, this is ill-formed.
13251             Diag(IdLoc, diag::err_enumerator_wrapped)
13252               << EnumVal.toString(10)
13253               << EltTy;
13254           else
13255             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
13256               << EnumVal.toString(10);
13257         } else {
13258           EltTy = T;
13259         }
13260 
13261         // Retrieve the last enumerator's value, extent that type to the
13262         // type that is supposed to be large enough to represent the incremented
13263         // value, then increment.
13264         EnumVal = LastEnumConst->getInitVal();
13265         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13266         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
13267         ++EnumVal;
13268 
13269         // If we're not in C++, diagnose the overflow of enumerator values,
13270         // which in C99 means that the enumerator value is not representable in
13271         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13272         // permits enumerator values that are representable in some larger
13273         // integral type.
13274         if (!getLangOpts().CPlusPlus && !T.isNull())
13275           Diag(IdLoc, diag::warn_enum_value_overflow);
13276       } else if (!getLangOpts().CPlusPlus &&
13277                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13278         // Enforce C99 6.7.2.2p2 even when we compute the next value.
13279         Diag(IdLoc, diag::ext_enum_value_not_int)
13280           << EnumVal.toString(10) << 1;
13281       }
13282     }
13283   }
13284 
13285   if (!EltTy->isDependentType()) {
13286     // Make the enumerator value match the signedness and size of the
13287     // enumerator's type.
13288     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
13289     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13290   }
13291 
13292   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
13293                                   Val, EnumVal);
13294 }
13295 
13296 
13297 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
13298                               SourceLocation IdLoc, IdentifierInfo *Id,
13299                               AttributeList *Attr,
13300                               SourceLocation EqualLoc, Expr *Val) {
13301   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
13302   EnumConstantDecl *LastEnumConst =
13303     cast_or_null<EnumConstantDecl>(lastEnumConst);
13304 
13305   // The scope passed in may not be a decl scope.  Zip up the scope tree until
13306   // we find one that is.
13307   S = getNonFieldDeclScope(S);
13308 
13309   // Verify that there isn't already something declared with this name in this
13310   // scope.
13311   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
13312                                          ForRedeclaration);
13313   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13314     // Maybe we will complain about the shadowed template parameter.
13315     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
13316     // Just pretend that we didn't see the previous declaration.
13317     PrevDecl = nullptr;
13318   }
13319 
13320   if (PrevDecl) {
13321     // When in C++, we may get a TagDecl with the same name; in this case the
13322     // enum constant will 'hide' the tag.
13323     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
13324            "Received TagDecl when not in C++!");
13325     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
13326       if (isa<EnumConstantDecl>(PrevDecl))
13327         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
13328       else
13329         Diag(IdLoc, diag::err_redefinition) << Id;
13330       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13331       return nullptr;
13332     }
13333   }
13334 
13335   // C++ [class.mem]p15:
13336   // If T is the name of a class, then each of the following shall have a name
13337   // different from T:
13338   // - every enumerator of every member of class T that is an unscoped
13339   // enumerated type
13340   if (CXXRecordDecl *Record
13341                       = dyn_cast<CXXRecordDecl>(
13342                              TheEnumDecl->getDeclContext()->getRedeclContext()))
13343     if (!TheEnumDecl->isScoped() &&
13344         Record->getIdentifier() && Record->getIdentifier() == Id)
13345       Diag(IdLoc, diag::err_member_name_of_class) << Id;
13346 
13347   EnumConstantDecl *New =
13348     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
13349 
13350   if (New) {
13351     // Process attributes.
13352     if (Attr) ProcessDeclAttributeList(S, New, Attr);
13353 
13354     // Register this decl in the current scope stack.
13355     New->setAccess(TheEnumDecl->getAccess());
13356     PushOnScopeChains(New, S);
13357   }
13358 
13359   ActOnDocumentableDecl(New);
13360 
13361   return New;
13362 }
13363 
13364 // Returns true when the enum initial expression does not trigger the
13365 // duplicate enum warning.  A few common cases are exempted as follows:
13366 // Element2 = Element1
13367 // Element2 = Element1 + 1
13368 // Element2 = Element1 - 1
13369 // Where Element2 and Element1 are from the same enum.
13370 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
13371   Expr *InitExpr = ECD->getInitExpr();
13372   if (!InitExpr)
13373     return true;
13374   InitExpr = InitExpr->IgnoreImpCasts();
13375 
13376   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
13377     if (!BO->isAdditiveOp())
13378       return true;
13379     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
13380     if (!IL)
13381       return true;
13382     if (IL->getValue() != 1)
13383       return true;
13384 
13385     InitExpr = BO->getLHS();
13386   }
13387 
13388   // This checks if the elements are from the same enum.
13389   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
13390   if (!DRE)
13391     return true;
13392 
13393   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
13394   if (!EnumConstant)
13395     return true;
13396 
13397   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
13398       Enum)
13399     return true;
13400 
13401   return false;
13402 }
13403 
13404 struct DupKey {
13405   int64_t val;
13406   bool isTombstoneOrEmptyKey;
13407   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
13408     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
13409 };
13410 
13411 static DupKey GetDupKey(const llvm::APSInt& Val) {
13412   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
13413                 false);
13414 }
13415 
13416 struct DenseMapInfoDupKey {
13417   static DupKey getEmptyKey() { return DupKey(0, true); }
13418   static DupKey getTombstoneKey() { return DupKey(1, true); }
13419   static unsigned getHashValue(const DupKey Key) {
13420     return (unsigned)(Key.val * 37);
13421   }
13422   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
13423     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
13424            LHS.val == RHS.val;
13425   }
13426 };
13427 
13428 // Emits a warning when an element is implicitly set a value that
13429 // a previous element has already been set to.
13430 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
13431                                         EnumDecl *Enum,
13432                                         QualType EnumType) {
13433   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
13434     return;
13435   // Avoid anonymous enums
13436   if (!Enum->getIdentifier())
13437     return;
13438 
13439   // Only check for small enums.
13440   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
13441     return;
13442 
13443   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
13444   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
13445 
13446   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
13447   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
13448           ValueToVectorMap;
13449 
13450   DuplicatesVector DupVector;
13451   ValueToVectorMap EnumMap;
13452 
13453   // Populate the EnumMap with all values represented by enum constants without
13454   // an initialier.
13455   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13456     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
13457 
13458     // Null EnumConstantDecl means a previous diagnostic has been emitted for
13459     // this constant.  Skip this enum since it may be ill-formed.
13460     if (!ECD) {
13461       return;
13462     }
13463 
13464     if (ECD->getInitExpr())
13465       continue;
13466 
13467     DupKey Key = GetDupKey(ECD->getInitVal());
13468     DeclOrVector &Entry = EnumMap[Key];
13469 
13470     // First time encountering this value.
13471     if (Entry.isNull())
13472       Entry = ECD;
13473   }
13474 
13475   // Create vectors for any values that has duplicates.
13476   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13477     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
13478     if (!ValidDuplicateEnum(ECD, Enum))
13479       continue;
13480 
13481     DupKey Key = GetDupKey(ECD->getInitVal());
13482 
13483     DeclOrVector& Entry = EnumMap[Key];
13484     if (Entry.isNull())
13485       continue;
13486 
13487     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
13488       // Ensure constants are different.
13489       if (D == ECD)
13490         continue;
13491 
13492       // Create new vector and push values onto it.
13493       ECDVector *Vec = new ECDVector();
13494       Vec->push_back(D);
13495       Vec->push_back(ECD);
13496 
13497       // Update entry to point to the duplicates vector.
13498       Entry = Vec;
13499 
13500       // Store the vector somewhere we can consult later for quick emission of
13501       // diagnostics.
13502       DupVector.push_back(Vec);
13503       continue;
13504     }
13505 
13506     ECDVector *Vec = Entry.get<ECDVector*>();
13507     // Make sure constants are not added more than once.
13508     if (*Vec->begin() == ECD)
13509       continue;
13510 
13511     Vec->push_back(ECD);
13512   }
13513 
13514   // Emit diagnostics.
13515   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
13516                                   DupVectorEnd = DupVector.end();
13517        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
13518     ECDVector *Vec = *DupVectorIter;
13519     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
13520 
13521     // Emit warning for one enum constant.
13522     ECDVector::iterator I = Vec->begin();
13523     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
13524       << (*I)->getName() << (*I)->getInitVal().toString(10)
13525       << (*I)->getSourceRange();
13526     ++I;
13527 
13528     // Emit one note for each of the remaining enum constants with
13529     // the same value.
13530     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
13531       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
13532         << (*I)->getName() << (*I)->getInitVal().toString(10)
13533         << (*I)->getSourceRange();
13534     delete Vec;
13535   }
13536 }
13537 
13538 bool
13539 Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
13540                         bool AllowMask) const {
13541   FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>();
13542   assert(FEAttr && "looking for value in non-flag enum");
13543 
13544   llvm::APInt FlagMask = ~FEAttr->getFlagBits();
13545   unsigned Width = FlagMask.getBitWidth();
13546 
13547   // We will try a zero-extended value for the regular check first.
13548   llvm::APInt ExtVal = Val.zextOrSelf(Width);
13549 
13550   // A value is in a flag enum if either its bits are a subset of the enum's
13551   // flag bits (the first condition) or we are allowing masks and the same is
13552   // true of its complement (the second condition). When masks are allowed, we
13553   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
13554   //
13555   // While it's true that any value could be used as a mask, the assumption is
13556   // that a mask will have all of the insignificant bits set. Anything else is
13557   // likely a logic error.
13558   if (!(FlagMask & ExtVal))
13559     return true;
13560 
13561   if (AllowMask) {
13562     // Try a one-extended value instead. This can happen if the enum is wider
13563     // than the constant used, in C with extensions to allow for wider enums.
13564     // The mask will still have the correct behaviour, so we give the user the
13565     // benefit of the doubt.
13566     //
13567     // FIXME: This heuristic can cause weird results if the enum was extended
13568     // to a larger type and is signed, because then bit-masks of smaller types
13569     // that get extended will fall out of range (e.g. ~0x1u). We currently don't
13570     // detect that case and will get a false positive for it. In most cases,
13571     // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may
13572     // be fine just to accept this as a warning.
13573     ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth());
13574     if (!(FlagMask & ~ExtVal))
13575       return true;
13576   }
13577 
13578   return false;
13579 }
13580 
13581 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
13582                          SourceLocation RBraceLoc, Decl *EnumDeclX,
13583                          ArrayRef<Decl *> Elements,
13584                          Scope *S, AttributeList *Attr) {
13585   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
13586   QualType EnumType = Context.getTypeDeclType(Enum);
13587 
13588   if (Attr)
13589     ProcessDeclAttributeList(S, Enum, Attr);
13590 
13591   if (Enum->isDependentType()) {
13592     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13593       EnumConstantDecl *ECD =
13594         cast_or_null<EnumConstantDecl>(Elements[i]);
13595       if (!ECD) continue;
13596 
13597       ECD->setType(EnumType);
13598     }
13599 
13600     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
13601     return;
13602   }
13603 
13604   // TODO: If the result value doesn't fit in an int, it must be a long or long
13605   // long value.  ISO C does not support this, but GCC does as an extension,
13606   // emit a warning.
13607   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13608   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
13609   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
13610 
13611   // Verify that all the values are okay, compute the size of the values, and
13612   // reverse the list.
13613   unsigned NumNegativeBits = 0;
13614   unsigned NumPositiveBits = 0;
13615 
13616   // Keep track of whether all elements have type int.
13617   bool AllElementsInt = true;
13618 
13619   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13620     EnumConstantDecl *ECD =
13621       cast_or_null<EnumConstantDecl>(Elements[i]);
13622     if (!ECD) continue;  // Already issued a diagnostic.
13623 
13624     const llvm::APSInt &InitVal = ECD->getInitVal();
13625 
13626     // Keep track of the size of positive and negative values.
13627     if (InitVal.isUnsigned() || InitVal.isNonNegative())
13628       NumPositiveBits = std::max(NumPositiveBits,
13629                                  (unsigned)InitVal.getActiveBits());
13630     else
13631       NumNegativeBits = std::max(NumNegativeBits,
13632                                  (unsigned)InitVal.getMinSignedBits());
13633 
13634     // Keep track of whether every enum element has type int (very commmon).
13635     if (AllElementsInt)
13636       AllElementsInt = ECD->getType() == Context.IntTy;
13637   }
13638 
13639   // Figure out the type that should be used for this enum.
13640   QualType BestType;
13641   unsigned BestWidth;
13642 
13643   // C++0x N3000 [conv.prom]p3:
13644   //   An rvalue of an unscoped enumeration type whose underlying
13645   //   type is not fixed can be converted to an rvalue of the first
13646   //   of the following types that can represent all the values of
13647   //   the enumeration: int, unsigned int, long int, unsigned long
13648   //   int, long long int, or unsigned long long int.
13649   // C99 6.4.4.3p2:
13650   //   An identifier declared as an enumeration constant has type int.
13651   // The C99 rule is modified by a gcc extension
13652   QualType BestPromotionType;
13653 
13654   bool Packed = Enum->hasAttr<PackedAttr>();
13655   // -fshort-enums is the equivalent to specifying the packed attribute on all
13656   // enum definitions.
13657   if (LangOpts.ShortEnums)
13658     Packed = true;
13659 
13660   if (Enum->isFixed()) {
13661     BestType = Enum->getIntegerType();
13662     if (BestType->isPromotableIntegerType())
13663       BestPromotionType = Context.getPromotedIntegerType(BestType);
13664     else
13665       BestPromotionType = BestType;
13666 
13667     BestWidth = Context.getIntWidth(BestType);
13668   }
13669   else if (NumNegativeBits) {
13670     // If there is a negative value, figure out the smallest integer type (of
13671     // int/long/longlong) that fits.
13672     // If it's packed, check also if it fits a char or a short.
13673     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
13674       BestType = Context.SignedCharTy;
13675       BestWidth = CharWidth;
13676     } else if (Packed && NumNegativeBits <= ShortWidth &&
13677                NumPositiveBits < ShortWidth) {
13678       BestType = Context.ShortTy;
13679       BestWidth = ShortWidth;
13680     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
13681       BestType = Context.IntTy;
13682       BestWidth = IntWidth;
13683     } else {
13684       BestWidth = Context.getTargetInfo().getLongWidth();
13685 
13686       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
13687         BestType = Context.LongTy;
13688       } else {
13689         BestWidth = Context.getTargetInfo().getLongLongWidth();
13690 
13691         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
13692           Diag(Enum->getLocation(), diag::ext_enum_too_large);
13693         BestType = Context.LongLongTy;
13694       }
13695     }
13696     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
13697   } else {
13698     // If there is no negative value, figure out the smallest type that fits
13699     // all of the enumerator values.
13700     // If it's packed, check also if it fits a char or a short.
13701     if (Packed && NumPositiveBits <= CharWidth) {
13702       BestType = Context.UnsignedCharTy;
13703       BestPromotionType = Context.IntTy;
13704       BestWidth = CharWidth;
13705     } else if (Packed && NumPositiveBits <= ShortWidth) {
13706       BestType = Context.UnsignedShortTy;
13707       BestPromotionType = Context.IntTy;
13708       BestWidth = ShortWidth;
13709     } else if (NumPositiveBits <= IntWidth) {
13710       BestType = Context.UnsignedIntTy;
13711       BestWidth = IntWidth;
13712       BestPromotionType
13713         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13714                            ? Context.UnsignedIntTy : Context.IntTy;
13715     } else if (NumPositiveBits <=
13716                (BestWidth = Context.getTargetInfo().getLongWidth())) {
13717       BestType = Context.UnsignedLongTy;
13718       BestPromotionType
13719         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13720                            ? Context.UnsignedLongTy : Context.LongTy;
13721     } else {
13722       BestWidth = Context.getTargetInfo().getLongLongWidth();
13723       assert(NumPositiveBits <= BestWidth &&
13724              "How could an initializer get larger than ULL?");
13725       BestType = Context.UnsignedLongLongTy;
13726       BestPromotionType
13727         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13728                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
13729     }
13730   }
13731 
13732   FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>();
13733   if (FEAttr)
13734     FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0);
13735 
13736   // Loop over all of the enumerator constants, changing their types to match
13737   // the type of the enum if needed. If we have a flag type, we also prepare the
13738   // FlagBits cache.
13739   for (auto *D : Elements) {
13740     auto *ECD = cast_or_null<EnumConstantDecl>(D);
13741     if (!ECD) continue;  // Already issued a diagnostic.
13742 
13743     // Standard C says the enumerators have int type, but we allow, as an
13744     // extension, the enumerators to be larger than int size.  If each
13745     // enumerator value fits in an int, type it as an int, otherwise type it the
13746     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
13747     // that X has type 'int', not 'unsigned'.
13748 
13749     // Determine whether the value fits into an int.
13750     llvm::APSInt InitVal = ECD->getInitVal();
13751 
13752     // If it fits into an integer type, force it.  Otherwise force it to match
13753     // the enum decl type.
13754     QualType NewTy;
13755     unsigned NewWidth;
13756     bool NewSign;
13757     if (!getLangOpts().CPlusPlus &&
13758         !Enum->isFixed() &&
13759         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
13760       NewTy = Context.IntTy;
13761       NewWidth = IntWidth;
13762       NewSign = true;
13763     } else if (ECD->getType() == BestType) {
13764       // Already the right type!
13765       if (getLangOpts().CPlusPlus)
13766         // C++ [dcl.enum]p4: Following the closing brace of an
13767         // enum-specifier, each enumerator has the type of its
13768         // enumeration.
13769         ECD->setType(EnumType);
13770       goto flagbits;
13771     } else {
13772       NewTy = BestType;
13773       NewWidth = BestWidth;
13774       NewSign = BestType->isSignedIntegerOrEnumerationType();
13775     }
13776 
13777     // Adjust the APSInt value.
13778     InitVal = InitVal.extOrTrunc(NewWidth);
13779     InitVal.setIsSigned(NewSign);
13780     ECD->setInitVal(InitVal);
13781 
13782     // Adjust the Expr initializer and type.
13783     if (ECD->getInitExpr() &&
13784         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
13785       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
13786                                                 CK_IntegralCast,
13787                                                 ECD->getInitExpr(),
13788                                                 /*base paths*/ nullptr,
13789                                                 VK_RValue));
13790     if (getLangOpts().CPlusPlus)
13791       // C++ [dcl.enum]p4: Following the closing brace of an
13792       // enum-specifier, each enumerator has the type of its
13793       // enumeration.
13794       ECD->setType(EnumType);
13795     else
13796       ECD->setType(NewTy);
13797 
13798 flagbits:
13799     // Check to see if we have a constant with exactly one bit set. Note that x
13800     // & (x - 1) will be nonzero if and only if x has more than one bit set.
13801     if (FEAttr) {
13802       llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth);
13803       if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) {
13804         FEAttr->getFlagBits() |= ExtVal;
13805       }
13806     }
13807   }
13808 
13809   if (FEAttr) {
13810     for (Decl *D : Elements) {
13811       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
13812       if (!ECD) continue;  // Already issued a diagnostic.
13813 
13814       llvm::APSInt InitVal = ECD->getInitVal();
13815       if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true))
13816         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
13817           << ECD << Enum;
13818     }
13819   }
13820 
13821 
13822 
13823   Enum->completeDefinition(BestType, BestPromotionType,
13824                            NumPositiveBits, NumNegativeBits);
13825 
13826   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
13827 
13828   // Now that the enum type is defined, ensure it's not been underaligned.
13829   if (Enum->hasAttrs())
13830     CheckAlignasUnderalignment(Enum);
13831 }
13832 
13833 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
13834                                   SourceLocation StartLoc,
13835                                   SourceLocation EndLoc) {
13836   StringLiteral *AsmString = cast<StringLiteral>(expr);
13837 
13838   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
13839                                                    AsmString, StartLoc,
13840                                                    EndLoc);
13841   CurContext->addDecl(New);
13842   return New;
13843 }
13844 
13845 static void checkModuleImportContext(Sema &S, Module *M,
13846                                      SourceLocation ImportLoc,
13847                                      DeclContext *DC) {
13848   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
13849     switch (LSD->getLanguage()) {
13850     case LinkageSpecDecl::lang_c:
13851       if (!M->IsExternC) {
13852         S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
13853           << M->getFullModuleName();
13854         S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
13855         return;
13856       }
13857       break;
13858     case LinkageSpecDecl::lang_cxx:
13859       break;
13860     }
13861     DC = LSD->getParent();
13862   }
13863 
13864   while (isa<LinkageSpecDecl>(DC))
13865     DC = DC->getParent();
13866   if (!isa<TranslationUnitDecl>(DC)) {
13867     S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
13868       << M->getFullModuleName() << DC;
13869     S.Diag(cast<Decl>(DC)->getLocStart(),
13870            diag::note_module_import_not_at_top_level)
13871       << DC;
13872   }
13873 }
13874 
13875 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
13876                                    SourceLocation ImportLoc,
13877                                    ModuleIdPath Path) {
13878   Module *Mod =
13879       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
13880                                    /*IsIncludeDirective=*/false);
13881   if (!Mod)
13882     return true;
13883 
13884   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13885 
13886   // FIXME: we should support importing a submodule within a different submodule
13887   // of the same top-level module. Until we do, make it an error rather than
13888   // silently ignoring the import.
13889   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
13890     Diag(ImportLoc, diag::err_module_self_import)
13891         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
13892   else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
13893     Diag(ImportLoc, diag::err_module_import_in_implementation)
13894         << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
13895 
13896   SmallVector<SourceLocation, 2> IdentifierLocs;
13897   Module *ModCheck = Mod;
13898   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13899     // If we've run out of module parents, just drop the remaining identifiers.
13900     // We need the length to be consistent.
13901     if (!ModCheck)
13902       break;
13903     ModCheck = ModCheck->Parent;
13904 
13905     IdentifierLocs.push_back(Path[I].second);
13906   }
13907 
13908   ImportDecl *Import = ImportDecl::Create(Context,
13909                                           Context.getTranslationUnitDecl(),
13910                                           AtLoc.isValid()? AtLoc : ImportLoc,
13911                                           Mod, IdentifierLocs);
13912   Context.getTranslationUnitDecl()->addDecl(Import);
13913   return Import;
13914 }
13915 
13916 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
13917   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13918 
13919   // FIXME: Should we synthesize an ImportDecl here?
13920   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13921                                       /*Complain=*/true);
13922 }
13923 
13924 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
13925                                                       Module *Mod) {
13926   // Bail if we're not allowed to implicitly import a module here.
13927   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
13928     return;
13929 
13930   // Create the implicit import declaration.
13931   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13932   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13933                                                    Loc, Mod, Loc);
13934   TU->addDecl(ImportD);
13935   Consumer.HandleImplicitImportDecl(ImportD);
13936 
13937   // Make the module visible.
13938   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13939                                       /*Complain=*/false);
13940 }
13941 
13942 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13943                                       IdentifierInfo* AliasName,
13944                                       SourceLocation PragmaLoc,
13945                                       SourceLocation NameLoc,
13946                                       SourceLocation AliasNameLoc) {
13947   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13948                                     LookupOrdinaryName);
13949   AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13950                                                     AliasName->getName(), 0);
13951 
13952   if (PrevDecl)
13953     PrevDecl->addAttr(Attr);
13954   else
13955     (void)ExtnameUndeclaredIdentifiers.insert(
13956       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13957 }
13958 
13959 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13960                              SourceLocation PragmaLoc,
13961                              SourceLocation NameLoc) {
13962   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
13963 
13964   if (PrevDecl) {
13965     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
13966   } else {
13967     (void)WeakUndeclaredIdentifiers.insert(
13968       std::pair<IdentifierInfo*,WeakInfo>
13969         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
13970   }
13971 }
13972 
13973 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13974                                 IdentifierInfo* AliasName,
13975                                 SourceLocation PragmaLoc,
13976                                 SourceLocation NameLoc,
13977                                 SourceLocation AliasNameLoc) {
13978   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13979                                     LookupOrdinaryName);
13980   WeakInfo W = WeakInfo(Name, NameLoc);
13981 
13982   if (PrevDecl) {
13983     if (!PrevDecl->hasAttr<AliasAttr>())
13984       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
13985         DeclApplyPragmaWeak(TUScope, ND, W);
13986   } else {
13987     (void)WeakUndeclaredIdentifiers.insert(
13988       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
13989   }
13990 }
13991 
13992 Decl *Sema::getObjCDeclContext() const {
13993   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13994 }
13995 
13996 AvailabilityResult Sema::getCurContextAvailability() const {
13997   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
13998   if (!D)
13999     return AR_Available;
14000 
14001   // If we are within an Objective-C method, we should consult
14002   // both the availability of the method as well as the
14003   // enclosing class.  If the class is (say) deprecated,
14004   // the entire method is considered deprecated from the
14005   // purpose of checking if the current context is deprecated.
14006   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
14007     AvailabilityResult R = MD->getAvailability();
14008     if (R != AR_Available)
14009       return R;
14010     D = MD->getClassInterface();
14011   }
14012   // If we are within an Objective-c @implementation, it
14013   // gets the same availability context as the @interface.
14014   else if (const ObjCImplementationDecl *ID =
14015             dyn_cast<ObjCImplementationDecl>(D)) {
14016     D = ID->getClassInterface();
14017   }
14018   // Recover from user error.
14019   return D ? D->getAvailability() : AR_Available;
14020 }
14021