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(D.getName().getKind() != UnqualifiedId::IK_TemplateId &&
5582              "should have a 'template<>' for this decl");
5583     }
5584 
5585     if (IsVariableTemplateSpecialization) {
5586       SourceLocation TemplateKWLoc =
5587           TemplateParamLists.size() > 0
5588               ? TemplateParamLists[0]->getTemplateLoc()
5589               : SourceLocation();
5590       DeclResult Res = ActOnVarTemplateSpecialization(
5591           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5592           IsPartialSpecialization);
5593       if (Res.isInvalid())
5594         return nullptr;
5595       NewVD = cast<VarDecl>(Res.get());
5596       AddToScope = false;
5597     } else
5598       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5599                               D.getIdentifierLoc(), II, R, TInfo, SC);
5600 
5601     // If this is supposed to be a variable template, create it as such.
5602     if (IsVariableTemplate) {
5603       NewTemplate =
5604           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5605                                   TemplateParams, NewVD);
5606       NewVD->setDescribedVarTemplate(NewTemplate);
5607     }
5608 
5609     // If this decl has an auto type in need of deduction, make a note of the
5610     // Decl so we can diagnose uses of it in its own initializer.
5611     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5612       ParsingInitForAutoVars.insert(NewVD);
5613 
5614     if (D.isInvalidType() || Invalid) {
5615       NewVD->setInvalidDecl();
5616       if (NewTemplate)
5617         NewTemplate->setInvalidDecl();
5618     }
5619 
5620     SetNestedNameSpecifier(NewVD, D);
5621 
5622     // If we have any template parameter lists that don't directly belong to
5623     // the variable (matching the scope specifier), store them.
5624     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5625     if (TemplateParamLists.size() > VDTemplateParamLists)
5626       NewVD->setTemplateParameterListsInfo(
5627           Context, TemplateParamLists.size() - VDTemplateParamLists,
5628           TemplateParamLists.data());
5629 
5630     if (D.getDeclSpec().isConstexprSpecified())
5631       NewVD->setConstexpr(true);
5632   }
5633 
5634   // Set the lexical context. If the declarator has a C++ scope specifier, the
5635   // lexical context will be different from the semantic context.
5636   NewVD->setLexicalDeclContext(CurContext);
5637   if (NewTemplate)
5638     NewTemplate->setLexicalDeclContext(CurContext);
5639 
5640   if (IsLocalExternDecl)
5641     NewVD->setLocalExternDecl();
5642 
5643   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5644     // C++11 [dcl.stc]p4:
5645     //   When thread_local is applied to a variable of block scope the
5646     //   storage-class-specifier static is implied if it does not appear
5647     //   explicitly.
5648     // Core issue: 'static' is not implied if the variable is declared
5649     //   'extern'.
5650     if (NewVD->hasLocalStorage() &&
5651         (SCSpec != DeclSpec::SCS_unspecified ||
5652          TSCS != DeclSpec::TSCS_thread_local ||
5653          !DC->isFunctionOrMethod()))
5654       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5655            diag::err_thread_non_global)
5656         << DeclSpec::getSpecifierName(TSCS);
5657     else if (!Context.getTargetInfo().isTLSSupported())
5658       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5659            diag::err_thread_unsupported);
5660     else
5661       NewVD->setTSCSpec(TSCS);
5662   }
5663 
5664   // C99 6.7.4p3
5665   //   An inline definition of a function with external linkage shall
5666   //   not contain a definition of a modifiable object with static or
5667   //   thread storage duration...
5668   // We only apply this when the function is required to be defined
5669   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5670   // that a local variable with thread storage duration still has to
5671   // be marked 'static'.  Also note that it's possible to get these
5672   // semantics in C++ using __attribute__((gnu_inline)).
5673   if (SC == SC_Static && S->getFnParent() != nullptr &&
5674       !NewVD->getType().isConstQualified()) {
5675     FunctionDecl *CurFD = getCurFunctionDecl();
5676     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5677       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5678            diag::warn_static_local_in_extern_inline);
5679       MaybeSuggestAddingStaticToDecl(CurFD);
5680     }
5681   }
5682 
5683   if (D.getDeclSpec().isModulePrivateSpecified()) {
5684     if (IsVariableTemplateSpecialization)
5685       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5686           << (IsPartialSpecialization ? 1 : 0)
5687           << FixItHint::CreateRemoval(
5688                  D.getDeclSpec().getModulePrivateSpecLoc());
5689     else if (IsExplicitSpecialization)
5690       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5691         << 2
5692         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5693     else if (NewVD->hasLocalStorage())
5694       Diag(NewVD->getLocation(), diag::err_module_private_local)
5695         << 0 << NewVD->getDeclName()
5696         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5697         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5698     else {
5699       NewVD->setModulePrivate();
5700       if (NewTemplate)
5701         NewTemplate->setModulePrivate();
5702     }
5703   }
5704 
5705   // Handle attributes prior to checking for duplicates in MergeVarDecl
5706   ProcessDeclAttributes(S, NewVD, D);
5707 
5708   if (getLangOpts().CUDA) {
5709     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5710     // storage [duration]."
5711     if (SC == SC_None && S->getFnParent() != nullptr &&
5712         (NewVD->hasAttr<CUDASharedAttr>() ||
5713          NewVD->hasAttr<CUDAConstantAttr>())) {
5714       NewVD->setStorageClass(SC_Static);
5715     }
5716   }
5717 
5718   // Ensure that dllimport globals without explicit storage class are treated as
5719   // extern. The storage class is set above using parsed attributes. Now we can
5720   // check the VarDecl itself.
5721   assert(!NewVD->hasAttr<DLLImportAttr>() ||
5722          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5723          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5724 
5725   // In auto-retain/release, infer strong retension for variables of
5726   // retainable type.
5727   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5728     NewVD->setInvalidDecl();
5729 
5730   // Handle GNU asm-label extension (encoded as an attribute).
5731   if (Expr *E = (Expr*)D.getAsmLabel()) {
5732     // The parser guarantees this is a string.
5733     StringLiteral *SE = cast<StringLiteral>(E);
5734     StringRef Label = SE->getString();
5735     if (S->getFnParent() != nullptr) {
5736       switch (SC) {
5737       case SC_None:
5738       case SC_Auto:
5739         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5740         break;
5741       case SC_Register:
5742         // Local Named register
5743         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5744           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5745         break;
5746       case SC_Static:
5747       case SC_Extern:
5748       case SC_PrivateExtern:
5749       case SC_OpenCLWorkGroupLocal:
5750         break;
5751       }
5752     } else if (SC == SC_Register) {
5753       // Global Named register
5754       if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5755         Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5756       if (!R->isIntegralType(Context) && !R->isPointerType()) {
5757         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
5758         NewVD->setInvalidDecl(true);
5759       }
5760     }
5761 
5762     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
5763                                                 Context, Label, 0));
5764   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5765     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5766       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5767     if (I != ExtnameUndeclaredIdentifiers.end()) {
5768       NewVD->addAttr(I->second);
5769       ExtnameUndeclaredIdentifiers.erase(I);
5770     }
5771   }
5772 
5773   // Diagnose shadowed variables before filtering for scope.
5774   if (D.getCXXScopeSpec().isEmpty())
5775     CheckShadow(S, NewVD, Previous);
5776 
5777   // Don't consider existing declarations that are in a different
5778   // scope and are out-of-semantic-context declarations (if the new
5779   // declaration has linkage).
5780   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5781                        D.getCXXScopeSpec().isNotEmpty() ||
5782                        IsExplicitSpecialization ||
5783                        IsVariableTemplateSpecialization);
5784 
5785   // Check whether the previous declaration is in the same block scope. This
5786   // affects whether we merge types with it, per C++11 [dcl.array]p3.
5787   if (getLangOpts().CPlusPlus &&
5788       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5789     NewVD->setPreviousDeclInSameBlockScope(
5790         Previous.isSingleResult() && !Previous.isShadowed() &&
5791         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
5792 
5793   if (!getLangOpts().CPlusPlus) {
5794     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5795   } else {
5796     // If this is an explicit specialization of a static data member, check it.
5797     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5798         CheckMemberSpecialization(NewVD, Previous))
5799       NewVD->setInvalidDecl();
5800 
5801     // Merge the decl with the existing one if appropriate.
5802     if (!Previous.empty()) {
5803       if (Previous.isSingleResult() &&
5804           isa<FieldDecl>(Previous.getFoundDecl()) &&
5805           D.getCXXScopeSpec().isSet()) {
5806         // The user tried to define a non-static data member
5807         // out-of-line (C++ [dcl.meaning]p1).
5808         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5809           << D.getCXXScopeSpec().getRange();
5810         Previous.clear();
5811         NewVD->setInvalidDecl();
5812       }
5813     } else if (D.getCXXScopeSpec().isSet()) {
5814       // No previous declaration in the qualifying scope.
5815       Diag(D.getIdentifierLoc(), diag::err_no_member)
5816         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
5817         << D.getCXXScopeSpec().getRange();
5818       NewVD->setInvalidDecl();
5819     }
5820 
5821     if (!IsVariableTemplateSpecialization)
5822       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5823 
5824     if (NewTemplate) {
5825       VarTemplateDecl *PrevVarTemplate =
5826           NewVD->getPreviousDecl()
5827               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5828               : nullptr;
5829 
5830       // Check the template parameter list of this declaration, possibly
5831       // merging in the template parameter list from the previous variable
5832       // template declaration.
5833       if (CheckTemplateParameterList(
5834               TemplateParams,
5835               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5836                               : nullptr,
5837               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5838                DC->isDependentContext())
5839                   ? TPC_ClassTemplateMember
5840                   : TPC_VarTemplate))
5841         NewVD->setInvalidDecl();
5842 
5843       // If we are providing an explicit specialization of a static variable
5844       // template, make a note of that.
5845       if (PrevVarTemplate &&
5846           PrevVarTemplate->getInstantiatedFromMemberTemplate())
5847         PrevVarTemplate->setMemberSpecialization();
5848     }
5849   }
5850 
5851   ProcessPragmaWeak(S, NewVD);
5852 
5853   // If this is the first declaration of an extern C variable, update
5854   // the map of such variables.
5855   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
5856       isIncompleteDeclExternC(*this, NewVD))
5857     RegisterLocallyScopedExternCDecl(NewVD, S);
5858 
5859   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5860     Decl *ManglingContextDecl;
5861     if (MangleNumberingContext *MCtx =
5862             getCurrentMangleNumberContext(NewVD->getDeclContext(),
5863                                           ManglingContextDecl)) {
5864       Context.setManglingNumber(
5865           NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
5866       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5867     }
5868   }
5869 
5870   if (D.isRedeclaration() && !Previous.empty()) {
5871     checkDLLAttributeRedeclaration(
5872         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
5873         IsExplicitSpecialization);
5874   }
5875 
5876   if (NewTemplate) {
5877     if (NewVD->isInvalidDecl())
5878       NewTemplate->setInvalidDecl();
5879     ActOnDocumentableDecl(NewTemplate);
5880     return NewTemplate;
5881   }
5882 
5883   return NewVD;
5884 }
5885 
5886 /// \brief Diagnose variable or built-in function shadowing.  Implements
5887 /// -Wshadow.
5888 ///
5889 /// This method is called whenever a VarDecl is added to a "useful"
5890 /// scope.
5891 ///
5892 /// \param S the scope in which the shadowing name is being declared
5893 /// \param R the lookup of the name
5894 ///
5895 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
5896   // Return if warning is ignored.
5897   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
5898     return;
5899 
5900   // Don't diagnose declarations at file scope.
5901   if (D->hasGlobalStorage())
5902     return;
5903 
5904   DeclContext *NewDC = D->getDeclContext();
5905 
5906   // Only diagnose if we're shadowing an unambiguous field or variable.
5907   if (R.getResultKind() != LookupResult::Found)
5908     return;
5909 
5910   NamedDecl* ShadowedDecl = R.getFoundDecl();
5911   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5912     return;
5913 
5914   // Fields are not shadowed by variables in C++ static methods.
5915   if (isa<FieldDecl>(ShadowedDecl))
5916     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5917       if (MD->isStatic())
5918         return;
5919 
5920   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5921     if (shadowedVar->isExternC()) {
5922       // For shadowing external vars, make sure that we point to the global
5923       // declaration, not a locally scoped extern declaration.
5924       for (auto I : shadowedVar->redecls())
5925         if (I->isFileVarDecl()) {
5926           ShadowedDecl = I;
5927           break;
5928         }
5929     }
5930 
5931   DeclContext *OldDC = ShadowedDecl->getDeclContext();
5932 
5933   // Only warn about certain kinds of shadowing for class members.
5934   if (NewDC && NewDC->isRecord()) {
5935     // In particular, don't warn about shadowing non-class members.
5936     if (!OldDC->isRecord())
5937       return;
5938 
5939     // TODO: should we warn about static data members shadowing
5940     // static data members from base classes?
5941 
5942     // TODO: don't diagnose for inaccessible shadowed members.
5943     // This is hard to do perfectly because we might friend the
5944     // shadowing context, but that's just a false negative.
5945   }
5946 
5947   // Determine what kind of declaration we're shadowing.
5948   unsigned Kind;
5949   if (isa<RecordDecl>(OldDC)) {
5950     if (isa<FieldDecl>(ShadowedDecl))
5951       Kind = 3; // field
5952     else
5953       Kind = 2; // static data member
5954   } else if (OldDC->isFileContext())
5955     Kind = 1; // global
5956   else
5957     Kind = 0; // local
5958 
5959   DeclarationName Name = R.getLookupName();
5960 
5961   // Emit warning and note.
5962   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5963     return;
5964   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
5965   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5966 }
5967 
5968 /// \brief Check -Wshadow without the advantage of a previous lookup.
5969 void Sema::CheckShadow(Scope *S, VarDecl *D) {
5970   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
5971     return;
5972 
5973   LookupResult R(*this, D->getDeclName(), D->getLocation(),
5974                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5975   LookupName(R, S);
5976   CheckShadow(S, D, R);
5977 }
5978 
5979 /// Check for conflict between this global or extern "C" declaration and
5980 /// previous global or extern "C" declarations. This is only used in C++.
5981 template<typename T>
5982 static bool checkGlobalOrExternCConflict(
5983     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5984   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5985   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
5986 
5987   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5988     // The common case: this global doesn't conflict with any extern "C"
5989     // declaration.
5990     return false;
5991   }
5992 
5993   if (Prev) {
5994     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5995       // Both the old and new declarations have C language linkage. This is a
5996       // redeclaration.
5997       Previous.clear();
5998       Previous.addDecl(Prev);
5999       return true;
6000     }
6001 
6002     // This is a global, non-extern "C" declaration, and there is a previous
6003     // non-global extern "C" declaration. Diagnose if this is a variable
6004     // declaration.
6005     if (!isa<VarDecl>(ND))
6006       return false;
6007   } else {
6008     // The declaration is extern "C". Check for any declaration in the
6009     // translation unit which might conflict.
6010     if (IsGlobal) {
6011       // We have already performed the lookup into the translation unit.
6012       IsGlobal = false;
6013       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6014            I != E; ++I) {
6015         if (isa<VarDecl>(*I)) {
6016           Prev = *I;
6017           break;
6018         }
6019       }
6020     } else {
6021       DeclContext::lookup_result R =
6022           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6023       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6024            I != E; ++I) {
6025         if (isa<VarDecl>(*I)) {
6026           Prev = *I;
6027           break;
6028         }
6029         // FIXME: If we have any other entity with this name in global scope,
6030         // the declaration is ill-formed, but that is a defect: it breaks the
6031         // 'stat' hack, for instance. Only variables can have mangled name
6032         // clashes with extern "C" declarations, so only they deserve a
6033         // diagnostic.
6034       }
6035     }
6036 
6037     if (!Prev)
6038       return false;
6039   }
6040 
6041   // Use the first declaration's location to ensure we point at something which
6042   // is lexically inside an extern "C" linkage-spec.
6043   assert(Prev && "should have found a previous declaration to diagnose");
6044   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6045     Prev = FD->getFirstDecl();
6046   else
6047     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6048 
6049   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6050     << IsGlobal << ND;
6051   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6052     << IsGlobal;
6053   return false;
6054 }
6055 
6056 /// Apply special rules for handling extern "C" declarations. Returns \c true
6057 /// if we have found that this is a redeclaration of some prior entity.
6058 ///
6059 /// Per C++ [dcl.link]p6:
6060 ///   Two declarations [for a function or variable] with C language linkage
6061 ///   with the same name that appear in different scopes refer to the same
6062 ///   [entity]. An entity with C language linkage shall not be declared with
6063 ///   the same name as an entity in global scope.
6064 template<typename T>
6065 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6066                                                   LookupResult &Previous) {
6067   if (!S.getLangOpts().CPlusPlus) {
6068     // In C, when declaring a global variable, look for a corresponding 'extern'
6069     // variable declared in function scope. We don't need this in C++, because
6070     // we find local extern decls in the surrounding file-scope DeclContext.
6071     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6072       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6073         Previous.clear();
6074         Previous.addDecl(Prev);
6075         return true;
6076       }
6077     }
6078     return false;
6079   }
6080 
6081   // A declaration in the translation unit can conflict with an extern "C"
6082   // declaration.
6083   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6084     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6085 
6086   // An extern "C" declaration can conflict with a declaration in the
6087   // translation unit or can be a redeclaration of an extern "C" declaration
6088   // in another scope.
6089   if (isIncompleteDeclExternC(S,ND))
6090     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6091 
6092   // Neither global nor extern "C": nothing to do.
6093   return false;
6094 }
6095 
6096 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6097   // If the decl is already known invalid, don't check it.
6098   if (NewVD->isInvalidDecl())
6099     return;
6100 
6101   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6102   QualType T = TInfo->getType();
6103 
6104   // Defer checking an 'auto' type until its initializer is attached.
6105   if (T->isUndeducedType())
6106     return;
6107 
6108   if (NewVD->hasAttrs())
6109     CheckAlignasUnderalignment(NewVD);
6110 
6111   if (T->isObjCObjectType()) {
6112     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6113       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6114     T = Context.getObjCObjectPointerType(T);
6115     NewVD->setType(T);
6116   }
6117 
6118   // Emit an error if an address space was applied to decl with local storage.
6119   // This includes arrays of objects with address space qualifiers, but not
6120   // automatic variables that point to other address spaces.
6121   // ISO/IEC TR 18037 S5.1.2
6122   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6123     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6124     NewVD->setInvalidDecl();
6125     return;
6126   }
6127 
6128   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6129   // __constant address space.
6130   if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
6131       && T.getAddressSpace() != LangAS::opencl_constant
6132       && !T->isSamplerT()){
6133     Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
6134     NewVD->setInvalidDecl();
6135     return;
6136   }
6137 
6138   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6139   // scope.
6140   if ((getLangOpts().OpenCLVersion >= 120)
6141       && NewVD->isStaticLocal()) {
6142     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6143     NewVD->setInvalidDecl();
6144     return;
6145   }
6146 
6147   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6148       && !NewVD->hasAttr<BlocksAttr>()) {
6149     if (getLangOpts().getGC() != LangOptions::NonGC)
6150       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6151     else {
6152       assert(!getLangOpts().ObjCAutoRefCount);
6153       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6154     }
6155   }
6156 
6157   bool isVM = T->isVariablyModifiedType();
6158   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6159       NewVD->hasAttr<BlocksAttr>())
6160     getCurFunction()->setHasBranchProtectedScope();
6161 
6162   if ((isVM && NewVD->hasLinkage()) ||
6163       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6164     bool SizeIsNegative;
6165     llvm::APSInt Oversized;
6166     TypeSourceInfo *FixedTInfo =
6167       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6168                                                     SizeIsNegative, Oversized);
6169     if (!FixedTInfo && T->isVariableArrayType()) {
6170       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6171       // FIXME: This won't give the correct result for
6172       // int a[10][n];
6173       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6174 
6175       if (NewVD->isFileVarDecl())
6176         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6177         << SizeRange;
6178       else if (NewVD->isStaticLocal())
6179         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6180         << SizeRange;
6181       else
6182         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6183         << SizeRange;
6184       NewVD->setInvalidDecl();
6185       return;
6186     }
6187 
6188     if (!FixedTInfo) {
6189       if (NewVD->isFileVarDecl())
6190         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6191       else
6192         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6193       NewVD->setInvalidDecl();
6194       return;
6195     }
6196 
6197     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6198     NewVD->setType(FixedTInfo->getType());
6199     NewVD->setTypeSourceInfo(FixedTInfo);
6200   }
6201 
6202   if (T->isVoidType()) {
6203     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6204     //                    of objects and functions.
6205     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6206       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6207         << T;
6208       NewVD->setInvalidDecl();
6209       return;
6210     }
6211   }
6212 
6213   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6214     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6215     NewVD->setInvalidDecl();
6216     return;
6217   }
6218 
6219   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6220     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6221     NewVD->setInvalidDecl();
6222     return;
6223   }
6224 
6225   if (NewVD->isConstexpr() && !T->isDependentType() &&
6226       RequireLiteralType(NewVD->getLocation(), T,
6227                          diag::err_constexpr_var_non_literal)) {
6228     NewVD->setInvalidDecl();
6229     return;
6230   }
6231 }
6232 
6233 /// \brief Perform semantic checking on a newly-created variable
6234 /// declaration.
6235 ///
6236 /// This routine performs all of the type-checking required for a
6237 /// variable declaration once it has been built. It is used both to
6238 /// check variables after they have been parsed and their declarators
6239 /// have been translated into a declaration, and to check variables
6240 /// that have been instantiated from a template.
6241 ///
6242 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6243 ///
6244 /// Returns true if the variable declaration is a redeclaration.
6245 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6246   CheckVariableDeclarationType(NewVD);
6247 
6248   // If the decl is already known invalid, don't check it.
6249   if (NewVD->isInvalidDecl())
6250     return false;
6251 
6252   // If we did not find anything by this name, look for a non-visible
6253   // extern "C" declaration with the same name.
6254   if (Previous.empty() &&
6255       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6256     Previous.setShadowed();
6257 
6258   // Filter out any non-conflicting previous declarations.
6259   filterNonConflictingPreviousDecls(Context, NewVD, Previous);
6260 
6261   if (!Previous.empty()) {
6262     MergeVarDecl(NewVD, Previous);
6263     return true;
6264   }
6265   return false;
6266 }
6267 
6268 /// \brief Data used with FindOverriddenMethod
6269 struct FindOverriddenMethodData {
6270   Sema *S;
6271   CXXMethodDecl *Method;
6272 };
6273 
6274 /// \brief Member lookup function that determines whether a given C++
6275 /// method overrides a method in a base class, to be used with
6276 /// CXXRecordDecl::lookupInBases().
6277 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
6278                                  CXXBasePath &Path,
6279                                  void *UserData) {
6280   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6281 
6282   FindOverriddenMethodData *Data
6283     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
6284 
6285   DeclarationName Name = Data->Method->getDeclName();
6286 
6287   // FIXME: Do we care about other names here too?
6288   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6289     // We really want to find the base class destructor here.
6290     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
6291     CanQualType CT = Data->S->Context.getCanonicalType(T);
6292 
6293     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
6294   }
6295 
6296   for (Path.Decls = BaseRecord->lookup(Name);
6297        !Path.Decls.empty();
6298        Path.Decls = Path.Decls.slice(1)) {
6299     NamedDecl *D = Path.Decls.front();
6300     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6301       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
6302         return true;
6303     }
6304   }
6305 
6306   return false;
6307 }
6308 
6309 namespace {
6310   enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6311 }
6312 /// \brief Report an error regarding overriding, along with any relevant
6313 /// overriden methods.
6314 ///
6315 /// \param DiagID the primary error to report.
6316 /// \param MD the overriding method.
6317 /// \param OEK which overrides to include as notes.
6318 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6319                             OverrideErrorKind OEK = OEK_All) {
6320   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6321   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6322                                       E = MD->end_overridden_methods();
6323        I != E; ++I) {
6324     // This check (& the OEK parameter) could be replaced by a predicate, but
6325     // without lambdas that would be overkill. This is still nicer than writing
6326     // out the diag loop 3 times.
6327     if ((OEK == OEK_All) ||
6328         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6329         (OEK == OEK_Deleted && (*I)->isDeleted()))
6330       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6331   }
6332 }
6333 
6334 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6335 /// and if so, check that it's a valid override and remember it.
6336 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6337   // Look for methods in base classes that this method might override.
6338   CXXBasePaths Paths;
6339   FindOverriddenMethodData Data;
6340   Data.Method = MD;
6341   Data.S = this;
6342   bool hasDeletedOverridenMethods = false;
6343   bool hasNonDeletedOverridenMethods = false;
6344   bool AddedAny = false;
6345   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
6346     for (auto *I : Paths.found_decls()) {
6347       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6348         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6349         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6350             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6351             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6352             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6353           hasDeletedOverridenMethods |= OldMD->isDeleted();
6354           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6355           AddedAny = true;
6356         }
6357       }
6358     }
6359   }
6360 
6361   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6362     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6363   }
6364   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6365     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6366   }
6367 
6368   return AddedAny;
6369 }
6370 
6371 namespace {
6372   // Struct for holding all of the extra arguments needed by
6373   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6374   struct ActOnFDArgs {
6375     Scope *S;
6376     Declarator &D;
6377     MultiTemplateParamsArg TemplateParamLists;
6378     bool AddToScope;
6379   };
6380 }
6381 
6382 namespace {
6383 
6384 // Callback to only accept typo corrections that have a non-zero edit distance.
6385 // Also only accept corrections that have the same parent decl.
6386 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6387  public:
6388   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6389                             CXXRecordDecl *Parent)
6390       : Context(Context), OriginalFD(TypoFD),
6391         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6392 
6393   bool ValidateCandidate(const TypoCorrection &candidate) override {
6394     if (candidate.getEditDistance() == 0)
6395       return false;
6396 
6397     SmallVector<unsigned, 1> MismatchedParams;
6398     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6399                                           CDeclEnd = candidate.end();
6400          CDecl != CDeclEnd; ++CDecl) {
6401       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6402 
6403       if (FD && !FD->hasBody() &&
6404           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6405         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6406           CXXRecordDecl *Parent = MD->getParent();
6407           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6408             return true;
6409         } else if (!ExpectedParent) {
6410           return true;
6411         }
6412       }
6413     }
6414 
6415     return false;
6416   }
6417 
6418  private:
6419   ASTContext &Context;
6420   FunctionDecl *OriginalFD;
6421   CXXRecordDecl *ExpectedParent;
6422 };
6423 
6424 }
6425 
6426 /// \brief Generate diagnostics for an invalid function redeclaration.
6427 ///
6428 /// This routine handles generating the diagnostic messages for an invalid
6429 /// function redeclaration, including finding possible similar declarations
6430 /// or performing typo correction if there are no previous declarations with
6431 /// the same name.
6432 ///
6433 /// Returns a NamedDecl iff typo correction was performed and substituting in
6434 /// the new declaration name does not cause new errors.
6435 static NamedDecl *DiagnoseInvalidRedeclaration(
6436     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6437     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6438   DeclarationName Name = NewFD->getDeclName();
6439   DeclContext *NewDC = NewFD->getDeclContext();
6440   SmallVector<unsigned, 1> MismatchedParams;
6441   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6442   TypoCorrection Correction;
6443   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6444   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6445                                    : diag::err_member_decl_does_not_match;
6446   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6447                     IsLocalFriend ? Sema::LookupLocalFriendName
6448                                   : Sema::LookupOrdinaryName,
6449                     Sema::ForRedeclaration);
6450 
6451   NewFD->setInvalidDecl();
6452   if (IsLocalFriend)
6453     SemaRef.LookupName(Prev, S);
6454   else
6455     SemaRef.LookupQualifiedName(Prev, NewDC);
6456   assert(!Prev.isAmbiguous() &&
6457          "Cannot have an ambiguity in previous-declaration lookup");
6458   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6459   if (!Prev.empty()) {
6460     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6461          Func != FuncEnd; ++Func) {
6462       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6463       if (FD &&
6464           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6465         // Add 1 to the index so that 0 can mean the mismatch didn't
6466         // involve a parameter
6467         unsigned ParamNum =
6468             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6469         NearMatches.push_back(std::make_pair(FD, ParamNum));
6470       }
6471     }
6472   // If the qualified name lookup yielded nothing, try typo correction
6473   } else if ((Correction = SemaRef.CorrectTypo(
6474                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6475                   &ExtraArgs.D.getCXXScopeSpec(),
6476                   llvm::make_unique<DifferentNameValidatorCCC>(
6477                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6478                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6479     // Set up everything for the call to ActOnFunctionDeclarator
6480     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6481                               ExtraArgs.D.getIdentifierLoc());
6482     Previous.clear();
6483     Previous.setLookupName(Correction.getCorrection());
6484     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6485                                     CDeclEnd = Correction.end();
6486          CDecl != CDeclEnd; ++CDecl) {
6487       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6488       if (FD && !FD->hasBody() &&
6489           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6490         Previous.addDecl(FD);
6491       }
6492     }
6493     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6494 
6495     NamedDecl *Result;
6496     // Retry building the function declaration with the new previous
6497     // declarations, and with errors suppressed.
6498     {
6499       // Trap errors.
6500       Sema::SFINAETrap Trap(SemaRef);
6501 
6502       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6503       // pieces need to verify the typo-corrected C++ declaration and hopefully
6504       // eliminate the need for the parameter pack ExtraArgs.
6505       Result = SemaRef.ActOnFunctionDeclarator(
6506           ExtraArgs.S, ExtraArgs.D,
6507           Correction.getCorrectionDecl()->getDeclContext(),
6508           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6509           ExtraArgs.AddToScope);
6510 
6511       if (Trap.hasErrorOccurred())
6512         Result = nullptr;
6513     }
6514 
6515     if (Result) {
6516       // Determine which correction we picked.
6517       Decl *Canonical = Result->getCanonicalDecl();
6518       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6519            I != E; ++I)
6520         if ((*I)->getCanonicalDecl() == Canonical)
6521           Correction.setCorrectionDecl(*I);
6522 
6523       SemaRef.diagnoseTypo(
6524           Correction,
6525           SemaRef.PDiag(IsLocalFriend
6526                           ? diag::err_no_matching_local_friend_suggest
6527                           : diag::err_member_decl_does_not_match_suggest)
6528             << Name << NewDC << IsDefinition);
6529       return Result;
6530     }
6531 
6532     // Pretend the typo correction never occurred
6533     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6534                               ExtraArgs.D.getIdentifierLoc());
6535     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6536     Previous.clear();
6537     Previous.setLookupName(Name);
6538   }
6539 
6540   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6541       << Name << NewDC << IsDefinition << NewFD->getLocation();
6542 
6543   bool NewFDisConst = false;
6544   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6545     NewFDisConst = NewMD->isConst();
6546 
6547   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6548        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6549        NearMatch != NearMatchEnd; ++NearMatch) {
6550     FunctionDecl *FD = NearMatch->first;
6551     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6552     bool FDisConst = MD && MD->isConst();
6553     bool IsMember = MD || !IsLocalFriend;
6554 
6555     // FIXME: These notes are poorly worded for the local friend case.
6556     if (unsigned Idx = NearMatch->second) {
6557       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6558       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6559       if (Loc.isInvalid()) Loc = FD->getLocation();
6560       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6561                                  : diag::note_local_decl_close_param_match)
6562         << Idx << FDParam->getType()
6563         << NewFD->getParamDecl(Idx - 1)->getType();
6564     } else if (FDisConst != NewFDisConst) {
6565       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6566           << NewFDisConst << FD->getSourceRange().getEnd();
6567     } else
6568       SemaRef.Diag(FD->getLocation(),
6569                    IsMember ? diag::note_member_def_close_match
6570                             : diag::note_local_decl_close_match);
6571   }
6572   return nullptr;
6573 }
6574 
6575 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
6576   switch (D.getDeclSpec().getStorageClassSpec()) {
6577   default: llvm_unreachable("Unknown storage class!");
6578   case DeclSpec::SCS_auto:
6579   case DeclSpec::SCS_register:
6580   case DeclSpec::SCS_mutable:
6581     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6582                  diag::err_typecheck_sclass_func);
6583     D.setInvalidType();
6584     break;
6585   case DeclSpec::SCS_unspecified: break;
6586   case DeclSpec::SCS_extern:
6587     if (D.getDeclSpec().isExternInLinkageSpec())
6588       return SC_None;
6589     return SC_Extern;
6590   case DeclSpec::SCS_static: {
6591     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6592       // C99 6.7.1p5:
6593       //   The declaration of an identifier for a function that has
6594       //   block scope shall have no explicit storage-class specifier
6595       //   other than extern
6596       // See also (C++ [dcl.stc]p4).
6597       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6598                    diag::err_static_block_func);
6599       break;
6600     } else
6601       return SC_Static;
6602   }
6603   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6604   }
6605 
6606   // No explicit storage class has already been returned
6607   return SC_None;
6608 }
6609 
6610 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6611                                            DeclContext *DC, QualType &R,
6612                                            TypeSourceInfo *TInfo,
6613                                            StorageClass SC,
6614                                            bool &IsVirtualOkay) {
6615   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6616   DeclarationName Name = NameInfo.getName();
6617 
6618   FunctionDecl *NewFD = nullptr;
6619   bool isInline = D.getDeclSpec().isInlineSpecified();
6620 
6621   if (!SemaRef.getLangOpts().CPlusPlus) {
6622     // Determine whether the function was written with a
6623     // prototype. This true when:
6624     //   - there is a prototype in the declarator, or
6625     //   - the type R of the function is some kind of typedef or other reference
6626     //     to a type name (which eventually refers to a function type).
6627     bool HasPrototype =
6628       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6629       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6630 
6631     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6632                                  D.getLocStart(), NameInfo, R,
6633                                  TInfo, SC, isInline,
6634                                  HasPrototype, false);
6635     if (D.isInvalidType())
6636       NewFD->setInvalidDecl();
6637 
6638     return NewFD;
6639   }
6640 
6641   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6642   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6643 
6644   // Check that the return type is not an abstract class type.
6645   // For record types, this is done by the AbstractClassUsageDiagnoser once
6646   // the class has been completely parsed.
6647   if (!DC->isRecord() &&
6648       SemaRef.RequireNonAbstractType(
6649           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6650           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
6651     D.setInvalidType();
6652 
6653   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6654     // This is a C++ constructor declaration.
6655     assert(DC->isRecord() &&
6656            "Constructors can only be declared in a member context");
6657 
6658     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6659     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6660                                       D.getLocStart(), NameInfo,
6661                                       R, TInfo, isExplicit, isInline,
6662                                       /*isImplicitlyDeclared=*/false,
6663                                       isConstexpr);
6664 
6665   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6666     // This is a C++ destructor declaration.
6667     if (DC->isRecord()) {
6668       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6669       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6670       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6671                                         SemaRef.Context, Record,
6672                                         D.getLocStart(),
6673                                         NameInfo, R, TInfo, isInline,
6674                                         /*isImplicitlyDeclared=*/false);
6675 
6676       // If the class is complete, then we now create the implicit exception
6677       // specification. If the class is incomplete or dependent, we can't do
6678       // it yet.
6679       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6680           Record->getDefinition() && !Record->isBeingDefined() &&
6681           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6682         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6683       }
6684 
6685       IsVirtualOkay = true;
6686       return NewDD;
6687 
6688     } else {
6689       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6690       D.setInvalidType();
6691 
6692       // Create a FunctionDecl to satisfy the function definition parsing
6693       // code path.
6694       return FunctionDecl::Create(SemaRef.Context, DC,
6695                                   D.getLocStart(),
6696                                   D.getIdentifierLoc(), Name, R, TInfo,
6697                                   SC, isInline,
6698                                   /*hasPrototype=*/true, isConstexpr);
6699     }
6700 
6701   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6702     if (!DC->isRecord()) {
6703       SemaRef.Diag(D.getIdentifierLoc(),
6704            diag::err_conv_function_not_member);
6705       return nullptr;
6706     }
6707 
6708     SemaRef.CheckConversionDeclarator(D, R, SC);
6709     IsVirtualOkay = true;
6710     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6711                                      D.getLocStart(), NameInfo,
6712                                      R, TInfo, isInline, isExplicit,
6713                                      isConstexpr, SourceLocation());
6714 
6715   } else if (DC->isRecord()) {
6716     // If the name of the function is the same as the name of the record,
6717     // then this must be an invalid constructor that has a return type.
6718     // (The parser checks for a return type and makes the declarator a
6719     // constructor if it has no return type).
6720     if (Name.getAsIdentifierInfo() &&
6721         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6722       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6723         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6724         << SourceRange(D.getIdentifierLoc());
6725       return nullptr;
6726     }
6727 
6728     // This is a C++ method declaration.
6729     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6730                                                cast<CXXRecordDecl>(DC),
6731                                                D.getLocStart(), NameInfo, R,
6732                                                TInfo, SC, isInline,
6733                                                isConstexpr, SourceLocation());
6734     IsVirtualOkay = !Ret->isStatic();
6735     return Ret;
6736   } else {
6737     bool isFriend =
6738         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
6739     if (!isFriend && SemaRef.CurContext->isRecord())
6740       return nullptr;
6741 
6742     // Determine whether the function was written with a
6743     // prototype. This true when:
6744     //   - we're in C++ (where every function has a prototype),
6745     return FunctionDecl::Create(SemaRef.Context, DC,
6746                                 D.getLocStart(),
6747                                 NameInfo, R, TInfo, SC, isInline,
6748                                 true/*HasPrototype*/, isConstexpr);
6749   }
6750 }
6751 
6752 enum OpenCLParamType {
6753   ValidKernelParam,
6754   PtrPtrKernelParam,
6755   PtrKernelParam,
6756   PrivatePtrKernelParam,
6757   InvalidKernelParam,
6758   RecordKernelParam
6759 };
6760 
6761 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6762   if (PT->isPointerType()) {
6763     QualType PointeeType = PT->getPointeeType();
6764     if (PointeeType->isPointerType())
6765       return PtrPtrKernelParam;
6766     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
6767                                               : PtrKernelParam;
6768   }
6769 
6770   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6771   // be used as builtin types.
6772 
6773   if (PT->isImageType())
6774     return PtrKernelParam;
6775 
6776   if (PT->isBooleanType())
6777     return InvalidKernelParam;
6778 
6779   if (PT->isEventT())
6780     return InvalidKernelParam;
6781 
6782   if (PT->isHalfType())
6783     return InvalidKernelParam;
6784 
6785   if (PT->isRecordType())
6786     return RecordKernelParam;
6787 
6788   return ValidKernelParam;
6789 }
6790 
6791 static void checkIsValidOpenCLKernelParameter(
6792   Sema &S,
6793   Declarator &D,
6794   ParmVarDecl *Param,
6795   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
6796   QualType PT = Param->getType();
6797 
6798   // Cache the valid types we encounter to avoid rechecking structs that are
6799   // used again
6800   if (ValidTypes.count(PT.getTypePtr()))
6801     return;
6802 
6803   switch (getOpenCLKernelParameterType(PT)) {
6804   case PtrPtrKernelParam:
6805     // OpenCL v1.2 s6.9.a:
6806     // A kernel function argument cannot be declared as a
6807     // pointer to a pointer type.
6808     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6809     D.setInvalidType();
6810     return;
6811 
6812   case PrivatePtrKernelParam:
6813     // OpenCL v1.2 s6.9.a:
6814     // A kernel function argument cannot be declared as a
6815     // pointer to the private address space.
6816     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
6817     D.setInvalidType();
6818     return;
6819 
6820     // OpenCL v1.2 s6.9.k:
6821     // Arguments to kernel functions in a program cannot be declared with the
6822     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6823     // uintptr_t or a struct and/or union that contain fields declared to be
6824     // one of these built-in scalar types.
6825 
6826   case InvalidKernelParam:
6827     // OpenCL v1.2 s6.8 n:
6828     // A kernel function argument cannot be declared
6829     // of event_t type.
6830     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6831     D.setInvalidType();
6832     return;
6833 
6834   case PtrKernelParam:
6835   case ValidKernelParam:
6836     ValidTypes.insert(PT.getTypePtr());
6837     return;
6838 
6839   case RecordKernelParam:
6840     break;
6841   }
6842 
6843   // Track nested structs we will inspect
6844   SmallVector<const Decl *, 4> VisitStack;
6845 
6846   // Track where we are in the nested structs. Items will migrate from
6847   // VisitStack to HistoryStack as we do the DFS for bad field.
6848   SmallVector<const FieldDecl *, 4> HistoryStack;
6849   HistoryStack.push_back(nullptr);
6850 
6851   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6852   VisitStack.push_back(PD);
6853 
6854   assert(VisitStack.back() && "First decl null?");
6855 
6856   do {
6857     const Decl *Next = VisitStack.pop_back_val();
6858     if (!Next) {
6859       assert(!HistoryStack.empty());
6860       // Found a marker, we have gone up a level
6861       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6862         ValidTypes.insert(Hist->getType().getTypePtr());
6863 
6864       continue;
6865     }
6866 
6867     // Adds everything except the original parameter declaration (which is not a
6868     // field itself) to the history stack.
6869     const RecordDecl *RD;
6870     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6871       HistoryStack.push_back(Field);
6872       RD = Field->getType()->castAs<RecordType>()->getDecl();
6873     } else {
6874       RD = cast<RecordDecl>(Next);
6875     }
6876 
6877     // Add a null marker so we know when we've gone back up a level
6878     VisitStack.push_back(nullptr);
6879 
6880     for (const auto *FD : RD->fields()) {
6881       QualType QT = FD->getType();
6882 
6883       if (ValidTypes.count(QT.getTypePtr()))
6884         continue;
6885 
6886       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6887       if (ParamType == ValidKernelParam)
6888         continue;
6889 
6890       if (ParamType == RecordKernelParam) {
6891         VisitStack.push_back(FD);
6892         continue;
6893       }
6894 
6895       // OpenCL v1.2 s6.9.p:
6896       // Arguments to kernel functions that are declared to be a struct or union
6897       // do not allow OpenCL objects to be passed as elements of the struct or
6898       // union.
6899       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
6900           ParamType == PrivatePtrKernelParam) {
6901         S.Diag(Param->getLocation(),
6902                diag::err_record_with_pointers_kernel_param)
6903           << PT->isUnionType()
6904           << PT;
6905       } else {
6906         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6907       }
6908 
6909       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6910         << PD->getDeclName();
6911 
6912       // We have an error, now let's go back up through history and show where
6913       // the offending field came from
6914       for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6915              E = HistoryStack.end(); I != E; ++I) {
6916         const FieldDecl *OuterField = *I;
6917         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6918           << OuterField->getType();
6919       }
6920 
6921       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6922         << QT->isPointerType()
6923         << QT;
6924       D.setInvalidType();
6925       return;
6926     }
6927   } while (!VisitStack.empty());
6928 }
6929 
6930 NamedDecl*
6931 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
6932                               TypeSourceInfo *TInfo, LookupResult &Previous,
6933                               MultiTemplateParamsArg TemplateParamLists,
6934                               bool &AddToScope) {
6935   QualType R = TInfo->getType();
6936 
6937   assert(R.getTypePtr()->isFunctionType());
6938 
6939   // TODO: consider using NameInfo for diagnostic.
6940   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6941   DeclarationName Name = NameInfo.getName();
6942   StorageClass SC = getFunctionStorageClass(*this, D);
6943 
6944   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6945     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6946          diag::err_invalid_thread)
6947       << DeclSpec::getSpecifierName(TSCS);
6948 
6949   if (D.isFirstDeclarationOfMember())
6950     adjustMemberFunctionCC(R, D.isStaticMember());
6951 
6952   bool isFriend = false;
6953   FunctionTemplateDecl *FunctionTemplate = nullptr;
6954   bool isExplicitSpecialization = false;
6955   bool isFunctionTemplateSpecialization = false;
6956 
6957   bool isDependentClassScopeExplicitSpecialization = false;
6958   bool HasExplicitTemplateArgs = false;
6959   TemplateArgumentListInfo TemplateArgs;
6960 
6961   bool isVirtualOkay = false;
6962 
6963   DeclContext *OriginalDC = DC;
6964   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6965 
6966   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6967                                               isVirtualOkay);
6968   if (!NewFD) return nullptr;
6969 
6970   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6971     NewFD->setTopLevelDeclInObjCContainer();
6972 
6973   // Set the lexical context. If this is a function-scope declaration, or has a
6974   // C++ scope specifier, or is the object of a friend declaration, the lexical
6975   // context will be different from the semantic context.
6976   NewFD->setLexicalDeclContext(CurContext);
6977 
6978   if (IsLocalExternDecl)
6979     NewFD->setLocalExternDecl();
6980 
6981   if (getLangOpts().CPlusPlus) {
6982     bool isInline = D.getDeclSpec().isInlineSpecified();
6983     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6984     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6985     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6986     isFriend = D.getDeclSpec().isFriendSpecified();
6987     if (isFriend && !isInline && D.isFunctionDefinition()) {
6988       // C++ [class.friend]p5
6989       //   A function can be defined in a friend declaration of a
6990       //   class . . . . Such a function is implicitly inline.
6991       NewFD->setImplicitlyInline();
6992     }
6993 
6994     // If this is a method defined in an __interface, and is not a constructor
6995     // or an overloaded operator, then set the pure flag (isVirtual will already
6996     // return true).
6997     if (const CXXRecordDecl *Parent =
6998           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6999       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7000         NewFD->setPure(true);
7001     }
7002 
7003     SetNestedNameSpecifier(NewFD, D);
7004     isExplicitSpecialization = false;
7005     isFunctionTemplateSpecialization = false;
7006     if (D.isInvalidType())
7007       NewFD->setInvalidDecl();
7008 
7009     // Match up the template parameter lists with the scope specifier, then
7010     // determine whether we have a template or a template specialization.
7011     bool Invalid = false;
7012     if (TemplateParameterList *TemplateParams =
7013             MatchTemplateParametersToScopeSpecifier(
7014                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7015                 D.getCXXScopeSpec(),
7016                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7017                     ? D.getName().TemplateId
7018                     : nullptr,
7019                 TemplateParamLists, isFriend, isExplicitSpecialization,
7020                 Invalid)) {
7021       if (TemplateParams->size() > 0) {
7022         // This is a function template
7023 
7024         // Check that we can declare a template here.
7025         if (CheckTemplateDeclScope(S, TemplateParams))
7026           NewFD->setInvalidDecl();
7027 
7028         // A destructor cannot be a template.
7029         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7030           Diag(NewFD->getLocation(), diag::err_destructor_template);
7031           NewFD->setInvalidDecl();
7032         }
7033 
7034         // If we're adding a template to a dependent context, we may need to
7035         // rebuilding some of the types used within the template parameter list,
7036         // now that we know what the current instantiation is.
7037         if (DC->isDependentContext()) {
7038           ContextRAII SavedContext(*this, DC);
7039           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7040             Invalid = true;
7041         }
7042 
7043 
7044         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7045                                                         NewFD->getLocation(),
7046                                                         Name, TemplateParams,
7047                                                         NewFD);
7048         FunctionTemplate->setLexicalDeclContext(CurContext);
7049         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7050 
7051         // For source fidelity, store the other template param lists.
7052         if (TemplateParamLists.size() > 1) {
7053           NewFD->setTemplateParameterListsInfo(Context,
7054                                                TemplateParamLists.size() - 1,
7055                                                TemplateParamLists.data());
7056         }
7057       } else {
7058         // This is a function template specialization.
7059         isFunctionTemplateSpecialization = true;
7060         // For source fidelity, store all the template param lists.
7061         if (TemplateParamLists.size() > 0)
7062           NewFD->setTemplateParameterListsInfo(Context,
7063                                                TemplateParamLists.size(),
7064                                                TemplateParamLists.data());
7065 
7066         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7067         if (isFriend) {
7068           // We want to remove the "template<>", found here.
7069           SourceRange RemoveRange = TemplateParams->getSourceRange();
7070 
7071           // If we remove the template<> and the name is not a
7072           // template-id, we're actually silently creating a problem:
7073           // the friend declaration will refer to an untemplated decl,
7074           // and clearly the user wants a template specialization.  So
7075           // we need to insert '<>' after the name.
7076           SourceLocation InsertLoc;
7077           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7078             InsertLoc = D.getName().getSourceRange().getEnd();
7079             InsertLoc = getLocForEndOfToken(InsertLoc);
7080           }
7081 
7082           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7083             << Name << RemoveRange
7084             << FixItHint::CreateRemoval(RemoveRange)
7085             << FixItHint::CreateInsertion(InsertLoc, "<>");
7086         }
7087       }
7088     }
7089     else {
7090       // All template param lists were matched against the scope specifier:
7091       // this is NOT (an explicit specialization of) a template.
7092       if (TemplateParamLists.size() > 0)
7093         // For source fidelity, store all the template param lists.
7094         NewFD->setTemplateParameterListsInfo(Context,
7095                                              TemplateParamLists.size(),
7096                                              TemplateParamLists.data());
7097     }
7098 
7099     if (Invalid) {
7100       NewFD->setInvalidDecl();
7101       if (FunctionTemplate)
7102         FunctionTemplate->setInvalidDecl();
7103     }
7104 
7105     // C++ [dcl.fct.spec]p5:
7106     //   The virtual specifier shall only be used in declarations of
7107     //   nonstatic class member functions that appear within a
7108     //   member-specification of a class declaration; see 10.3.
7109     //
7110     if (isVirtual && !NewFD->isInvalidDecl()) {
7111       if (!isVirtualOkay) {
7112         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7113              diag::err_virtual_non_function);
7114       } else if (!CurContext->isRecord()) {
7115         // 'virtual' was specified outside of the class.
7116         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7117              diag::err_virtual_out_of_class)
7118           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7119       } else if (NewFD->getDescribedFunctionTemplate()) {
7120         // C++ [temp.mem]p3:
7121         //  A member function template shall not be virtual.
7122         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7123              diag::err_virtual_member_function_template)
7124           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7125       } else {
7126         // Okay: Add virtual to the method.
7127         NewFD->setVirtualAsWritten(true);
7128       }
7129 
7130       if (getLangOpts().CPlusPlus14 &&
7131           NewFD->getReturnType()->isUndeducedType())
7132         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7133     }
7134 
7135     if (getLangOpts().CPlusPlus14 &&
7136         (NewFD->isDependentContext() ||
7137          (isFriend && CurContext->isDependentContext())) &&
7138         NewFD->getReturnType()->isUndeducedType()) {
7139       // If the function template is referenced directly (for instance, as a
7140       // member of the current instantiation), pretend it has a dependent type.
7141       // This is not really justified by the standard, but is the only sane
7142       // thing to do.
7143       // FIXME: For a friend function, we have not marked the function as being
7144       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7145       const FunctionProtoType *FPT =
7146           NewFD->getType()->castAs<FunctionProtoType>();
7147       QualType Result =
7148           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7149       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7150                                              FPT->getExtProtoInfo()));
7151     }
7152 
7153     // C++ [dcl.fct.spec]p3:
7154     //  The inline specifier shall not appear on a block scope function
7155     //  declaration.
7156     if (isInline && !NewFD->isInvalidDecl()) {
7157       if (CurContext->isFunctionOrMethod()) {
7158         // 'inline' is not allowed on block scope function declaration.
7159         Diag(D.getDeclSpec().getInlineSpecLoc(),
7160              diag::err_inline_declaration_block_scope) << Name
7161           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7162       }
7163     }
7164 
7165     // C++ [dcl.fct.spec]p6:
7166     //  The explicit specifier shall be used only in the declaration of a
7167     //  constructor or conversion function within its class definition;
7168     //  see 12.3.1 and 12.3.2.
7169     if (isExplicit && !NewFD->isInvalidDecl()) {
7170       if (!CurContext->isRecord()) {
7171         // 'explicit' was specified outside of the class.
7172         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7173              diag::err_explicit_out_of_class)
7174           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7175       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7176                  !isa<CXXConversionDecl>(NewFD)) {
7177         // 'explicit' was specified on a function that wasn't a constructor
7178         // or conversion function.
7179         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7180              diag::err_explicit_non_ctor_or_conv_function)
7181           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7182       }
7183     }
7184 
7185     if (isConstexpr) {
7186       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7187       // are implicitly inline.
7188       NewFD->setImplicitlyInline();
7189 
7190       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7191       // be either constructors or to return a literal type. Therefore,
7192       // destructors cannot be declared constexpr.
7193       if (isa<CXXDestructorDecl>(NewFD))
7194         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7195     }
7196 
7197     // If __module_private__ was specified, mark the function accordingly.
7198     if (D.getDeclSpec().isModulePrivateSpecified()) {
7199       if (isFunctionTemplateSpecialization) {
7200         SourceLocation ModulePrivateLoc
7201           = D.getDeclSpec().getModulePrivateSpecLoc();
7202         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7203           << 0
7204           << FixItHint::CreateRemoval(ModulePrivateLoc);
7205       } else {
7206         NewFD->setModulePrivate();
7207         if (FunctionTemplate)
7208           FunctionTemplate->setModulePrivate();
7209       }
7210     }
7211 
7212     if (isFriend) {
7213       if (FunctionTemplate) {
7214         FunctionTemplate->setObjectOfFriendDecl();
7215         FunctionTemplate->setAccess(AS_public);
7216       }
7217       NewFD->setObjectOfFriendDecl();
7218       NewFD->setAccess(AS_public);
7219     }
7220 
7221     // If a function is defined as defaulted or deleted, mark it as such now.
7222     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7223     // definition kind to FDK_Definition.
7224     switch (D.getFunctionDefinitionKind()) {
7225       case FDK_Declaration:
7226       case FDK_Definition:
7227         break;
7228 
7229       case FDK_Defaulted:
7230         NewFD->setDefaulted();
7231         break;
7232 
7233       case FDK_Deleted:
7234         NewFD->setDeletedAsWritten();
7235         break;
7236     }
7237 
7238     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7239         D.isFunctionDefinition()) {
7240       // C++ [class.mfct]p2:
7241       //   A member function may be defined (8.4) in its class definition, in
7242       //   which case it is an inline member function (7.1.2)
7243       NewFD->setImplicitlyInline();
7244     }
7245 
7246     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7247         !CurContext->isRecord()) {
7248       // C++ [class.static]p1:
7249       //   A data or function member of a class may be declared static
7250       //   in a class definition, in which case it is a static member of
7251       //   the class.
7252 
7253       // Complain about the 'static' specifier if it's on an out-of-line
7254       // member function definition.
7255       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7256            diag::err_static_out_of_line)
7257         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7258     }
7259 
7260     // C++11 [except.spec]p15:
7261     //   A deallocation function with no exception-specification is treated
7262     //   as if it were specified with noexcept(true).
7263     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7264     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7265          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7266         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7267       NewFD->setType(Context.getFunctionType(
7268           FPT->getReturnType(), FPT->getParamTypes(),
7269           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7270   }
7271 
7272   // Filter out previous declarations that don't match the scope.
7273   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7274                        D.getCXXScopeSpec().isNotEmpty() ||
7275                        isExplicitSpecialization ||
7276                        isFunctionTemplateSpecialization);
7277 
7278   // Handle GNU asm-label extension (encoded as an attribute).
7279   if (Expr *E = (Expr*) D.getAsmLabel()) {
7280     // The parser guarantees this is a string.
7281     StringLiteral *SE = cast<StringLiteral>(E);
7282     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7283                                                 SE->getString(), 0));
7284   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7285     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7286       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7287     if (I != ExtnameUndeclaredIdentifiers.end()) {
7288       NewFD->addAttr(I->second);
7289       ExtnameUndeclaredIdentifiers.erase(I);
7290     }
7291   }
7292 
7293   // Copy the parameter declarations from the declarator D to the function
7294   // declaration NewFD, if they are available.  First scavenge them into Params.
7295   SmallVector<ParmVarDecl*, 16> Params;
7296   if (D.isFunctionDeclarator()) {
7297     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7298 
7299     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7300     // function that takes no arguments, not a function that takes a
7301     // single void argument.
7302     // We let through "const void" here because Sema::GetTypeForDeclarator
7303     // already checks for that case.
7304     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7305       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7306         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7307         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7308         Param->setDeclContext(NewFD);
7309         Params.push_back(Param);
7310 
7311         if (Param->isInvalidDecl())
7312           NewFD->setInvalidDecl();
7313       }
7314     }
7315 
7316   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7317     // When we're declaring a function with a typedef, typeof, etc as in the
7318     // following example, we'll need to synthesize (unnamed)
7319     // parameters for use in the declaration.
7320     //
7321     // @code
7322     // typedef void fn(int);
7323     // fn f;
7324     // @endcode
7325 
7326     // Synthesize a parameter for each argument type.
7327     for (const auto &AI : FT->param_types()) {
7328       ParmVarDecl *Param =
7329           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7330       Param->setScopeInfo(0, Params.size());
7331       Params.push_back(Param);
7332     }
7333   } else {
7334     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7335            "Should not need args for typedef of non-prototype fn");
7336   }
7337 
7338   // Finally, we know we have the right number of parameters, install them.
7339   NewFD->setParams(Params);
7340 
7341   // Find all anonymous symbols defined during the declaration of this function
7342   // and add to NewFD. This lets us track decls such 'enum Y' in:
7343   //
7344   //   void f(enum Y {AA} x) {}
7345   //
7346   // which would otherwise incorrectly end up in the translation unit scope.
7347   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7348   DeclsInPrototypeScope.clear();
7349 
7350   if (D.getDeclSpec().isNoreturnSpecified())
7351     NewFD->addAttr(
7352         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7353                                        Context, 0));
7354 
7355   // Functions returning a variably modified type violate C99 6.7.5.2p2
7356   // because all functions have linkage.
7357   if (!NewFD->isInvalidDecl() &&
7358       NewFD->getReturnType()->isVariablyModifiedType()) {
7359     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7360     NewFD->setInvalidDecl();
7361   }
7362 
7363   if (D.isFunctionDefinition() && CodeSegStack.CurrentValue &&
7364       !NewFD->hasAttr<SectionAttr>()) {
7365     NewFD->addAttr(
7366         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7367                                     CodeSegStack.CurrentValue->getString(),
7368                                     CodeSegStack.CurrentPragmaLocation));
7369     if (UnifySection(CodeSegStack.CurrentValue->getString(),
7370                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
7371                          ASTContext::PSF_Read,
7372                      NewFD))
7373       NewFD->dropAttr<SectionAttr>();
7374   }
7375 
7376   // Handle attributes.
7377   ProcessDeclAttributes(S, NewFD, D);
7378 
7379   QualType RetType = NewFD->getReturnType();
7380   const CXXRecordDecl *Ret = RetType->isRecordType() ?
7381       RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
7382   if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
7383       Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
7384     const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7385     // Attach WarnUnusedResult to functions returning types with that attribute.
7386     // Don't apply the attribute to that type's own non-static member functions
7387     // (to avoid warning on things like assignment operators)
7388     if (!MD || MD->getParent() != Ret)
7389       NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
7390   }
7391 
7392   if (getLangOpts().OpenCL) {
7393     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7394     // type declaration will generate a compilation error.
7395     unsigned AddressSpace = RetType.getAddressSpace();
7396     if (AddressSpace == LangAS::opencl_local ||
7397         AddressSpace == LangAS::opencl_global ||
7398         AddressSpace == LangAS::opencl_constant) {
7399       Diag(NewFD->getLocation(),
7400            diag::err_opencl_return_value_with_address_space);
7401       NewFD->setInvalidDecl();
7402     }
7403   }
7404 
7405   if (!getLangOpts().CPlusPlus) {
7406     // Perform semantic checking on the function declaration.
7407     bool isExplicitSpecialization=false;
7408     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7409       CheckMain(NewFD, D.getDeclSpec());
7410 
7411     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7412       CheckMSVCRTEntryPoint(NewFD);
7413 
7414     if (!NewFD->isInvalidDecl())
7415       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7416                                                   isExplicitSpecialization));
7417     else if (!Previous.empty())
7418       // Make graceful recovery from an invalid redeclaration.
7419       D.setRedeclaration(true);
7420     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7421             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7422            "previous declaration set still overloaded");
7423 
7424     // Diagnose no-prototype function declarations with calling conventions that
7425     // don't support variadic calls. Only do this in C and do it after merging
7426     // possibly prototyped redeclarations.
7427     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
7428     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
7429       CallingConv CC = FT->getExtInfo().getCC();
7430       if (!supportsVariadicCall(CC)) {
7431         // Windows system headers sometimes accidentally use stdcall without
7432         // (void) parameters, so we relax this to a warning.
7433         int DiagID =
7434             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
7435         Diag(NewFD->getLocation(), DiagID)
7436             << FunctionType::getNameForCallConv(CC);
7437       }
7438     }
7439   } else {
7440     // C++11 [replacement.functions]p3:
7441     //  The program's definitions shall not be specified as inline.
7442     //
7443     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7444     //
7445     // Suppress the diagnostic if the function is __attribute__((used)), since
7446     // that forces an external definition to be emitted.
7447     if (D.getDeclSpec().isInlineSpecified() &&
7448         NewFD->isReplaceableGlobalAllocationFunction() &&
7449         !NewFD->hasAttr<UsedAttr>())
7450       Diag(D.getDeclSpec().getInlineSpecLoc(),
7451            diag::ext_operator_new_delete_declared_inline)
7452         << NewFD->getDeclName();
7453 
7454     // If the declarator is a template-id, translate the parser's template
7455     // argument list into our AST format.
7456     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7457       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7458       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7459       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7460       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7461                                          TemplateId->NumArgs);
7462       translateTemplateArguments(TemplateArgsPtr,
7463                                  TemplateArgs);
7464 
7465       HasExplicitTemplateArgs = true;
7466 
7467       if (NewFD->isInvalidDecl()) {
7468         HasExplicitTemplateArgs = false;
7469       } else if (FunctionTemplate) {
7470         // Function template with explicit template arguments.
7471         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7472           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7473 
7474         HasExplicitTemplateArgs = false;
7475       } else {
7476         assert((isFunctionTemplateSpecialization ||
7477                 D.getDeclSpec().isFriendSpecified()) &&
7478                "should have a 'template<>' for this decl");
7479         // "friend void foo<>(int);" is an implicit specialization decl.
7480         isFunctionTemplateSpecialization = true;
7481       }
7482     } else if (isFriend && isFunctionTemplateSpecialization) {
7483       // This combination is only possible in a recovery case;  the user
7484       // wrote something like:
7485       //   template <> friend void foo(int);
7486       // which we're recovering from as if the user had written:
7487       //   friend void foo<>(int);
7488       // Go ahead and fake up a template id.
7489       HasExplicitTemplateArgs = true;
7490       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7491       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7492     }
7493 
7494     // If it's a friend (and only if it's a friend), it's possible
7495     // that either the specialized function type or the specialized
7496     // template is dependent, and therefore matching will fail.  In
7497     // this case, don't check the specialization yet.
7498     bool InstantiationDependent = false;
7499     if (isFunctionTemplateSpecialization && isFriend &&
7500         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7501          TemplateSpecializationType::anyDependentTemplateArguments(
7502             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7503             InstantiationDependent))) {
7504       assert(HasExplicitTemplateArgs &&
7505              "friend function specialization without template args");
7506       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7507                                                        Previous))
7508         NewFD->setInvalidDecl();
7509     } else if (isFunctionTemplateSpecialization) {
7510       if (CurContext->isDependentContext() && CurContext->isRecord()
7511           && !isFriend) {
7512         isDependentClassScopeExplicitSpecialization = true;
7513         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7514           diag::ext_function_specialization_in_class :
7515           diag::err_function_specialization_in_class)
7516           << NewFD->getDeclName();
7517       } else if (CheckFunctionTemplateSpecialization(NewFD,
7518                                   (HasExplicitTemplateArgs ? &TemplateArgs
7519                                                            : nullptr),
7520                                                      Previous))
7521         NewFD->setInvalidDecl();
7522 
7523       // C++ [dcl.stc]p1:
7524       //   A storage-class-specifier shall not be specified in an explicit
7525       //   specialization (14.7.3)
7526       FunctionTemplateSpecializationInfo *Info =
7527           NewFD->getTemplateSpecializationInfo();
7528       if (Info && SC != SC_None) {
7529         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7530           Diag(NewFD->getLocation(),
7531                diag::err_explicit_specialization_inconsistent_storage_class)
7532             << SC
7533             << FixItHint::CreateRemoval(
7534                                       D.getDeclSpec().getStorageClassSpecLoc());
7535 
7536         else
7537           Diag(NewFD->getLocation(),
7538                diag::ext_explicit_specialization_storage_class)
7539             << FixItHint::CreateRemoval(
7540                                       D.getDeclSpec().getStorageClassSpecLoc());
7541       }
7542 
7543     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7544       if (CheckMemberSpecialization(NewFD, Previous))
7545           NewFD->setInvalidDecl();
7546     }
7547 
7548     // Perform semantic checking on the function declaration.
7549     if (!isDependentClassScopeExplicitSpecialization) {
7550       if (!NewFD->isInvalidDecl() && NewFD->isMain())
7551         CheckMain(NewFD, D.getDeclSpec());
7552 
7553       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7554         CheckMSVCRTEntryPoint(NewFD);
7555 
7556       if (!NewFD->isInvalidDecl())
7557         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7558                                                     isExplicitSpecialization));
7559     }
7560 
7561     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7562             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7563            "previous declaration set still overloaded");
7564 
7565     NamedDecl *PrincipalDecl = (FunctionTemplate
7566                                 ? cast<NamedDecl>(FunctionTemplate)
7567                                 : NewFD);
7568 
7569     if (isFriend && D.isRedeclaration()) {
7570       AccessSpecifier Access = AS_public;
7571       if (!NewFD->isInvalidDecl())
7572         Access = NewFD->getPreviousDecl()->getAccess();
7573 
7574       NewFD->setAccess(Access);
7575       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7576     }
7577 
7578     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7579         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7580       PrincipalDecl->setNonMemberOperator();
7581 
7582     // If we have a function template, check the template parameter
7583     // list. This will check and merge default template arguments.
7584     if (FunctionTemplate) {
7585       FunctionTemplateDecl *PrevTemplate =
7586                                      FunctionTemplate->getPreviousDecl();
7587       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7588                        PrevTemplate ? PrevTemplate->getTemplateParameters()
7589                                     : nullptr,
7590                             D.getDeclSpec().isFriendSpecified()
7591                               ? (D.isFunctionDefinition()
7592                                    ? TPC_FriendFunctionTemplateDefinition
7593                                    : TPC_FriendFunctionTemplate)
7594                               : (D.getCXXScopeSpec().isSet() &&
7595                                  DC && DC->isRecord() &&
7596                                  DC->isDependentContext())
7597                                   ? TPC_ClassTemplateMember
7598                                   : TPC_FunctionTemplate);
7599     }
7600 
7601     if (NewFD->isInvalidDecl()) {
7602       // Ignore all the rest of this.
7603     } else if (!D.isRedeclaration()) {
7604       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7605                                        AddToScope };
7606       // Fake up an access specifier if it's supposed to be a class member.
7607       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7608         NewFD->setAccess(AS_public);
7609 
7610       // Qualified decls generally require a previous declaration.
7611       if (D.getCXXScopeSpec().isSet()) {
7612         // ...with the major exception of templated-scope or
7613         // dependent-scope friend declarations.
7614 
7615         // TODO: we currently also suppress this check in dependent
7616         // contexts because (1) the parameter depth will be off when
7617         // matching friend templates and (2) we might actually be
7618         // selecting a friend based on a dependent factor.  But there
7619         // are situations where these conditions don't apply and we
7620         // can actually do this check immediately.
7621         if (isFriend &&
7622             (TemplateParamLists.size() ||
7623              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7624              CurContext->isDependentContext())) {
7625           // ignore these
7626         } else {
7627           // The user tried to provide an out-of-line definition for a
7628           // function that is a member of a class or namespace, but there
7629           // was no such member function declared (C++ [class.mfct]p2,
7630           // C++ [namespace.memdef]p2). For example:
7631           //
7632           // class X {
7633           //   void f() const;
7634           // };
7635           //
7636           // void X::f() { } // ill-formed
7637           //
7638           // Complain about this problem, and attempt to suggest close
7639           // matches (e.g., those that differ only in cv-qualifiers and
7640           // whether the parameter types are references).
7641 
7642           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7643                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
7644             AddToScope = ExtraArgs.AddToScope;
7645             return Result;
7646           }
7647         }
7648 
7649         // Unqualified local friend declarations are required to resolve
7650         // to something.
7651       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7652         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7653                 *this, Previous, NewFD, ExtraArgs, true, S)) {
7654           AddToScope = ExtraArgs.AddToScope;
7655           return Result;
7656         }
7657       }
7658 
7659     } else if (!D.isFunctionDefinition() &&
7660                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
7661                !isFriend && !isFunctionTemplateSpecialization &&
7662                !isExplicitSpecialization) {
7663       // An out-of-line member function declaration must also be a
7664       // definition (C++ [class.mfct]p2).
7665       // Note that this is not the case for explicit specializations of
7666       // function templates or member functions of class templates, per
7667       // C++ [temp.expl.spec]p2. We also allow these declarations as an
7668       // extension for compatibility with old SWIG code which likes to
7669       // generate them.
7670       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7671         << D.getCXXScopeSpec().getRange();
7672     }
7673   }
7674 
7675   ProcessPragmaWeak(S, NewFD);
7676   checkAttributesAfterMerging(*this, *NewFD);
7677 
7678   AddKnownFunctionAttributes(NewFD);
7679 
7680   if (NewFD->hasAttr<OverloadableAttr>() &&
7681       !NewFD->getType()->getAs<FunctionProtoType>()) {
7682     Diag(NewFD->getLocation(),
7683          diag::err_attribute_overloadable_no_prototype)
7684       << NewFD;
7685 
7686     // Turn this into a variadic function with no parameters.
7687     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7688     FunctionProtoType::ExtProtoInfo EPI(
7689         Context.getDefaultCallingConvention(true, false));
7690     EPI.Variadic = true;
7691     EPI.ExtInfo = FT->getExtInfo();
7692 
7693     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
7694     NewFD->setType(R);
7695   }
7696 
7697   // If there's a #pragma GCC visibility in scope, and this isn't a class
7698   // member, set the visibility of this function.
7699   if (!DC->isRecord() && NewFD->isExternallyVisible())
7700     AddPushedVisibilityAttribute(NewFD);
7701 
7702   // If there's a #pragma clang arc_cf_code_audited in scope, consider
7703   // marking the function.
7704   AddCFAuditedAttribute(NewFD);
7705 
7706   // If this is a function definition, check if we have to apply optnone due to
7707   // a pragma.
7708   if(D.isFunctionDefinition())
7709     AddRangeBasedOptnone(NewFD);
7710 
7711   // If this is the first declaration of an extern C variable, update
7712   // the map of such variables.
7713   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7714       isIncompleteDeclExternC(*this, NewFD))
7715     RegisterLocallyScopedExternCDecl(NewFD, S);
7716 
7717   // Set this FunctionDecl's range up to the right paren.
7718   NewFD->setRangeEnd(D.getSourceRange().getEnd());
7719 
7720   if (D.isRedeclaration() && !Previous.empty()) {
7721     checkDLLAttributeRedeclaration(
7722         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
7723         isExplicitSpecialization || isFunctionTemplateSpecialization);
7724   }
7725 
7726   if (getLangOpts().CPlusPlus) {
7727     if (FunctionTemplate) {
7728       if (NewFD->isInvalidDecl())
7729         FunctionTemplate->setInvalidDecl();
7730       return FunctionTemplate;
7731     }
7732   }
7733 
7734   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7735     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7736     if ((getLangOpts().OpenCLVersion >= 120)
7737         && (SC == SC_Static)) {
7738       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7739       D.setInvalidType();
7740     }
7741 
7742     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7743     if (!NewFD->getReturnType()->isVoidType()) {
7744       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
7745       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
7746           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
7747                                 : FixItHint());
7748       D.setInvalidType();
7749     }
7750 
7751     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
7752     for (auto Param : NewFD->params())
7753       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
7754   }
7755 
7756   MarkUnusedFileScopedDecl(NewFD);
7757 
7758   if (getLangOpts().CUDA)
7759     if (IdentifierInfo *II = NewFD->getIdentifier())
7760       if (!NewFD->isInvalidDecl() &&
7761           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7762         if (II->isStr("cudaConfigureCall")) {
7763           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
7764             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7765 
7766           Context.setcudaConfigureCallDecl(NewFD);
7767         }
7768       }
7769 
7770   // Here we have an function template explicit specialization at class scope.
7771   // The actually specialization will be postponed to template instatiation
7772   // time via the ClassScopeFunctionSpecializationDecl node.
7773   if (isDependentClassScopeExplicitSpecialization) {
7774     ClassScopeFunctionSpecializationDecl *NewSpec =
7775                          ClassScopeFunctionSpecializationDecl::Create(
7776                                 Context, CurContext, SourceLocation(),
7777                                 cast<CXXMethodDecl>(NewFD),
7778                                 HasExplicitTemplateArgs, TemplateArgs);
7779     CurContext->addDecl(NewSpec);
7780     AddToScope = false;
7781   }
7782 
7783   return NewFD;
7784 }
7785 
7786 /// \brief Perform semantic checking of a new function declaration.
7787 ///
7788 /// Performs semantic analysis of the new function declaration
7789 /// NewFD. This routine performs all semantic checking that does not
7790 /// require the actual declarator involved in the declaration, and is
7791 /// used both for the declaration of functions as they are parsed
7792 /// (called via ActOnDeclarator) and for the declaration of functions
7793 /// that have been instantiated via C++ template instantiation (called
7794 /// via InstantiateDecl).
7795 ///
7796 /// \param IsExplicitSpecialization whether this new function declaration is
7797 /// an explicit specialization of the previous declaration.
7798 ///
7799 /// This sets NewFD->isInvalidDecl() to true if there was an error.
7800 ///
7801 /// \returns true if the function declaration is a redeclaration.
7802 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
7803                                     LookupResult &Previous,
7804                                     bool IsExplicitSpecialization) {
7805   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7806          "Variably modified return types are not handled here");
7807 
7808   // Determine whether the type of this function should be merged with
7809   // a previous visible declaration. This never happens for functions in C++,
7810   // and always happens in C if the previous declaration was visible.
7811   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7812                                !Previous.isShadowed();
7813 
7814   // Filter out any non-conflicting previous declarations.
7815   filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7816 
7817   bool Redeclaration = false;
7818   NamedDecl *OldDecl = nullptr;
7819 
7820   // Merge or overload the declaration with an existing declaration of
7821   // the same name, if appropriate.
7822   if (!Previous.empty()) {
7823     // Determine whether NewFD is an overload of PrevDecl or
7824     // a declaration that requires merging. If it's an overload,
7825     // there's no more work to do here; we'll just add the new
7826     // function to the scope.
7827     if (!AllowOverloadingOfFunction(Previous, Context)) {
7828       NamedDecl *Candidate = Previous.getFoundDecl();
7829       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7830         Redeclaration = true;
7831         OldDecl = Candidate;
7832       }
7833     } else {
7834       switch (CheckOverload(S, NewFD, Previous, OldDecl,
7835                             /*NewIsUsingDecl*/ false)) {
7836       case Ovl_Match:
7837         Redeclaration = true;
7838         break;
7839 
7840       case Ovl_NonFunction:
7841         Redeclaration = true;
7842         break;
7843 
7844       case Ovl_Overload:
7845         Redeclaration = false;
7846         break;
7847       }
7848 
7849       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7850         // If a function name is overloadable in C, then every function
7851         // with that name must be marked "overloadable".
7852         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7853           << Redeclaration << NewFD;
7854         NamedDecl *OverloadedDecl = nullptr;
7855         if (Redeclaration)
7856           OverloadedDecl = OldDecl;
7857         else if (!Previous.empty())
7858           OverloadedDecl = Previous.getRepresentativeDecl();
7859         if (OverloadedDecl)
7860           Diag(OverloadedDecl->getLocation(),
7861                diag::note_attribute_overloadable_prev_overload);
7862         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7863       }
7864     }
7865   }
7866 
7867   // Check for a previous extern "C" declaration with this name.
7868   if (!Redeclaration &&
7869       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7870     filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7871     if (!Previous.empty()) {
7872       // This is an extern "C" declaration with the same name as a previous
7873       // declaration, and thus redeclares that entity...
7874       Redeclaration = true;
7875       OldDecl = Previous.getFoundDecl();
7876       MergeTypeWithPrevious = false;
7877 
7878       // ... except in the presence of __attribute__((overloadable)).
7879       if (OldDecl->hasAttr<OverloadableAttr>()) {
7880         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7881           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7882             << Redeclaration << NewFD;
7883           Diag(Previous.getFoundDecl()->getLocation(),
7884                diag::note_attribute_overloadable_prev_overload);
7885           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7886         }
7887         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7888           Redeclaration = false;
7889           OldDecl = nullptr;
7890         }
7891       }
7892     }
7893   }
7894 
7895   // C++11 [dcl.constexpr]p8:
7896   //   A constexpr specifier for a non-static member function that is not
7897   //   a constructor declares that member function to be const.
7898   //
7899   // This needs to be delayed until we know whether this is an out-of-line
7900   // definition of a static member function.
7901   //
7902   // This rule is not present in C++1y, so we produce a backwards
7903   // compatibility warning whenever it happens in C++11.
7904   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7905   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
7906       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
7907       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7908     CXXMethodDecl *OldMD = nullptr;
7909     if (OldDecl)
7910       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
7911     if (!OldMD || !OldMD->isStatic()) {
7912       const FunctionProtoType *FPT =
7913         MD->getType()->castAs<FunctionProtoType>();
7914       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7915       EPI.TypeQuals |= Qualifiers::Const;
7916       MD->setType(Context.getFunctionType(FPT->getReturnType(),
7917                                           FPT->getParamTypes(), EPI));
7918 
7919       // Warn that we did this, if we're not performing template instantiation.
7920       // In that case, we'll have warned already when the template was defined.
7921       if (ActiveTemplateInstantiations.empty()) {
7922         SourceLocation AddConstLoc;
7923         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7924                 .IgnoreParens().getAs<FunctionTypeLoc>())
7925           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
7926 
7927         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
7928           << FixItHint::CreateInsertion(AddConstLoc, " const");
7929       }
7930     }
7931   }
7932 
7933   if (Redeclaration) {
7934     // NewFD and OldDecl represent declarations that need to be
7935     // merged.
7936     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
7937       NewFD->setInvalidDecl();
7938       return Redeclaration;
7939     }
7940 
7941     Previous.clear();
7942     Previous.addDecl(OldDecl);
7943 
7944     if (FunctionTemplateDecl *OldTemplateDecl
7945                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7946       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7947       FunctionTemplateDecl *NewTemplateDecl
7948         = NewFD->getDescribedFunctionTemplate();
7949       assert(NewTemplateDecl && "Template/non-template mismatch");
7950       if (CXXMethodDecl *Method
7951             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7952         Method->setAccess(OldTemplateDecl->getAccess());
7953         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
7954       }
7955 
7956       // If this is an explicit specialization of a member that is a function
7957       // template, mark it as a member specialization.
7958       if (IsExplicitSpecialization &&
7959           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7960         NewTemplateDecl->setMemberSpecialization();
7961         assert(OldTemplateDecl->isMemberSpecialization());
7962       }
7963 
7964     } else {
7965       // This needs to happen first so that 'inline' propagates.
7966       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
7967 
7968       if (isa<CXXMethodDecl>(NewFD)) {
7969         // A valid redeclaration of a C++ method must be out-of-line,
7970         // but (unfortunately) it's not necessarily a definition
7971         // because of templates, which means that the previous
7972         // declaration is not necessarily from the class definition.
7973 
7974         // For just setting the access, that doesn't matter.
7975         CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7976         NewFD->setAccess(oldMethod->getAccess());
7977 
7978         // Update the key-function state if necessary for this ABI.
7979         if (NewFD->isInlined() &&
7980             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7981           // setNonKeyFunction needs to work with the original
7982           // declaration from the class definition, and isVirtual() is
7983           // just faster in that case, so map back to that now.
7984           oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
7985           if (oldMethod->isVirtual()) {
7986             Context.setNonKeyFunction(oldMethod);
7987           }
7988         }
7989       }
7990     }
7991   }
7992 
7993   // Semantic checking for this function declaration (in isolation).
7994 
7995   if (getLangOpts().CPlusPlus) {
7996     // C++-specific checks.
7997     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7998       CheckConstructor(Constructor);
7999     } else if (CXXDestructorDecl *Destructor =
8000                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8001       CXXRecordDecl *Record = Destructor->getParent();
8002       QualType ClassType = Context.getTypeDeclType(Record);
8003 
8004       // FIXME: Shouldn't we be able to perform this check even when the class
8005       // type is dependent? Both gcc and edg can handle that.
8006       if (!ClassType->isDependentType()) {
8007         DeclarationName Name
8008           = Context.DeclarationNames.getCXXDestructorName(
8009                                         Context.getCanonicalType(ClassType));
8010         if (NewFD->getDeclName() != Name) {
8011           Diag(NewFD->getLocation(), diag::err_destructor_name);
8012           NewFD->setInvalidDecl();
8013           return Redeclaration;
8014         }
8015       }
8016     } else if (CXXConversionDecl *Conversion
8017                = dyn_cast<CXXConversionDecl>(NewFD)) {
8018       ActOnConversionDeclarator(Conversion);
8019     }
8020 
8021     // Find any virtual functions that this function overrides.
8022     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8023       if (!Method->isFunctionTemplateSpecialization() &&
8024           !Method->getDescribedFunctionTemplate() &&
8025           Method->isCanonicalDecl()) {
8026         if (AddOverriddenMethods(Method->getParent(), Method)) {
8027           // If the function was marked as "static", we have a problem.
8028           if (NewFD->getStorageClass() == SC_Static) {
8029             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8030           }
8031         }
8032       }
8033 
8034       if (Method->isStatic())
8035         checkThisInStaticMemberFunctionType(Method);
8036     }
8037 
8038     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8039     if (NewFD->isOverloadedOperator() &&
8040         CheckOverloadedOperatorDeclaration(NewFD)) {
8041       NewFD->setInvalidDecl();
8042       return Redeclaration;
8043     }
8044 
8045     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8046     if (NewFD->getLiteralIdentifier() &&
8047         CheckLiteralOperatorDeclaration(NewFD)) {
8048       NewFD->setInvalidDecl();
8049       return Redeclaration;
8050     }
8051 
8052     // In C++, check default arguments now that we have merged decls. Unless
8053     // the lexical context is the class, because in this case this is done
8054     // during delayed parsing anyway.
8055     if (!CurContext->isRecord())
8056       CheckCXXDefaultArguments(NewFD);
8057 
8058     // If this function declares a builtin function, check the type of this
8059     // declaration against the expected type for the builtin.
8060     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8061       ASTContext::GetBuiltinTypeError Error;
8062       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8063       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8064       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8065         // The type of this function differs from the type of the builtin,
8066         // so forget about the builtin entirely.
8067         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
8068       }
8069     }
8070 
8071     // If this function is declared as being extern "C", then check to see if
8072     // the function returns a UDT (class, struct, or union type) that is not C
8073     // compatible, and if it does, warn the user.
8074     // But, issue any diagnostic on the first declaration only.
8075     if (Previous.empty() && NewFD->isExternC()) {
8076       QualType R = NewFD->getReturnType();
8077       if (R->isIncompleteType() && !R->isVoidType())
8078         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8079             << NewFD << R;
8080       else if (!R.isPODType(Context) && !R->isVoidType() &&
8081                !R->isObjCObjectPointerType())
8082         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8083     }
8084   }
8085   return Redeclaration;
8086 }
8087 
8088 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8089   // C++11 [basic.start.main]p3:
8090   //   A program that [...] declares main to be inline, static or
8091   //   constexpr is ill-formed.
8092   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8093   //   appear in a declaration of main.
8094   // static main is not an error under C99, but we should warn about it.
8095   // We accept _Noreturn main as an extension.
8096   if (FD->getStorageClass() == SC_Static)
8097     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8098          ? diag::err_static_main : diag::warn_static_main)
8099       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8100   if (FD->isInlineSpecified())
8101     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8102       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8103   if (DS.isNoreturnSpecified()) {
8104     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8105     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8106     Diag(NoreturnLoc, diag::ext_noreturn_main);
8107     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8108       << FixItHint::CreateRemoval(NoreturnRange);
8109   }
8110   if (FD->isConstexpr()) {
8111     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8112       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8113     FD->setConstexpr(false);
8114   }
8115 
8116   if (getLangOpts().OpenCL) {
8117     Diag(FD->getLocation(), diag::err_opencl_no_main)
8118         << FD->hasAttr<OpenCLKernelAttr>();
8119     FD->setInvalidDecl();
8120     return;
8121   }
8122 
8123   QualType T = FD->getType();
8124   assert(T->isFunctionType() && "function decl is not of function type");
8125   const FunctionType* FT = T->castAs<FunctionType>();
8126 
8127   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8128     // In C with GNU extensions we allow main() to have non-integer return
8129     // type, but we should warn about the extension, and we disable the
8130     // implicit-return-zero rule.
8131 
8132     // GCC in C mode accepts qualified 'int'.
8133     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8134       FD->setHasImplicitReturnZero(true);
8135     else {
8136       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8137       SourceRange RTRange = FD->getReturnTypeSourceRange();
8138       if (RTRange.isValid())
8139         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8140             << FixItHint::CreateReplacement(RTRange, "int");
8141     }
8142   } else {
8143     // In C and C++, main magically returns 0 if you fall off the end;
8144     // set the flag which tells us that.
8145     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8146 
8147     // All the standards say that main() should return 'int'.
8148     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8149       FD->setHasImplicitReturnZero(true);
8150     else {
8151       // Otherwise, this is just a flat-out error.
8152       SourceRange RTRange = FD->getReturnTypeSourceRange();
8153       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8154           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8155                                 : FixItHint());
8156       FD->setInvalidDecl(true);
8157     }
8158   }
8159 
8160   // Treat protoless main() as nullary.
8161   if (isa<FunctionNoProtoType>(FT)) return;
8162 
8163   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8164   unsigned nparams = FTP->getNumParams();
8165   assert(FD->getNumParams() == nparams);
8166 
8167   bool HasExtraParameters = (nparams > 3);
8168 
8169   // Darwin passes an undocumented fourth argument of type char**.  If
8170   // other platforms start sprouting these, the logic below will start
8171   // getting shifty.
8172   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8173     HasExtraParameters = false;
8174 
8175   if (HasExtraParameters) {
8176     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8177     FD->setInvalidDecl(true);
8178     nparams = 3;
8179   }
8180 
8181   // FIXME: a lot of the following diagnostics would be improved
8182   // if we had some location information about types.
8183 
8184   QualType CharPP =
8185     Context.getPointerType(Context.getPointerType(Context.CharTy));
8186   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8187 
8188   for (unsigned i = 0; i < nparams; ++i) {
8189     QualType AT = FTP->getParamType(i);
8190 
8191     bool mismatch = true;
8192 
8193     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8194       mismatch = false;
8195     else if (Expected[i] == CharPP) {
8196       // As an extension, the following forms are okay:
8197       //   char const **
8198       //   char const * const *
8199       //   char * const *
8200 
8201       QualifierCollector qs;
8202       const PointerType* PT;
8203       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8204           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8205           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8206                               Context.CharTy)) {
8207         qs.removeConst();
8208         mismatch = !qs.empty();
8209       }
8210     }
8211 
8212     if (mismatch) {
8213       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8214       // TODO: suggest replacing given type with expected type
8215       FD->setInvalidDecl(true);
8216     }
8217   }
8218 
8219   if (nparams == 1 && !FD->isInvalidDecl()) {
8220     Diag(FD->getLocation(), diag::warn_main_one_arg);
8221   }
8222 
8223   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8224     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8225     FD->setInvalidDecl();
8226   }
8227 }
8228 
8229 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8230   QualType T = FD->getType();
8231   assert(T->isFunctionType() && "function decl is not of function type");
8232   const FunctionType *FT = T->castAs<FunctionType>();
8233 
8234   // Set an implicit return of 'zero' if the function can return some integral,
8235   // enumeration, pointer or nullptr type.
8236   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8237       FT->getReturnType()->isAnyPointerType() ||
8238       FT->getReturnType()->isNullPtrType())
8239     // DllMain is exempt because a return value of zero means it failed.
8240     if (FD->getName() != "DllMain")
8241       FD->setHasImplicitReturnZero(true);
8242 
8243   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8244     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8245     FD->setInvalidDecl();
8246   }
8247 }
8248 
8249 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8250   // FIXME: Need strict checking.  In C89, we need to check for
8251   // any assignment, increment, decrement, function-calls, or
8252   // commas outside of a sizeof.  In C99, it's the same list,
8253   // except that the aforementioned are allowed in unevaluated
8254   // expressions.  Everything else falls under the
8255   // "may accept other forms of constant expressions" exception.
8256   // (We never end up here for C++, so the constant expression
8257   // rules there don't matter.)
8258   const Expr *Culprit;
8259   if (Init->isConstantInitializer(Context, false, &Culprit))
8260     return false;
8261   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8262     << Culprit->getSourceRange();
8263   return true;
8264 }
8265 
8266 namespace {
8267   // Visits an initialization expression to see if OrigDecl is evaluated in
8268   // its own initialization and throws a warning if it does.
8269   class SelfReferenceChecker
8270       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8271     Sema &S;
8272     Decl *OrigDecl;
8273     bool isRecordType;
8274     bool isPODType;
8275     bool isReferenceType;
8276 
8277     bool isInitList;
8278     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8279   public:
8280     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8281 
8282     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8283                                                     S(S), OrigDecl(OrigDecl) {
8284       isPODType = false;
8285       isRecordType = false;
8286       isReferenceType = false;
8287       isInitList = false;
8288       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8289         isPODType = VD->getType().isPODType(S.Context);
8290         isRecordType = VD->getType()->isRecordType();
8291         isReferenceType = VD->getType()->isReferenceType();
8292       }
8293     }
8294 
8295     // For most expressions, just call the visitor.  For initializer lists,
8296     // track the index of the field being initialized since fields are
8297     // initialized in order allowing use of previously initialized fields.
8298     void CheckExpr(Expr *E) {
8299       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8300       if (!InitList) {
8301         Visit(E);
8302         return;
8303       }
8304 
8305       // Track and increment the index here.
8306       isInitList = true;
8307       InitFieldIndex.push_back(0);
8308       for (auto Child : InitList->children()) {
8309         CheckExpr(cast<Expr>(Child));
8310         ++InitFieldIndex.back();
8311       }
8312       InitFieldIndex.pop_back();
8313     }
8314 
8315     // Returns true if MemberExpr is checked and no futher checking is needed.
8316     // Returns false if additional checking is required.
8317     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8318       llvm::SmallVector<FieldDecl*, 4> Fields;
8319       Expr *Base = E;
8320       bool ReferenceField = false;
8321 
8322       // Get the field memebers used.
8323       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8324         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8325         if (!FD)
8326           return false;
8327         Fields.push_back(FD);
8328         if (FD->getType()->isReferenceType())
8329           ReferenceField = true;
8330         Base = ME->getBase()->IgnoreParenImpCasts();
8331       }
8332 
8333       // Keep checking only if the base Decl is the same.
8334       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8335       if (!DRE || DRE->getDecl() != OrigDecl)
8336         return false;
8337 
8338       // A reference field can be bound to an unininitialized field.
8339       if (CheckReference && !ReferenceField)
8340         return true;
8341 
8342       // Convert FieldDecls to their index number.
8343       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8344       for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) {
8345         UsedFieldIndex.push_back((*I)->getFieldIndex());
8346       }
8347 
8348       // See if a warning is needed by checking the first difference in index
8349       // numbers.  If field being used has index less than the field being
8350       // initialized, then the use is safe.
8351       for (auto UsedIter = UsedFieldIndex.begin(),
8352                 UsedEnd = UsedFieldIndex.end(),
8353                 OrigIter = InitFieldIndex.begin(),
8354                 OrigEnd = InitFieldIndex.end();
8355            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8356         if (*UsedIter < *OrigIter)
8357           return true;
8358         if (*UsedIter > *OrigIter)
8359           break;
8360       }
8361 
8362       // TODO: Add a different warning which will print the field names.
8363       HandleDeclRefExpr(DRE);
8364       return true;
8365     }
8366 
8367     // For most expressions, the cast is directly above the DeclRefExpr.
8368     // For conditional operators, the cast can be outside the conditional
8369     // operator if both expressions are DeclRefExpr's.
8370     void HandleValue(Expr *E) {
8371       E = E->IgnoreParens();
8372       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8373         HandleDeclRefExpr(DRE);
8374         return;
8375       }
8376 
8377       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8378         Visit(CO->getCond());
8379         HandleValue(CO->getTrueExpr());
8380         HandleValue(CO->getFalseExpr());
8381         return;
8382       }
8383 
8384       if (BinaryConditionalOperator *BCO =
8385               dyn_cast<BinaryConditionalOperator>(E)) {
8386         Visit(BCO->getCond());
8387         HandleValue(BCO->getFalseExpr());
8388         return;
8389       }
8390 
8391       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8392         HandleValue(OVE->getSourceExpr());
8393         return;
8394       }
8395 
8396       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8397         if (BO->getOpcode() == BO_Comma) {
8398           Visit(BO->getLHS());
8399           HandleValue(BO->getRHS());
8400           return;
8401         }
8402       }
8403 
8404       if (isa<MemberExpr>(E)) {
8405         if (isInitList) {
8406           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8407                                       false /*CheckReference*/))
8408             return;
8409         }
8410 
8411         Expr *Base = E->IgnoreParenImpCasts();
8412         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8413           // Check for static member variables and don't warn on them.
8414           if (!isa<FieldDecl>(ME->getMemberDecl()))
8415             return;
8416           Base = ME->getBase()->IgnoreParenImpCasts();
8417         }
8418         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8419           HandleDeclRefExpr(DRE);
8420         return;
8421       }
8422 
8423       Visit(E);
8424     }
8425 
8426     // Reference types not handled in HandleValue are handled here since all
8427     // uses of references are bad, not just r-value uses.
8428     void VisitDeclRefExpr(DeclRefExpr *E) {
8429       if (isReferenceType)
8430         HandleDeclRefExpr(E);
8431     }
8432 
8433     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8434       if (E->getCastKind() == CK_LValueToRValue) {
8435         HandleValue(E->getSubExpr());
8436         return;
8437       }
8438 
8439       Inherited::VisitImplicitCastExpr(E);
8440     }
8441 
8442     void VisitMemberExpr(MemberExpr *E) {
8443       if (isInitList) {
8444         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8445           return;
8446       }
8447 
8448       // Don't warn on arrays since they can be treated as pointers.
8449       if (E->getType()->canDecayToPointerType()) return;
8450 
8451       // Warn when a non-static method call is followed by non-static member
8452       // field accesses, which is followed by a DeclRefExpr.
8453       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8454       bool Warn = (MD && !MD->isStatic());
8455       Expr *Base = E->getBase()->IgnoreParenImpCasts();
8456       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8457         if (!isa<FieldDecl>(ME->getMemberDecl()))
8458           Warn = false;
8459         Base = ME->getBase()->IgnoreParenImpCasts();
8460       }
8461 
8462       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8463         if (Warn)
8464           HandleDeclRefExpr(DRE);
8465         return;
8466       }
8467 
8468       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8469       // Visit that expression.
8470       Visit(Base);
8471     }
8472 
8473     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8474       Expr *Callee = E->getCallee();
8475 
8476       if (isa<UnresolvedLookupExpr>(Callee))
8477         return Inherited::VisitCXXOperatorCallExpr(E);
8478 
8479       Visit(Callee);
8480       for (auto Arg: E->arguments())
8481         HandleValue(Arg->IgnoreParenImpCasts());
8482     }
8483 
8484     void VisitUnaryOperator(UnaryOperator *E) {
8485       // For POD record types, addresses of its own members are well-defined.
8486       if (E->getOpcode() == UO_AddrOf && isRecordType &&
8487           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8488         if (!isPODType)
8489           HandleValue(E->getSubExpr());
8490         return;
8491       }
8492 
8493       if (E->isIncrementDecrementOp()) {
8494         HandleValue(E->getSubExpr());
8495         return;
8496       }
8497 
8498       Inherited::VisitUnaryOperator(E);
8499     }
8500 
8501     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8502 
8503     void VisitCXXConstructExpr(CXXConstructExpr *E) {
8504       if (E->getConstructor()->isCopyConstructor()) {
8505         Expr *ArgExpr = E->getArg(0);
8506         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
8507           if (ILE->getNumInits() == 1)
8508             ArgExpr = ILE->getInit(0);
8509         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8510           if (ICE->getCastKind() == CK_NoOp)
8511             ArgExpr = ICE->getSubExpr();
8512         HandleValue(ArgExpr);
8513         return;
8514       }
8515       Inherited::VisitCXXConstructExpr(E);
8516     }
8517 
8518     void VisitCallExpr(CallExpr *E) {
8519       // Treat std::move as a use.
8520       if (E->getNumArgs() == 1) {
8521         if (FunctionDecl *FD = E->getDirectCallee()) {
8522           if (FD->isInStdNamespace() && FD->getIdentifier() &&
8523               FD->getIdentifier()->isStr("move")) {
8524             HandleValue(E->getArg(0));
8525             return;
8526           }
8527         }
8528       }
8529 
8530       Inherited::VisitCallExpr(E);
8531     }
8532 
8533     void VisitBinaryOperator(BinaryOperator *E) {
8534       if (E->isCompoundAssignmentOp()) {
8535         HandleValue(E->getLHS());
8536         Visit(E->getRHS());
8537         return;
8538       }
8539 
8540       Inherited::VisitBinaryOperator(E);
8541     }
8542 
8543     // A custom visitor for BinaryConditionalOperator is needed because the
8544     // regular visitor would check the condition and true expression separately
8545     // but both point to the same place giving duplicate diagnostics.
8546     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
8547       Visit(E->getCond());
8548       Visit(E->getFalseExpr());
8549     }
8550 
8551     void HandleDeclRefExpr(DeclRefExpr *DRE) {
8552       Decl* ReferenceDecl = DRE->getDecl();
8553       if (OrigDecl != ReferenceDecl) return;
8554       unsigned diag;
8555       if (isReferenceType) {
8556         diag = diag::warn_uninit_self_reference_in_reference_init;
8557       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8558         diag = diag::warn_static_self_reference_in_init;
8559       } else {
8560         diag = diag::warn_uninit_self_reference_in_init;
8561       }
8562 
8563       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
8564                             S.PDiag(diag)
8565                               << DRE->getNameInfo().getName()
8566                               << OrigDecl->getLocation()
8567                               << DRE->getSourceRange());
8568     }
8569   };
8570 
8571   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8572   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8573                                  bool DirectInit) {
8574     // Parameters arguments are occassionially constructed with itself,
8575     // for instance, in recursive functions.  Skip them.
8576     if (isa<ParmVarDecl>(OrigDecl))
8577       return;
8578 
8579     E = E->IgnoreParens();
8580 
8581     // Skip checking T a = a where T is not a record or reference type.
8582     // Doing so is a way to silence uninitialized warnings.
8583     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8584       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8585         if (ICE->getCastKind() == CK_LValueToRValue)
8586           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8587             if (DRE->getDecl() == OrigDecl)
8588               return;
8589 
8590     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
8591   }
8592 }
8593 
8594 /// AddInitializerToDecl - Adds the initializer Init to the
8595 /// declaration dcl. If DirectInit is true, this is C++ direct
8596 /// initialization rather than copy initialization.
8597 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8598                                 bool DirectInit, bool TypeMayContainAuto) {
8599   // If there is no declaration, there was an error parsing it.  Just ignore
8600   // the initializer.
8601   if (!RealDecl || RealDecl->isInvalidDecl()) {
8602     CorrectDelayedTyposInExpr(Init);
8603     return;
8604   }
8605 
8606   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8607     // With declarators parsed the way they are, the parser cannot
8608     // distinguish between a normal initializer and a pure-specifier.
8609     // Thus this grotesque test.
8610     IntegerLiteral *IL;
8611     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
8612         Context.getCanonicalType(IL->getType()) == Context.IntTy)
8613       CheckPureMethod(Method, Init->getSourceRange());
8614     else {
8615       Diag(Method->getLocation(), diag::err_member_function_initialization)
8616         << Method->getDeclName() << Init->getSourceRange();
8617       Method->setInvalidDecl();
8618     }
8619     return;
8620   }
8621 
8622   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8623   if (!VDecl) {
8624     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8625     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8626     RealDecl->setInvalidDecl();
8627     return;
8628   }
8629   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8630 
8631   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8632   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8633     Expr *DeduceInit = Init;
8634     // Initializer could be a C++ direct-initializer. Deduction only works if it
8635     // contains exactly one expression.
8636     if (CXXDirectInit) {
8637       if (CXXDirectInit->getNumExprs() == 0) {
8638         // It isn't possible to write this directly, but it is possible to
8639         // end up in this situation with "auto x(some_pack...);"
8640         Diag(CXXDirectInit->getLocStart(),
8641              VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8642                                     : diag::err_auto_var_init_no_expression)
8643           << VDecl->getDeclName() << VDecl->getType()
8644           << VDecl->getSourceRange();
8645         RealDecl->setInvalidDecl();
8646         return;
8647       } else if (CXXDirectInit->getNumExprs() > 1) {
8648         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8649              VDecl->isInitCapture()
8650                  ? diag::err_init_capture_multiple_expressions
8651                  : diag::err_auto_var_init_multiple_expressions)
8652           << VDecl->getDeclName() << VDecl->getType()
8653           << VDecl->getSourceRange();
8654         RealDecl->setInvalidDecl();
8655         return;
8656       } else {
8657         DeduceInit = CXXDirectInit->getExpr(0);
8658         if (isa<InitListExpr>(DeduceInit))
8659           Diag(CXXDirectInit->getLocStart(),
8660                diag::err_auto_var_init_paren_braces)
8661             << VDecl->getDeclName() << VDecl->getType()
8662             << VDecl->getSourceRange();
8663       }
8664     }
8665 
8666     // Expressions default to 'id' when we're in a debugger.
8667     bool DefaultedToAuto = false;
8668     if (getLangOpts().DebuggerCastResultToId &&
8669         Init->getType() == Context.UnknownAnyTy) {
8670       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8671       if (Result.isInvalid()) {
8672         VDecl->setInvalidDecl();
8673         return;
8674       }
8675       Init = Result.get();
8676       DefaultedToAuto = true;
8677     }
8678 
8679     QualType DeducedType;
8680     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8681             DAR_Failed)
8682       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8683     if (DeducedType.isNull()) {
8684       RealDecl->setInvalidDecl();
8685       return;
8686     }
8687     VDecl->setType(DeducedType);
8688     assert(VDecl->isLinkageValid());
8689 
8690     // In ARC, infer lifetime.
8691     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8692       VDecl->setInvalidDecl();
8693 
8694     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8695     // 'id' instead of a specific object type prevents most of our usual checks.
8696     // We only want to warn outside of template instantiations, though:
8697     // inside a template, the 'id' could have come from a parameter.
8698     if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8699         DeducedType->isObjCIdType()) {
8700       SourceLocation Loc =
8701           VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8702       Diag(Loc, diag::warn_auto_var_is_id)
8703         << VDecl->getDeclName() << DeduceInit->getSourceRange();
8704     }
8705 
8706     // If this is a redeclaration, check that the type we just deduced matches
8707     // the previously declared type.
8708     if (VarDecl *Old = VDecl->getPreviousDecl()) {
8709       // We never need to merge the type, because we cannot form an incomplete
8710       // array of auto, nor deduce such a type.
8711       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8712     }
8713 
8714     // Check the deduced type is valid for a variable declaration.
8715     CheckVariableDeclarationType(VDecl);
8716     if (VDecl->isInvalidDecl())
8717       return;
8718   }
8719 
8720   // dllimport cannot be used on variable definitions.
8721   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8722     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8723     VDecl->setInvalidDecl();
8724     return;
8725   }
8726 
8727   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8728     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8729     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8730     VDecl->setInvalidDecl();
8731     return;
8732   }
8733 
8734   if (!VDecl->getType()->isDependentType()) {
8735     // A definition must end up with a complete type, which means it must be
8736     // complete with the restriction that an array type might be completed by
8737     // the initializer; note that later code assumes this restriction.
8738     QualType BaseDeclType = VDecl->getType();
8739     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8740       BaseDeclType = Array->getElementType();
8741     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8742                             diag::err_typecheck_decl_incomplete_type)) {
8743       RealDecl->setInvalidDecl();
8744       return;
8745     }
8746 
8747     // The variable can not have an abstract class type.
8748     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8749                                diag::err_abstract_type_in_decl,
8750                                AbstractVariableType))
8751       VDecl->setInvalidDecl();
8752   }
8753 
8754   const VarDecl *Def;
8755   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8756     Diag(VDecl->getLocation(), diag::err_redefinition)
8757       << VDecl->getDeclName();
8758     Diag(Def->getLocation(), diag::note_previous_definition);
8759     VDecl->setInvalidDecl();
8760     return;
8761   }
8762 
8763   const VarDecl *PrevInit = nullptr;
8764   if (getLangOpts().CPlusPlus) {
8765     // C++ [class.static.data]p4
8766     //   If a static data member is of const integral or const
8767     //   enumeration type, its declaration in the class definition can
8768     //   specify a constant-initializer which shall be an integral
8769     //   constant expression (5.19). In that case, the member can appear
8770     //   in integral constant expressions. The member shall still be
8771     //   defined in a namespace scope if it is used in the program and the
8772     //   namespace scope definition shall not contain an initializer.
8773     //
8774     // We already performed a redefinition check above, but for static
8775     // data members we also need to check whether there was an in-class
8776     // declaration with an initializer.
8777     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8778       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8779           << VDecl->getDeclName();
8780       Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
8781       return;
8782     }
8783 
8784     if (VDecl->hasLocalStorage())
8785       getCurFunction()->setHasBranchProtectedScope();
8786 
8787     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8788       VDecl->setInvalidDecl();
8789       return;
8790     }
8791   }
8792 
8793   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8794   // a kernel function cannot be initialized."
8795   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8796     Diag(VDecl->getLocation(), diag::err_local_cant_init);
8797     VDecl->setInvalidDecl();
8798     return;
8799   }
8800 
8801   // Get the decls type and save a reference for later, since
8802   // CheckInitializerTypes may change it.
8803   QualType DclT = VDecl->getType(), SavT = DclT;
8804 
8805   // Expressions default to 'id' when we're in a debugger
8806   // and we are assigning it to a variable of Objective-C pointer type.
8807   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8808       Init->getType() == Context.UnknownAnyTy) {
8809     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8810     if (Result.isInvalid()) {
8811       VDecl->setInvalidDecl();
8812       return;
8813     }
8814     Init = Result.get();
8815   }
8816 
8817   // Perform the initialization.
8818   if (!VDecl->isInvalidDecl()) {
8819     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8820     InitializationKind Kind
8821       = DirectInit ?
8822           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8823                                                            Init->getLocStart(),
8824                                                            Init->getLocEnd())
8825                         : InitializationKind::CreateDirectList(
8826                                                           VDecl->getLocation())
8827                    : InitializationKind::CreateCopy(VDecl->getLocation(),
8828                                                     Init->getLocStart());
8829 
8830     MultiExprArg Args = Init;
8831     if (CXXDirectInit)
8832       Args = MultiExprArg(CXXDirectInit->getExprs(),
8833                           CXXDirectInit->getNumExprs());
8834 
8835     // Try to correct any TypoExprs in the initialization arguments.
8836     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
8837       ExprResult Res =
8838           CorrectDelayedTyposInExpr(Args[Idx], [this, Entity, Kind](Expr *E) {
8839             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
8840             return Init.Failed() ? ExprError() : E;
8841           });
8842       if (Res.isInvalid()) {
8843         VDecl->setInvalidDecl();
8844       } else if (Res.get() != Args[Idx]) {
8845         Args[Idx] = Res.get();
8846       }
8847     }
8848     if (VDecl->isInvalidDecl())
8849       return;
8850 
8851     InitializationSequence InitSeq(*this, Entity, Kind, Args);
8852     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8853     if (Result.isInvalid()) {
8854       VDecl->setInvalidDecl();
8855       return;
8856     }
8857 
8858     Init = Result.getAs<Expr>();
8859   }
8860 
8861   // Check for self-references within variable initializers.
8862   // Variables declared within a function/method body (except for references)
8863   // are handled by a dataflow analysis.
8864   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8865       VDecl->getType()->isReferenceType()) {
8866     CheckSelfReference(*this, RealDecl, Init, DirectInit);
8867   }
8868 
8869   // If the type changed, it means we had an incomplete type that was
8870   // completed by the initializer. For example:
8871   //   int ary[] = { 1, 3, 5 };
8872   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
8873   if (!VDecl->isInvalidDecl() && (DclT != SavT))
8874     VDecl->setType(DclT);
8875 
8876   if (!VDecl->isInvalidDecl()) {
8877     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8878 
8879     if (VDecl->hasAttr<BlocksAttr>())
8880       checkRetainCycles(VDecl, Init);
8881 
8882     // It is safe to assign a weak reference into a strong variable.
8883     // Although this code can still have problems:
8884     //   id x = self.weakProp;
8885     //   id y = self.weakProp;
8886     // we do not warn to warn spuriously when 'x' and 'y' are on separate
8887     // paths through the function. This should be revisited if
8888     // -Wrepeated-use-of-weak is made flow-sensitive.
8889     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
8890         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8891                          Init->getLocStart()))
8892         getCurFunction()->markSafeWeakUse(Init);
8893   }
8894 
8895   // The initialization is usually a full-expression.
8896   //
8897   // FIXME: If this is a braced initialization of an aggregate, it is not
8898   // an expression, and each individual field initializer is a separate
8899   // full-expression. For instance, in:
8900   //
8901   //   struct Temp { ~Temp(); };
8902   //   struct S { S(Temp); };
8903   //   struct T { S a, b; } t = { Temp(), Temp() }
8904   //
8905   // we should destroy the first Temp before constructing the second.
8906   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8907                                           false,
8908                                           VDecl->isConstexpr());
8909   if (Result.isInvalid()) {
8910     VDecl->setInvalidDecl();
8911     return;
8912   }
8913   Init = Result.get();
8914 
8915   // Attach the initializer to the decl.
8916   VDecl->setInit(Init);
8917 
8918   if (VDecl->isLocalVarDecl()) {
8919     // C99 6.7.8p4: All the expressions in an initializer for an object that has
8920     // static storage duration shall be constant expressions or string literals.
8921     // C++ does not have this restriction.
8922     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8923       const Expr *Culprit;
8924       if (VDecl->getStorageClass() == SC_Static)
8925         CheckForConstantInitializer(Init, DclT);
8926       // C89 is stricter than C99 for non-static aggregate types.
8927       // C89 6.5.7p3: All the expressions [...] in an initializer list
8928       // for an object that has aggregate or union type shall be
8929       // constant expressions.
8930       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
8931                isa<InitListExpr>(Init) &&
8932                !Init->isConstantInitializer(Context, false, &Culprit))
8933         Diag(Culprit->getExprLoc(),
8934              diag::ext_aggregate_init_not_constant)
8935           << Culprit->getSourceRange();
8936     }
8937   } else if (VDecl->isStaticDataMember() &&
8938              VDecl->getLexicalDeclContext()->isRecord()) {
8939     // This is an in-class initialization for a static data member, e.g.,
8940     //
8941     // struct S {
8942     //   static const int value = 17;
8943     // };
8944 
8945     // C++ [class.mem]p4:
8946     //   A member-declarator can contain a constant-initializer only
8947     //   if it declares a static member (9.4) of const integral or
8948     //   const enumeration type, see 9.4.2.
8949     //
8950     // C++11 [class.static.data]p3:
8951     //   If a non-volatile const static data member is of integral or
8952     //   enumeration type, its declaration in the class definition can
8953     //   specify a brace-or-equal-initializer in which every initalizer-clause
8954     //   that is an assignment-expression is a constant expression. A static
8955     //   data member of literal type can be declared in the class definition
8956     //   with the constexpr specifier; if so, its declaration shall specify a
8957     //   brace-or-equal-initializer in which every initializer-clause that is
8958     //   an assignment-expression is a constant expression.
8959 
8960     // Do nothing on dependent types.
8961     if (DclT->isDependentType()) {
8962 
8963     // Allow any 'static constexpr' members, whether or not they are of literal
8964     // type. We separately check that every constexpr variable is of literal
8965     // type.
8966     } else if (VDecl->isConstexpr()) {
8967 
8968     // Require constness.
8969     } else if (!DclT.isConstQualified()) {
8970       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8971         << Init->getSourceRange();
8972       VDecl->setInvalidDecl();
8973 
8974     // We allow integer constant expressions in all cases.
8975     } else if (DclT->isIntegralOrEnumerationType()) {
8976       // Check whether the expression is a constant expression.
8977       SourceLocation Loc;
8978       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
8979         // In C++11, a non-constexpr const static data member with an
8980         // in-class initializer cannot be volatile.
8981         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8982       else if (Init->isValueDependent())
8983         ; // Nothing to check.
8984       else if (Init->isIntegerConstantExpr(Context, &Loc))
8985         ; // Ok, it's an ICE!
8986       else if (Init->isEvaluatable(Context)) {
8987         // If we can constant fold the initializer through heroics, accept it,
8988         // but report this as a use of an extension for -pedantic.
8989         Diag(Loc, diag::ext_in_class_initializer_non_constant)
8990           << Init->getSourceRange();
8991       } else {
8992         // Otherwise, this is some crazy unknown case.  Report the issue at the
8993         // location provided by the isIntegerConstantExpr failed check.
8994         Diag(Loc, diag::err_in_class_initializer_non_constant)
8995           << Init->getSourceRange();
8996         VDecl->setInvalidDecl();
8997       }
8998 
8999     // We allow foldable floating-point constants as an extension.
9000     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9001       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9002       // it anyway and provide a fixit to add the 'constexpr'.
9003       if (getLangOpts().CPlusPlus11) {
9004         Diag(VDecl->getLocation(),
9005              diag::ext_in_class_initializer_float_type_cxx11)
9006             << DclT << Init->getSourceRange();
9007         Diag(VDecl->getLocStart(),
9008              diag::note_in_class_initializer_float_type_cxx11)
9009             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9010       } else {
9011         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9012           << DclT << Init->getSourceRange();
9013 
9014         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9015           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9016             << Init->getSourceRange();
9017           VDecl->setInvalidDecl();
9018         }
9019       }
9020 
9021     // Suggest adding 'constexpr' in C++11 for literal types.
9022     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9023       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9024         << DclT << Init->getSourceRange()
9025         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9026       VDecl->setConstexpr(true);
9027 
9028     } else {
9029       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9030         << DclT << Init->getSourceRange();
9031       VDecl->setInvalidDecl();
9032     }
9033   } else if (VDecl->isFileVarDecl()) {
9034     if (VDecl->getStorageClass() == SC_Extern &&
9035         (!getLangOpts().CPlusPlus ||
9036          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9037            VDecl->isExternC())) &&
9038         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9039       Diag(VDecl->getLocation(), diag::warn_extern_init);
9040 
9041     // C99 6.7.8p4. All file scoped initializers need to be constant.
9042     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9043       CheckForConstantInitializer(Init, DclT);
9044   }
9045 
9046   // We will represent direct-initialization similarly to copy-initialization:
9047   //    int x(1);  -as-> int x = 1;
9048   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9049   //
9050   // Clients that want to distinguish between the two forms, can check for
9051   // direct initializer using VarDecl::getInitStyle().
9052   // A major benefit is that clients that don't particularly care about which
9053   // exactly form was it (like the CodeGen) can handle both cases without
9054   // special case code.
9055 
9056   // C++ 8.5p11:
9057   // The form of initialization (using parentheses or '=') is generally
9058   // insignificant, but does matter when the entity being initialized has a
9059   // class type.
9060   if (CXXDirectInit) {
9061     assert(DirectInit && "Call-style initializer must be direct init.");
9062     VDecl->setInitStyle(VarDecl::CallInit);
9063   } else if (DirectInit) {
9064     // This must be list-initialization. No other way is direct-initialization.
9065     VDecl->setInitStyle(VarDecl::ListInit);
9066   }
9067 
9068   CheckCompleteVariableDeclaration(VDecl);
9069 }
9070 
9071 /// ActOnInitializerError - Given that there was an error parsing an
9072 /// initializer for the given declaration, try to return to some form
9073 /// of sanity.
9074 void Sema::ActOnInitializerError(Decl *D) {
9075   // Our main concern here is re-establishing invariants like "a
9076   // variable's type is either dependent or complete".
9077   if (!D || D->isInvalidDecl()) return;
9078 
9079   VarDecl *VD = dyn_cast<VarDecl>(D);
9080   if (!VD) return;
9081 
9082   // Auto types are meaningless if we can't make sense of the initializer.
9083   if (ParsingInitForAutoVars.count(D)) {
9084     D->setInvalidDecl();
9085     return;
9086   }
9087 
9088   QualType Ty = VD->getType();
9089   if (Ty->isDependentType()) return;
9090 
9091   // Require a complete type.
9092   if (RequireCompleteType(VD->getLocation(),
9093                           Context.getBaseElementType(Ty),
9094                           diag::err_typecheck_decl_incomplete_type)) {
9095     VD->setInvalidDecl();
9096     return;
9097   }
9098 
9099   // Require a non-abstract type.
9100   if (RequireNonAbstractType(VD->getLocation(), Ty,
9101                              diag::err_abstract_type_in_decl,
9102                              AbstractVariableType)) {
9103     VD->setInvalidDecl();
9104     return;
9105   }
9106 
9107   // Don't bother complaining about constructors or destructors,
9108   // though.
9109 }
9110 
9111 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9112                                   bool TypeMayContainAuto) {
9113   // If there is no declaration, there was an error parsing it. Just ignore it.
9114   if (!RealDecl)
9115     return;
9116 
9117   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9118     QualType Type = Var->getType();
9119 
9120     // C++11 [dcl.spec.auto]p3
9121     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9122       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9123         << Var->getDeclName() << Type;
9124       Var->setInvalidDecl();
9125       return;
9126     }
9127 
9128     // C++11 [class.static.data]p3: A static data member can be declared with
9129     // the constexpr specifier; if so, its declaration shall specify
9130     // a brace-or-equal-initializer.
9131     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9132     // the definition of a variable [...] or the declaration of a static data
9133     // member.
9134     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9135       if (Var->isStaticDataMember())
9136         Diag(Var->getLocation(),
9137              diag::err_constexpr_static_mem_var_requires_init)
9138           << Var->getDeclName();
9139       else
9140         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9141       Var->setInvalidDecl();
9142       return;
9143     }
9144 
9145     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9146     // be initialized.
9147     if (!Var->isInvalidDecl() &&
9148         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9149         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9150       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9151       Var->setInvalidDecl();
9152       return;
9153     }
9154 
9155     switch (Var->isThisDeclarationADefinition()) {
9156     case VarDecl::Definition:
9157       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9158         break;
9159 
9160       // We have an out-of-line definition of a static data member
9161       // that has an in-class initializer, so we type-check this like
9162       // a declaration.
9163       //
9164       // Fall through
9165 
9166     case VarDecl::DeclarationOnly:
9167       // It's only a declaration.
9168 
9169       // Block scope. C99 6.7p7: If an identifier for an object is
9170       // declared with no linkage (C99 6.2.2p6), the type for the
9171       // object shall be complete.
9172       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9173           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9174           RequireCompleteType(Var->getLocation(), Type,
9175                               diag::err_typecheck_decl_incomplete_type))
9176         Var->setInvalidDecl();
9177 
9178       // Make sure that the type is not abstract.
9179       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9180           RequireNonAbstractType(Var->getLocation(), Type,
9181                                  diag::err_abstract_type_in_decl,
9182                                  AbstractVariableType))
9183         Var->setInvalidDecl();
9184       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9185           Var->getStorageClass() == SC_PrivateExtern) {
9186         Diag(Var->getLocation(), diag::warn_private_extern);
9187         Diag(Var->getLocation(), diag::note_private_extern);
9188       }
9189 
9190       return;
9191 
9192     case VarDecl::TentativeDefinition:
9193       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9194       // object that has file scope without an initializer, and without a
9195       // storage-class specifier or with the storage-class specifier "static",
9196       // constitutes a tentative definition. Note: A tentative definition with
9197       // external linkage is valid (C99 6.2.2p5).
9198       if (!Var->isInvalidDecl()) {
9199         if (const IncompleteArrayType *ArrayT
9200                                     = Context.getAsIncompleteArrayType(Type)) {
9201           if (RequireCompleteType(Var->getLocation(),
9202                                   ArrayT->getElementType(),
9203                                   diag::err_illegal_decl_array_incomplete_type))
9204             Var->setInvalidDecl();
9205         } else if (Var->getStorageClass() == SC_Static) {
9206           // C99 6.9.2p3: If the declaration of an identifier for an object is
9207           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9208           // declared type shall not be an incomplete type.
9209           // NOTE: code such as the following
9210           //     static struct s;
9211           //     struct s { int a; };
9212           // is accepted by gcc. Hence here we issue a warning instead of
9213           // an error and we do not invalidate the static declaration.
9214           // NOTE: to avoid multiple warnings, only check the first declaration.
9215           if (Var->isFirstDecl())
9216             RequireCompleteType(Var->getLocation(), Type,
9217                                 diag::ext_typecheck_decl_incomplete_type);
9218         }
9219       }
9220 
9221       // Record the tentative definition; we're done.
9222       if (!Var->isInvalidDecl())
9223         TentativeDefinitions.push_back(Var);
9224       return;
9225     }
9226 
9227     // Provide a specific diagnostic for uninitialized variable
9228     // definitions with incomplete array type.
9229     if (Type->isIncompleteArrayType()) {
9230       Diag(Var->getLocation(),
9231            diag::err_typecheck_incomplete_array_needs_initializer);
9232       Var->setInvalidDecl();
9233       return;
9234     }
9235 
9236     // Provide a specific diagnostic for uninitialized variable
9237     // definitions with reference type.
9238     if (Type->isReferenceType()) {
9239       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9240         << Var->getDeclName()
9241         << SourceRange(Var->getLocation(), Var->getLocation());
9242       Var->setInvalidDecl();
9243       return;
9244     }
9245 
9246     // Do not attempt to type-check the default initializer for a
9247     // variable with dependent type.
9248     if (Type->isDependentType())
9249       return;
9250 
9251     if (Var->isInvalidDecl())
9252       return;
9253 
9254     if (!Var->hasAttr<AliasAttr>()) {
9255       if (RequireCompleteType(Var->getLocation(),
9256                               Context.getBaseElementType(Type),
9257                               diag::err_typecheck_decl_incomplete_type)) {
9258         Var->setInvalidDecl();
9259         return;
9260       }
9261     }
9262 
9263     // The variable can not have an abstract class type.
9264     if (RequireNonAbstractType(Var->getLocation(), Type,
9265                                diag::err_abstract_type_in_decl,
9266                                AbstractVariableType)) {
9267       Var->setInvalidDecl();
9268       return;
9269     }
9270 
9271     // Check for jumps past the implicit initializer.  C++0x
9272     // clarifies that this applies to a "variable with automatic
9273     // storage duration", not a "local variable".
9274     // C++11 [stmt.dcl]p3
9275     //   A program that jumps from a point where a variable with automatic
9276     //   storage duration is not in scope to a point where it is in scope is
9277     //   ill-formed unless the variable has scalar type, class type with a
9278     //   trivial default constructor and a trivial destructor, a cv-qualified
9279     //   version of one of these types, or an array of one of the preceding
9280     //   types and is declared without an initializer.
9281     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9282       if (const RecordType *Record
9283             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9284         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9285         // Mark the function for further checking even if the looser rules of
9286         // C++11 do not require such checks, so that we can diagnose
9287         // incompatibilities with C++98.
9288         if (!CXXRecord->isPOD())
9289           getCurFunction()->setHasBranchProtectedScope();
9290       }
9291     }
9292 
9293     // C++03 [dcl.init]p9:
9294     //   If no initializer is specified for an object, and the
9295     //   object is of (possibly cv-qualified) non-POD class type (or
9296     //   array thereof), the object shall be default-initialized; if
9297     //   the object is of const-qualified type, the underlying class
9298     //   type shall have a user-declared default
9299     //   constructor. Otherwise, if no initializer is specified for
9300     //   a non- static object, the object and its subobjects, if
9301     //   any, have an indeterminate initial value); if the object
9302     //   or any of its subobjects are of const-qualified type, the
9303     //   program is ill-formed.
9304     // C++0x [dcl.init]p11:
9305     //   If no initializer is specified for an object, the object is
9306     //   default-initialized; [...].
9307     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9308     InitializationKind Kind
9309       = InitializationKind::CreateDefault(Var->getLocation());
9310 
9311     InitializationSequence InitSeq(*this, Entity, Kind, None);
9312     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9313     if (Init.isInvalid())
9314       Var->setInvalidDecl();
9315     else if (Init.get()) {
9316       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9317       // This is important for template substitution.
9318       Var->setInitStyle(VarDecl::CallInit);
9319     }
9320 
9321     CheckCompleteVariableDeclaration(Var);
9322   }
9323 }
9324 
9325 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9326   VarDecl *VD = dyn_cast<VarDecl>(D);
9327   if (!VD) {
9328     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9329     D->setInvalidDecl();
9330     return;
9331   }
9332 
9333   VD->setCXXForRangeDecl(true);
9334 
9335   // for-range-declaration cannot be given a storage class specifier.
9336   int Error = -1;
9337   switch (VD->getStorageClass()) {
9338   case SC_None:
9339     break;
9340   case SC_Extern:
9341     Error = 0;
9342     break;
9343   case SC_Static:
9344     Error = 1;
9345     break;
9346   case SC_PrivateExtern:
9347     Error = 2;
9348     break;
9349   case SC_Auto:
9350     Error = 3;
9351     break;
9352   case SC_Register:
9353     Error = 4;
9354     break;
9355   case SC_OpenCLWorkGroupLocal:
9356     llvm_unreachable("Unexpected storage class");
9357   }
9358   if (VD->isConstexpr())
9359     Error = 5;
9360   if (Error != -1) {
9361     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9362       << VD->getDeclName() << Error;
9363     D->setInvalidDecl();
9364   }
9365 }
9366 
9367 StmtResult
9368 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9369                                  IdentifierInfo *Ident,
9370                                  ParsedAttributes &Attrs,
9371                                  SourceLocation AttrEnd) {
9372   // C++1y [stmt.iter]p1:
9373   //   A range-based for statement of the form
9374   //      for ( for-range-identifier : for-range-initializer ) statement
9375   //   is equivalent to
9376   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
9377   DeclSpec DS(Attrs.getPool().getFactory());
9378 
9379   const char *PrevSpec;
9380   unsigned DiagID;
9381   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9382                      getPrintingPolicy());
9383 
9384   Declarator D(DS, Declarator::ForContext);
9385   D.SetIdentifier(Ident, IdentLoc);
9386   D.takeAttributes(Attrs, AttrEnd);
9387 
9388   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9389   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9390                 EmptyAttrs, IdentLoc);
9391   Decl *Var = ActOnDeclarator(S, D);
9392   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9393   FinalizeDeclaration(Var);
9394   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9395                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
9396 }
9397 
9398 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9399   if (var->isInvalidDecl()) return;
9400 
9401   // In ARC, don't allow jumps past the implicit initialization of a
9402   // local retaining variable.
9403   if (getLangOpts().ObjCAutoRefCount &&
9404       var->hasLocalStorage()) {
9405     switch (var->getType().getObjCLifetime()) {
9406     case Qualifiers::OCL_None:
9407     case Qualifiers::OCL_ExplicitNone:
9408     case Qualifiers::OCL_Autoreleasing:
9409       break;
9410 
9411     case Qualifiers::OCL_Weak:
9412     case Qualifiers::OCL_Strong:
9413       getCurFunction()->setHasBranchProtectedScope();
9414       break;
9415     }
9416   }
9417 
9418   // Warn about externally-visible variables being defined without a
9419   // prior declaration.  We only want to do this for global
9420   // declarations, but we also specifically need to avoid doing it for
9421   // class members because the linkage of an anonymous class can
9422   // change if it's later given a typedef name.
9423   if (var->isThisDeclarationADefinition() &&
9424       var->getDeclContext()->getRedeclContext()->isFileContext() &&
9425       var->isExternallyVisible() && var->hasLinkage() &&
9426       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9427                                   var->getLocation())) {
9428     // Find a previous declaration that's not a definition.
9429     VarDecl *prev = var->getPreviousDecl();
9430     while (prev && prev->isThisDeclarationADefinition())
9431       prev = prev->getPreviousDecl();
9432 
9433     if (!prev)
9434       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9435   }
9436 
9437   if (var->getTLSKind() == VarDecl::TLS_Static) {
9438     const Expr *Culprit;
9439     if (var->getType().isDestructedType()) {
9440       // GNU C++98 edits for __thread, [basic.start.term]p3:
9441       //   The type of an object with thread storage duration shall not
9442       //   have a non-trivial destructor.
9443       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9444       if (getLangOpts().CPlusPlus11)
9445         Diag(var->getLocation(), diag::note_use_thread_local);
9446     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9447                !var->getInit()->isConstantInitializer(
9448                    Context, var->getType()->isReferenceType(), &Culprit)) {
9449       // GNU C++98 edits for __thread, [basic.start.init]p4:
9450       //   An object of thread storage duration shall not require dynamic
9451       //   initialization.
9452       // FIXME: Need strict checking here.
9453       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9454         << Culprit->getSourceRange();
9455       if (getLangOpts().CPlusPlus11)
9456         Diag(var->getLocation(), diag::note_use_thread_local);
9457     }
9458 
9459   }
9460 
9461   if (var->isThisDeclarationADefinition() &&
9462       ActiveTemplateInstantiations.empty()) {
9463     PragmaStack<StringLiteral *> *Stack = nullptr;
9464     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
9465     if (var->getType().isConstQualified())
9466       Stack = &ConstSegStack;
9467     else if (!var->getInit()) {
9468       Stack = &BSSSegStack;
9469       SectionFlags |= ASTContext::PSF_Write;
9470     } else {
9471       Stack = &DataSegStack;
9472       SectionFlags |= ASTContext::PSF_Write;
9473     }
9474     if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue)
9475       var->addAttr(
9476           SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
9477                                       Stack->CurrentValue->getString(),
9478                                       Stack->CurrentPragmaLocation));
9479     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
9480       if (UnifySection(SA->getName(), SectionFlags, var))
9481         var->dropAttr<SectionAttr>();
9482 
9483     // Apply the init_seg attribute if this has an initializer.  If the
9484     // initializer turns out to not be dynamic, we'll end up ignoring this
9485     // attribute.
9486     if (CurInitSeg && var->getInit())
9487       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
9488                                                CurInitSegLoc));
9489   }
9490 
9491   // All the following checks are C++ only.
9492   if (!getLangOpts().CPlusPlus) return;
9493 
9494   QualType type = var->getType();
9495   if (type->isDependentType()) return;
9496 
9497   // __block variables might require us to capture a copy-initializer.
9498   if (var->hasAttr<BlocksAttr>()) {
9499     // It's currently invalid to ever have a __block variable with an
9500     // array type; should we diagnose that here?
9501 
9502     // Regardless, we don't want to ignore array nesting when
9503     // constructing this copy.
9504     if (type->isStructureOrClassType()) {
9505       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
9506       SourceLocation poi = var->getLocation();
9507       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
9508       ExprResult result
9509         = PerformMoveOrCopyInitialization(
9510             InitializedEntity::InitializeBlock(poi, type, false),
9511             var, var->getType(), varRef, /*AllowNRVO=*/true);
9512       if (!result.isInvalid()) {
9513         result = MaybeCreateExprWithCleanups(result);
9514         Expr *init = result.getAs<Expr>();
9515         Context.setBlockVarCopyInits(var, init);
9516       }
9517     }
9518   }
9519 
9520   Expr *Init = var->getInit();
9521   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
9522   QualType baseType = Context.getBaseElementType(type);
9523 
9524   if (!var->getDeclContext()->isDependentContext() &&
9525       Init && !Init->isValueDependent()) {
9526     if (IsGlobal && !var->isConstexpr() &&
9527         !getDiagnostics().isIgnored(diag::warn_global_constructor,
9528                                     var->getLocation())) {
9529       // Warn about globals which don't have a constant initializer.  Don't
9530       // warn about globals with a non-trivial destructor because we already
9531       // warned about them.
9532       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
9533       if (!(RD && !RD->hasTrivialDestructor()) &&
9534           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
9535         Diag(var->getLocation(), diag::warn_global_constructor)
9536           << Init->getSourceRange();
9537     }
9538 
9539     if (var->isConstexpr()) {
9540       SmallVector<PartialDiagnosticAt, 8> Notes;
9541       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
9542         SourceLocation DiagLoc = var->getLocation();
9543         // If the note doesn't add any useful information other than a source
9544         // location, fold it into the primary diagnostic.
9545         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9546               diag::note_invalid_subexpr_in_const_expr) {
9547           DiagLoc = Notes[0].first;
9548           Notes.clear();
9549         }
9550         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
9551           << var << Init->getSourceRange();
9552         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9553           Diag(Notes[I].first, Notes[I].second);
9554       }
9555     } else if (var->isUsableInConstantExpressions(Context)) {
9556       // Check whether the initializer of a const variable of integral or
9557       // enumeration type is an ICE now, since we can't tell whether it was
9558       // initialized by a constant expression if we check later.
9559       var->checkInitIsICE();
9560     }
9561   }
9562 
9563   // Require the destructor.
9564   if (const RecordType *recordType = baseType->getAs<RecordType>())
9565     FinalizeVarWithDestructor(var, recordType);
9566 }
9567 
9568 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9569 /// any semantic actions necessary after any initializer has been attached.
9570 void
9571 Sema::FinalizeDeclaration(Decl *ThisDecl) {
9572   // Note that we are no longer parsing the initializer for this declaration.
9573   ParsingInitForAutoVars.erase(ThisDecl);
9574 
9575   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
9576   if (!VD)
9577     return;
9578 
9579   checkAttributesAfterMerging(*this, *VD);
9580 
9581   // Static locals inherit dll attributes from their function.
9582   if (VD->isStaticLocal()) {
9583     if (FunctionDecl *FD =
9584             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
9585       if (Attr *A = getDLLAttr(FD)) {
9586         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
9587         NewAttr->setInherited(true);
9588         VD->addAttr(NewAttr);
9589       }
9590     }
9591   }
9592 
9593   // Grab the dllimport or dllexport attribute off of the VarDecl.
9594   const InheritableAttr *DLLAttr = getDLLAttr(VD);
9595 
9596   // Imported static data members cannot be defined out-of-line.
9597   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
9598     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
9599         VD->isThisDeclarationADefinition()) {
9600       // We allow definitions of dllimport class template static data members
9601       // with a warning.
9602       CXXRecordDecl *Context =
9603         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
9604       bool IsClassTemplateMember =
9605           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
9606           Context->getDescribedClassTemplate();
9607 
9608       Diag(VD->getLocation(),
9609            IsClassTemplateMember
9610                ? diag::warn_attribute_dllimport_static_field_definition
9611                : diag::err_attribute_dllimport_static_field_definition);
9612       Diag(IA->getLocation(), diag::note_attribute);
9613       if (!IsClassTemplateMember)
9614         VD->setInvalidDecl();
9615     }
9616   }
9617 
9618   // dllimport/dllexport variables cannot be thread local, their TLS index
9619   // isn't exported with the variable.
9620   if (DLLAttr && VD->getTLSKind()) {
9621     Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
9622                                                                   << DLLAttr;
9623     VD->setInvalidDecl();
9624   }
9625 
9626   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9627     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
9628       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
9629       VD->dropAttr<UsedAttr>();
9630     }
9631   }
9632 
9633   const DeclContext *DC = VD->getDeclContext();
9634   // If there's a #pragma GCC visibility in scope, and this isn't a class
9635   // member, set the visibility of this variable.
9636   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
9637     AddPushedVisibilityAttribute(VD);
9638 
9639   // FIXME: Warn on unused templates.
9640   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
9641       !isa<VarTemplatePartialSpecializationDecl>(VD))
9642     MarkUnusedFileScopedDecl(VD);
9643 
9644   // Now we have parsed the initializer and can update the table of magic
9645   // tag values.
9646   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
9647       !VD->getType()->isIntegralOrEnumerationType())
9648     return;
9649 
9650   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
9651     const Expr *MagicValueExpr = VD->getInit();
9652     if (!MagicValueExpr) {
9653       continue;
9654     }
9655     llvm::APSInt MagicValueInt;
9656     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9657       Diag(I->getRange().getBegin(),
9658            diag::err_type_tag_for_datatype_not_ice)
9659         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9660       continue;
9661     }
9662     if (MagicValueInt.getActiveBits() > 64) {
9663       Diag(I->getRange().getBegin(),
9664            diag::err_type_tag_for_datatype_too_large)
9665         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9666       continue;
9667     }
9668     uint64_t MagicValue = MagicValueInt.getZExtValue();
9669     RegisterTypeTagForDatatype(I->getArgumentKind(),
9670                                MagicValue,
9671                                I->getMatchingCType(),
9672                                I->getLayoutCompatible(),
9673                                I->getMustBeNull());
9674   }
9675 }
9676 
9677 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
9678                                                    ArrayRef<Decl *> Group) {
9679   SmallVector<Decl*, 8> Decls;
9680 
9681   if (DS.isTypeSpecOwned())
9682     Decls.push_back(DS.getRepAsDecl());
9683 
9684   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
9685   for (unsigned i = 0, e = Group.size(); i != e; ++i)
9686     if (Decl *D = Group[i]) {
9687       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9688         if (!FirstDeclaratorInGroup)
9689           FirstDeclaratorInGroup = DD;
9690       Decls.push_back(D);
9691     }
9692 
9693   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
9694     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
9695       HandleTagNumbering(*this, Tag, S);
9696       if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9697         Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9698     }
9699   }
9700 
9701   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
9702 }
9703 
9704 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
9705 /// group, performing any necessary semantic checking.
9706 Sema::DeclGroupPtrTy
9707 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
9708                            bool TypeMayContainAuto) {
9709   // C++0x [dcl.spec.auto]p7:
9710   //   If the type deduced for the template parameter U is not the same in each
9711   //   deduction, the program is ill-formed.
9712   // FIXME: When initializer-list support is added, a distinction is needed
9713   // between the deduced type U and the deduced type which 'auto' stands for.
9714   //   auto a = 0, b = { 1, 2, 3 };
9715   // is legal because the deduced type U is 'int' in both cases.
9716   if (TypeMayContainAuto && Group.size() > 1) {
9717     QualType Deduced;
9718     CanQualType DeducedCanon;
9719     VarDecl *DeducedDecl = nullptr;
9720     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
9721       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9722         AutoType *AT = D->getType()->getContainedAutoType();
9723         // Don't reissue diagnostics when instantiating a template.
9724         if (AT && D->isInvalidDecl())
9725           break;
9726         QualType U = AT ? AT->getDeducedType() : QualType();
9727         if (!U.isNull()) {
9728           CanQualType UCanon = Context.getCanonicalType(U);
9729           if (Deduced.isNull()) {
9730             Deduced = U;
9731             DeducedCanon = UCanon;
9732             DeducedDecl = D;
9733           } else if (DeducedCanon != UCanon) {
9734             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9735                  diag::err_auto_different_deductions)
9736               << (AT->isDecltypeAuto() ? 1 : 0)
9737               << Deduced << DeducedDecl->getDeclName()
9738               << U << D->getDeclName()
9739               << DeducedDecl->getInit()->getSourceRange()
9740               << D->getInit()->getSourceRange();
9741             D->setInvalidDecl();
9742             break;
9743           }
9744         }
9745       }
9746     }
9747   }
9748 
9749   ActOnDocumentableDecls(Group);
9750 
9751   return DeclGroupPtrTy::make(
9752       DeclGroupRef::Create(Context, Group.data(), Group.size()));
9753 }
9754 
9755 void Sema::ActOnDocumentableDecl(Decl *D) {
9756   ActOnDocumentableDecls(D);
9757 }
9758 
9759 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
9760   // Don't parse the comment if Doxygen diagnostics are ignored.
9761   if (Group.empty() || !Group[0])
9762    return;
9763 
9764   if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation()))
9765     return;
9766 
9767   if (Group.size() >= 2) {
9768     // This is a decl group.  Normally it will contain only declarations
9769     // produced from declarator list.  But in case we have any definitions or
9770     // additional declaration references:
9771     //   'typedef struct S {} S;'
9772     //   'typedef struct S *S;'
9773     //   'struct S *pS;'
9774     // FinalizeDeclaratorGroup adds these as separate declarations.
9775     Decl *MaybeTagDecl = Group[0];
9776     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
9777       Group = Group.slice(1);
9778     }
9779   }
9780 
9781   // See if there are any new comments that are not attached to a decl.
9782   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9783   if (!Comments.empty() &&
9784       !Comments.back()->isAttached()) {
9785     // There is at least one comment that not attached to a decl.
9786     // Maybe it should be attached to one of these decls?
9787     //
9788     // Note that this way we pick up not only comments that precede the
9789     // declaration, but also comments that *follow* the declaration -- thanks to
9790     // the lookahead in the lexer: we've consumed the semicolon and looked
9791     // ahead through comments.
9792     for (unsigned i = 0, e = Group.size(); i != e; ++i)
9793       Context.getCommentForDecl(Group[i], &PP);
9794   }
9795 }
9796 
9797 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9798 /// to introduce parameters into function prototype scope.
9799 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
9800   const DeclSpec &DS = D.getDeclSpec();
9801 
9802   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
9803 
9804   // C++03 [dcl.stc]p2 also permits 'auto'.
9805   StorageClass SC = SC_None;
9806   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
9807     SC = SC_Register;
9808   } else if (getLangOpts().CPlusPlus &&
9809              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9810     SC = SC_Auto;
9811   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
9812     Diag(DS.getStorageClassSpecLoc(),
9813          diag::err_invalid_storage_class_in_func_decl);
9814     D.getMutableDeclSpec().ClearStorageClassSpecs();
9815   }
9816 
9817   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9818     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9819       << DeclSpec::getSpecifierName(TSCS);
9820   if (DS.isConstexprSpecified())
9821     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
9822       << 0;
9823 
9824   DiagnoseFunctionSpecifiers(DS);
9825 
9826   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9827   QualType parmDeclType = TInfo->getType();
9828 
9829   if (getLangOpts().CPlusPlus) {
9830     // Check that there are no default arguments inside the type of this
9831     // parameter.
9832     CheckExtraCXXDefaultArguments(D);
9833 
9834     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9835     if (D.getCXXScopeSpec().isSet()) {
9836       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9837         << D.getCXXScopeSpec().getRange();
9838       D.getCXXScopeSpec().clear();
9839     }
9840   }
9841 
9842   // Ensure we have a valid name
9843   IdentifierInfo *II = nullptr;
9844   if (D.hasName()) {
9845     II = D.getIdentifier();
9846     if (!II) {
9847       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9848         << GetNameForDeclarator(D).getName();
9849       D.setInvalidType(true);
9850     }
9851   }
9852 
9853   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
9854   if (II) {
9855     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9856                    ForRedeclaration);
9857     LookupName(R, S);
9858     if (R.isSingleResult()) {
9859       NamedDecl *PrevDecl = R.getFoundDecl();
9860       if (PrevDecl->isTemplateParameter()) {
9861         // Maybe we will complain about the shadowed template parameter.
9862         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9863         // Just pretend that we didn't see the previous declaration.
9864         PrevDecl = nullptr;
9865       } else if (S->isDeclScope(PrevDecl)) {
9866         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
9867         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9868 
9869         // Recover by removing the name
9870         II = nullptr;
9871         D.SetIdentifier(nullptr, D.getIdentifierLoc());
9872         D.setInvalidType(true);
9873       }
9874     }
9875   }
9876 
9877   // Temporarily put parameter variables in the translation unit, not
9878   // the enclosing context.  This prevents them from accidentally
9879   // looking like class members in C++.
9880   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
9881                                     D.getLocStart(),
9882                                     D.getIdentifierLoc(), II,
9883                                     parmDeclType, TInfo,
9884                                     SC);
9885 
9886   if (D.isInvalidType())
9887     New->setInvalidDecl();
9888 
9889   assert(S->isFunctionPrototypeScope());
9890   assert(S->getFunctionPrototypeDepth() >= 1);
9891   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9892                     S->getNextFunctionPrototypeIndex());
9893 
9894   // Add the parameter declaration into this scope.
9895   S->AddDecl(New);
9896   if (II)
9897     IdResolver.AddDecl(New);
9898 
9899   ProcessDeclAttributes(S, New, D);
9900 
9901   if (D.getDeclSpec().isModulePrivateSpecified())
9902     Diag(New->getLocation(), diag::err_module_private_local)
9903       << 1 << New->getDeclName()
9904       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9905       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9906 
9907   if (New->hasAttr<BlocksAttr>()) {
9908     Diag(New->getLocation(), diag::err_block_on_nonlocal);
9909   }
9910   return New;
9911 }
9912 
9913 /// \brief Synthesizes a variable for a parameter arising from a
9914 /// typedef.
9915 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9916                                               SourceLocation Loc,
9917                                               QualType T) {
9918   /* FIXME: setting StartLoc == Loc.
9919      Would it be worth to modify callers so as to provide proper source
9920      location for the unnamed parameters, embedding the parameter's type? */
9921   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
9922                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
9923                                            SC_None, nullptr);
9924   Param->setImplicit();
9925   return Param;
9926 }
9927 
9928 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9929                                     ParmVarDecl * const *ParamEnd) {
9930   // Don't diagnose unused-parameter errors in template instantiations; we
9931   // will already have done so in the template itself.
9932   if (!ActiveTemplateInstantiations.empty())
9933     return;
9934 
9935   for (; Param != ParamEnd; ++Param) {
9936     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
9937         !(*Param)->hasAttr<UnusedAttr>()) {
9938       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9939         << (*Param)->getDeclName();
9940     }
9941   }
9942 }
9943 
9944 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9945                                                   ParmVarDecl * const *ParamEnd,
9946                                                   QualType ReturnTy,
9947                                                   NamedDecl *D) {
9948   if (LangOpts.NumLargeByValueCopy == 0) // No check.
9949     return;
9950 
9951   // Warn if the return value is pass-by-value and larger than the specified
9952   // threshold.
9953   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
9954     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
9955     if (Size > LangOpts.NumLargeByValueCopy)
9956       Diag(D->getLocation(), diag::warn_return_value_size)
9957           << D->getDeclName() << Size;
9958   }
9959 
9960   // Warn if any parameter is pass-by-value and larger than the specified
9961   // threshold.
9962   for (; Param != ParamEnd; ++Param) {
9963     QualType T = (*Param)->getType();
9964     if (T->isDependentType() || !T.isPODType(Context))
9965       continue;
9966     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
9967     if (Size > LangOpts.NumLargeByValueCopy)
9968       Diag((*Param)->getLocation(), diag::warn_parameter_size)
9969           << (*Param)->getDeclName() << Size;
9970   }
9971 }
9972 
9973 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9974                                   SourceLocation NameLoc, IdentifierInfo *Name,
9975                                   QualType T, TypeSourceInfo *TSInfo,
9976                                   StorageClass SC) {
9977   // In ARC, infer a lifetime qualifier for appropriate parameter types.
9978   if (getLangOpts().ObjCAutoRefCount &&
9979       T.getObjCLifetime() == Qualifiers::OCL_None &&
9980       T->isObjCLifetimeType()) {
9981 
9982     Qualifiers::ObjCLifetime lifetime;
9983 
9984     // Special cases for arrays:
9985     //   - if it's const, use __unsafe_unretained
9986     //   - otherwise, it's an error
9987     if (T->isArrayType()) {
9988       if (!T.isConstQualified()) {
9989         DelayedDiagnostics.add(
9990             sema::DelayedDiagnostic::makeForbiddenType(
9991             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
9992       }
9993       lifetime = Qualifiers::OCL_ExplicitNone;
9994     } else {
9995       lifetime = T->getObjCARCImplicitLifetime();
9996     }
9997     T = Context.getLifetimeQualifiedType(T, lifetime);
9998   }
9999 
10000   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10001                                          Context.getAdjustedParameterType(T),
10002                                          TSInfo, SC, nullptr);
10003 
10004   // Parameters can not be abstract class types.
10005   // For record types, this is done by the AbstractClassUsageDiagnoser once
10006   // the class has been completely parsed.
10007   if (!CurContext->isRecord() &&
10008       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10009                              AbstractParamType))
10010     New->setInvalidDecl();
10011 
10012   // Parameter declarators cannot be interface types. All ObjC objects are
10013   // passed by reference.
10014   if (T->isObjCObjectType()) {
10015     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10016     Diag(NameLoc,
10017          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10018       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10019     T = Context.getObjCObjectPointerType(T);
10020     New->setType(T);
10021   }
10022 
10023   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10024   // duration shall not be qualified by an address-space qualifier."
10025   // Since all parameters have automatic store duration, they can not have
10026   // an address space.
10027   if (T.getAddressSpace() != 0) {
10028     // OpenCL allows function arguments declared to be an array of a type
10029     // to be qualified with an address space.
10030     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10031       Diag(NameLoc, diag::err_arg_with_address_space);
10032       New->setInvalidDecl();
10033     }
10034   }
10035 
10036   return New;
10037 }
10038 
10039 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10040                                            SourceLocation LocAfterDecls) {
10041   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10042 
10043   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10044   // for a K&R function.
10045   if (!FTI.hasPrototype) {
10046     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10047       --i;
10048       if (FTI.Params[i].Param == nullptr) {
10049         SmallString<256> Code;
10050         llvm::raw_svector_ostream(Code)
10051             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10052         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10053             << FTI.Params[i].Ident
10054             << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
10055 
10056         // Implicitly declare the argument as type 'int' for lack of a better
10057         // type.
10058         AttributeFactory attrs;
10059         DeclSpec DS(attrs);
10060         const char* PrevSpec; // unused
10061         unsigned DiagID; // unused
10062         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10063                            DiagID, Context.getPrintingPolicy());
10064         // Use the identifier location for the type source range.
10065         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10066         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10067         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10068         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10069         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10070       }
10071     }
10072   }
10073 }
10074 
10075 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
10076   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10077   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10078   Scope *ParentScope = FnBodyScope->getParent();
10079 
10080   D.setFunctionDefinitionKind(FDK_Definition);
10081   Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
10082   return ActOnStartOfFunctionDef(FnBodyScope, DP);
10083 }
10084 
10085 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10086   Consumer.HandleInlineMethodDefinition(D);
10087 }
10088 
10089 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10090                              const FunctionDecl*& PossibleZeroParamPrototype) {
10091   // Don't warn about invalid declarations.
10092   if (FD->isInvalidDecl())
10093     return false;
10094 
10095   // Or declarations that aren't global.
10096   if (!FD->isGlobal())
10097     return false;
10098 
10099   // Don't warn about C++ member functions.
10100   if (isa<CXXMethodDecl>(FD))
10101     return false;
10102 
10103   // Don't warn about 'main'.
10104   if (FD->isMain())
10105     return false;
10106 
10107   // Don't warn about inline functions.
10108   if (FD->isInlined())
10109     return false;
10110 
10111   // Don't warn about function templates.
10112   if (FD->getDescribedFunctionTemplate())
10113     return false;
10114 
10115   // Don't warn about function template specializations.
10116   if (FD->isFunctionTemplateSpecialization())
10117     return false;
10118 
10119   // Don't warn for OpenCL kernels.
10120   if (FD->hasAttr<OpenCLKernelAttr>())
10121     return false;
10122 
10123   bool MissingPrototype = true;
10124   for (const FunctionDecl *Prev = FD->getPreviousDecl();
10125        Prev; Prev = Prev->getPreviousDecl()) {
10126     // Ignore any declarations that occur in function or method
10127     // scope, because they aren't visible from the header.
10128     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10129       continue;
10130 
10131     MissingPrototype = !Prev->getType()->isFunctionProtoType();
10132     if (FD->getNumParams() == 0)
10133       PossibleZeroParamPrototype = Prev;
10134     break;
10135   }
10136 
10137   return MissingPrototype;
10138 }
10139 
10140 void
10141 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10142                                    const FunctionDecl *EffectiveDefinition) {
10143   // Don't complain if we're in GNU89 mode and the previous definition
10144   // was an extern inline function.
10145   const FunctionDecl *Definition = EffectiveDefinition;
10146   if (!Definition)
10147     if (!FD->isDefined(Definition))
10148       return;
10149 
10150   if (canRedefineFunction(Definition, getLangOpts()))
10151     return;
10152 
10153   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10154       Definition->getStorageClass() == SC_Extern)
10155     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10156         << FD->getDeclName() << getLangOpts().CPlusPlus;
10157   else
10158     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10159 
10160   Diag(Definition->getLocation(), diag::note_previous_definition);
10161   FD->setInvalidDecl();
10162 }
10163 
10164 
10165 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10166                                    Sema &S) {
10167   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10168 
10169   LambdaScopeInfo *LSI = S.PushLambdaScope();
10170   LSI->CallOperator = CallOperator;
10171   LSI->Lambda = LambdaClass;
10172   LSI->ReturnType = CallOperator->getReturnType();
10173   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10174 
10175   if (LCD == LCD_None)
10176     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10177   else if (LCD == LCD_ByCopy)
10178     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10179   else if (LCD == LCD_ByRef)
10180     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10181   DeclarationNameInfo DNI = CallOperator->getNameInfo();
10182 
10183   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10184   LSI->Mutable = !CallOperator->isConst();
10185 
10186   // Add the captures to the LSI so they can be noted as already
10187   // captured within tryCaptureVar.
10188   auto I = LambdaClass->field_begin();
10189   for (const auto &C : LambdaClass->captures()) {
10190     if (C.capturesVariable()) {
10191       VarDecl *VD = C.getCapturedVar();
10192       if (VD->isInitCapture())
10193         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10194       QualType CaptureType = VD->getType();
10195       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10196       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10197           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
10198           /*EllipsisLoc*/C.isPackExpansion()
10199                          ? C.getEllipsisLoc() : SourceLocation(),
10200           CaptureType, /*Expr*/ nullptr);
10201 
10202     } else if (C.capturesThis()) {
10203       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10204                               S.getCurrentThisType(), /*Expr*/ nullptr);
10205     } else {
10206       LSI->addVLATypeCapture(C.getLocation(), I->getType());
10207     }
10208     ++I;
10209   }
10210 }
10211 
10212 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
10213   // Clear the last template instantiation error context.
10214   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10215 
10216   if (!D)
10217     return D;
10218   FunctionDecl *FD = nullptr;
10219 
10220   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10221     FD = FunTmpl->getTemplatedDecl();
10222   else
10223     FD = cast<FunctionDecl>(D);
10224   // If we are instantiating a generic lambda call operator, push
10225   // a LambdaScopeInfo onto the function stack.  But use the information
10226   // that's already been calculated (ActOnLambdaExpr) to prime the current
10227   // LambdaScopeInfo.
10228   // When the template operator is being specialized, the LambdaScopeInfo,
10229   // has to be properly restored so that tryCaptureVariable doesn't try
10230   // and capture any new variables. In addition when calculating potential
10231   // captures during transformation of nested lambdas, it is necessary to
10232   // have the LSI properly restored.
10233   if (isGenericLambdaCallOperatorSpecialization(FD)) {
10234     assert(ActiveTemplateInstantiations.size() &&
10235       "There should be an active template instantiation on the stack "
10236       "when instantiating a generic lambda!");
10237     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10238   }
10239   else
10240     // Enter a new function scope
10241     PushFunctionScope();
10242 
10243   // See if this is a redefinition.
10244   if (!FD->isLateTemplateParsed())
10245     CheckForFunctionRedefinition(FD);
10246 
10247   // Builtin functions cannot be defined.
10248   if (unsigned BuiltinID = FD->getBuiltinID()) {
10249     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10250         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10251       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10252       FD->setInvalidDecl();
10253     }
10254   }
10255 
10256   // The return type of a function definition must be complete
10257   // (C99 6.9.1p3, C++ [dcl.fct]p6).
10258   QualType ResultType = FD->getReturnType();
10259   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10260       !FD->isInvalidDecl() &&
10261       RequireCompleteType(FD->getLocation(), ResultType,
10262                           diag::err_func_def_incomplete_result))
10263     FD->setInvalidDecl();
10264 
10265   // GNU warning -Wmissing-prototypes:
10266   //   Warn if a global function is defined without a previous
10267   //   prototype declaration. This warning is issued even if the
10268   //   definition itself provides a prototype. The aim is to detect
10269   //   global functions that fail to be declared in header files.
10270   const FunctionDecl *PossibleZeroParamPrototype = nullptr;
10271   if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
10272     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
10273 
10274     if (PossibleZeroParamPrototype) {
10275       // We found a declaration that is not a prototype,
10276       // but that could be a zero-parameter prototype
10277       if (TypeSourceInfo *TI =
10278               PossibleZeroParamPrototype->getTypeSourceInfo()) {
10279         TypeLoc TL = TI->getTypeLoc();
10280         if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
10281           Diag(PossibleZeroParamPrototype->getLocation(),
10282                diag::note_declaration_not_a_prototype)
10283             << PossibleZeroParamPrototype
10284             << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
10285       }
10286     }
10287   }
10288 
10289   if (FnBodyScope)
10290     PushDeclContext(FnBodyScope, FD);
10291 
10292   // Check the validity of our function parameters
10293   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10294                            /*CheckParameterNames=*/true);
10295 
10296   // Introduce our parameters into the function scope
10297   for (auto Param : FD->params()) {
10298     Param->setOwningFunction(FD);
10299 
10300     // If this has an identifier, add it to the scope stack.
10301     if (Param->getIdentifier() && FnBodyScope) {
10302       CheckShadow(FnBodyScope, Param);
10303 
10304       PushOnScopeChains(Param, FnBodyScope);
10305     }
10306   }
10307 
10308   // If we had any tags defined in the function prototype,
10309   // introduce them into the function scope.
10310   if (FnBodyScope) {
10311     for (ArrayRef<NamedDecl *>::iterator
10312              I = FD->getDeclsInPrototypeScope().begin(),
10313              E = FD->getDeclsInPrototypeScope().end();
10314          I != E; ++I) {
10315       NamedDecl *D = *I;
10316 
10317       // Some of these decls (like enums) may have been pinned to the translation unit
10318       // for lack of a real context earlier. If so, remove from the translation unit
10319       // and reattach to the current context.
10320       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10321         // Is the decl actually in the context?
10322         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10323           if (DI == D) {
10324             Context.getTranslationUnitDecl()->removeDecl(D);
10325             break;
10326           }
10327         }
10328         // Either way, reassign the lexical decl context to our FunctionDecl.
10329         D->setLexicalDeclContext(CurContext);
10330       }
10331 
10332       // If the decl has a non-null name, make accessible in the current scope.
10333       if (!D->getName().empty())
10334         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10335 
10336       // Similarly, dive into enums and fish their constants out, making them
10337       // accessible in this scope.
10338       if (auto *ED = dyn_cast<EnumDecl>(D)) {
10339         for (auto *EI : ED->enumerators())
10340           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10341       }
10342     }
10343   }
10344 
10345   // Ensure that the function's exception specification is instantiated.
10346   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10347     ResolveExceptionSpec(D->getLocation(), FPT);
10348 
10349   // dllimport cannot be applied to non-inline function definitions.
10350   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10351       !FD->isTemplateInstantiation()) {
10352     assert(!FD->hasAttr<DLLExportAttr>());
10353     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10354     FD->setInvalidDecl();
10355     return D;
10356   }
10357   // We want to attach documentation to original Decl (which might be
10358   // a function template).
10359   ActOnDocumentableDecl(D);
10360   if (getCurLexicalContext()->isObjCContainer() &&
10361       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10362       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10363     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10364 
10365   return D;
10366 }
10367 
10368 /// \brief Given the set of return statements within a function body,
10369 /// compute the variables that are subject to the named return value
10370 /// optimization.
10371 ///
10372 /// Each of the variables that is subject to the named return value
10373 /// optimization will be marked as NRVO variables in the AST, and any
10374 /// return statement that has a marked NRVO variable as its NRVO candidate can
10375 /// use the named return value optimization.
10376 ///
10377 /// This function applies a very simplistic algorithm for NRVO: if every return
10378 /// statement in the scope of a variable has the same NRVO candidate, that
10379 /// candidate is an NRVO variable.
10380 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
10381   ReturnStmt **Returns = Scope->Returns.data();
10382 
10383   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10384     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10385       if (!NRVOCandidate->isNRVOVariable())
10386         Returns[I]->setNRVOCandidate(nullptr);
10387     }
10388   }
10389 }
10390 
10391 bool Sema::canDelayFunctionBody(const Declarator &D) {
10392   // We can't delay parsing the body of a constexpr function template (yet).
10393   if (D.getDeclSpec().isConstexprSpecified())
10394     return false;
10395 
10396   // We can't delay parsing the body of a function template with a deduced
10397   // return type (yet).
10398   if (D.getDeclSpec().containsPlaceholderType()) {
10399     // If the placeholder introduces a non-deduced trailing return type,
10400     // we can still delay parsing it.
10401     if (D.getNumTypeObjects()) {
10402       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10403       if (Outer.Kind == DeclaratorChunk::Function &&
10404           Outer.Fun.hasTrailingReturnType()) {
10405         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10406         return Ty.isNull() || !Ty->isUndeducedType();
10407       }
10408     }
10409     return false;
10410   }
10411 
10412   return true;
10413 }
10414 
10415 bool Sema::canSkipFunctionBody(Decl *D) {
10416   // We cannot skip the body of a function (or function template) which is
10417   // constexpr, since we may need to evaluate its body in order to parse the
10418   // rest of the file.
10419   // We cannot skip the body of a function with an undeduced return type,
10420   // because any callers of that function need to know the type.
10421   if (const FunctionDecl *FD = D->getAsFunction())
10422     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
10423       return false;
10424   return Consumer.shouldSkipFunctionBody(D);
10425 }
10426 
10427 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
10428   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
10429     FD->setHasSkippedBody();
10430   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
10431     MD->setHasSkippedBody();
10432   return ActOnFinishFunctionBody(Decl, nullptr);
10433 }
10434 
10435 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
10436   return ActOnFinishFunctionBody(D, BodyArg, false);
10437 }
10438 
10439 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
10440                                     bool IsInstantiation) {
10441   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
10442 
10443   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10444   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
10445 
10446   if (FD) {
10447     FD->setBody(Body);
10448 
10449     if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
10450         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
10451       // If the function has a deduced result type but contains no 'return'
10452       // statements, the result type as written must be exactly 'auto', and
10453       // the deduced result type is 'void'.
10454       if (!FD->getReturnType()->getAs<AutoType>()) {
10455         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
10456             << FD->getReturnType();
10457         FD->setInvalidDecl();
10458       } else {
10459         // Substitute 'void' for the 'auto' in the type.
10460         TypeLoc ResultType = getReturnTypeLoc(FD);
10461         Context.adjustDeducedFunctionResultType(
10462             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
10463       }
10464     }
10465 
10466     // The only way to be included in UndefinedButUsed is if there is an
10467     // ODR use before the definition. Avoid the expensive map lookup if this
10468     // is the first declaration.
10469     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
10470       if (!FD->isExternallyVisible())
10471         UndefinedButUsed.erase(FD);
10472       else if (FD->isInlined() &&
10473                (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10474                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
10475         UndefinedButUsed.erase(FD);
10476     }
10477 
10478     // If the function implicitly returns zero (like 'main') or is naked,
10479     // don't complain about missing return statements.
10480     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
10481       WP.disableCheckFallThrough();
10482 
10483     // MSVC permits the use of pure specifier (=0) on function definition,
10484     // defined at class scope, warn about this non-standard construct.
10485     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
10486       Diag(FD->getLocation(), diag::ext_pure_function_definition);
10487 
10488     if (!FD->isInvalidDecl()) {
10489       // Don't diagnose unused parameters of defaulted or deleted functions.
10490       if (Body)
10491         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
10492       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
10493                                              FD->getReturnType(), FD);
10494 
10495       // If this is a structor, we need a vtable.
10496       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
10497         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
10498       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
10499         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
10500 
10501       // Try to apply the named return value optimization. We have to check
10502       // if we can do this here because lambdas keep return statements around
10503       // to deduce an implicit return type.
10504       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
10505           !FD->isDependentContext())
10506         computeNRVO(Body, getCurFunction());
10507     }
10508 
10509     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
10510            "Function parsing confused");
10511   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
10512     assert(MD == getCurMethodDecl() && "Method parsing confused");
10513     MD->setBody(Body);
10514     if (!MD->isInvalidDecl()) {
10515       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
10516       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
10517                                              MD->getReturnType(), MD);
10518 
10519       if (Body)
10520         computeNRVO(Body, getCurFunction());
10521     }
10522     if (getCurFunction()->ObjCShouldCallSuper) {
10523       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
10524         << MD->getSelector().getAsString();
10525       getCurFunction()->ObjCShouldCallSuper = false;
10526     }
10527     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
10528       const ObjCMethodDecl *InitMethod = nullptr;
10529       bool isDesignated =
10530           MD->isDesignatedInitializerForTheInterface(&InitMethod);
10531       assert(isDesignated && InitMethod);
10532       (void)isDesignated;
10533 
10534       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
10535         auto IFace = MD->getClassInterface();
10536         if (!IFace)
10537           return false;
10538         auto SuperD = IFace->getSuperClass();
10539         if (!SuperD)
10540           return false;
10541         return SuperD->getIdentifier() ==
10542             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
10543       };
10544       // Don't issue this warning for unavailable inits or direct subclasses
10545       // of NSObject.
10546       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
10547         Diag(MD->getLocation(),
10548              diag::warn_objc_designated_init_missing_super_call);
10549         Diag(InitMethod->getLocation(),
10550              diag::note_objc_designated_init_marked_here);
10551       }
10552       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
10553     }
10554     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
10555       // Don't issue this warning for unavaialable inits.
10556       if (!MD->isUnavailable())
10557         Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
10558       getCurFunction()->ObjCWarnForNoInitDelegation = false;
10559     }
10560   } else {
10561     return nullptr;
10562   }
10563 
10564   assert(!getCurFunction()->ObjCShouldCallSuper &&
10565          "This should only be set for ObjC methods, which should have been "
10566          "handled in the block above.");
10567 
10568   // Verify and clean out per-function state.
10569   if (Body) {
10570     // C++ constructors that have function-try-blocks can't have return
10571     // statements in the handlers of that block. (C++ [except.handle]p14)
10572     // Verify this.
10573     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
10574       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
10575 
10576     // Verify that gotos and switch cases don't jump into scopes illegally.
10577     if (getCurFunction()->NeedsScopeChecking() &&
10578         !PP.isCodeCompletionEnabled())
10579       DiagnoseInvalidJumps(Body);
10580 
10581     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
10582       if (!Destructor->getParent()->isDependentType())
10583         CheckDestructor(Destructor);
10584 
10585       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10586                                              Destructor->getParent());
10587     }
10588 
10589     // If any errors have occurred, clear out any temporaries that may have
10590     // been leftover. This ensures that these temporaries won't be picked up for
10591     // deletion in some later function.
10592     if (getDiagnostics().hasErrorOccurred() ||
10593         getDiagnostics().getSuppressAllDiagnostics()) {
10594       DiscardCleanupsInEvaluationContext();
10595     }
10596     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
10597         !isa<FunctionTemplateDecl>(dcl)) {
10598       // Since the body is valid, issue any analysis-based warnings that are
10599       // enabled.
10600       ActivePolicy = &WP;
10601     }
10602 
10603     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10604         (!CheckConstexprFunctionDecl(FD) ||
10605          !CheckConstexprFunctionBody(FD, Body)))
10606       FD->setInvalidDecl();
10607 
10608     if (FD && FD->hasAttr<NakedAttr>()) {
10609       for (const Stmt *S : Body->children()) {
10610         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
10611           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
10612           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
10613           FD->setInvalidDecl();
10614           break;
10615         }
10616       }
10617     }
10618 
10619     assert(ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
10620            && "Leftover temporaries in function");
10621     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
10622     assert(MaybeODRUseExprs.empty() &&
10623            "Leftover expressions for odr-use checking");
10624   }
10625 
10626   if (!IsInstantiation)
10627     PopDeclContext();
10628 
10629   PopFunctionScopeInfo(ActivePolicy, dcl);
10630   // If any errors have occurred, clear out any temporaries that may have
10631   // been leftover. This ensures that these temporaries won't be picked up for
10632   // deletion in some later function.
10633   if (getDiagnostics().hasErrorOccurred()) {
10634     DiscardCleanupsInEvaluationContext();
10635   }
10636 
10637   return dcl;
10638 }
10639 
10640 
10641 /// When we finish delayed parsing of an attribute, we must attach it to the
10642 /// relevant Decl.
10643 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
10644                                        ParsedAttributes &Attrs) {
10645   // Always attach attributes to the underlying decl.
10646   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
10647     D = TD->getTemplatedDecl();
10648   ProcessDeclAttributeList(S, D, Attrs.getList());
10649 
10650   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
10651     if (Method->isStatic())
10652       checkThisInStaticMemberFunctionAttributes(Method);
10653 }
10654 
10655 
10656 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
10657 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
10658 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
10659                                           IdentifierInfo &II, Scope *S) {
10660   // Before we produce a declaration for an implicitly defined
10661   // function, see whether there was a locally-scoped declaration of
10662   // this name as a function or variable. If so, use that
10663   // (non-visible) declaration, and complain about it.
10664   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
10665     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
10666     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
10667     return ExternCPrev;
10668   }
10669 
10670   // Extension in C99.  Legal in C90, but warn about it.
10671   unsigned diag_id;
10672   if (II.getName().startswith("__builtin_"))
10673     diag_id = diag::warn_builtin_unknown;
10674   else if (getLangOpts().C99)
10675     diag_id = diag::ext_implicit_function_decl;
10676   else
10677     diag_id = diag::warn_implicit_function_decl;
10678   Diag(Loc, diag_id) << &II;
10679 
10680   // Because typo correction is expensive, only do it if the implicit
10681   // function declaration is going to be treated as an error.
10682   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
10683     TypoCorrection Corrected;
10684     if (S &&
10685         (Corrected = CorrectTypo(
10686              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
10687              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
10688       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
10689                    /*ErrorRecovery*/false);
10690   }
10691 
10692   // Set a Declarator for the implicit definition: int foo();
10693   const char *Dummy;
10694   AttributeFactory attrFactory;
10695   DeclSpec DS(attrFactory);
10696   unsigned DiagID;
10697   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
10698                                   Context.getPrintingPolicy());
10699   (void)Error; // Silence warning.
10700   assert(!Error && "Error setting up implicit decl!");
10701   SourceLocation NoLoc;
10702   Declarator D(DS, Declarator::BlockContext);
10703   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
10704                                              /*IsAmbiguous=*/false,
10705                                              /*LParenLoc=*/NoLoc,
10706                                              /*Params=*/nullptr,
10707                                              /*NumParams=*/0,
10708                                              /*EllipsisLoc=*/NoLoc,
10709                                              /*RParenLoc=*/NoLoc,
10710                                              /*TypeQuals=*/0,
10711                                              /*RefQualifierIsLvalueRef=*/true,
10712                                              /*RefQualifierLoc=*/NoLoc,
10713                                              /*ConstQualifierLoc=*/NoLoc,
10714                                              /*VolatileQualifierLoc=*/NoLoc,
10715                                              /*RestrictQualifierLoc=*/NoLoc,
10716                                              /*MutableLoc=*/NoLoc,
10717                                              EST_None,
10718                                              /*ESpecLoc=*/NoLoc,
10719                                              /*Exceptions=*/nullptr,
10720                                              /*ExceptionRanges=*/nullptr,
10721                                              /*NumExceptions=*/0,
10722                                              /*NoexceptExpr=*/nullptr,
10723                                              /*ExceptionSpecTokens=*/nullptr,
10724                                              Loc, Loc, D),
10725                 DS.getAttributes(),
10726                 SourceLocation());
10727   D.SetIdentifier(&II, Loc);
10728 
10729   // Insert this function into translation-unit scope.
10730 
10731   DeclContext *PrevDC = CurContext;
10732   CurContext = Context.getTranslationUnitDecl();
10733 
10734   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
10735   FD->setImplicit();
10736 
10737   CurContext = PrevDC;
10738 
10739   AddKnownFunctionAttributes(FD);
10740 
10741   return FD;
10742 }
10743 
10744 /// \brief Adds any function attributes that we know a priori based on
10745 /// the declaration of this function.
10746 ///
10747 /// These attributes can apply both to implicitly-declared builtins
10748 /// (like __builtin___printf_chk) or to library-declared functions
10749 /// like NSLog or printf.
10750 ///
10751 /// We need to check for duplicate attributes both here and where user-written
10752 /// attributes are applied to declarations.
10753 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10754   if (FD->isInvalidDecl())
10755     return;
10756 
10757   // If this is a built-in function, map its builtin attributes to
10758   // actual attributes.
10759   if (unsigned BuiltinID = FD->getBuiltinID()) {
10760     // Handle printf-formatting attributes.
10761     unsigned FormatIdx;
10762     bool HasVAListArg;
10763     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
10764       if (!FD->hasAttr<FormatAttr>()) {
10765         const char *fmt = "printf";
10766         unsigned int NumParams = FD->getNumParams();
10767         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10768             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10769           fmt = "NSString";
10770         FD->addAttr(FormatAttr::CreateImplicit(Context,
10771                                                &Context.Idents.get(fmt),
10772                                                FormatIdx+1,
10773                                                HasVAListArg ? 0 : FormatIdx+2,
10774                                                FD->getLocation()));
10775       }
10776     }
10777     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10778                                              HasVAListArg)) {
10779      if (!FD->hasAttr<FormatAttr>())
10780        FD->addAttr(FormatAttr::CreateImplicit(Context,
10781                                               &Context.Idents.get("scanf"),
10782                                               FormatIdx+1,
10783                                               HasVAListArg ? 0 : FormatIdx+2,
10784                                               FD->getLocation()));
10785     }
10786 
10787     // Mark const if we don't care about errno and that is the only
10788     // thing preventing the function from being const. This allows
10789     // IRgen to use LLVM intrinsics for such functions.
10790     if (!getLangOpts().MathErrno &&
10791         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
10792       if (!FD->hasAttr<ConstAttr>())
10793         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10794     }
10795 
10796     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10797         !FD->hasAttr<ReturnsTwiceAttr>())
10798       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10799                                          FD->getLocation()));
10800     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
10801       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
10802     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
10803       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10804   }
10805 
10806   IdentifierInfo *Name = FD->getIdentifier();
10807   if (!Name)
10808     return;
10809   if ((!getLangOpts().CPlusPlus &&
10810        FD->getDeclContext()->isTranslationUnit()) ||
10811       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
10812        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
10813        LinkageSpecDecl::lang_c)) {
10814     // Okay: this could be a libc/libm/Objective-C function we know
10815     // about.
10816   } else
10817     return;
10818 
10819   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
10820     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
10821     // target-specific builtins, perhaps?
10822     if (!FD->hasAttr<FormatAttr>())
10823       FD->addAttr(FormatAttr::CreateImplicit(Context,
10824                                              &Context.Idents.get("printf"), 2,
10825                                              Name->isStr("vasprintf") ? 0 : 3,
10826                                              FD->getLocation()));
10827   }
10828 
10829   if (Name->isStr("__CFStringMakeConstantString")) {
10830     // We already have a __builtin___CFStringMakeConstantString,
10831     // but builds that use -fno-constant-cfstrings don't go through that.
10832     if (!FD->hasAttr<FormatArgAttr>())
10833       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10834                                                 FD->getLocation()));
10835   }
10836 }
10837 
10838 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
10839                                     TypeSourceInfo *TInfo) {
10840   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
10841   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
10842 
10843   if (!TInfo) {
10844     assert(D.isInvalidType() && "no declarator info for valid type");
10845     TInfo = Context.getTrivialTypeSourceInfo(T);
10846   }
10847 
10848   // Scope manipulation handled by caller.
10849   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
10850                                            D.getLocStart(),
10851                                            D.getIdentifierLoc(),
10852                                            D.getIdentifier(),
10853                                            TInfo);
10854 
10855   // Bail out immediately if we have an invalid declaration.
10856   if (D.isInvalidType()) {
10857     NewTD->setInvalidDecl();
10858     return NewTD;
10859   }
10860 
10861   if (D.getDeclSpec().isModulePrivateSpecified()) {
10862     if (CurContext->isFunctionOrMethod())
10863       Diag(NewTD->getLocation(), diag::err_module_private_local)
10864         << 2 << NewTD->getDeclName()
10865         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10866         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10867     else
10868       NewTD->setModulePrivate();
10869   }
10870 
10871   // C++ [dcl.typedef]p8:
10872   //   If the typedef declaration defines an unnamed class (or
10873   //   enum), the first typedef-name declared by the declaration
10874   //   to be that class type (or enum type) is used to denote the
10875   //   class type (or enum type) for linkage purposes only.
10876   // We need to check whether the type was declared in the declaration.
10877   switch (D.getDeclSpec().getTypeSpecType()) {
10878   case TST_enum:
10879   case TST_struct:
10880   case TST_interface:
10881   case TST_union:
10882   case TST_class: {
10883     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10884 
10885     // Do nothing if the tag is not anonymous or already has an
10886     // associated typedef (from an earlier typedef in this decl group).
10887     if (tagFromDeclSpec->getIdentifier()) break;
10888     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
10889 
10890     // A well-formed anonymous tag must always be a TUK_Definition.
10891     assert(tagFromDeclSpec->isThisDeclarationADefinition());
10892 
10893     // The type must match the tag exactly;  no qualifiers allowed.
10894     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10895       break;
10896 
10897     // If we've already computed linkage for the anonymous tag, then
10898     // adding a typedef name for the anonymous decl can change that
10899     // linkage, which might be a serious problem.  Diagnose this as
10900     // unsupported and ignore the typedef name.  TODO: we should
10901     // pursue this as a language defect and establish a formal rule
10902     // for how to handle it.
10903     if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10904       Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10905 
10906       SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
10907       tagLoc = getLocForEndOfToken(tagLoc);
10908 
10909       llvm::SmallString<40> textToInsert;
10910       textToInsert += ' ';
10911       textToInsert += D.getIdentifier()->getName();
10912       Diag(tagLoc, diag::note_typedef_changes_linkage)
10913         << FixItHint::CreateInsertion(tagLoc, textToInsert);
10914       break;
10915     }
10916 
10917     // Otherwise, set this is the anon-decl typedef for the tag.
10918     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
10919     break;
10920   }
10921 
10922   default:
10923     break;
10924   }
10925 
10926   return NewTD;
10927 }
10928 
10929 
10930 /// \brief Check that this is a valid underlying type for an enum declaration.
10931 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10932   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10933   QualType T = TI->getType();
10934 
10935   if (T->isDependentType())
10936     return false;
10937 
10938   if (const BuiltinType *BT = T->getAs<BuiltinType>())
10939     if (BT->isInteger())
10940       return false;
10941 
10942   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10943   return true;
10944 }
10945 
10946 /// Check whether this is a valid redeclaration of a previous enumeration.
10947 /// \return true if the redeclaration was invalid.
10948 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10949                                   QualType EnumUnderlyingTy,
10950                                   const EnumDecl *Prev) {
10951   bool IsFixed = !EnumUnderlyingTy.isNull();
10952 
10953   if (IsScoped != Prev->isScoped()) {
10954     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10955       << Prev->isScoped();
10956     Diag(Prev->getLocation(), diag::note_previous_declaration);
10957     return true;
10958   }
10959 
10960   if (IsFixed && Prev->isFixed()) {
10961     if (!EnumUnderlyingTy->isDependentType() &&
10962         !Prev->getIntegerType()->isDependentType() &&
10963         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
10964                                         Prev->getIntegerType())) {
10965       // TODO: Highlight the underlying type of the redeclaration.
10966       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10967         << EnumUnderlyingTy << Prev->getIntegerType();
10968       Diag(Prev->getLocation(), diag::note_previous_declaration)
10969           << Prev->getIntegerTypeRange();
10970       return true;
10971     }
10972   } else if (IsFixed != Prev->isFixed()) {
10973     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10974       << Prev->isFixed();
10975     Diag(Prev->getLocation(), diag::note_previous_declaration);
10976     return true;
10977   }
10978 
10979   return false;
10980 }
10981 
10982 /// \brief Get diagnostic %select index for tag kind for
10983 /// redeclaration diagnostic message.
10984 /// WARNING: Indexes apply to particular diagnostics only!
10985 ///
10986 /// \returns diagnostic %select index.
10987 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
10988   switch (Tag) {
10989   case TTK_Struct: return 0;
10990   case TTK_Interface: return 1;
10991   case TTK_Class:  return 2;
10992   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
10993   }
10994 }
10995 
10996 /// \brief Determine if tag kind is a class-key compatible with
10997 /// class for redeclaration (class, struct, or __interface).
10998 ///
10999 /// \returns true iff the tag kind is compatible.
11000 static bool isClassCompatTagKind(TagTypeKind Tag)
11001 {
11002   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11003 }
11004 
11005 /// \brief Determine whether a tag with a given kind is acceptable
11006 /// as a redeclaration of the given tag declaration.
11007 ///
11008 /// \returns true if the new tag kind is acceptable, false otherwise.
11009 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11010                                         TagTypeKind NewTag, bool isDefinition,
11011                                         SourceLocation NewTagLoc,
11012                                         const IdentifierInfo &Name) {
11013   // C++ [dcl.type.elab]p3:
11014   //   The class-key or enum keyword present in the
11015   //   elaborated-type-specifier shall agree in kind with the
11016   //   declaration to which the name in the elaborated-type-specifier
11017   //   refers. This rule also applies to the form of
11018   //   elaborated-type-specifier that declares a class-name or
11019   //   friend class since it can be construed as referring to the
11020   //   definition of the class. Thus, in any
11021   //   elaborated-type-specifier, the enum keyword shall be used to
11022   //   refer to an enumeration (7.2), the union class-key shall be
11023   //   used to refer to a union (clause 9), and either the class or
11024   //   struct class-key shall be used to refer to a class (clause 9)
11025   //   declared using the class or struct class-key.
11026   TagTypeKind OldTag = Previous->getTagKind();
11027   if (!isDefinition || !isClassCompatTagKind(NewTag))
11028     if (OldTag == NewTag)
11029       return true;
11030 
11031   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11032     // Warn about the struct/class tag mismatch.
11033     bool isTemplate = false;
11034     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11035       isTemplate = Record->getDescribedClassTemplate();
11036 
11037     if (!ActiveTemplateInstantiations.empty()) {
11038       // In a template instantiation, do not offer fix-its for tag mismatches
11039       // since they usually mess up the template instead of fixing the problem.
11040       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11041         << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11042         << getRedeclDiagFromTagKind(OldTag);
11043       return true;
11044     }
11045 
11046     if (isDefinition) {
11047       // On definitions, check previous tags and issue a fix-it for each
11048       // one that doesn't match the current tag.
11049       if (Previous->getDefinition()) {
11050         // Don't suggest fix-its for redefinitions.
11051         return true;
11052       }
11053 
11054       bool previousMismatch = false;
11055       for (auto I : Previous->redecls()) {
11056         if (I->getTagKind() != NewTag) {
11057           if (!previousMismatch) {
11058             previousMismatch = true;
11059             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11060               << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11061               << getRedeclDiagFromTagKind(I->getTagKind());
11062           }
11063           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11064             << getRedeclDiagFromTagKind(NewTag)
11065             << FixItHint::CreateReplacement(I->getInnerLocStart(),
11066                  TypeWithKeyword::getTagTypeKindName(NewTag));
11067         }
11068       }
11069       return true;
11070     }
11071 
11072     // Check for a previous definition.  If current tag and definition
11073     // are same type, do nothing.  If no definition, but disagree with
11074     // with previous tag type, give a warning, but no fix-it.
11075     const TagDecl *Redecl = Previous->getDefinition() ?
11076                             Previous->getDefinition() : Previous;
11077     if (Redecl->getTagKind() == NewTag) {
11078       return true;
11079     }
11080 
11081     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11082       << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11083       << getRedeclDiagFromTagKind(OldTag);
11084     Diag(Redecl->getLocation(), diag::note_previous_use);
11085 
11086     // If there is a previous definition, suggest a fix-it.
11087     if (Previous->getDefinition()) {
11088         Diag(NewTagLoc, diag::note_struct_class_suggestion)
11089           << getRedeclDiagFromTagKind(Redecl->getTagKind())
11090           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11091                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11092     }
11093 
11094     return true;
11095   }
11096   return false;
11097 }
11098 
11099 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11100 /// from an outer enclosing namespace or file scope inside a friend declaration.
11101 /// This should provide the commented out code in the following snippet:
11102 ///   namespace N {
11103 ///     struct X;
11104 ///     namespace M {
11105 ///       struct Y { friend struct /*N::*/ X; };
11106 ///     }
11107 ///   }
11108 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11109                                          SourceLocation NameLoc) {
11110   // While the decl is in a namespace, do repeated lookup of that name and see
11111   // if we get the same namespace back.  If we do not, continue until
11112   // translation unit scope, at which point we have a fully qualified NNS.
11113   SmallVector<IdentifierInfo *, 4> Namespaces;
11114   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11115   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11116     // This tag should be declared in a namespace, which can only be enclosed by
11117     // other namespaces.  Bail if there's an anonymous namespace in the chain.
11118     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11119     if (!Namespace || Namespace->isAnonymousNamespace())
11120       return FixItHint();
11121     IdentifierInfo *II = Namespace->getIdentifier();
11122     Namespaces.push_back(II);
11123     NamedDecl *Lookup = SemaRef.LookupSingleName(
11124         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11125     if (Lookup == Namespace)
11126       break;
11127   }
11128 
11129   // Once we have all the namespaces, reverse them to go outermost first, and
11130   // build an NNS.
11131   SmallString<64> Insertion;
11132   llvm::raw_svector_ostream OS(Insertion);
11133   if (DC->isTranslationUnit())
11134     OS << "::";
11135   std::reverse(Namespaces.begin(), Namespaces.end());
11136   for (auto *II : Namespaces)
11137     OS << II->getName() << "::";
11138   OS.flush();
11139   return FixItHint::CreateInsertion(NameLoc, Insertion);
11140 }
11141 
11142 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
11143 /// former case, Name will be non-null.  In the later case, Name will be null.
11144 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11145 /// reference/declaration/definition of a tag.
11146 ///
11147 /// IsTypeSpecifier is true if this is a type-specifier (or
11148 /// trailing-type-specifier) other than one in an alias-declaration.
11149 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11150                      SourceLocation KWLoc, CXXScopeSpec &SS,
11151                      IdentifierInfo *Name, SourceLocation NameLoc,
11152                      AttributeList *Attr, AccessSpecifier AS,
11153                      SourceLocation ModulePrivateLoc,
11154                      MultiTemplateParamsArg TemplateParameterLists,
11155                      bool &OwnedDecl, bool &IsDependent,
11156                      SourceLocation ScopedEnumKWLoc,
11157                      bool ScopedEnumUsesClassTag,
11158                      TypeResult UnderlyingType,
11159                      bool IsTypeSpecifier) {
11160   // If this is not a definition, it must have a name.
11161   IdentifierInfo *OrigName = Name;
11162   assert((Name != nullptr || TUK == TUK_Definition) &&
11163          "Nameless record must be a definition!");
11164   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11165 
11166   OwnedDecl = false;
11167   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11168   bool ScopedEnum = ScopedEnumKWLoc.isValid();
11169 
11170   // FIXME: Check explicit specializations more carefully.
11171   bool isExplicitSpecialization = false;
11172   bool Invalid = false;
11173 
11174   // We only need to do this matching if we have template parameters
11175   // or a scope specifier, which also conveniently avoids this work
11176   // for non-C++ cases.
11177   if (TemplateParameterLists.size() > 0 ||
11178       (SS.isNotEmpty() && TUK != TUK_Reference)) {
11179     if (TemplateParameterList *TemplateParams =
11180             MatchTemplateParametersToScopeSpecifier(
11181                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11182                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11183       if (Kind == TTK_Enum) {
11184         Diag(KWLoc, diag::err_enum_template);
11185         return nullptr;
11186       }
11187 
11188       if (TemplateParams->size() > 0) {
11189         // This is a declaration or definition of a class template (which may
11190         // be a member of another template).
11191 
11192         if (Invalid)
11193           return nullptr;
11194 
11195         OwnedDecl = false;
11196         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11197                                                SS, Name, NameLoc, Attr,
11198                                                TemplateParams, AS,
11199                                                ModulePrivateLoc,
11200                                                /*FriendLoc*/SourceLocation(),
11201                                                TemplateParameterLists.size()-1,
11202                                                TemplateParameterLists.data());
11203         return Result.get();
11204       } else {
11205         // The "template<>" header is extraneous.
11206         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11207           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11208         isExplicitSpecialization = true;
11209       }
11210     }
11211   }
11212 
11213   // Figure out the underlying type if this a enum declaration. We need to do
11214   // this early, because it's needed to detect if this is an incompatible
11215   // redeclaration.
11216   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11217 
11218   if (Kind == TTK_Enum) {
11219     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11220       // No underlying type explicitly specified, or we failed to parse the
11221       // type, default to int.
11222       EnumUnderlying = Context.IntTy.getTypePtr();
11223     else if (UnderlyingType.get()) {
11224       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11225       // integral type; any cv-qualification is ignored.
11226       TypeSourceInfo *TI = nullptr;
11227       GetTypeFromParser(UnderlyingType.get(), &TI);
11228       EnumUnderlying = TI;
11229 
11230       if (CheckEnumUnderlyingType(TI))
11231         // Recover by falling back to int.
11232         EnumUnderlying = Context.IntTy.getTypePtr();
11233 
11234       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11235                                           UPPC_FixedUnderlyingType))
11236         EnumUnderlying = Context.IntTy.getTypePtr();
11237 
11238     } else if (getLangOpts().MSVCCompat)
11239       // Microsoft enums are always of int type.
11240       EnumUnderlying = Context.IntTy.getTypePtr();
11241   }
11242 
11243   DeclContext *SearchDC = CurContext;
11244   DeclContext *DC = CurContext;
11245   bool isStdBadAlloc = false;
11246 
11247   RedeclarationKind Redecl = ForRedeclaration;
11248   if (TUK == TUK_Friend || TUK == TUK_Reference)
11249     Redecl = NotForRedeclaration;
11250 
11251   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11252   if (Name && SS.isNotEmpty()) {
11253     // We have a nested-name tag ('struct foo::bar').
11254 
11255     // Check for invalid 'foo::'.
11256     if (SS.isInvalid()) {
11257       Name = nullptr;
11258       goto CreateNewDecl;
11259     }
11260 
11261     // If this is a friend or a reference to a class in a dependent
11262     // context, don't try to make a decl for it.
11263     if (TUK == TUK_Friend || TUK == TUK_Reference) {
11264       DC = computeDeclContext(SS, false);
11265       if (!DC) {
11266         IsDependent = true;
11267         return nullptr;
11268       }
11269     } else {
11270       DC = computeDeclContext(SS, true);
11271       if (!DC) {
11272         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11273           << SS.getRange();
11274         return nullptr;
11275       }
11276     }
11277 
11278     if (RequireCompleteDeclContext(SS, DC))
11279       return nullptr;
11280 
11281     SearchDC = DC;
11282     // Look-up name inside 'foo::'.
11283     LookupQualifiedName(Previous, DC);
11284 
11285     if (Previous.isAmbiguous())
11286       return nullptr;
11287 
11288     if (Previous.empty()) {
11289       // Name lookup did not find anything. However, if the
11290       // nested-name-specifier refers to the current instantiation,
11291       // and that current instantiation has any dependent base
11292       // classes, we might find something at instantiation time: treat
11293       // this as a dependent elaborated-type-specifier.
11294       // But this only makes any sense for reference-like lookups.
11295       if (Previous.wasNotFoundInCurrentInstantiation() &&
11296           (TUK == TUK_Reference || TUK == TUK_Friend)) {
11297         IsDependent = true;
11298         return nullptr;
11299       }
11300 
11301       // A tag 'foo::bar' must already exist.
11302       Diag(NameLoc, diag::err_not_tag_in_scope)
11303         << Kind << Name << DC << SS.getRange();
11304       Name = nullptr;
11305       Invalid = true;
11306       goto CreateNewDecl;
11307     }
11308   } else if (Name) {
11309     // If this is a named struct, check to see if there was a previous forward
11310     // declaration or definition.
11311     // FIXME: We're looking into outer scopes here, even when we
11312     // shouldn't be. Doing so can result in ambiguities that we
11313     // shouldn't be diagnosing.
11314     LookupName(Previous, S);
11315 
11316     // When declaring or defining a tag, ignore ambiguities introduced
11317     // by types using'ed into this scope.
11318     if (Previous.isAmbiguous() &&
11319         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
11320       LookupResult::Filter F = Previous.makeFilter();
11321       while (F.hasNext()) {
11322         NamedDecl *ND = F.next();
11323         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
11324           F.erase();
11325       }
11326       F.done();
11327     }
11328 
11329     // C++11 [namespace.memdef]p3:
11330     //   If the name in a friend declaration is neither qualified nor
11331     //   a template-id and the declaration is a function or an
11332     //   elaborated-type-specifier, the lookup to determine whether
11333     //   the entity has been previously declared shall not consider
11334     //   any scopes outside the innermost enclosing namespace.
11335     //
11336     // MSVC doesn't implement the above rule for types, so a friend tag
11337     // declaration may be a redeclaration of a type declared in an enclosing
11338     // scope.  They do implement this rule for friend functions.
11339     //
11340     // Does it matter that this should be by scope instead of by
11341     // semantic context?
11342     if (!Previous.empty() && TUK == TUK_Friend) {
11343       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
11344       LookupResult::Filter F = Previous.makeFilter();
11345       bool FriendSawTagOutsideEnclosingNamespace = false;
11346       while (F.hasNext()) {
11347         NamedDecl *ND = F.next();
11348         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11349         if (DC->isFileContext() &&
11350             !EnclosingNS->Encloses(ND->getDeclContext())) {
11351           if (getLangOpts().MSVCCompat)
11352             FriendSawTagOutsideEnclosingNamespace = true;
11353           else
11354             F.erase();
11355         }
11356       }
11357       F.done();
11358 
11359       // Diagnose this MSVC extension in the easy case where lookup would have
11360       // unambiguously found something outside the enclosing namespace.
11361       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
11362         NamedDecl *ND = Previous.getFoundDecl();
11363         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
11364             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
11365       }
11366     }
11367 
11368     // Note:  there used to be some attempt at recovery here.
11369     if (Previous.isAmbiguous())
11370       return nullptr;
11371 
11372     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
11373       // FIXME: This makes sure that we ignore the contexts associated
11374       // with C structs, unions, and enums when looking for a matching
11375       // tag declaration or definition. See the similar lookup tweak
11376       // in Sema::LookupName; is there a better way to deal with this?
11377       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
11378         SearchDC = SearchDC->getParent();
11379     }
11380   }
11381 
11382   if (Previous.isSingleResult() &&
11383       Previous.getFoundDecl()->isTemplateParameter()) {
11384     // Maybe we will complain about the shadowed template parameter.
11385     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
11386     // Just pretend that we didn't see the previous declaration.
11387     Previous.clear();
11388   }
11389 
11390   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
11391       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
11392     // This is a declaration of or a reference to "std::bad_alloc".
11393     isStdBadAlloc = true;
11394 
11395     if (Previous.empty() && StdBadAlloc) {
11396       // std::bad_alloc has been implicitly declared (but made invisible to
11397       // name lookup). Fill in this implicit declaration as the previous
11398       // declaration, so that the declarations get chained appropriately.
11399       Previous.addDecl(getStdBadAlloc());
11400     }
11401   }
11402 
11403   // If we didn't find a previous declaration, and this is a reference
11404   // (or friend reference), move to the correct scope.  In C++, we
11405   // also need to do a redeclaration lookup there, just in case
11406   // there's a shadow friend decl.
11407   if (Name && Previous.empty() &&
11408       (TUK == TUK_Reference || TUK == TUK_Friend)) {
11409     if (Invalid) goto CreateNewDecl;
11410     assert(SS.isEmpty());
11411 
11412     if (TUK == TUK_Reference) {
11413       // C++ [basic.scope.pdecl]p5:
11414       //   -- for an elaborated-type-specifier of the form
11415       //
11416       //          class-key identifier
11417       //
11418       //      if the elaborated-type-specifier is used in the
11419       //      decl-specifier-seq or parameter-declaration-clause of a
11420       //      function defined in namespace scope, the identifier is
11421       //      declared as a class-name in the namespace that contains
11422       //      the declaration; otherwise, except as a friend
11423       //      declaration, the identifier is declared in the smallest
11424       //      non-class, non-function-prototype scope that contains the
11425       //      declaration.
11426       //
11427       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
11428       // C structs and unions.
11429       //
11430       // It is an error in C++ to declare (rather than define) an enum
11431       // type, including via an elaborated type specifier.  We'll
11432       // diagnose that later; for now, declare the enum in the same
11433       // scope as we would have picked for any other tag type.
11434       //
11435       // GNU C also supports this behavior as part of its incomplete
11436       // enum types extension, while GNU C++ does not.
11437       //
11438       // Find the context where we'll be declaring the tag.
11439       // FIXME: We would like to maintain the current DeclContext as the
11440       // lexical context,
11441       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
11442         SearchDC = SearchDC->getParent();
11443 
11444       // Find the scope where we'll be declaring the tag.
11445       while (S->isClassScope() ||
11446              (getLangOpts().CPlusPlus &&
11447               S->isFunctionPrototypeScope()) ||
11448              ((S->getFlags() & Scope::DeclScope) == 0) ||
11449              (S->getEntity() && S->getEntity()->isTransparentContext()))
11450         S = S->getParent();
11451     } else {
11452       assert(TUK == TUK_Friend);
11453       // C++ [namespace.memdef]p3:
11454       //   If a friend declaration in a non-local class first declares a
11455       //   class or function, the friend class or function is a member of
11456       //   the innermost enclosing namespace.
11457       SearchDC = SearchDC->getEnclosingNamespaceContext();
11458     }
11459 
11460     // In C++, we need to do a redeclaration lookup to properly
11461     // diagnose some problems.
11462     if (getLangOpts().CPlusPlus) {
11463       Previous.setRedeclarationKind(ForRedeclaration);
11464       LookupQualifiedName(Previous, SearchDC);
11465     }
11466   }
11467 
11468   if (!Previous.empty()) {
11469     NamedDecl *PrevDecl = Previous.getFoundDecl();
11470     NamedDecl *DirectPrevDecl =
11471         getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
11472 
11473     // It's okay to have a tag decl in the same scope as a typedef
11474     // which hides a tag decl in the same scope.  Finding this
11475     // insanity with a redeclaration lookup can only actually happen
11476     // in C++.
11477     //
11478     // This is also okay for elaborated-type-specifiers, which is
11479     // technically forbidden by the current standard but which is
11480     // okay according to the likely resolution of an open issue;
11481     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
11482     if (getLangOpts().CPlusPlus) {
11483       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11484         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
11485           TagDecl *Tag = TT->getDecl();
11486           if (Tag->getDeclName() == Name &&
11487               Tag->getDeclContext()->getRedeclContext()
11488                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
11489             PrevDecl = Tag;
11490             Previous.clear();
11491             Previous.addDecl(Tag);
11492             Previous.resolveKind();
11493           }
11494         }
11495       }
11496     }
11497 
11498     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
11499       // If this is a use of a previous tag, or if the tag is already declared
11500       // in the same scope (so that the definition/declaration completes or
11501       // rementions the tag), reuse the decl.
11502       if (TUK == TUK_Reference || TUK == TUK_Friend ||
11503           isDeclInScope(DirectPrevDecl, SearchDC, S,
11504                         SS.isNotEmpty() || isExplicitSpecialization)) {
11505         // Make sure that this wasn't declared as an enum and now used as a
11506         // struct or something similar.
11507         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
11508                                           TUK == TUK_Definition, KWLoc,
11509                                           *Name)) {
11510           bool SafeToContinue
11511             = (PrevTagDecl->getTagKind() != TTK_Enum &&
11512                Kind != TTK_Enum);
11513           if (SafeToContinue)
11514             Diag(KWLoc, diag::err_use_with_wrong_tag)
11515               << Name
11516               << FixItHint::CreateReplacement(SourceRange(KWLoc),
11517                                               PrevTagDecl->getKindName());
11518           else
11519             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
11520           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
11521 
11522           if (SafeToContinue)
11523             Kind = PrevTagDecl->getTagKind();
11524           else {
11525             // Recover by making this an anonymous redefinition.
11526             Name = nullptr;
11527             Previous.clear();
11528             Invalid = true;
11529           }
11530         }
11531 
11532         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
11533           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
11534 
11535           // If this is an elaborated-type-specifier for a scoped enumeration,
11536           // the 'class' keyword is not necessary and not permitted.
11537           if (TUK == TUK_Reference || TUK == TUK_Friend) {
11538             if (ScopedEnum)
11539               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
11540                 << PrevEnum->isScoped()
11541                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
11542             return PrevTagDecl;
11543           }
11544 
11545           QualType EnumUnderlyingTy;
11546           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11547             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
11548           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
11549             EnumUnderlyingTy = QualType(T, 0);
11550 
11551           // All conflicts with previous declarations are recovered by
11552           // returning the previous declaration, unless this is a definition,
11553           // in which case we want the caller to bail out.
11554           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
11555                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
11556             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
11557         }
11558 
11559         // C++11 [class.mem]p1:
11560         //   A member shall not be declared twice in the member-specification,
11561         //   except that a nested class or member class template can be declared
11562         //   and then later defined.
11563         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
11564             S->isDeclScope(PrevDecl)) {
11565           Diag(NameLoc, diag::ext_member_redeclared);
11566           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
11567         }
11568 
11569         if (!Invalid) {
11570           // If this is a use, just return the declaration we found, unless
11571           // we have attributes.
11572 
11573           // FIXME: In the future, return a variant or some other clue
11574           // for the consumer of this Decl to know it doesn't own it.
11575           // For our current ASTs this shouldn't be a problem, but will
11576           // need to be changed with DeclGroups.
11577           if (!Attr &&
11578               ((TUK == TUK_Reference &&
11579                 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
11580                || TUK == TUK_Friend))
11581             return PrevTagDecl;
11582 
11583           // Diagnose attempts to redefine a tag.
11584           if (TUK == TUK_Definition) {
11585             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
11586               // If we're defining a specialization and the previous definition
11587               // is from an implicit instantiation, don't emit an error
11588               // here; we'll catch this in the general case below.
11589               bool IsExplicitSpecializationAfterInstantiation = false;
11590               if (isExplicitSpecialization) {
11591                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
11592                   IsExplicitSpecializationAfterInstantiation =
11593                     RD->getTemplateSpecializationKind() !=
11594                     TSK_ExplicitSpecialization;
11595                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
11596                   IsExplicitSpecializationAfterInstantiation =
11597                     ED->getTemplateSpecializationKind() !=
11598                     TSK_ExplicitSpecialization;
11599               }
11600 
11601               if (!IsExplicitSpecializationAfterInstantiation) {
11602                 // A redeclaration in function prototype scope in C isn't
11603                 // visible elsewhere, so merely issue a warning.
11604                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
11605                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
11606                 else
11607                   Diag(NameLoc, diag::err_redefinition) << Name;
11608                 Diag(Def->getLocation(), diag::note_previous_definition);
11609                 // If this is a redefinition, recover by making this
11610                 // struct be anonymous, which will make any later
11611                 // references get the previous definition.
11612                 Name = nullptr;
11613                 Previous.clear();
11614                 Invalid = true;
11615               }
11616             } else {
11617               // If the type is currently being defined, complain
11618               // about a nested redefinition.
11619               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
11620               if (TD->isBeingDefined()) {
11621                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
11622                 Diag(PrevTagDecl->getLocation(),
11623                      diag::note_previous_definition);
11624                 Name = nullptr;
11625                 Previous.clear();
11626                 Invalid = true;
11627               }
11628             }
11629 
11630             // Okay, this is definition of a previously declared or referenced
11631             // tag. We're going to create a new Decl for it.
11632           }
11633 
11634           // Okay, we're going to make a redeclaration.  If this is some kind
11635           // of reference, make sure we build the redeclaration in the same DC
11636           // as the original, and ignore the current access specifier.
11637           if (TUK == TUK_Friend || TUK == TUK_Reference) {
11638             SearchDC = PrevTagDecl->getDeclContext();
11639             AS = AS_none;
11640           }
11641         }
11642         // If we get here we have (another) forward declaration or we
11643         // have a definition.  Just create a new decl.
11644 
11645       } else {
11646         // If we get here, this is a definition of a new tag type in a nested
11647         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
11648         // new decl/type.  We set PrevDecl to NULL so that the entities
11649         // have distinct types.
11650         Previous.clear();
11651       }
11652       // If we get here, we're going to create a new Decl. If PrevDecl
11653       // is non-NULL, it's a definition of the tag declared by
11654       // PrevDecl. If it's NULL, we have a new definition.
11655 
11656 
11657     // Otherwise, PrevDecl is not a tag, but was found with tag
11658     // lookup.  This is only actually possible in C++, where a few
11659     // things like templates still live in the tag namespace.
11660     } else {
11661       // Use a better diagnostic if an elaborated-type-specifier
11662       // found the wrong kind of type on the first
11663       // (non-redeclaration) lookup.
11664       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
11665           !Previous.isForRedeclaration()) {
11666         unsigned Kind = 0;
11667         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11668         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11669         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11670         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
11671         Diag(PrevDecl->getLocation(), diag::note_declared_at);
11672         Invalid = true;
11673 
11674       // Otherwise, only diagnose if the declaration is in scope.
11675       } else if (!isDeclInScope(PrevDecl, SearchDC, S,
11676                                 SS.isNotEmpty() || isExplicitSpecialization)) {
11677         // do nothing
11678 
11679       // Diagnose implicit declarations introduced by elaborated types.
11680       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
11681         unsigned Kind = 0;
11682         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11683         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11684         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11685         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
11686         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11687         Invalid = true;
11688 
11689       // Otherwise it's a declaration.  Call out a particularly common
11690       // case here.
11691       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11692         unsigned Kind = 0;
11693         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
11694         Diag(NameLoc, diag::err_tag_definition_of_typedef)
11695           << Name << Kind << TND->getUnderlyingType();
11696         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11697         Invalid = true;
11698 
11699       // Otherwise, diagnose.
11700       } else {
11701         // The tag name clashes with something else in the target scope,
11702         // issue an error and recover by making this tag be anonymous.
11703         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
11704         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11705         Name = nullptr;
11706         Invalid = true;
11707       }
11708 
11709       // The existing declaration isn't relevant to us; we're in a
11710       // new scope, so clear out the previous declaration.
11711       Previous.clear();
11712     }
11713   }
11714 
11715 CreateNewDecl:
11716 
11717   TagDecl *PrevDecl = nullptr;
11718   if (Previous.isSingleResult())
11719     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
11720 
11721   // If there is an identifier, use the location of the identifier as the
11722   // location of the decl, otherwise use the location of the struct/union
11723   // keyword.
11724   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
11725 
11726   // Otherwise, create a new declaration. If there is a previous
11727   // declaration of the same entity, the two will be linked via
11728   // PrevDecl.
11729   TagDecl *New;
11730 
11731   bool IsForwardReference = false;
11732   if (Kind == TTK_Enum) {
11733     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11734     // enum X { A, B, C } D;    D should chain to X.
11735     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
11736                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
11737                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
11738     // If this is an undefined enum, warn.
11739     if (TUK != TUK_Definition && !Invalid) {
11740       TagDecl *Def;
11741       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
11742           cast<EnumDecl>(New)->isFixed()) {
11743         // C++0x: 7.2p2: opaque-enum-declaration.
11744         // Conflicts are diagnosed above. Do nothing.
11745       }
11746       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
11747         Diag(Loc, diag::ext_forward_ref_enum_def)
11748           << New;
11749         Diag(Def->getLocation(), diag::note_previous_definition);
11750       } else {
11751         unsigned DiagID = diag::ext_forward_ref_enum;
11752         if (getLangOpts().MSVCCompat)
11753           DiagID = diag::ext_ms_forward_ref_enum;
11754         else if (getLangOpts().CPlusPlus)
11755           DiagID = diag::err_forward_ref_enum;
11756         Diag(Loc, DiagID);
11757 
11758         // If this is a forward-declared reference to an enumeration, make a
11759         // note of it; we won't actually be introducing the declaration into
11760         // the declaration context.
11761         if (TUK == TUK_Reference)
11762           IsForwardReference = true;
11763       }
11764     }
11765 
11766     if (EnumUnderlying) {
11767       EnumDecl *ED = cast<EnumDecl>(New);
11768       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11769         ED->setIntegerTypeSourceInfo(TI);
11770       else
11771         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
11772       ED->setPromotionType(ED->getIntegerType());
11773     }
11774 
11775   } else {
11776     // struct/union/class
11777 
11778     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11779     // struct X { int A; } D;    D should chain to X.
11780     if (getLangOpts().CPlusPlus) {
11781       // FIXME: Look for a way to use RecordDecl for simple structs.
11782       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11783                                   cast_or_null<CXXRecordDecl>(PrevDecl));
11784 
11785       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
11786         StdBadAlloc = cast<CXXRecordDecl>(New);
11787     } else
11788       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11789                                cast_or_null<RecordDecl>(PrevDecl));
11790   }
11791 
11792   // C++11 [dcl.type]p3:
11793   //   A type-specifier-seq shall not define a class or enumeration [...].
11794   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11795     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11796       << Context.getTagDeclType(New);
11797     Invalid = true;
11798   }
11799 
11800   // Maybe add qualifier info.
11801   if (SS.isNotEmpty()) {
11802     if (SS.isSet()) {
11803       // If this is either a declaration or a definition, check the
11804       // nested-name-specifier against the current context. We don't do this
11805       // for explicit specializations, because they have similar checking
11806       // (with more specific diagnostics) in the call to
11807       // CheckMemberSpecialization, below.
11808       if (!isExplicitSpecialization &&
11809           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11810           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
11811         Invalid = true;
11812 
11813       New->setQualifierInfo(SS.getWithLocInContext(Context));
11814       if (TemplateParameterLists.size() > 0) {
11815         New->setTemplateParameterListsInfo(Context,
11816                                            TemplateParameterLists.size(),
11817                                            TemplateParameterLists.data());
11818       }
11819     }
11820     else
11821       Invalid = true;
11822   }
11823 
11824   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11825     // Add alignment attributes if necessary; these attributes are checked when
11826     // the ASTContext lays out the structure.
11827     //
11828     // It is important for implementing the correct semantics that this
11829     // happen here (in act on tag decl). The #pragma pack stack is
11830     // maintained as a result of parser callbacks which can occur at
11831     // many points during the parsing of a struct declaration (because
11832     // the #pragma tokens are effectively skipped over during the
11833     // parsing of the struct).
11834     if (TUK == TUK_Definition) {
11835       AddAlignmentAttributesForRecord(RD);
11836       AddMsStructLayoutForRecord(RD);
11837     }
11838   }
11839 
11840   if (ModulePrivateLoc.isValid()) {
11841     if (isExplicitSpecialization)
11842       Diag(New->getLocation(), diag::err_module_private_specialization)
11843         << 2
11844         << FixItHint::CreateRemoval(ModulePrivateLoc);
11845     // __module_private__ does not apply to local classes. However, we only
11846     // diagnose this as an error when the declaration specifiers are
11847     // freestanding. Here, we just ignore the __module_private__.
11848     else if (!SearchDC->isFunctionOrMethod())
11849       New->setModulePrivate();
11850   }
11851 
11852   // If this is a specialization of a member class (of a class template),
11853   // check the specialization.
11854   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
11855     Invalid = true;
11856 
11857   // If we're declaring or defining a tag in function prototype scope in C,
11858   // note that this type can only be used within the function and add it to
11859   // the list of decls to inject into the function definition scope.
11860   if ((Name || Kind == TTK_Enum) &&
11861       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
11862     if (getLangOpts().CPlusPlus) {
11863       // C++ [dcl.fct]p6:
11864       //   Types shall not be defined in return or parameter types.
11865       if (TUK == TUK_Definition && !IsTypeSpecifier) {
11866         Diag(Loc, diag::err_type_defined_in_param_type)
11867             << Name;
11868         Invalid = true;
11869       }
11870     } else {
11871       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11872     }
11873     DeclsInPrototypeScope.push_back(New);
11874   }
11875 
11876   if (Invalid)
11877     New->setInvalidDecl();
11878 
11879   if (Attr)
11880     ProcessDeclAttributeList(S, New, Attr);
11881 
11882   // Set the lexical context. If the tag has a C++ scope specifier, the
11883   // lexical context will be different from the semantic context.
11884   New->setLexicalDeclContext(CurContext);
11885 
11886   // Mark this as a friend decl if applicable.
11887   // In Microsoft mode, a friend declaration also acts as a forward
11888   // declaration so we always pass true to setObjectOfFriendDecl to make
11889   // the tag name visible.
11890   if (TUK == TUK_Friend)
11891     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
11892 
11893   // Set the access specifier.
11894   if (!Invalid && SearchDC->isRecord())
11895     SetMemberAccessSpecifier(New, PrevDecl, AS);
11896 
11897   if (TUK == TUK_Definition)
11898     New->startDefinition();
11899 
11900   // If this has an identifier, add it to the scope stack.
11901   if (TUK == TUK_Friend) {
11902     // We might be replacing an existing declaration in the lookup tables;
11903     // if so, borrow its access specifier.
11904     if (PrevDecl)
11905       New->setAccess(PrevDecl->getAccess());
11906 
11907     DeclContext *DC = New->getDeclContext()->getRedeclContext();
11908     DC->makeDeclVisibleInContext(New);
11909     if (Name) // can be null along some error paths
11910       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11911         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
11912   } else if (Name) {
11913     S = getNonFieldDeclScope(S);
11914     PushOnScopeChains(New, S, !IsForwardReference);
11915     if (IsForwardReference)
11916       SearchDC->makeDeclVisibleInContext(New);
11917 
11918   } else {
11919     CurContext->addDecl(New);
11920   }
11921 
11922   // If this is the C FILE type, notify the AST context.
11923   if (IdentifierInfo *II = New->getIdentifier())
11924     if (!New->isInvalidDecl() &&
11925         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
11926         II->isStr("FILE"))
11927       Context.setFILEDecl(New);
11928 
11929   if (PrevDecl)
11930     mergeDeclAttributes(New, PrevDecl);
11931 
11932   // If there's a #pragma GCC visibility in scope, set the visibility of this
11933   // record.
11934   AddPushedVisibilityAttribute(New);
11935 
11936   OwnedDecl = true;
11937   // In C++, don't return an invalid declaration. We can't recover well from
11938   // the cases where we make the type anonymous.
11939   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
11940 }
11941 
11942 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
11943   AdjustDeclIfTemplate(TagD);
11944   TagDecl *Tag = cast<TagDecl>(TagD);
11945 
11946   // Enter the tag context.
11947   PushDeclContext(S, Tag);
11948 
11949   ActOnDocumentableDecl(TagD);
11950 
11951   // If there's a #pragma GCC visibility in scope, set the visibility of this
11952   // record.
11953   AddPushedVisibilityAttribute(Tag);
11954 }
11955 
11956 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
11957   assert(isa<ObjCContainerDecl>(IDecl) &&
11958          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11959   DeclContext *OCD = cast<DeclContext>(IDecl);
11960   assert(getContainingDC(OCD) == CurContext &&
11961       "The next DeclContext should be lexically contained in the current one.");
11962   CurContext = OCD;
11963   return IDecl;
11964 }
11965 
11966 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
11967                                            SourceLocation FinalLoc,
11968                                            bool IsFinalSpelledSealed,
11969                                            SourceLocation LBraceLoc) {
11970   AdjustDeclIfTemplate(TagD);
11971   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
11972 
11973   FieldCollector->StartClass();
11974 
11975   if (!Record->getIdentifier())
11976     return;
11977 
11978   if (FinalLoc.isValid())
11979     Record->addAttr(new (Context)
11980                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11981 
11982   // C++ [class]p2:
11983   //   [...] The class-name is also inserted into the scope of the
11984   //   class itself; this is known as the injected-class-name. For
11985   //   purposes of access checking, the injected-class-name is treated
11986   //   as if it were a public member name.
11987   CXXRecordDecl *InjectedClassName
11988     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11989                             Record->getLocStart(), Record->getLocation(),
11990                             Record->getIdentifier(),
11991                             /*PrevDecl=*/nullptr,
11992                             /*DelayTypeCreation=*/true);
11993   Context.getTypeDeclType(InjectedClassName, Record);
11994   InjectedClassName->setImplicit();
11995   InjectedClassName->setAccess(AS_public);
11996   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11997       InjectedClassName->setDescribedClassTemplate(Template);
11998   PushOnScopeChains(InjectedClassName, S);
11999   assert(InjectedClassName->isInjectedClassName() &&
12000          "Broken injected-class-name");
12001 }
12002 
12003 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
12004                                     SourceLocation RBraceLoc) {
12005   AdjustDeclIfTemplate(TagD);
12006   TagDecl *Tag = cast<TagDecl>(TagD);
12007   Tag->setRBraceLoc(RBraceLoc);
12008 
12009   // Make sure we "complete" the definition even it is invalid.
12010   if (Tag->isBeingDefined()) {
12011     assert(Tag->isInvalidDecl() && "We should already have completed it");
12012     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12013       RD->completeDefinition();
12014   }
12015 
12016   if (isa<CXXRecordDecl>(Tag))
12017     FieldCollector->FinishClass();
12018 
12019   // Exit this scope of this tag's definition.
12020   PopDeclContext();
12021 
12022   if (getCurLexicalContext()->isObjCContainer() &&
12023       Tag->getDeclContext()->isFileContext())
12024     Tag->setTopLevelDeclInObjCContainer();
12025 
12026   // Notify the consumer that we've defined a tag.
12027   if (!Tag->isInvalidDecl())
12028     Consumer.HandleTagDeclDefinition(Tag);
12029 }
12030 
12031 void Sema::ActOnObjCContainerFinishDefinition() {
12032   // Exit this scope of this interface definition.
12033   PopDeclContext();
12034 }
12035 
12036 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12037   assert(DC == CurContext && "Mismatch of container contexts");
12038   OriginalLexicalContext = DC;
12039   ActOnObjCContainerFinishDefinition();
12040 }
12041 
12042 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12043   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12044   OriginalLexicalContext = nullptr;
12045 }
12046 
12047 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12048   AdjustDeclIfTemplate(TagD);
12049   TagDecl *Tag = cast<TagDecl>(TagD);
12050   Tag->setInvalidDecl();
12051 
12052   // Make sure we "complete" the definition even it is invalid.
12053   if (Tag->isBeingDefined()) {
12054     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12055       RD->completeDefinition();
12056   }
12057 
12058   // We're undoing ActOnTagStartDefinition here, not
12059   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12060   // the FieldCollector.
12061 
12062   PopDeclContext();
12063 }
12064 
12065 // Note that FieldName may be null for anonymous bitfields.
12066 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12067                                 IdentifierInfo *FieldName,
12068                                 QualType FieldTy, bool IsMsStruct,
12069                                 Expr *BitWidth, bool *ZeroWidth) {
12070   // Default to true; that shouldn't confuse checks for emptiness
12071   if (ZeroWidth)
12072     *ZeroWidth = true;
12073 
12074   // C99 6.7.2.1p4 - verify the field type.
12075   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12076   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12077     // Handle incomplete types with specific error.
12078     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12079       return ExprError();
12080     if (FieldName)
12081       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12082         << FieldName << FieldTy << BitWidth->getSourceRange();
12083     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12084       << FieldTy << BitWidth->getSourceRange();
12085   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12086                                              UPPC_BitFieldWidth))
12087     return ExprError();
12088 
12089   // If the bit-width is type- or value-dependent, don't try to check
12090   // it now.
12091   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12092     return BitWidth;
12093 
12094   llvm::APSInt Value;
12095   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12096   if (ICE.isInvalid())
12097     return ICE;
12098   BitWidth = ICE.get();
12099 
12100   if (Value != 0 && ZeroWidth)
12101     *ZeroWidth = false;
12102 
12103   // Zero-width bitfield is ok for anonymous field.
12104   if (Value == 0 && FieldName)
12105     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12106 
12107   if (Value.isSigned() && Value.isNegative()) {
12108     if (FieldName)
12109       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12110                << FieldName << Value.toString(10);
12111     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12112       << Value.toString(10);
12113   }
12114 
12115   if (!FieldTy->isDependentType()) {
12116     uint64_t TypeSize = Context.getTypeSize(FieldTy);
12117     if (Value.getZExtValue() > TypeSize) {
12118       if (!getLangOpts().CPlusPlus || IsMsStruct ||
12119           Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12120         if (FieldName)
12121           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
12122             << FieldName << (unsigned)Value.getZExtValue()
12123             << (unsigned)TypeSize;
12124 
12125         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
12126           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12127       }
12128 
12129       if (FieldName)
12130         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
12131           << FieldName << (unsigned)Value.getZExtValue()
12132           << (unsigned)TypeSize;
12133       else
12134         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
12135           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12136     }
12137   }
12138 
12139   return BitWidth;
12140 }
12141 
12142 /// ActOnField - Each field of a C struct/union is passed into this in order
12143 /// to create a FieldDecl object for it.
12144 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
12145                        Declarator &D, Expr *BitfieldWidth) {
12146   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12147                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12148                                /*InitStyle=*/ICIS_NoInit, AS_public);
12149   return Res;
12150 }
12151 
12152 /// HandleField - Analyze a field of a C struct or a C++ data member.
12153 ///
12154 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12155                              SourceLocation DeclStart,
12156                              Declarator &D, Expr *BitWidth,
12157                              InClassInitStyle InitStyle,
12158                              AccessSpecifier AS) {
12159   IdentifierInfo *II = D.getIdentifier();
12160   SourceLocation Loc = DeclStart;
12161   if (II) Loc = D.getIdentifierLoc();
12162 
12163   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12164   QualType T = TInfo->getType();
12165   if (getLangOpts().CPlusPlus) {
12166     CheckExtraCXXDefaultArguments(D);
12167 
12168     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12169                                         UPPC_DataMemberType)) {
12170       D.setInvalidType();
12171       T = Context.IntTy;
12172       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12173     }
12174   }
12175 
12176   // TR 18037 does not allow fields to be declared with address spaces.
12177   if (T.getQualifiers().hasAddressSpace()) {
12178     Diag(Loc, diag::err_field_with_address_space);
12179     D.setInvalidType();
12180   }
12181 
12182   // OpenCL 1.2 spec, s6.9 r:
12183   // The event type cannot be used to declare a structure or union field.
12184   if (LangOpts.OpenCL && T->isEventT()) {
12185     Diag(Loc, diag::err_event_t_struct_field);
12186     D.setInvalidType();
12187   }
12188 
12189   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12190 
12191   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12192     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12193          diag::err_invalid_thread)
12194       << DeclSpec::getSpecifierName(TSCS);
12195 
12196   // Check to see if this name was declared as a member previously
12197   NamedDecl *PrevDecl = nullptr;
12198   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12199   LookupName(Previous, S);
12200   switch (Previous.getResultKind()) {
12201     case LookupResult::Found:
12202     case LookupResult::FoundUnresolvedValue:
12203       PrevDecl = Previous.getAsSingle<NamedDecl>();
12204       break;
12205 
12206     case LookupResult::FoundOverloaded:
12207       PrevDecl = Previous.getRepresentativeDecl();
12208       break;
12209 
12210     case LookupResult::NotFound:
12211     case LookupResult::NotFoundInCurrentInstantiation:
12212     case LookupResult::Ambiguous:
12213       break;
12214   }
12215   Previous.suppressDiagnostics();
12216 
12217   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12218     // Maybe we will complain about the shadowed template parameter.
12219     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12220     // Just pretend that we didn't see the previous declaration.
12221     PrevDecl = nullptr;
12222   }
12223 
12224   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12225     PrevDecl = nullptr;
12226 
12227   bool Mutable
12228     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
12229   SourceLocation TSSL = D.getLocStart();
12230   FieldDecl *NewFD
12231     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
12232                      TSSL, AS, PrevDecl, &D);
12233 
12234   if (NewFD->isInvalidDecl())
12235     Record->setInvalidDecl();
12236 
12237   if (D.getDeclSpec().isModulePrivateSpecified())
12238     NewFD->setModulePrivate();
12239 
12240   if (NewFD->isInvalidDecl() && PrevDecl) {
12241     // Don't introduce NewFD into scope; there's already something
12242     // with the same name in the same scope.
12243   } else if (II) {
12244     PushOnScopeChains(NewFD, S);
12245   } else
12246     Record->addDecl(NewFD);
12247 
12248   return NewFD;
12249 }
12250 
12251 /// \brief Build a new FieldDecl and check its well-formedness.
12252 ///
12253 /// This routine builds a new FieldDecl given the fields name, type,
12254 /// record, etc. \p PrevDecl should refer to any previous declaration
12255 /// with the same name and in the same scope as the field to be
12256 /// created.
12257 ///
12258 /// \returns a new FieldDecl.
12259 ///
12260 /// \todo The Declarator argument is a hack. It will be removed once
12261 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
12262                                 TypeSourceInfo *TInfo,
12263                                 RecordDecl *Record, SourceLocation Loc,
12264                                 bool Mutable, Expr *BitWidth,
12265                                 InClassInitStyle InitStyle,
12266                                 SourceLocation TSSL,
12267                                 AccessSpecifier AS, NamedDecl *PrevDecl,
12268                                 Declarator *D) {
12269   IdentifierInfo *II = Name.getAsIdentifierInfo();
12270   bool InvalidDecl = false;
12271   if (D) InvalidDecl = D->isInvalidType();
12272 
12273   // If we receive a broken type, recover by assuming 'int' and
12274   // marking this declaration as invalid.
12275   if (T.isNull()) {
12276     InvalidDecl = true;
12277     T = Context.IntTy;
12278   }
12279 
12280   QualType EltTy = Context.getBaseElementType(T);
12281   if (!EltTy->isDependentType()) {
12282     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
12283       // Fields of incomplete type force their record to be invalid.
12284       Record->setInvalidDecl();
12285       InvalidDecl = true;
12286     } else {
12287       NamedDecl *Def;
12288       EltTy->isIncompleteType(&Def);
12289       if (Def && Def->isInvalidDecl()) {
12290         Record->setInvalidDecl();
12291         InvalidDecl = true;
12292       }
12293     }
12294   }
12295 
12296   // OpenCL v1.2 s6.9.c: bitfields are not supported.
12297   if (BitWidth && getLangOpts().OpenCL) {
12298     Diag(Loc, diag::err_opencl_bitfields);
12299     InvalidDecl = true;
12300   }
12301 
12302   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12303   // than a variably modified type.
12304   if (!InvalidDecl && T->isVariablyModifiedType()) {
12305     bool SizeIsNegative;
12306     llvm::APSInt Oversized;
12307 
12308     TypeSourceInfo *FixedTInfo =
12309       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
12310                                                     SizeIsNegative,
12311                                                     Oversized);
12312     if (FixedTInfo) {
12313       Diag(Loc, diag::warn_illegal_constant_array_size);
12314       TInfo = FixedTInfo;
12315       T = FixedTInfo->getType();
12316     } else {
12317       if (SizeIsNegative)
12318         Diag(Loc, diag::err_typecheck_negative_array_size);
12319       else if (Oversized.getBoolValue())
12320         Diag(Loc, diag::err_array_too_large)
12321           << Oversized.toString(10);
12322       else
12323         Diag(Loc, diag::err_typecheck_field_variable_size);
12324       InvalidDecl = true;
12325     }
12326   }
12327 
12328   // Fields can not have abstract class types
12329   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
12330                                              diag::err_abstract_type_in_decl,
12331                                              AbstractFieldType))
12332     InvalidDecl = true;
12333 
12334   bool ZeroWidth = false;
12335   // If this is declared as a bit-field, check the bit-field.
12336   if (!InvalidDecl && BitWidth) {
12337     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
12338                               &ZeroWidth).get();
12339     if (!BitWidth) {
12340       InvalidDecl = true;
12341       BitWidth = nullptr;
12342       ZeroWidth = false;
12343     }
12344   }
12345 
12346   // Check that 'mutable' is consistent with the type of the declaration.
12347   if (!InvalidDecl && Mutable) {
12348     unsigned DiagID = 0;
12349     if (T->isReferenceType())
12350       DiagID = diag::err_mutable_reference;
12351     else if (T.isConstQualified())
12352       DiagID = diag::err_mutable_const;
12353 
12354     if (DiagID) {
12355       SourceLocation ErrLoc = Loc;
12356       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
12357         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
12358       Diag(ErrLoc, DiagID);
12359       Mutable = false;
12360       InvalidDecl = true;
12361     }
12362   }
12363 
12364   // C++11 [class.union]p8 (DR1460):
12365   //   At most one variant member of a union may have a
12366   //   brace-or-equal-initializer.
12367   if (InitStyle != ICIS_NoInit)
12368     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
12369 
12370   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
12371                                        BitWidth, Mutable, InitStyle);
12372   if (InvalidDecl)
12373     NewFD->setInvalidDecl();
12374 
12375   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
12376     Diag(Loc, diag::err_duplicate_member) << II;
12377     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12378     NewFD->setInvalidDecl();
12379   }
12380 
12381   if (!InvalidDecl && getLangOpts().CPlusPlus) {
12382     if (Record->isUnion()) {
12383       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12384         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
12385         if (RDecl->getDefinition()) {
12386           // C++ [class.union]p1: An object of a class with a non-trivial
12387           // constructor, a non-trivial copy constructor, a non-trivial
12388           // destructor, or a non-trivial copy assignment operator
12389           // cannot be a member of a union, nor can an array of such
12390           // objects.
12391           if (CheckNontrivialField(NewFD))
12392             NewFD->setInvalidDecl();
12393         }
12394       }
12395 
12396       // C++ [class.union]p1: If a union contains a member of reference type,
12397       // the program is ill-formed, except when compiling with MSVC extensions
12398       // enabled.
12399       if (EltTy->isReferenceType()) {
12400         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
12401                                     diag::ext_union_member_of_reference_type :
12402                                     diag::err_union_member_of_reference_type)
12403           << NewFD->getDeclName() << EltTy;
12404         if (!getLangOpts().MicrosoftExt)
12405           NewFD->setInvalidDecl();
12406       }
12407     }
12408   }
12409 
12410   // FIXME: We need to pass in the attributes given an AST
12411   // representation, not a parser representation.
12412   if (D) {
12413     // FIXME: The current scope is almost... but not entirely... correct here.
12414     ProcessDeclAttributes(getCurScope(), NewFD, *D);
12415 
12416     if (NewFD->hasAttrs())
12417       CheckAlignasUnderalignment(NewFD);
12418   }
12419 
12420   // In auto-retain/release, infer strong retension for fields of
12421   // retainable type.
12422   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
12423     NewFD->setInvalidDecl();
12424 
12425   if (T.isObjCGCWeak())
12426     Diag(Loc, diag::warn_attribute_weak_on_field);
12427 
12428   NewFD->setAccess(AS);
12429   return NewFD;
12430 }
12431 
12432 bool Sema::CheckNontrivialField(FieldDecl *FD) {
12433   assert(FD);
12434   assert(getLangOpts().CPlusPlus && "valid check only for C++");
12435 
12436   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
12437     return false;
12438 
12439   QualType EltTy = Context.getBaseElementType(FD->getType());
12440   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12441     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
12442     if (RDecl->getDefinition()) {
12443       // We check for copy constructors before constructors
12444       // because otherwise we'll never get complaints about
12445       // copy constructors.
12446 
12447       CXXSpecialMember member = CXXInvalid;
12448       // We're required to check for any non-trivial constructors. Since the
12449       // implicit default constructor is suppressed if there are any
12450       // user-declared constructors, we just need to check that there is a
12451       // trivial default constructor and a trivial copy constructor. (We don't
12452       // worry about move constructors here, since this is a C++98 check.)
12453       if (RDecl->hasNonTrivialCopyConstructor())
12454         member = CXXCopyConstructor;
12455       else if (!RDecl->hasTrivialDefaultConstructor())
12456         member = CXXDefaultConstructor;
12457       else if (RDecl->hasNonTrivialCopyAssignment())
12458         member = CXXCopyAssignment;
12459       else if (RDecl->hasNonTrivialDestructor())
12460         member = CXXDestructor;
12461 
12462       if (member != CXXInvalid) {
12463         if (!getLangOpts().CPlusPlus11 &&
12464             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
12465           // Objective-C++ ARC: it is an error to have a non-trivial field of
12466           // a union. However, system headers in Objective-C programs
12467           // occasionally have Objective-C lifetime objects within unions,
12468           // and rather than cause the program to fail, we make those
12469           // members unavailable.
12470           SourceLocation Loc = FD->getLocation();
12471           if (getSourceManager().isInSystemHeader(Loc)) {
12472             if (!FD->hasAttr<UnavailableAttr>())
12473               FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12474                                   "this system field has retaining ownership",
12475                                   Loc));
12476             return false;
12477           }
12478         }
12479 
12480         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
12481                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
12482                diag::err_illegal_union_or_anon_struct_member)
12483           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
12484         DiagnoseNontrivial(RDecl, member);
12485         return !getLangOpts().CPlusPlus11;
12486       }
12487     }
12488   }
12489 
12490   return false;
12491 }
12492 
12493 /// TranslateIvarVisibility - Translate visibility from a token ID to an
12494 ///  AST enum value.
12495 static ObjCIvarDecl::AccessControl
12496 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
12497   switch (ivarVisibility) {
12498   default: llvm_unreachable("Unknown visitibility kind");
12499   case tok::objc_private: return ObjCIvarDecl::Private;
12500   case tok::objc_public: return ObjCIvarDecl::Public;
12501   case tok::objc_protected: return ObjCIvarDecl::Protected;
12502   case tok::objc_package: return ObjCIvarDecl::Package;
12503   }
12504 }
12505 
12506 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
12507 /// in order to create an IvarDecl object for it.
12508 Decl *Sema::ActOnIvar(Scope *S,
12509                                 SourceLocation DeclStart,
12510                                 Declarator &D, Expr *BitfieldWidth,
12511                                 tok::ObjCKeywordKind Visibility) {
12512 
12513   IdentifierInfo *II = D.getIdentifier();
12514   Expr *BitWidth = (Expr*)BitfieldWidth;
12515   SourceLocation Loc = DeclStart;
12516   if (II) Loc = D.getIdentifierLoc();
12517 
12518   // FIXME: Unnamed fields can be handled in various different ways, for
12519   // example, unnamed unions inject all members into the struct namespace!
12520 
12521   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12522   QualType T = TInfo->getType();
12523 
12524   if (BitWidth) {
12525     // 6.7.2.1p3, 6.7.2.1p4
12526     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
12527     if (!BitWidth)
12528       D.setInvalidType();
12529   } else {
12530     // Not a bitfield.
12531 
12532     // validate II.
12533 
12534   }
12535   if (T->isReferenceType()) {
12536     Diag(Loc, diag::err_ivar_reference_type);
12537     D.setInvalidType();
12538   }
12539   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12540   // than a variably modified type.
12541   else if (T->isVariablyModifiedType()) {
12542     Diag(Loc, diag::err_typecheck_ivar_variable_size);
12543     D.setInvalidType();
12544   }
12545 
12546   // Get the visibility (access control) for this ivar.
12547   ObjCIvarDecl::AccessControl ac =
12548     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
12549                                         : ObjCIvarDecl::None;
12550   // Must set ivar's DeclContext to its enclosing interface.
12551   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
12552   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
12553     return nullptr;
12554   ObjCContainerDecl *EnclosingContext;
12555   if (ObjCImplementationDecl *IMPDecl =
12556       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12557     if (LangOpts.ObjCRuntime.isFragile()) {
12558     // Case of ivar declared in an implementation. Context is that of its class.
12559       EnclosingContext = IMPDecl->getClassInterface();
12560       assert(EnclosingContext && "Implementation has no class interface!");
12561     }
12562     else
12563       EnclosingContext = EnclosingDecl;
12564   } else {
12565     if (ObjCCategoryDecl *CDecl =
12566         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12567       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
12568         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
12569         return nullptr;
12570       }
12571     }
12572     EnclosingContext = EnclosingDecl;
12573   }
12574 
12575   // Construct the decl.
12576   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
12577                                              DeclStart, Loc, II, T,
12578                                              TInfo, ac, (Expr *)BitfieldWidth);
12579 
12580   if (II) {
12581     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
12582                                            ForRedeclaration);
12583     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
12584         && !isa<TagDecl>(PrevDecl)) {
12585       Diag(Loc, diag::err_duplicate_member) << II;
12586       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12587       NewID->setInvalidDecl();
12588     }
12589   }
12590 
12591   // Process attributes attached to the ivar.
12592   ProcessDeclAttributes(S, NewID, D);
12593 
12594   if (D.isInvalidType())
12595     NewID->setInvalidDecl();
12596 
12597   // In ARC, infer 'retaining' for ivars of retainable type.
12598   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
12599     NewID->setInvalidDecl();
12600 
12601   if (D.getDeclSpec().isModulePrivateSpecified())
12602     NewID->setModulePrivate();
12603 
12604   if (II) {
12605     // FIXME: When interfaces are DeclContexts, we'll need to add
12606     // these to the interface.
12607     S->AddDecl(NewID);
12608     IdResolver.AddDecl(NewID);
12609   }
12610 
12611   if (LangOpts.ObjCRuntime.isNonFragile() &&
12612       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
12613     Diag(Loc, diag::warn_ivars_in_interface);
12614 
12615   return NewID;
12616 }
12617 
12618 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
12619 /// class and class extensions. For every class \@interface and class
12620 /// extension \@interface, if the last ivar is a bitfield of any type,
12621 /// then add an implicit `char :0` ivar to the end of that interface.
12622 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
12623                              SmallVectorImpl<Decl *> &AllIvarDecls) {
12624   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
12625     return;
12626 
12627   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
12628   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
12629 
12630   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
12631     return;
12632   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
12633   if (!ID) {
12634     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
12635       if (!CD->IsClassExtension())
12636         return;
12637     }
12638     // No need to add this to end of @implementation.
12639     else
12640       return;
12641   }
12642   // All conditions are met. Add a new bitfield to the tail end of ivars.
12643   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
12644   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
12645 
12646   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
12647                               DeclLoc, DeclLoc, nullptr,
12648                               Context.CharTy,
12649                               Context.getTrivialTypeSourceInfo(Context.CharTy,
12650                                                                DeclLoc),
12651                               ObjCIvarDecl::Private, BW,
12652                               true);
12653   AllIvarDecls.push_back(Ivar);
12654 }
12655 
12656 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
12657                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
12658                        SourceLocation RBrac, AttributeList *Attr) {
12659   assert(EnclosingDecl && "missing record or interface decl");
12660 
12661   // If this is an Objective-C @implementation or category and we have
12662   // new fields here we should reset the layout of the interface since
12663   // it will now change.
12664   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
12665     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
12666     switch (DC->getKind()) {
12667     default: break;
12668     case Decl::ObjCCategory:
12669       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
12670       break;
12671     case Decl::ObjCImplementation:
12672       Context.
12673         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
12674       break;
12675     }
12676   }
12677 
12678   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
12679 
12680   // Start counting up the number of named members; make sure to include
12681   // members of anonymous structs and unions in the total.
12682   unsigned NumNamedMembers = 0;
12683   if (Record) {
12684     for (const auto *I : Record->decls()) {
12685       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
12686         if (IFD->getDeclName())
12687           ++NumNamedMembers;
12688     }
12689   }
12690 
12691   // Verify that all the fields are okay.
12692   SmallVector<FieldDecl*, 32> RecFields;
12693 
12694   bool ARCErrReported = false;
12695   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
12696        i != end; ++i) {
12697     FieldDecl *FD = cast<FieldDecl>(*i);
12698 
12699     // Get the type for the field.
12700     const Type *FDTy = FD->getType().getTypePtr();
12701 
12702     if (!FD->isAnonymousStructOrUnion()) {
12703       // Remember all fields written by the user.
12704       RecFields.push_back(FD);
12705     }
12706 
12707     // If the field is already invalid for some reason, don't emit more
12708     // diagnostics about it.
12709     if (FD->isInvalidDecl()) {
12710       EnclosingDecl->setInvalidDecl();
12711       continue;
12712     }
12713 
12714     // C99 6.7.2.1p2:
12715     //   A structure or union shall not contain a member with
12716     //   incomplete or function type (hence, a structure shall not
12717     //   contain an instance of itself, but may contain a pointer to
12718     //   an instance of itself), except that the last member of a
12719     //   structure with more than one named member may have incomplete
12720     //   array type; such a structure (and any union containing,
12721     //   possibly recursively, a member that is such a structure)
12722     //   shall not be a member of a structure or an element of an
12723     //   array.
12724     if (FDTy->isFunctionType()) {
12725       // Field declared as a function.
12726       Diag(FD->getLocation(), diag::err_field_declared_as_function)
12727         << FD->getDeclName();
12728       FD->setInvalidDecl();
12729       EnclosingDecl->setInvalidDecl();
12730       continue;
12731     } else if (FDTy->isIncompleteArrayType() && Record &&
12732                ((i + 1 == Fields.end() && !Record->isUnion()) ||
12733                 ((getLangOpts().MicrosoftExt ||
12734                   getLangOpts().CPlusPlus) &&
12735                  (i + 1 == Fields.end() || Record->isUnion())))) {
12736       // Flexible array member.
12737       // Microsoft and g++ is more permissive regarding flexible array.
12738       // It will accept flexible array in union and also
12739       // as the sole element of a struct/class.
12740       unsigned DiagID = 0;
12741       if (Record->isUnion())
12742         DiagID = getLangOpts().MicrosoftExt
12743                      ? diag::ext_flexible_array_union_ms
12744                      : getLangOpts().CPlusPlus
12745                            ? diag::ext_flexible_array_union_gnu
12746                            : diag::err_flexible_array_union;
12747       else if (Fields.size() == 1)
12748         DiagID = getLangOpts().MicrosoftExt
12749                      ? diag::ext_flexible_array_empty_aggregate_ms
12750                      : getLangOpts().CPlusPlus
12751                            ? diag::ext_flexible_array_empty_aggregate_gnu
12752                            : NumNamedMembers < 1
12753                                  ? diag::err_flexible_array_empty_aggregate
12754                                  : 0;
12755 
12756       if (DiagID)
12757         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
12758                                         << Record->getTagKind();
12759       // While the layout of types that contain virtual bases is not specified
12760       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
12761       // virtual bases after the derived members.  This would make a flexible
12762       // array member declared at the end of an object not adjacent to the end
12763       // of the type.
12764       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
12765         if (RD->getNumVBases() != 0)
12766           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
12767             << FD->getDeclName() << Record->getTagKind();
12768       if (!getLangOpts().C99)
12769         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
12770           << FD->getDeclName() << Record->getTagKind();
12771 
12772       // If the element type has a non-trivial destructor, we would not
12773       // implicitly destroy the elements, so disallow it for now.
12774       //
12775       // FIXME: GCC allows this. We should probably either implicitly delete
12776       // the destructor of the containing class, or just allow this.
12777       QualType BaseElem = Context.getBaseElementType(FD->getType());
12778       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
12779         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
12780           << FD->getDeclName() << FD->getType();
12781         FD->setInvalidDecl();
12782         EnclosingDecl->setInvalidDecl();
12783         continue;
12784       }
12785       // Okay, we have a legal flexible array member at the end of the struct.
12786       Record->setHasFlexibleArrayMember(true);
12787     } else if (!FDTy->isDependentType() &&
12788                RequireCompleteType(FD->getLocation(), FD->getType(),
12789                                    diag::err_field_incomplete)) {
12790       // Incomplete type
12791       FD->setInvalidDecl();
12792       EnclosingDecl->setInvalidDecl();
12793       continue;
12794     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
12795       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
12796         // A type which contains a flexible array member is considered to be a
12797         // flexible array member.
12798         Record->setHasFlexibleArrayMember(true);
12799         if (!Record->isUnion()) {
12800           // If this is a struct/class and this is not the last element, reject
12801           // it.  Note that GCC supports variable sized arrays in the middle of
12802           // structures.
12803           if (i + 1 != Fields.end())
12804             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
12805               << FD->getDeclName() << FD->getType();
12806           else {
12807             // We support flexible arrays at the end of structs in
12808             // other structs as an extension.
12809             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12810               << FD->getDeclName();
12811           }
12812         }
12813       }
12814       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12815           RequireNonAbstractType(FD->getLocation(), FD->getType(),
12816                                  diag::err_abstract_type_in_decl,
12817                                  AbstractIvarType)) {
12818         // Ivars can not have abstract class types
12819         FD->setInvalidDecl();
12820       }
12821       if (Record && FDTTy->getDecl()->hasObjectMember())
12822         Record->setHasObjectMember(true);
12823       if (Record && FDTTy->getDecl()->hasVolatileMember())
12824         Record->setHasVolatileMember(true);
12825     } else if (FDTy->isObjCObjectType()) {
12826       /// A field cannot be an Objective-c object
12827       Diag(FD->getLocation(), diag::err_statically_allocated_object)
12828         << FixItHint::CreateInsertion(FD->getLocation(), "*");
12829       QualType T = Context.getObjCObjectPointerType(FD->getType());
12830       FD->setType(T);
12831     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12832                (!getLangOpts().CPlusPlus || Record->isUnion())) {
12833       // It's an error in ARC if a field has lifetime.
12834       // We don't want to report this in a system header, though,
12835       // so we just make the field unavailable.
12836       // FIXME: that's really not sufficient; we need to make the type
12837       // itself invalid to, say, initialize or copy.
12838       QualType T = FD->getType();
12839       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12840       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12841         SourceLocation loc = FD->getLocation();
12842         if (getSourceManager().isInSystemHeader(loc)) {
12843           if (!FD->hasAttr<UnavailableAttr>()) {
12844             FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12845                               "this system field has retaining ownership",
12846                               loc));
12847           }
12848         } else {
12849           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
12850             << T->isBlockPointerType() << Record->getTagKind();
12851         }
12852         ARCErrReported = true;
12853       }
12854     } else if (getLangOpts().ObjC1 &&
12855                getLangOpts().getGC() != LangOptions::NonGC &&
12856                Record && !Record->hasObjectMember()) {
12857       if (FD->getType()->isObjCObjectPointerType() ||
12858           FD->getType().isObjCGCStrong())
12859         Record->setHasObjectMember(true);
12860       else if (Context.getAsArrayType(FD->getType())) {
12861         QualType BaseType = Context.getBaseElementType(FD->getType());
12862         if (BaseType->isRecordType() &&
12863             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
12864           Record->setHasObjectMember(true);
12865         else if (BaseType->isObjCObjectPointerType() ||
12866                  BaseType.isObjCGCStrong())
12867                Record->setHasObjectMember(true);
12868       }
12869     }
12870     if (Record && FD->getType().isVolatileQualified())
12871       Record->setHasVolatileMember(true);
12872     // Keep track of the number of named members.
12873     if (FD->getIdentifier())
12874       ++NumNamedMembers;
12875   }
12876 
12877   // Okay, we successfully defined 'Record'.
12878   if (Record) {
12879     bool Completed = false;
12880     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12881       if (!CXXRecord->isInvalidDecl()) {
12882         // Set access bits correctly on the directly-declared conversions.
12883         for (CXXRecordDecl::conversion_iterator
12884                I = CXXRecord->conversion_begin(),
12885                E = CXXRecord->conversion_end(); I != E; ++I)
12886           I.setAccess((*I)->getAccess());
12887 
12888         if (!CXXRecord->isDependentType()) {
12889           if (CXXRecord->hasUserDeclaredDestructor()) {
12890             // Adjust user-defined destructor exception spec.
12891             if (getLangOpts().CPlusPlus11)
12892               AdjustDestructorExceptionSpec(CXXRecord,
12893                                             CXXRecord->getDestructor());
12894           }
12895 
12896           // Add any implicitly-declared members to this class.
12897           AddImplicitlyDeclaredMembersToClass(CXXRecord);
12898 
12899           // If we have virtual base classes, we may end up finding multiple
12900           // final overriders for a given virtual function. Check for this
12901           // problem now.
12902           if (CXXRecord->getNumVBases()) {
12903             CXXFinalOverriderMap FinalOverriders;
12904             CXXRecord->getFinalOverriders(FinalOverriders);
12905 
12906             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12907                                              MEnd = FinalOverriders.end();
12908                  M != MEnd; ++M) {
12909               for (OverridingMethods::iterator SO = M->second.begin(),
12910                                             SOEnd = M->second.end();
12911                    SO != SOEnd; ++SO) {
12912                 assert(SO->second.size() > 0 &&
12913                        "Virtual function without overridding functions?");
12914                 if (SO->second.size() == 1)
12915                   continue;
12916 
12917                 // C++ [class.virtual]p2:
12918                 //   In a derived class, if a virtual member function of a base
12919                 //   class subobject has more than one final overrider the
12920                 //   program is ill-formed.
12921                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
12922                   << (const NamedDecl *)M->first << Record;
12923                 Diag(M->first->getLocation(),
12924                      diag::note_overridden_virtual_function);
12925                 for (OverridingMethods::overriding_iterator
12926                           OM = SO->second.begin(),
12927                        OMEnd = SO->second.end();
12928                      OM != OMEnd; ++OM)
12929                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
12930                     << (const NamedDecl *)M->first << OM->Method->getParent();
12931 
12932                 Record->setInvalidDecl();
12933               }
12934             }
12935             CXXRecord->completeDefinition(&FinalOverriders);
12936             Completed = true;
12937           }
12938         }
12939       }
12940     }
12941 
12942     if (!Completed)
12943       Record->completeDefinition();
12944 
12945     if (Record->hasAttrs()) {
12946       CheckAlignasUnderalignment(Record);
12947 
12948       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
12949         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
12950                                            IA->getRange(), IA->getBestCase(),
12951                                            IA->getSemanticSpelling());
12952     }
12953 
12954     // Check if the structure/union declaration is a type that can have zero
12955     // size in C. For C this is a language extension, for C++ it may cause
12956     // compatibility problems.
12957     bool CheckForZeroSize;
12958     if (!getLangOpts().CPlusPlus) {
12959       CheckForZeroSize = true;
12960     } else {
12961       // For C++ filter out types that cannot be referenced in C code.
12962       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12963       CheckForZeroSize =
12964           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12965           !CXXRecord->isDependentType() &&
12966           CXXRecord->isCLike();
12967     }
12968     if (CheckForZeroSize) {
12969       bool ZeroSize = true;
12970       bool IsEmpty = true;
12971       unsigned NonBitFields = 0;
12972       for (RecordDecl::field_iterator I = Record->field_begin(),
12973                                       E = Record->field_end();
12974            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12975         IsEmpty = false;
12976         if (I->isUnnamedBitfield()) {
12977           if (I->getBitWidthValue(Context) > 0)
12978             ZeroSize = false;
12979         } else {
12980           ++NonBitFields;
12981           QualType FieldType = I->getType();
12982           if (FieldType->isIncompleteType() ||
12983               !Context.getTypeSizeInChars(FieldType).isZero())
12984             ZeroSize = false;
12985         }
12986       }
12987 
12988       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12989       // allowed in C++, but warn if its declaration is inside
12990       // extern "C" block.
12991       if (ZeroSize) {
12992         Diag(RecLoc, getLangOpts().CPlusPlus ?
12993                          diag::warn_zero_size_struct_union_in_extern_c :
12994                          diag::warn_zero_size_struct_union_compat)
12995           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12996       }
12997 
12998       // Structs without named members are extension in C (C99 6.7.2.1p7),
12999       // but are accepted by GCC.
13000       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
13001         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
13002                                diag::ext_no_named_members_in_struct_union)
13003           << Record->isUnion();
13004       }
13005     }
13006   } else {
13007     ObjCIvarDecl **ClsFields =
13008       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
13009     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
13010       ID->setEndOfDefinitionLoc(RBrac);
13011       // Add ivar's to class's DeclContext.
13012       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13013         ClsFields[i]->setLexicalDeclContext(ID);
13014         ID->addDecl(ClsFields[i]);
13015       }
13016       // Must enforce the rule that ivars in the base classes may not be
13017       // duplicates.
13018       if (ID->getSuperClass())
13019         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13020     } else if (ObjCImplementationDecl *IMPDecl =
13021                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13022       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13023       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13024         // Ivar declared in @implementation never belongs to the implementation.
13025         // Only it is in implementation's lexical context.
13026         ClsFields[I]->setLexicalDeclContext(IMPDecl);
13027       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13028       IMPDecl->setIvarLBraceLoc(LBrac);
13029       IMPDecl->setIvarRBraceLoc(RBrac);
13030     } else if (ObjCCategoryDecl *CDecl =
13031                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13032       // case of ivars in class extension; all other cases have been
13033       // reported as errors elsewhere.
13034       // FIXME. Class extension does not have a LocEnd field.
13035       // CDecl->setLocEnd(RBrac);
13036       // Add ivar's to class extension's DeclContext.
13037       // Diagnose redeclaration of private ivars.
13038       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13039       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13040         if (IDecl) {
13041           if (const ObjCIvarDecl *ClsIvar =
13042               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13043             Diag(ClsFields[i]->getLocation(),
13044                  diag::err_duplicate_ivar_declaration);
13045             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13046             continue;
13047           }
13048           for (const auto *Ext : IDecl->known_extensions()) {
13049             if (const ObjCIvarDecl *ClsExtIvar
13050                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13051               Diag(ClsFields[i]->getLocation(),
13052                    diag::err_duplicate_ivar_declaration);
13053               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13054               continue;
13055             }
13056           }
13057         }
13058         ClsFields[i]->setLexicalDeclContext(CDecl);
13059         CDecl->addDecl(ClsFields[i]);
13060       }
13061       CDecl->setIvarLBraceLoc(LBrac);
13062       CDecl->setIvarRBraceLoc(RBrac);
13063     }
13064   }
13065 
13066   if (Attr)
13067     ProcessDeclAttributeList(S, Record, Attr);
13068 }
13069 
13070 /// \brief Determine whether the given integral value is representable within
13071 /// the given type T.
13072 static bool isRepresentableIntegerValue(ASTContext &Context,
13073                                         llvm::APSInt &Value,
13074                                         QualType T) {
13075   assert(T->isIntegralType(Context) && "Integral type required!");
13076   unsigned BitWidth = Context.getIntWidth(T);
13077 
13078   if (Value.isUnsigned() || Value.isNonNegative()) {
13079     if (T->isSignedIntegerOrEnumerationType())
13080       --BitWidth;
13081     return Value.getActiveBits() <= BitWidth;
13082   }
13083   return Value.getMinSignedBits() <= BitWidth;
13084 }
13085 
13086 // \brief Given an integral type, return the next larger integral type
13087 // (or a NULL type of no such type exists).
13088 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13089   // FIXME: Int128/UInt128 support, which also needs to be introduced into
13090   // enum checking below.
13091   assert(T->isIntegralType(Context) && "Integral type required!");
13092   const unsigned NumTypes = 4;
13093   QualType SignedIntegralTypes[NumTypes] = {
13094     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13095   };
13096   QualType UnsignedIntegralTypes[NumTypes] = {
13097     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
13098     Context.UnsignedLongLongTy
13099   };
13100 
13101   unsigned BitWidth = Context.getTypeSize(T);
13102   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13103                                                         : UnsignedIntegralTypes;
13104   for (unsigned I = 0; I != NumTypes; ++I)
13105     if (Context.getTypeSize(Types[I]) > BitWidth)
13106       return Types[I];
13107 
13108   return QualType();
13109 }
13110 
13111 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13112                                           EnumConstantDecl *LastEnumConst,
13113                                           SourceLocation IdLoc,
13114                                           IdentifierInfo *Id,
13115                                           Expr *Val) {
13116   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13117   llvm::APSInt EnumVal(IntWidth);
13118   QualType EltTy;
13119 
13120   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13121     Val = nullptr;
13122 
13123   if (Val)
13124     Val = DefaultLvalueConversion(Val).get();
13125 
13126   if (Val) {
13127     if (Enum->isDependentType() || Val->isTypeDependent())
13128       EltTy = Context.DependentTy;
13129     else {
13130       SourceLocation ExpLoc;
13131       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13132           !getLangOpts().MSVCCompat) {
13133         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13134         // constant-expression in the enumerator-definition shall be a converted
13135         // constant expression of the underlying type.
13136         EltTy = Enum->getIntegerType();
13137         ExprResult Converted =
13138           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13139                                            CCEK_Enumerator);
13140         if (Converted.isInvalid())
13141           Val = nullptr;
13142         else
13143           Val = Converted.get();
13144       } else if (!Val->isValueDependent() &&
13145                  !(Val = VerifyIntegerConstantExpression(Val,
13146                                                          &EnumVal).get())) {
13147         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13148       } else {
13149         if (Enum->isFixed()) {
13150           EltTy = Enum->getIntegerType();
13151 
13152           // In Obj-C and Microsoft mode, require the enumeration value to be
13153           // representable in the underlying type of the enumeration. In C++11,
13154           // we perform a non-narrowing conversion as part of converted constant
13155           // expression checking.
13156           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13157             if (getLangOpts().MSVCCompat) {
13158               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13159               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13160             } else
13161               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13162           } else
13163             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13164         } else if (getLangOpts().CPlusPlus) {
13165           // C++11 [dcl.enum]p5:
13166           //   If the underlying type is not fixed, the type of each enumerator
13167           //   is the type of its initializing value:
13168           //     - If an initializer is specified for an enumerator, the
13169           //       initializing value has the same type as the expression.
13170           EltTy = Val->getType();
13171         } else {
13172           // C99 6.7.2.2p2:
13173           //   The expression that defines the value of an enumeration constant
13174           //   shall be an integer constant expression that has a value
13175           //   representable as an int.
13176 
13177           // Complain if the value is not representable in an int.
13178           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13179             Diag(IdLoc, diag::ext_enum_value_not_int)
13180               << EnumVal.toString(10) << Val->getSourceRange()
13181               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13182           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13183             // Force the type of the expression to 'int'.
13184             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13185           }
13186           EltTy = Val->getType();
13187         }
13188       }
13189     }
13190   }
13191 
13192   if (!Val) {
13193     if (Enum->isDependentType())
13194       EltTy = Context.DependentTy;
13195     else if (!LastEnumConst) {
13196       // C++0x [dcl.enum]p5:
13197       //   If the underlying type is not fixed, the type of each enumerator
13198       //   is the type of its initializing value:
13199       //     - If no initializer is specified for the first enumerator, the
13200       //       initializing value has an unspecified integral type.
13201       //
13202       // GCC uses 'int' for its unspecified integral type, as does
13203       // C99 6.7.2.2p3.
13204       if (Enum->isFixed()) {
13205         EltTy = Enum->getIntegerType();
13206       }
13207       else {
13208         EltTy = Context.IntTy;
13209       }
13210     } else {
13211       // Assign the last value + 1.
13212       EnumVal = LastEnumConst->getInitVal();
13213       ++EnumVal;
13214       EltTy = LastEnumConst->getType();
13215 
13216       // Check for overflow on increment.
13217       if (EnumVal < LastEnumConst->getInitVal()) {
13218         // C++0x [dcl.enum]p5:
13219         //   If the underlying type is not fixed, the type of each enumerator
13220         //   is the type of its initializing value:
13221         //
13222         //     - Otherwise the type of the initializing value is the same as
13223         //       the type of the initializing value of the preceding enumerator
13224         //       unless the incremented value is not representable in that type,
13225         //       in which case the type is an unspecified integral type
13226         //       sufficient to contain the incremented value. If no such type
13227         //       exists, the program is ill-formed.
13228         QualType T = getNextLargerIntegralType(Context, EltTy);
13229         if (T.isNull() || Enum->isFixed()) {
13230           // There is no integral type larger enough to represent this
13231           // value. Complain, then allow the value to wrap around.
13232           EnumVal = LastEnumConst->getInitVal();
13233           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
13234           ++EnumVal;
13235           if (Enum->isFixed())
13236             // When the underlying type is fixed, this is ill-formed.
13237             Diag(IdLoc, diag::err_enumerator_wrapped)
13238               << EnumVal.toString(10)
13239               << EltTy;
13240           else
13241             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
13242               << EnumVal.toString(10);
13243         } else {
13244           EltTy = T;
13245         }
13246 
13247         // Retrieve the last enumerator's value, extent that type to the
13248         // type that is supposed to be large enough to represent the incremented
13249         // value, then increment.
13250         EnumVal = LastEnumConst->getInitVal();
13251         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13252         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
13253         ++EnumVal;
13254 
13255         // If we're not in C++, diagnose the overflow of enumerator values,
13256         // which in C99 means that the enumerator value is not representable in
13257         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13258         // permits enumerator values that are representable in some larger
13259         // integral type.
13260         if (!getLangOpts().CPlusPlus && !T.isNull())
13261           Diag(IdLoc, diag::warn_enum_value_overflow);
13262       } else if (!getLangOpts().CPlusPlus &&
13263                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13264         // Enforce C99 6.7.2.2p2 even when we compute the next value.
13265         Diag(IdLoc, diag::ext_enum_value_not_int)
13266           << EnumVal.toString(10) << 1;
13267       }
13268     }
13269   }
13270 
13271   if (!EltTy->isDependentType()) {
13272     // Make the enumerator value match the signedness and size of the
13273     // enumerator's type.
13274     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
13275     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13276   }
13277 
13278   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
13279                                   Val, EnumVal);
13280 }
13281 
13282 
13283 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
13284                               SourceLocation IdLoc, IdentifierInfo *Id,
13285                               AttributeList *Attr,
13286                               SourceLocation EqualLoc, Expr *Val) {
13287   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
13288   EnumConstantDecl *LastEnumConst =
13289     cast_or_null<EnumConstantDecl>(lastEnumConst);
13290 
13291   // The scope passed in may not be a decl scope.  Zip up the scope tree until
13292   // we find one that is.
13293   S = getNonFieldDeclScope(S);
13294 
13295   // Verify that there isn't already something declared with this name in this
13296   // scope.
13297   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
13298                                          ForRedeclaration);
13299   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13300     // Maybe we will complain about the shadowed template parameter.
13301     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
13302     // Just pretend that we didn't see the previous declaration.
13303     PrevDecl = nullptr;
13304   }
13305 
13306   if (PrevDecl) {
13307     // When in C++, we may get a TagDecl with the same name; in this case the
13308     // enum constant will 'hide' the tag.
13309     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
13310            "Received TagDecl when not in C++!");
13311     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
13312       if (isa<EnumConstantDecl>(PrevDecl))
13313         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
13314       else
13315         Diag(IdLoc, diag::err_redefinition) << Id;
13316       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13317       return nullptr;
13318     }
13319   }
13320 
13321   // C++ [class.mem]p15:
13322   // If T is the name of a class, then each of the following shall have a name
13323   // different from T:
13324   // - every enumerator of every member of class T that is an unscoped
13325   // enumerated type
13326   if (CXXRecordDecl *Record
13327                       = dyn_cast<CXXRecordDecl>(
13328                              TheEnumDecl->getDeclContext()->getRedeclContext()))
13329     if (!TheEnumDecl->isScoped() &&
13330         Record->getIdentifier() && Record->getIdentifier() == Id)
13331       Diag(IdLoc, diag::err_member_name_of_class) << Id;
13332 
13333   EnumConstantDecl *New =
13334     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
13335 
13336   if (New) {
13337     // Process attributes.
13338     if (Attr) ProcessDeclAttributeList(S, New, Attr);
13339 
13340     // Register this decl in the current scope stack.
13341     New->setAccess(TheEnumDecl->getAccess());
13342     PushOnScopeChains(New, S);
13343   }
13344 
13345   ActOnDocumentableDecl(New);
13346 
13347   return New;
13348 }
13349 
13350 // Returns true when the enum initial expression does not trigger the
13351 // duplicate enum warning.  A few common cases are exempted as follows:
13352 // Element2 = Element1
13353 // Element2 = Element1 + 1
13354 // Element2 = Element1 - 1
13355 // Where Element2 and Element1 are from the same enum.
13356 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
13357   Expr *InitExpr = ECD->getInitExpr();
13358   if (!InitExpr)
13359     return true;
13360   InitExpr = InitExpr->IgnoreImpCasts();
13361 
13362   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
13363     if (!BO->isAdditiveOp())
13364       return true;
13365     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
13366     if (!IL)
13367       return true;
13368     if (IL->getValue() != 1)
13369       return true;
13370 
13371     InitExpr = BO->getLHS();
13372   }
13373 
13374   // This checks if the elements are from the same enum.
13375   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
13376   if (!DRE)
13377     return true;
13378 
13379   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
13380   if (!EnumConstant)
13381     return true;
13382 
13383   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
13384       Enum)
13385     return true;
13386 
13387   return false;
13388 }
13389 
13390 struct DupKey {
13391   int64_t val;
13392   bool isTombstoneOrEmptyKey;
13393   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
13394     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
13395 };
13396 
13397 static DupKey GetDupKey(const llvm::APSInt& Val) {
13398   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
13399                 false);
13400 }
13401 
13402 struct DenseMapInfoDupKey {
13403   static DupKey getEmptyKey() { return DupKey(0, true); }
13404   static DupKey getTombstoneKey() { return DupKey(1, true); }
13405   static unsigned getHashValue(const DupKey Key) {
13406     return (unsigned)(Key.val * 37);
13407   }
13408   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
13409     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
13410            LHS.val == RHS.val;
13411   }
13412 };
13413 
13414 // Emits a warning when an element is implicitly set a value that
13415 // a previous element has already been set to.
13416 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
13417                                         EnumDecl *Enum,
13418                                         QualType EnumType) {
13419   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
13420     return;
13421   // Avoid anonymous enums
13422   if (!Enum->getIdentifier())
13423     return;
13424 
13425   // Only check for small enums.
13426   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
13427     return;
13428 
13429   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
13430   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
13431 
13432   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
13433   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
13434           ValueToVectorMap;
13435 
13436   DuplicatesVector DupVector;
13437   ValueToVectorMap EnumMap;
13438 
13439   // Populate the EnumMap with all values represented by enum constants without
13440   // an initialier.
13441   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13442     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
13443 
13444     // Null EnumConstantDecl means a previous diagnostic has been emitted for
13445     // this constant.  Skip this enum since it may be ill-formed.
13446     if (!ECD) {
13447       return;
13448     }
13449 
13450     if (ECD->getInitExpr())
13451       continue;
13452 
13453     DupKey Key = GetDupKey(ECD->getInitVal());
13454     DeclOrVector &Entry = EnumMap[Key];
13455 
13456     // First time encountering this value.
13457     if (Entry.isNull())
13458       Entry = ECD;
13459   }
13460 
13461   // Create vectors for any values that has duplicates.
13462   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13463     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
13464     if (!ValidDuplicateEnum(ECD, Enum))
13465       continue;
13466 
13467     DupKey Key = GetDupKey(ECD->getInitVal());
13468 
13469     DeclOrVector& Entry = EnumMap[Key];
13470     if (Entry.isNull())
13471       continue;
13472 
13473     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
13474       // Ensure constants are different.
13475       if (D == ECD)
13476         continue;
13477 
13478       // Create new vector and push values onto it.
13479       ECDVector *Vec = new ECDVector();
13480       Vec->push_back(D);
13481       Vec->push_back(ECD);
13482 
13483       // Update entry to point to the duplicates vector.
13484       Entry = Vec;
13485 
13486       // Store the vector somewhere we can consult later for quick emission of
13487       // diagnostics.
13488       DupVector.push_back(Vec);
13489       continue;
13490     }
13491 
13492     ECDVector *Vec = Entry.get<ECDVector*>();
13493     // Make sure constants are not added more than once.
13494     if (*Vec->begin() == ECD)
13495       continue;
13496 
13497     Vec->push_back(ECD);
13498   }
13499 
13500   // Emit diagnostics.
13501   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
13502                                   DupVectorEnd = DupVector.end();
13503        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
13504     ECDVector *Vec = *DupVectorIter;
13505     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
13506 
13507     // Emit warning for one enum constant.
13508     ECDVector::iterator I = Vec->begin();
13509     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
13510       << (*I)->getName() << (*I)->getInitVal().toString(10)
13511       << (*I)->getSourceRange();
13512     ++I;
13513 
13514     // Emit one note for each of the remaining enum constants with
13515     // the same value.
13516     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
13517       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
13518         << (*I)->getName() << (*I)->getInitVal().toString(10)
13519         << (*I)->getSourceRange();
13520     delete Vec;
13521   }
13522 }
13523 
13524 bool
13525 Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
13526                         bool AllowMask) const {
13527   FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>();
13528   assert(FEAttr && "looking for value in non-flag enum");
13529 
13530   llvm::APInt FlagMask = ~FEAttr->getFlagBits();
13531   unsigned Width = FlagMask.getBitWidth();
13532 
13533   // We will try a zero-extended value for the regular check first.
13534   llvm::APInt ExtVal = Val.zextOrSelf(Width);
13535 
13536   // A value is in a flag enum if either its bits are a subset of the enum's
13537   // flag bits (the first condition) or we are allowing masks and the same is
13538   // true of its complement (the second condition). When masks are allowed, we
13539   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
13540   //
13541   // While it's true that any value could be used as a mask, the assumption is
13542   // that a mask will have all of the insignificant bits set. Anything else is
13543   // likely a logic error.
13544   if (!(FlagMask & ExtVal))
13545     return true;
13546 
13547   if (AllowMask) {
13548     // Try a one-extended value instead. This can happen if the enum is wider
13549     // than the constant used, in C with extensions to allow for wider enums.
13550     // The mask will still have the correct behaviour, so we give the user the
13551     // benefit of the doubt.
13552     //
13553     // FIXME: This heuristic can cause weird results if the enum was extended
13554     // to a larger type and is signed, because then bit-masks of smaller types
13555     // that get extended will fall out of range (e.g. ~0x1u). We currently don't
13556     // detect that case and will get a false positive for it. In most cases,
13557     // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may
13558     // be fine just to accept this as a warning.
13559     ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth());
13560     if (!(FlagMask & ~ExtVal))
13561       return true;
13562   }
13563 
13564   return false;
13565 }
13566 
13567 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
13568                          SourceLocation RBraceLoc, Decl *EnumDeclX,
13569                          ArrayRef<Decl *> Elements,
13570                          Scope *S, AttributeList *Attr) {
13571   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
13572   QualType EnumType = Context.getTypeDeclType(Enum);
13573 
13574   if (Attr)
13575     ProcessDeclAttributeList(S, Enum, Attr);
13576 
13577   if (Enum->isDependentType()) {
13578     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13579       EnumConstantDecl *ECD =
13580         cast_or_null<EnumConstantDecl>(Elements[i]);
13581       if (!ECD) continue;
13582 
13583       ECD->setType(EnumType);
13584     }
13585 
13586     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
13587     return;
13588   }
13589 
13590   // TODO: If the result value doesn't fit in an int, it must be a long or long
13591   // long value.  ISO C does not support this, but GCC does as an extension,
13592   // emit a warning.
13593   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13594   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
13595   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
13596 
13597   // Verify that all the values are okay, compute the size of the values, and
13598   // reverse the list.
13599   unsigned NumNegativeBits = 0;
13600   unsigned NumPositiveBits = 0;
13601 
13602   // Keep track of whether all elements have type int.
13603   bool AllElementsInt = true;
13604 
13605   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13606     EnumConstantDecl *ECD =
13607       cast_or_null<EnumConstantDecl>(Elements[i]);
13608     if (!ECD) continue;  // Already issued a diagnostic.
13609 
13610     const llvm::APSInt &InitVal = ECD->getInitVal();
13611 
13612     // Keep track of the size of positive and negative values.
13613     if (InitVal.isUnsigned() || InitVal.isNonNegative())
13614       NumPositiveBits = std::max(NumPositiveBits,
13615                                  (unsigned)InitVal.getActiveBits());
13616     else
13617       NumNegativeBits = std::max(NumNegativeBits,
13618                                  (unsigned)InitVal.getMinSignedBits());
13619 
13620     // Keep track of whether every enum element has type int (very commmon).
13621     if (AllElementsInt)
13622       AllElementsInt = ECD->getType() == Context.IntTy;
13623   }
13624 
13625   // Figure out the type that should be used for this enum.
13626   QualType BestType;
13627   unsigned BestWidth;
13628 
13629   // C++0x N3000 [conv.prom]p3:
13630   //   An rvalue of an unscoped enumeration type whose underlying
13631   //   type is not fixed can be converted to an rvalue of the first
13632   //   of the following types that can represent all the values of
13633   //   the enumeration: int, unsigned int, long int, unsigned long
13634   //   int, long long int, or unsigned long long int.
13635   // C99 6.4.4.3p2:
13636   //   An identifier declared as an enumeration constant has type int.
13637   // The C99 rule is modified by a gcc extension
13638   QualType BestPromotionType;
13639 
13640   bool Packed = Enum->hasAttr<PackedAttr>();
13641   // -fshort-enums is the equivalent to specifying the packed attribute on all
13642   // enum definitions.
13643   if (LangOpts.ShortEnums)
13644     Packed = true;
13645 
13646   if (Enum->isFixed()) {
13647     BestType = Enum->getIntegerType();
13648     if (BestType->isPromotableIntegerType())
13649       BestPromotionType = Context.getPromotedIntegerType(BestType);
13650     else
13651       BestPromotionType = BestType;
13652 
13653     BestWidth = Context.getIntWidth(BestType);
13654   }
13655   else if (NumNegativeBits) {
13656     // If there is a negative value, figure out the smallest integer type (of
13657     // int/long/longlong) that fits.
13658     // If it's packed, check also if it fits a char or a short.
13659     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
13660       BestType = Context.SignedCharTy;
13661       BestWidth = CharWidth;
13662     } else if (Packed && NumNegativeBits <= ShortWidth &&
13663                NumPositiveBits < ShortWidth) {
13664       BestType = Context.ShortTy;
13665       BestWidth = ShortWidth;
13666     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
13667       BestType = Context.IntTy;
13668       BestWidth = IntWidth;
13669     } else {
13670       BestWidth = Context.getTargetInfo().getLongWidth();
13671 
13672       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
13673         BestType = Context.LongTy;
13674       } else {
13675         BestWidth = Context.getTargetInfo().getLongLongWidth();
13676 
13677         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
13678           Diag(Enum->getLocation(), diag::ext_enum_too_large);
13679         BestType = Context.LongLongTy;
13680       }
13681     }
13682     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
13683   } else {
13684     // If there is no negative value, figure out the smallest type that fits
13685     // all of the enumerator values.
13686     // If it's packed, check also if it fits a char or a short.
13687     if (Packed && NumPositiveBits <= CharWidth) {
13688       BestType = Context.UnsignedCharTy;
13689       BestPromotionType = Context.IntTy;
13690       BestWidth = CharWidth;
13691     } else if (Packed && NumPositiveBits <= ShortWidth) {
13692       BestType = Context.UnsignedShortTy;
13693       BestPromotionType = Context.IntTy;
13694       BestWidth = ShortWidth;
13695     } else if (NumPositiveBits <= IntWidth) {
13696       BestType = Context.UnsignedIntTy;
13697       BestWidth = IntWidth;
13698       BestPromotionType
13699         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13700                            ? Context.UnsignedIntTy : Context.IntTy;
13701     } else if (NumPositiveBits <=
13702                (BestWidth = Context.getTargetInfo().getLongWidth())) {
13703       BestType = Context.UnsignedLongTy;
13704       BestPromotionType
13705         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13706                            ? Context.UnsignedLongTy : Context.LongTy;
13707     } else {
13708       BestWidth = Context.getTargetInfo().getLongLongWidth();
13709       assert(NumPositiveBits <= BestWidth &&
13710              "How could an initializer get larger than ULL?");
13711       BestType = Context.UnsignedLongLongTy;
13712       BestPromotionType
13713         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13714                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
13715     }
13716   }
13717 
13718   FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>();
13719   if (FEAttr)
13720     FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0);
13721 
13722   // Loop over all of the enumerator constants, changing their types to match
13723   // the type of the enum if needed. If we have a flag type, we also prepare the
13724   // FlagBits cache.
13725   for (auto *D : Elements) {
13726     auto *ECD = cast_or_null<EnumConstantDecl>(D);
13727     if (!ECD) continue;  // Already issued a diagnostic.
13728 
13729     // Standard C says the enumerators have int type, but we allow, as an
13730     // extension, the enumerators to be larger than int size.  If each
13731     // enumerator value fits in an int, type it as an int, otherwise type it the
13732     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
13733     // that X has type 'int', not 'unsigned'.
13734 
13735     // Determine whether the value fits into an int.
13736     llvm::APSInt InitVal = ECD->getInitVal();
13737 
13738     // If it fits into an integer type, force it.  Otherwise force it to match
13739     // the enum decl type.
13740     QualType NewTy;
13741     unsigned NewWidth;
13742     bool NewSign;
13743     if (!getLangOpts().CPlusPlus &&
13744         !Enum->isFixed() &&
13745         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
13746       NewTy = Context.IntTy;
13747       NewWidth = IntWidth;
13748       NewSign = true;
13749     } else if (ECD->getType() == BestType) {
13750       // Already the right type!
13751       if (getLangOpts().CPlusPlus)
13752         // C++ [dcl.enum]p4: Following the closing brace of an
13753         // enum-specifier, each enumerator has the type of its
13754         // enumeration.
13755         ECD->setType(EnumType);
13756       goto flagbits;
13757     } else {
13758       NewTy = BestType;
13759       NewWidth = BestWidth;
13760       NewSign = BestType->isSignedIntegerOrEnumerationType();
13761     }
13762 
13763     // Adjust the APSInt value.
13764     InitVal = InitVal.extOrTrunc(NewWidth);
13765     InitVal.setIsSigned(NewSign);
13766     ECD->setInitVal(InitVal);
13767 
13768     // Adjust the Expr initializer and type.
13769     if (ECD->getInitExpr() &&
13770         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
13771       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
13772                                                 CK_IntegralCast,
13773                                                 ECD->getInitExpr(),
13774                                                 /*base paths*/ nullptr,
13775                                                 VK_RValue));
13776     if (getLangOpts().CPlusPlus)
13777       // C++ [dcl.enum]p4: Following the closing brace of an
13778       // enum-specifier, each enumerator has the type of its
13779       // enumeration.
13780       ECD->setType(EnumType);
13781     else
13782       ECD->setType(NewTy);
13783 
13784 flagbits:
13785     // Check to see if we have a constant with exactly one bit set. Note that x
13786     // & (x - 1) will be nonzero if and only if x has more than one bit set.
13787     if (FEAttr) {
13788       llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth);
13789       if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) {
13790         FEAttr->getFlagBits() |= ExtVal;
13791       }
13792     }
13793   }
13794 
13795   if (FEAttr) {
13796     for (Decl *D : Elements) {
13797       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
13798       if (!ECD) continue;  // Already issued a diagnostic.
13799 
13800       llvm::APSInt InitVal = ECD->getInitVal();
13801       if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true))
13802         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
13803           << ECD << Enum;
13804     }
13805   }
13806 
13807 
13808 
13809   Enum->completeDefinition(BestType, BestPromotionType,
13810                            NumPositiveBits, NumNegativeBits);
13811 
13812   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
13813 
13814   // Now that the enum type is defined, ensure it's not been underaligned.
13815   if (Enum->hasAttrs())
13816     CheckAlignasUnderalignment(Enum);
13817 }
13818 
13819 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
13820                                   SourceLocation StartLoc,
13821                                   SourceLocation EndLoc) {
13822   StringLiteral *AsmString = cast<StringLiteral>(expr);
13823 
13824   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
13825                                                    AsmString, StartLoc,
13826                                                    EndLoc);
13827   CurContext->addDecl(New);
13828   return New;
13829 }
13830 
13831 static void checkModuleImportContext(Sema &S, Module *M,
13832                                      SourceLocation ImportLoc,
13833                                      DeclContext *DC) {
13834   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
13835     switch (LSD->getLanguage()) {
13836     case LinkageSpecDecl::lang_c:
13837       if (!M->IsExternC) {
13838         S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
13839           << M->getFullModuleName();
13840         S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
13841         return;
13842       }
13843       break;
13844     case LinkageSpecDecl::lang_cxx:
13845       break;
13846     }
13847     DC = LSD->getParent();
13848   }
13849 
13850   while (isa<LinkageSpecDecl>(DC))
13851     DC = DC->getParent();
13852   if (!isa<TranslationUnitDecl>(DC)) {
13853     S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
13854       << M->getFullModuleName() << DC;
13855     S.Diag(cast<Decl>(DC)->getLocStart(),
13856            diag::note_module_import_not_at_top_level)
13857       << DC;
13858   }
13859 }
13860 
13861 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
13862                                    SourceLocation ImportLoc,
13863                                    ModuleIdPath Path) {
13864   Module *Mod =
13865       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
13866                                    /*IsIncludeDirective=*/false);
13867   if (!Mod)
13868     return true;
13869 
13870   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13871 
13872   // FIXME: we should support importing a submodule within a different submodule
13873   // of the same top-level module. Until we do, make it an error rather than
13874   // silently ignoring the import.
13875   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
13876     Diag(ImportLoc, diag::err_module_self_import)
13877         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
13878   else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
13879     Diag(ImportLoc, diag::err_module_import_in_implementation)
13880         << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
13881 
13882   SmallVector<SourceLocation, 2> IdentifierLocs;
13883   Module *ModCheck = Mod;
13884   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13885     // If we've run out of module parents, just drop the remaining identifiers.
13886     // We need the length to be consistent.
13887     if (!ModCheck)
13888       break;
13889     ModCheck = ModCheck->Parent;
13890 
13891     IdentifierLocs.push_back(Path[I].second);
13892   }
13893 
13894   ImportDecl *Import = ImportDecl::Create(Context,
13895                                           Context.getTranslationUnitDecl(),
13896                                           AtLoc.isValid()? AtLoc : ImportLoc,
13897                                           Mod, IdentifierLocs);
13898   Context.getTranslationUnitDecl()->addDecl(Import);
13899   return Import;
13900 }
13901 
13902 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
13903   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13904 
13905   // FIXME: Should we synthesize an ImportDecl here?
13906   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13907                                       /*Complain=*/true);
13908 }
13909 
13910 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
13911                                                       Module *Mod) {
13912   // Bail if we're not allowed to implicitly import a module here.
13913   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
13914     return;
13915 
13916   // Create the implicit import declaration.
13917   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13918   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13919                                                    Loc, Mod, Loc);
13920   TU->addDecl(ImportD);
13921   Consumer.HandleImplicitImportDecl(ImportD);
13922 
13923   // Make the module visible.
13924   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13925                                       /*Complain=*/false);
13926 }
13927 
13928 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13929                                       IdentifierInfo* AliasName,
13930                                       SourceLocation PragmaLoc,
13931                                       SourceLocation NameLoc,
13932                                       SourceLocation AliasNameLoc) {
13933   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13934                                     LookupOrdinaryName);
13935   AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13936                                                     AliasName->getName(), 0);
13937 
13938   if (PrevDecl)
13939     PrevDecl->addAttr(Attr);
13940   else
13941     (void)ExtnameUndeclaredIdentifiers.insert(
13942       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13943 }
13944 
13945 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13946                              SourceLocation PragmaLoc,
13947                              SourceLocation NameLoc) {
13948   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
13949 
13950   if (PrevDecl) {
13951     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
13952   } else {
13953     (void)WeakUndeclaredIdentifiers.insert(
13954       std::pair<IdentifierInfo*,WeakInfo>
13955         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
13956   }
13957 }
13958 
13959 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13960                                 IdentifierInfo* AliasName,
13961                                 SourceLocation PragmaLoc,
13962                                 SourceLocation NameLoc,
13963                                 SourceLocation AliasNameLoc) {
13964   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13965                                     LookupOrdinaryName);
13966   WeakInfo W = WeakInfo(Name, NameLoc);
13967 
13968   if (PrevDecl) {
13969     if (!PrevDecl->hasAttr<AliasAttr>())
13970       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
13971         DeclApplyPragmaWeak(TUScope, ND, W);
13972   } else {
13973     (void)WeakUndeclaredIdentifiers.insert(
13974       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
13975   }
13976 }
13977 
13978 Decl *Sema::getObjCDeclContext() const {
13979   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13980 }
13981 
13982 AvailabilityResult Sema::getCurContextAvailability() const {
13983   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
13984   if (!D)
13985     return AR_Available;
13986 
13987   // If we are within an Objective-C method, we should consult
13988   // both the availability of the method as well as the
13989   // enclosing class.  If the class is (say) deprecated,
13990   // the entire method is considered deprecated from the
13991   // purpose of checking if the current context is deprecated.
13992   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13993     AvailabilityResult R = MD->getAvailability();
13994     if (R != AR_Available)
13995       return R;
13996     D = MD->getClassInterface();
13997   }
13998   // If we are within an Objective-c @implementation, it
13999   // gets the same availability context as the @interface.
14000   else if (const ObjCImplementationDecl *ID =
14001             dyn_cast<ObjCImplementationDecl>(D)) {
14002     D = ID->getClassInterface();
14003   }
14004   // Recover from user error.
14005   return D ? D->getAvailability() : AR_Available;
14006 }
14007