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(), AttrSpellingListIndex);
2159   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2160     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2161   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2162     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2163   else if (isa<AlignedAttr>(Attr))
2164     // AlignedAttrs are handled separately, because we need to handle all
2165     // such attributes on a declaration at the same time.
2166     NewAttr = nullptr;
2167   else if (isa<DeprecatedAttr>(Attr) && Override)
2168     NewAttr = nullptr;
2169   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2170     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2171 
2172   if (NewAttr) {
2173     NewAttr->setInherited(true);
2174     D->addAttr(NewAttr);
2175     return true;
2176   }
2177 
2178   return false;
2179 }
2180 
2181 static const Decl *getDefinition(const Decl *D) {
2182   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2183     return TD->getDefinition();
2184   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2185     const VarDecl *Def = VD->getDefinition();
2186     if (Def)
2187       return Def;
2188     return VD->getActingDefinition();
2189   }
2190   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2191     const FunctionDecl* Def;
2192     if (FD->isDefined(Def))
2193       return Def;
2194   }
2195   return nullptr;
2196 }
2197 
2198 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2199   for (const auto *Attribute : D->attrs())
2200     if (Attribute->getKind() == Kind)
2201       return true;
2202   return false;
2203 }
2204 
2205 /// checkNewAttributesAfterDef - If we already have a definition, check that
2206 /// there are no new attributes in this declaration.
2207 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2208   if (!New->hasAttrs())
2209     return;
2210 
2211   const Decl *Def = getDefinition(Old);
2212   if (!Def || Def == New)
2213     return;
2214 
2215   AttrVec &NewAttributes = New->getAttrs();
2216   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2217     const Attr *NewAttribute = NewAttributes[I];
2218 
2219     if (isa<AliasAttr>(NewAttribute)) {
2220       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2221         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2222       else {
2223         VarDecl *VD = cast<VarDecl>(New);
2224         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2225                                 VarDecl::TentativeDefinition
2226                             ? diag::err_alias_after_tentative
2227                             : diag::err_redefinition;
2228         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2229         S.Diag(Def->getLocation(), diag::note_previous_definition);
2230         VD->setInvalidDecl();
2231       }
2232       ++I;
2233       continue;
2234     }
2235 
2236     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2237       // Tentative definitions are only interesting for the alias check above.
2238       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2239         ++I;
2240         continue;
2241       }
2242     }
2243 
2244     if (hasAttribute(Def, NewAttribute->getKind())) {
2245       ++I;
2246       continue; // regular attr merging will take care of validating this.
2247     }
2248 
2249     if (isa<C11NoReturnAttr>(NewAttribute)) {
2250       // C's _Noreturn is allowed to be added to a function after it is defined.
2251       ++I;
2252       continue;
2253     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2254       if (AA->isAlignas()) {
2255         // C++11 [dcl.align]p6:
2256         //   if any declaration of an entity has an alignment-specifier,
2257         //   every defining declaration of that entity shall specify an
2258         //   equivalent alignment.
2259         // C11 6.7.5/7:
2260         //   If the definition of an object does not have an alignment
2261         //   specifier, any other declaration of that object shall also
2262         //   have no alignment specifier.
2263         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2264           << AA;
2265         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2266           << AA;
2267         NewAttributes.erase(NewAttributes.begin() + I);
2268         --E;
2269         continue;
2270       }
2271     }
2272 
2273     S.Diag(NewAttribute->getLocation(),
2274            diag::warn_attribute_precede_definition);
2275     S.Diag(Def->getLocation(), diag::note_previous_definition);
2276     NewAttributes.erase(NewAttributes.begin() + I);
2277     --E;
2278   }
2279 }
2280 
2281 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2282 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2283                                AvailabilityMergeKind AMK) {
2284   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2285     UsedAttr *NewAttr = OldAttr->clone(Context);
2286     NewAttr->setInherited(true);
2287     New->addAttr(NewAttr);
2288   }
2289 
2290   if (!Old->hasAttrs() && !New->hasAttrs())
2291     return;
2292 
2293   // attributes declared post-definition are currently ignored
2294   checkNewAttributesAfterDef(*this, New, Old);
2295 
2296   if (!Old->hasAttrs())
2297     return;
2298 
2299   bool foundAny = New->hasAttrs();
2300 
2301   // Ensure that any moving of objects within the allocated map is done before
2302   // we process them.
2303   if (!foundAny) New->setAttrs(AttrVec());
2304 
2305   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2306     bool Override = false;
2307     // Ignore deprecated/unavailable/availability attributes if requested.
2308     if (isa<DeprecatedAttr>(I) ||
2309         isa<UnavailableAttr>(I) ||
2310         isa<AvailabilityAttr>(I)) {
2311       switch (AMK) {
2312       case AMK_None:
2313         continue;
2314 
2315       case AMK_Redeclaration:
2316         break;
2317 
2318       case AMK_Override:
2319         Override = true;
2320         break;
2321       }
2322     }
2323 
2324     // Already handled.
2325     if (isa<UsedAttr>(I))
2326       continue;
2327 
2328     if (mergeDeclAttribute(*this, New, I, Override))
2329       foundAny = true;
2330   }
2331 
2332   if (mergeAlignedAttrs(*this, New, Old))
2333     foundAny = true;
2334 
2335   if (!foundAny) New->dropAttrs();
2336 }
2337 
2338 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2339 /// to the new one.
2340 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2341                                      const ParmVarDecl *oldDecl,
2342                                      Sema &S) {
2343   // C++11 [dcl.attr.depend]p2:
2344   //   The first declaration of a function shall specify the
2345   //   carries_dependency attribute for its declarator-id if any declaration
2346   //   of the function specifies the carries_dependency attribute.
2347   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2348   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2349     S.Diag(CDA->getLocation(),
2350            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2351     // Find the first declaration of the parameter.
2352     // FIXME: Should we build redeclaration chains for function parameters?
2353     const FunctionDecl *FirstFD =
2354       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2355     const ParmVarDecl *FirstVD =
2356       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2357     S.Diag(FirstVD->getLocation(),
2358            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2359   }
2360 
2361   if (!oldDecl->hasAttrs())
2362     return;
2363 
2364   bool foundAny = newDecl->hasAttrs();
2365 
2366   // Ensure that any moving of objects within the allocated map is
2367   // done before we process them.
2368   if (!foundAny) newDecl->setAttrs(AttrVec());
2369 
2370   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2371     if (!DeclHasAttr(newDecl, I)) {
2372       InheritableAttr *newAttr =
2373         cast<InheritableParamAttr>(I->clone(S.Context));
2374       newAttr->setInherited(true);
2375       newDecl->addAttr(newAttr);
2376       foundAny = true;
2377     }
2378   }
2379 
2380   if (!foundAny) newDecl->dropAttrs();
2381 }
2382 
2383 namespace {
2384 
2385 /// Used in MergeFunctionDecl to keep track of function parameters in
2386 /// C.
2387 struct GNUCompatibleParamWarning {
2388   ParmVarDecl *OldParm;
2389   ParmVarDecl *NewParm;
2390   QualType PromotedType;
2391 };
2392 
2393 }
2394 
2395 /// getSpecialMember - get the special member enum for a method.
2396 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2397   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2398     if (Ctor->isDefaultConstructor())
2399       return Sema::CXXDefaultConstructor;
2400 
2401     if (Ctor->isCopyConstructor())
2402       return Sema::CXXCopyConstructor;
2403 
2404     if (Ctor->isMoveConstructor())
2405       return Sema::CXXMoveConstructor;
2406   } else if (isa<CXXDestructorDecl>(MD)) {
2407     return Sema::CXXDestructor;
2408   } else if (MD->isCopyAssignmentOperator()) {
2409     return Sema::CXXCopyAssignment;
2410   } else if (MD->isMoveAssignmentOperator()) {
2411     return Sema::CXXMoveAssignment;
2412   }
2413 
2414   return Sema::CXXInvalid;
2415 }
2416 
2417 // Determine whether the previous declaration was a definition, implicit
2418 // declaration, or a declaration.
2419 template <typename T>
2420 static std::pair<diag::kind, SourceLocation>
2421 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2422   diag::kind PrevDiag;
2423   SourceLocation OldLocation = Old->getLocation();
2424   if (Old->isThisDeclarationADefinition())
2425     PrevDiag = diag::note_previous_definition;
2426   else if (Old->isImplicit()) {
2427     PrevDiag = diag::note_previous_implicit_declaration;
2428     if (OldLocation.isInvalid())
2429       OldLocation = New->getLocation();
2430   } else
2431     PrevDiag = diag::note_previous_declaration;
2432   return std::make_pair(PrevDiag, OldLocation);
2433 }
2434 
2435 /// canRedefineFunction - checks if a function can be redefined. Currently,
2436 /// only extern inline functions can be redefined, and even then only in
2437 /// GNU89 mode.
2438 static bool canRedefineFunction(const FunctionDecl *FD,
2439                                 const LangOptions& LangOpts) {
2440   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2441           !LangOpts.CPlusPlus &&
2442           FD->isInlineSpecified() &&
2443           FD->getStorageClass() == SC_Extern);
2444 }
2445 
2446 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2447   const AttributedType *AT = T->getAs<AttributedType>();
2448   while (AT && !AT->isCallingConv())
2449     AT = AT->getModifiedType()->getAs<AttributedType>();
2450   return AT;
2451 }
2452 
2453 template <typename T>
2454 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2455   const DeclContext *DC = Old->getDeclContext();
2456   if (DC->isRecord())
2457     return false;
2458 
2459   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2460   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2461     return true;
2462   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2463     return true;
2464   return false;
2465 }
2466 
2467 /// MergeFunctionDecl - We just parsed a function 'New' from
2468 /// declarator D which has the same name and scope as a previous
2469 /// declaration 'Old'.  Figure out how to resolve this situation,
2470 /// merging decls or emitting diagnostics as appropriate.
2471 ///
2472 /// In C++, New and Old must be declarations that are not
2473 /// overloaded. Use IsOverload to determine whether New and Old are
2474 /// overloaded, and to select the Old declaration that New should be
2475 /// merged with.
2476 ///
2477 /// Returns true if there was an error, false otherwise.
2478 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2479                              Scope *S, bool MergeTypeWithOld) {
2480   // Verify the old decl was also a function.
2481   FunctionDecl *Old = OldD->getAsFunction();
2482   if (!Old) {
2483     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2484       if (New->getFriendObjectKind()) {
2485         Diag(New->getLocation(), diag::err_using_decl_friend);
2486         Diag(Shadow->getTargetDecl()->getLocation(),
2487              diag::note_using_decl_target);
2488         Diag(Shadow->getUsingDecl()->getLocation(),
2489              diag::note_using_decl) << 0;
2490         return true;
2491       }
2492 
2493       // C++11 [namespace.udecl]p14:
2494       //   If a function declaration in namespace scope or block scope has the
2495       //   same name and the same parameter-type-list as a function introduced
2496       //   by a using-declaration, and the declarations do not declare the same
2497       //   function, the program is ill-formed.
2498 
2499       // Check whether the two declarations might declare the same function.
2500       Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2501       if (Old &&
2502           !Old->getDeclContext()->getRedeclContext()->Equals(
2503               New->getDeclContext()->getRedeclContext()) &&
2504           !(Old->isExternC() && New->isExternC()))
2505         Old = nullptr;
2506 
2507       if (!Old) {
2508         Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2509         Diag(Shadow->getTargetDecl()->getLocation(),
2510              diag::note_using_decl_target);
2511         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2512         return true;
2513       }
2514       OldD = Old;
2515     } else {
2516       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2517         << New->getDeclName();
2518       Diag(OldD->getLocation(), diag::note_previous_definition);
2519       return true;
2520     }
2521   }
2522 
2523   // If the old declaration is invalid, just give up here.
2524   if (Old->isInvalidDecl())
2525     return true;
2526 
2527   diag::kind PrevDiag;
2528   SourceLocation OldLocation;
2529   std::tie(PrevDiag, OldLocation) =
2530       getNoteDiagForInvalidRedeclaration(Old, New);
2531 
2532   // Don't complain about this if we're in GNU89 mode and the old function
2533   // is an extern inline function.
2534   // Don't complain about specializations. They are not supposed to have
2535   // storage classes.
2536   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2537       New->getStorageClass() == SC_Static &&
2538       Old->hasExternalFormalLinkage() &&
2539       !New->getTemplateSpecializationInfo() &&
2540       !canRedefineFunction(Old, getLangOpts())) {
2541     if (getLangOpts().MicrosoftExt) {
2542       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2543       Diag(OldLocation, PrevDiag);
2544     } else {
2545       Diag(New->getLocation(), diag::err_static_non_static) << New;
2546       Diag(OldLocation, PrevDiag);
2547       return true;
2548     }
2549   }
2550 
2551 
2552   // If a function is first declared with a calling convention, but is later
2553   // declared or defined without one, all following decls assume the calling
2554   // convention of the first.
2555   //
2556   // It's OK if a function is first declared without a calling convention,
2557   // but is later declared or defined with the default calling convention.
2558   //
2559   // To test if either decl has an explicit calling convention, we look for
2560   // AttributedType sugar nodes on the type as written.  If they are missing or
2561   // were canonicalized away, we assume the calling convention was implicit.
2562   //
2563   // Note also that we DO NOT return at this point, because we still have
2564   // other tests to run.
2565   QualType OldQType = Context.getCanonicalType(Old->getType());
2566   QualType NewQType = Context.getCanonicalType(New->getType());
2567   const FunctionType *OldType = cast<FunctionType>(OldQType);
2568   const FunctionType *NewType = cast<FunctionType>(NewQType);
2569   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2570   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2571   bool RequiresAdjustment = false;
2572 
2573   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2574     FunctionDecl *First = Old->getFirstDecl();
2575     const FunctionType *FT =
2576         First->getType().getCanonicalType()->castAs<FunctionType>();
2577     FunctionType::ExtInfo FI = FT->getExtInfo();
2578     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2579     if (!NewCCExplicit) {
2580       // Inherit the CC from the previous declaration if it was specified
2581       // there but not here.
2582       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2583       RequiresAdjustment = true;
2584     } else {
2585       // Calling conventions aren't compatible, so complain.
2586       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2587       Diag(New->getLocation(), diag::err_cconv_change)
2588         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2589         << !FirstCCExplicit
2590         << (!FirstCCExplicit ? "" :
2591             FunctionType::getNameForCallConv(FI.getCC()));
2592 
2593       // Put the note on the first decl, since it is the one that matters.
2594       Diag(First->getLocation(), diag::note_previous_declaration);
2595       return true;
2596     }
2597   }
2598 
2599   // FIXME: diagnose the other way around?
2600   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2601     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2602     RequiresAdjustment = true;
2603   }
2604 
2605   // Merge regparm attribute.
2606   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2607       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2608     if (NewTypeInfo.getHasRegParm()) {
2609       Diag(New->getLocation(), diag::err_regparm_mismatch)
2610         << NewType->getRegParmType()
2611         << OldType->getRegParmType();
2612       Diag(OldLocation, diag::note_previous_declaration);
2613       return true;
2614     }
2615 
2616     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2617     RequiresAdjustment = true;
2618   }
2619 
2620   // Merge ns_returns_retained attribute.
2621   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2622     if (NewTypeInfo.getProducesResult()) {
2623       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2624       Diag(OldLocation, diag::note_previous_declaration);
2625       return true;
2626     }
2627 
2628     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2629     RequiresAdjustment = true;
2630   }
2631 
2632   if (RequiresAdjustment) {
2633     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2634     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2635     New->setType(QualType(AdjustedType, 0));
2636     NewQType = Context.getCanonicalType(New->getType());
2637     NewType = cast<FunctionType>(NewQType);
2638   }
2639 
2640   // If this redeclaration makes the function inline, we may need to add it to
2641   // UndefinedButUsed.
2642   if (!Old->isInlined() && New->isInlined() &&
2643       !New->hasAttr<GNUInlineAttr>() &&
2644       (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2645       Old->isUsed(false) &&
2646       !Old->isDefined() && !New->isThisDeclarationADefinition())
2647     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2648                                            SourceLocation()));
2649 
2650   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2651   // about it.
2652   if (New->hasAttr<GNUInlineAttr>() &&
2653       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2654     UndefinedButUsed.erase(Old->getCanonicalDecl());
2655   }
2656 
2657   if (getLangOpts().CPlusPlus) {
2658     // (C++98 13.1p2):
2659     //   Certain function declarations cannot be overloaded:
2660     //     -- Function declarations that differ only in the return type
2661     //        cannot be overloaded.
2662 
2663     // Go back to the type source info to compare the declared return types,
2664     // per C++1y [dcl.type.auto]p13:
2665     //   Redeclarations or specializations of a function or function template
2666     //   with a declared return type that uses a placeholder type shall also
2667     //   use that placeholder, not a deduced type.
2668     QualType OldDeclaredReturnType =
2669         (Old->getTypeSourceInfo()
2670              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2671              : OldType)->getReturnType();
2672     QualType NewDeclaredReturnType =
2673         (New->getTypeSourceInfo()
2674              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2675              : NewType)->getReturnType();
2676     QualType ResQT;
2677     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2678         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2679           New->isLocalExternDecl())) {
2680       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2681           OldDeclaredReturnType->isObjCObjectPointerType())
2682         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2683       if (ResQT.isNull()) {
2684         if (New->isCXXClassMember() && New->isOutOfLine())
2685           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2686               << New << New->getReturnTypeSourceRange();
2687         else
2688           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2689               << New->getReturnTypeSourceRange();
2690         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2691                                     << Old->getReturnTypeSourceRange();
2692         return true;
2693       }
2694       else
2695         NewQType = ResQT;
2696     }
2697 
2698     QualType OldReturnType = OldType->getReturnType();
2699     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2700     if (OldReturnType != NewReturnType) {
2701       // If this function has a deduced return type and has already been
2702       // defined, copy the deduced value from the old declaration.
2703       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2704       if (OldAT && OldAT->isDeduced()) {
2705         New->setType(
2706             SubstAutoType(New->getType(),
2707                           OldAT->isDependentType() ? Context.DependentTy
2708                                                    : OldAT->getDeducedType()));
2709         NewQType = Context.getCanonicalType(
2710             SubstAutoType(NewQType,
2711                           OldAT->isDependentType() ? Context.DependentTy
2712                                                    : OldAT->getDeducedType()));
2713       }
2714     }
2715 
2716     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2717     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2718     if (OldMethod && NewMethod) {
2719       // Preserve triviality.
2720       NewMethod->setTrivial(OldMethod->isTrivial());
2721 
2722       // MSVC allows explicit template specialization at class scope:
2723       // 2 CXXMethodDecls referring to the same function will be injected.
2724       // We don't want a redeclaration error.
2725       bool IsClassScopeExplicitSpecialization =
2726                               OldMethod->isFunctionTemplateSpecialization() &&
2727                               NewMethod->isFunctionTemplateSpecialization();
2728       bool isFriend = NewMethod->getFriendObjectKind();
2729 
2730       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2731           !IsClassScopeExplicitSpecialization) {
2732         //    -- Member function declarations with the same name and the
2733         //       same parameter types cannot be overloaded if any of them
2734         //       is a static member function declaration.
2735         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2736           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2737           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2738           return true;
2739         }
2740 
2741         // C++ [class.mem]p1:
2742         //   [...] A member shall not be declared twice in the
2743         //   member-specification, except that a nested class or member
2744         //   class template can be declared and then later defined.
2745         if (ActiveTemplateInstantiations.empty()) {
2746           unsigned NewDiag;
2747           if (isa<CXXConstructorDecl>(OldMethod))
2748             NewDiag = diag::err_constructor_redeclared;
2749           else if (isa<CXXDestructorDecl>(NewMethod))
2750             NewDiag = diag::err_destructor_redeclared;
2751           else if (isa<CXXConversionDecl>(NewMethod))
2752             NewDiag = diag::err_conv_function_redeclared;
2753           else
2754             NewDiag = diag::err_member_redeclared;
2755 
2756           Diag(New->getLocation(), NewDiag);
2757         } else {
2758           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2759             << New << New->getType();
2760         }
2761         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2762 
2763       // Complain if this is an explicit declaration of a special
2764       // member that was initially declared implicitly.
2765       //
2766       // As an exception, it's okay to befriend such methods in order
2767       // to permit the implicit constructor/destructor/operator calls.
2768       } else if (OldMethod->isImplicit()) {
2769         if (isFriend) {
2770           NewMethod->setImplicit();
2771         } else {
2772           Diag(NewMethod->getLocation(),
2773                diag::err_definition_of_implicitly_declared_member)
2774             << New << getSpecialMember(OldMethod);
2775           return true;
2776         }
2777       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2778         Diag(NewMethod->getLocation(),
2779              diag::err_definition_of_explicitly_defaulted_member)
2780           << getSpecialMember(OldMethod);
2781         return true;
2782       }
2783     }
2784 
2785     // C++11 [dcl.attr.noreturn]p1:
2786     //   The first declaration of a function shall specify the noreturn
2787     //   attribute if any declaration of that function specifies the noreturn
2788     //   attribute.
2789     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2790     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2791       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2792       Diag(Old->getFirstDecl()->getLocation(),
2793            diag::note_noreturn_missing_first_decl);
2794     }
2795 
2796     // C++11 [dcl.attr.depend]p2:
2797     //   The first declaration of a function shall specify the
2798     //   carries_dependency attribute for its declarator-id if any declaration
2799     //   of the function specifies the carries_dependency attribute.
2800     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2801     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2802       Diag(CDA->getLocation(),
2803            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2804       Diag(Old->getFirstDecl()->getLocation(),
2805            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2806     }
2807 
2808     // (C++98 8.3.5p3):
2809     //   All declarations for a function shall agree exactly in both the
2810     //   return type and the parameter-type-list.
2811     // We also want to respect all the extended bits except noreturn.
2812 
2813     // noreturn should now match unless the old type info didn't have it.
2814     QualType OldQTypeForComparison = OldQType;
2815     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2816       assert(OldQType == QualType(OldType, 0));
2817       const FunctionType *OldTypeForComparison
2818         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2819       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2820       assert(OldQTypeForComparison.isCanonical());
2821     }
2822 
2823     if (haveIncompatibleLanguageLinkages(Old, New)) {
2824       // As a special case, retain the language linkage from previous
2825       // declarations of a friend function as an extension.
2826       //
2827       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2828       // and is useful because there's otherwise no way to specify language
2829       // linkage within class scope.
2830       //
2831       // Check cautiously as the friend object kind isn't yet complete.
2832       if (New->getFriendObjectKind() != Decl::FOK_None) {
2833         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2834         Diag(OldLocation, PrevDiag);
2835       } else {
2836         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2837         Diag(OldLocation, PrevDiag);
2838         return true;
2839       }
2840     }
2841 
2842     if (OldQTypeForComparison == NewQType)
2843       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2844 
2845     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2846         New->isLocalExternDecl()) {
2847       // It's OK if we couldn't merge types for a local function declaraton
2848       // if either the old or new type is dependent. We'll merge the types
2849       // when we instantiate the function.
2850       return false;
2851     }
2852 
2853     // Fall through for conflicting redeclarations and redefinitions.
2854   }
2855 
2856   // C: Function types need to be compatible, not identical. This handles
2857   // duplicate function decls like "void f(int); void f(enum X);" properly.
2858   if (!getLangOpts().CPlusPlus &&
2859       Context.typesAreCompatible(OldQType, NewQType)) {
2860     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2861     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2862     const FunctionProtoType *OldProto = nullptr;
2863     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
2864         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2865       // The old declaration provided a function prototype, but the
2866       // new declaration does not. Merge in the prototype.
2867       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2868       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
2869       NewQType =
2870           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2871                                   OldProto->getExtProtoInfo());
2872       New->setType(NewQType);
2873       New->setHasInheritedPrototype();
2874 
2875       // Synthesize parameters with the same types.
2876       SmallVector<ParmVarDecl*, 16> Params;
2877       for (const auto &ParamType : OldProto->param_types()) {
2878         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
2879                                                  SourceLocation(), nullptr,
2880                                                  ParamType, /*TInfo=*/nullptr,
2881                                                  SC_None, nullptr);
2882         Param->setScopeInfo(0, Params.size());
2883         Param->setImplicit();
2884         Params.push_back(Param);
2885       }
2886 
2887       New->setParams(Params);
2888     }
2889 
2890     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2891   }
2892 
2893   // GNU C permits a K&R definition to follow a prototype declaration
2894   // if the declared types of the parameters in the K&R definition
2895   // match the types in the prototype declaration, even when the
2896   // promoted types of the parameters from the K&R definition differ
2897   // from the types in the prototype. GCC then keeps the types from
2898   // the prototype.
2899   //
2900   // If a variadic prototype is followed by a non-variadic K&R definition,
2901   // the K&R definition becomes variadic.  This is sort of an edge case, but
2902   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2903   // C99 6.9.1p8.
2904   if (!getLangOpts().CPlusPlus &&
2905       Old->hasPrototype() && !New->hasPrototype() &&
2906       New->getType()->getAs<FunctionProtoType>() &&
2907       Old->getNumParams() == New->getNumParams()) {
2908     SmallVector<QualType, 16> ArgTypes;
2909     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2910     const FunctionProtoType *OldProto
2911       = Old->getType()->getAs<FunctionProtoType>();
2912     const FunctionProtoType *NewProto
2913       = New->getType()->getAs<FunctionProtoType>();
2914 
2915     // Determine whether this is the GNU C extension.
2916     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2917                                                NewProto->getReturnType());
2918     bool LooseCompatible = !MergedReturn.isNull();
2919     for (unsigned Idx = 0, End = Old->getNumParams();
2920          LooseCompatible && Idx != End; ++Idx) {
2921       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2922       ParmVarDecl *NewParm = New->getParamDecl(Idx);
2923       if (Context.typesAreCompatible(OldParm->getType(),
2924                                      NewProto->getParamType(Idx))) {
2925         ArgTypes.push_back(NewParm->getType());
2926       } else if (Context.typesAreCompatible(OldParm->getType(),
2927                                             NewParm->getType(),
2928                                             /*CompareUnqualified=*/true)) {
2929         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2930                                            NewProto->getParamType(Idx) };
2931         Warnings.push_back(Warn);
2932         ArgTypes.push_back(NewParm->getType());
2933       } else
2934         LooseCompatible = false;
2935     }
2936 
2937     if (LooseCompatible) {
2938       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2939         Diag(Warnings[Warn].NewParm->getLocation(),
2940              diag::ext_param_promoted_not_compatible_with_prototype)
2941           << Warnings[Warn].PromotedType
2942           << Warnings[Warn].OldParm->getType();
2943         if (Warnings[Warn].OldParm->getLocation().isValid())
2944           Diag(Warnings[Warn].OldParm->getLocation(),
2945                diag::note_previous_declaration);
2946       }
2947 
2948       if (MergeTypeWithOld)
2949         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2950                                              OldProto->getExtProtoInfo()));
2951       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2952     }
2953 
2954     // Fall through to diagnose conflicting types.
2955   }
2956 
2957   // A function that has already been declared has been redeclared or
2958   // defined with a different type; show an appropriate diagnostic.
2959 
2960   // If the previous declaration was an implicitly-generated builtin
2961   // declaration, then at the very least we should use a specialized note.
2962   unsigned BuiltinID;
2963   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2964     // If it's actually a library-defined builtin function like 'malloc'
2965     // or 'printf', just warn about the incompatible redeclaration.
2966     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2967       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2968       Diag(OldLocation, diag::note_previous_builtin_declaration)
2969         << Old << Old->getType();
2970 
2971       // If this is a global redeclaration, just forget hereafter
2972       // about the "builtin-ness" of the function.
2973       //
2974       // Doing this for local extern declarations is problematic.  If
2975       // the builtin declaration remains visible, a second invalid
2976       // local declaration will produce a hard error; if it doesn't
2977       // remain visible, a single bogus local redeclaration (which is
2978       // actually only a warning) could break all the downstream code.
2979       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
2980         New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2981 
2982       return false;
2983     }
2984 
2985     PrevDiag = diag::note_previous_builtin_declaration;
2986   }
2987 
2988   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2989   Diag(OldLocation, PrevDiag) << Old << Old->getType();
2990   return true;
2991 }
2992 
2993 /// \brief Completes the merge of two function declarations that are
2994 /// known to be compatible.
2995 ///
2996 /// This routine handles the merging of attributes and other
2997 /// properties of function declarations from the old declaration to
2998 /// the new declaration, once we know that New is in fact a
2999 /// redeclaration of Old.
3000 ///
3001 /// \returns false
3002 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3003                                         Scope *S, bool MergeTypeWithOld) {
3004   // Merge the attributes
3005   mergeDeclAttributes(New, Old);
3006 
3007   // Merge "pure" flag.
3008   if (Old->isPure())
3009     New->setPure();
3010 
3011   // Merge "used" flag.
3012   if (Old->getMostRecentDecl()->isUsed(false))
3013     New->setIsUsed();
3014 
3015   // Merge attributes from the parameters.  These can mismatch with K&R
3016   // declarations.
3017   if (New->getNumParams() == Old->getNumParams())
3018     for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
3019       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
3020                                *this);
3021 
3022   if (getLangOpts().CPlusPlus)
3023     return MergeCXXFunctionDecl(New, Old, S);
3024 
3025   // Merge the function types so the we get the composite types for the return
3026   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3027   // was visible.
3028   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3029   if (!Merged.isNull() && MergeTypeWithOld)
3030     New->setType(Merged);
3031 
3032   return false;
3033 }
3034 
3035 
3036 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3037                                 ObjCMethodDecl *oldMethod) {
3038 
3039   // Merge the attributes, including deprecated/unavailable
3040   AvailabilityMergeKind MergeKind =
3041     isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3042                                                    : AMK_Override;
3043   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3044 
3045   // Merge attributes from the parameters.
3046   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3047                                        oe = oldMethod->param_end();
3048   for (ObjCMethodDecl::param_iterator
3049          ni = newMethod->param_begin(), ne = newMethod->param_end();
3050        ni != ne && oi != oe; ++ni, ++oi)
3051     mergeParamDeclAttributes(*ni, *oi, *this);
3052 
3053   CheckObjCMethodOverride(newMethod, oldMethod);
3054 }
3055 
3056 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3057 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3058 /// emitting diagnostics as appropriate.
3059 ///
3060 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3061 /// to here in AddInitializerToDecl. We can't check them before the initializer
3062 /// is attached.
3063 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3064                              bool MergeTypeWithOld) {
3065   if (New->isInvalidDecl() || Old->isInvalidDecl())
3066     return;
3067 
3068   QualType MergedT;
3069   if (getLangOpts().CPlusPlus) {
3070     if (New->getType()->isUndeducedType()) {
3071       // We don't know what the new type is until the initializer is attached.
3072       return;
3073     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3074       // These could still be something that needs exception specs checked.
3075       return MergeVarDeclExceptionSpecs(New, Old);
3076     }
3077     // C++ [basic.link]p10:
3078     //   [...] the types specified by all declarations referring to a given
3079     //   object or function shall be identical, except that declarations for an
3080     //   array object can specify array types that differ by the presence or
3081     //   absence of a major array bound (8.3.4).
3082     else if (Old->getType()->isIncompleteArrayType() &&
3083              New->getType()->isArrayType()) {
3084       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3085       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3086       if (Context.hasSameType(OldArray->getElementType(),
3087                               NewArray->getElementType()))
3088         MergedT = New->getType();
3089     } else if (Old->getType()->isArrayType() &&
3090                New->getType()->isIncompleteArrayType()) {
3091       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3092       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3093       if (Context.hasSameType(OldArray->getElementType(),
3094                               NewArray->getElementType()))
3095         MergedT = Old->getType();
3096     } else if (New->getType()->isObjCObjectPointerType() &&
3097                Old->getType()->isObjCObjectPointerType()) {
3098       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3099                                               Old->getType());
3100     }
3101   } else {
3102     // C 6.2.7p2:
3103     //   All declarations that refer to the same object or function shall have
3104     //   compatible type.
3105     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3106   }
3107   if (MergedT.isNull()) {
3108     // It's OK if we couldn't merge types if either type is dependent, for a
3109     // block-scope variable. In other cases (static data members of class
3110     // templates, variable templates, ...), we require the types to be
3111     // equivalent.
3112     // FIXME: The C++ standard doesn't say anything about this.
3113     if ((New->getType()->isDependentType() ||
3114          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3115       // If the old type was dependent, we can't merge with it, so the new type
3116       // becomes dependent for now. We'll reproduce the original type when we
3117       // instantiate the TypeSourceInfo for the variable.
3118       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3119         New->setType(Context.DependentTy);
3120       return;
3121     }
3122 
3123     // FIXME: Even if this merging succeeds, some other non-visible declaration
3124     // of this variable might have an incompatible type. For instance:
3125     //
3126     //   extern int arr[];
3127     //   void f() { extern int arr[2]; }
3128     //   void g() { extern int arr[3]; }
3129     //
3130     // Neither C nor C++ requires a diagnostic for this, but we should still try
3131     // to diagnose it.
3132     Diag(New->getLocation(), diag::err_redefinition_different_type)
3133       << New->getDeclName() << New->getType() << Old->getType();
3134     Diag(Old->getLocation(), diag::note_previous_definition);
3135     return New->setInvalidDecl();
3136   }
3137 
3138   // Don't actually update the type on the new declaration if the old
3139   // declaration was an extern declaration in a different scope.
3140   if (MergeTypeWithOld)
3141     New->setType(MergedT);
3142 }
3143 
3144 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3145                                   LookupResult &Previous) {
3146   // C11 6.2.7p4:
3147   //   For an identifier with internal or external linkage declared
3148   //   in a scope in which a prior declaration of that identifier is
3149   //   visible, if the prior declaration specifies internal or
3150   //   external linkage, the type of the identifier at the later
3151   //   declaration becomes the composite type.
3152   //
3153   // If the variable isn't visible, we do not merge with its type.
3154   if (Previous.isShadowed())
3155     return false;
3156 
3157   if (S.getLangOpts().CPlusPlus) {
3158     // C++11 [dcl.array]p3:
3159     //   If there is a preceding declaration of the entity in the same
3160     //   scope in which the bound was specified, an omitted array bound
3161     //   is taken to be the same as in that earlier declaration.
3162     return NewVD->isPreviousDeclInSameBlockScope() ||
3163            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3164             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3165   } else {
3166     // If the old declaration was function-local, don't merge with its
3167     // type unless we're in the same function.
3168     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3169            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3170   }
3171 }
3172 
3173 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3174 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3175 /// situation, merging decls or emitting diagnostics as appropriate.
3176 ///
3177 /// Tentative definition rules (C99 6.9.2p2) are checked by
3178 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3179 /// definitions here, since the initializer hasn't been attached.
3180 ///
3181 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3182   // If the new decl is already invalid, don't do any other checking.
3183   if (New->isInvalidDecl())
3184     return;
3185 
3186   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3187 
3188   // Verify the old decl was also a variable or variable template.
3189   VarDecl *Old = nullptr;
3190   VarTemplateDecl *OldTemplate = nullptr;
3191   if (Previous.isSingleResult()) {
3192     if (NewTemplate) {
3193       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3194       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3195     } else
3196       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3197   }
3198   if (!Old) {
3199     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3200       << New->getDeclName();
3201     Diag(Previous.getRepresentativeDecl()->getLocation(),
3202          diag::note_previous_definition);
3203     return New->setInvalidDecl();
3204   }
3205 
3206   if (!shouldLinkPossiblyHiddenDecl(Old, New))
3207     return;
3208 
3209   // Ensure the template parameters are compatible.
3210   if (NewTemplate &&
3211       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3212                                       OldTemplate->getTemplateParameters(),
3213                                       /*Complain=*/true, TPL_TemplateMatch))
3214     return;
3215 
3216   // C++ [class.mem]p1:
3217   //   A member shall not be declared twice in the member-specification [...]
3218   //
3219   // Here, we need only consider static data members.
3220   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3221     Diag(New->getLocation(), diag::err_duplicate_member)
3222       << New->getIdentifier();
3223     Diag(Old->getLocation(), diag::note_previous_declaration);
3224     New->setInvalidDecl();
3225   }
3226 
3227   mergeDeclAttributes(New, Old);
3228   // Warn if an already-declared variable is made a weak_import in a subsequent
3229   // declaration
3230   if (New->hasAttr<WeakImportAttr>() &&
3231       Old->getStorageClass() == SC_None &&
3232       !Old->hasAttr<WeakImportAttr>()) {
3233     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3234     Diag(Old->getLocation(), diag::note_previous_definition);
3235     // Remove weak_import attribute on new declaration.
3236     New->dropAttr<WeakImportAttr>();
3237   }
3238 
3239   // Merge the types.
3240   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3241 
3242   if (New->isInvalidDecl())
3243     return;
3244 
3245   diag::kind PrevDiag;
3246   SourceLocation OldLocation;
3247   std::tie(PrevDiag, OldLocation) =
3248       getNoteDiagForInvalidRedeclaration(Old, New);
3249 
3250   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3251   if (New->getStorageClass() == SC_Static &&
3252       !New->isStaticDataMember() &&
3253       Old->hasExternalFormalLinkage()) {
3254     if (getLangOpts().MicrosoftExt) {
3255       Diag(New->getLocation(), diag::ext_static_non_static)
3256           << New->getDeclName();
3257       Diag(OldLocation, PrevDiag);
3258     } else {
3259       Diag(New->getLocation(), diag::err_static_non_static)
3260           << New->getDeclName();
3261       Diag(OldLocation, PrevDiag);
3262       return New->setInvalidDecl();
3263     }
3264   }
3265   // C99 6.2.2p4:
3266   //   For an identifier declared with the storage-class specifier
3267   //   extern in a scope in which a prior declaration of that
3268   //   identifier is visible,23) if the prior declaration specifies
3269   //   internal or external linkage, the linkage of the identifier at
3270   //   the later declaration is the same as the linkage specified at
3271   //   the prior declaration. If no prior declaration is visible, or
3272   //   if the prior declaration specifies no linkage, then the
3273   //   identifier has external linkage.
3274   if (New->hasExternalStorage() && Old->hasLinkage())
3275     /* Okay */;
3276   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3277            !New->isStaticDataMember() &&
3278            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3279     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3280     Diag(OldLocation, PrevDiag);
3281     return New->setInvalidDecl();
3282   }
3283 
3284   // Check if extern is followed by non-extern and vice-versa.
3285   if (New->hasExternalStorage() &&
3286       !Old->hasLinkage() && Old->isLocalVarDecl()) {
3287     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3288     Diag(OldLocation, PrevDiag);
3289     return New->setInvalidDecl();
3290   }
3291   if (Old->hasLinkage() && New->isLocalVarDecl() &&
3292       !New->hasExternalStorage()) {
3293     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3294     Diag(OldLocation, PrevDiag);
3295     return New->setInvalidDecl();
3296   }
3297 
3298   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3299 
3300   // FIXME: The test for external storage here seems wrong? We still
3301   // need to check for mismatches.
3302   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3303       // Don't complain about out-of-line definitions of static members.
3304       !(Old->getLexicalDeclContext()->isRecord() &&
3305         !New->getLexicalDeclContext()->isRecord())) {
3306     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3307     Diag(OldLocation, PrevDiag);
3308     return New->setInvalidDecl();
3309   }
3310 
3311   if (New->getTLSKind() != Old->getTLSKind()) {
3312     if (!Old->getTLSKind()) {
3313       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3314       Diag(OldLocation, PrevDiag);
3315     } else if (!New->getTLSKind()) {
3316       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3317       Diag(OldLocation, PrevDiag);
3318     } else {
3319       // Do not allow redeclaration to change the variable between requiring
3320       // static and dynamic initialization.
3321       // FIXME: GCC allows this, but uses the TLS keyword on the first
3322       // declaration to determine the kind. Do we need to be compatible here?
3323       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3324         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3325       Diag(OldLocation, PrevDiag);
3326     }
3327   }
3328 
3329   // C++ doesn't have tentative definitions, so go right ahead and check here.
3330   const VarDecl *Def;
3331   if (getLangOpts().CPlusPlus &&
3332       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3333       (Def = Old->getDefinition())) {
3334     Diag(New->getLocation(), diag::err_redefinition) << New;
3335     Diag(Def->getLocation(), diag::note_previous_definition);
3336     New->setInvalidDecl();
3337     return;
3338   }
3339 
3340   if (haveIncompatibleLanguageLinkages(Old, New)) {
3341     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3342     Diag(OldLocation, PrevDiag);
3343     New->setInvalidDecl();
3344     return;
3345   }
3346 
3347   // Merge "used" flag.
3348   if (Old->getMostRecentDecl()->isUsed(false))
3349     New->setIsUsed();
3350 
3351   // Keep a chain of previous declarations.
3352   New->setPreviousDecl(Old);
3353   if (NewTemplate)
3354     NewTemplate->setPreviousDecl(OldTemplate);
3355 
3356   // Inherit access appropriately.
3357   New->setAccess(Old->getAccess());
3358   if (NewTemplate)
3359     NewTemplate->setAccess(New->getAccess());
3360 }
3361 
3362 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3363 /// no declarator (e.g. "struct foo;") is parsed.
3364 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3365                                        DeclSpec &DS) {
3366   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3367 }
3368 
3369 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
3370   if (!S.Context.getLangOpts().CPlusPlus)
3371     return;
3372 
3373   if (isa<CXXRecordDecl>(Tag->getParent())) {
3374     // If this tag is the direct child of a class, number it if
3375     // it is anonymous.
3376     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3377       return;
3378     MangleNumberingContext &MCtx =
3379         S.Context.getManglingNumberContext(Tag->getParent());
3380     S.Context.setManglingNumber(
3381         Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
3382     return;
3383   }
3384 
3385   // If this tag isn't a direct child of a class, number it if it is local.
3386   Decl *ManglingContextDecl;
3387   if (MangleNumberingContext *MCtx =
3388           S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3389                                           ManglingContextDecl)) {
3390     S.Context.setManglingNumber(
3391         Tag,
3392         MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
3393   }
3394 }
3395 
3396 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3397 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3398 /// parameters to cope with template friend declarations.
3399 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3400                                        DeclSpec &DS,
3401                                        MultiTemplateParamsArg TemplateParams,
3402                                        bool IsExplicitInstantiation) {
3403   Decl *TagD = nullptr;
3404   TagDecl *Tag = nullptr;
3405   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3406       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3407       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3408       DS.getTypeSpecType() == DeclSpec::TST_union ||
3409       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3410     TagD = DS.getRepAsDecl();
3411 
3412     if (!TagD) // We probably had an error
3413       return nullptr;
3414 
3415     // Note that the above type specs guarantee that the
3416     // type rep is a Decl, whereas in many of the others
3417     // it's a Type.
3418     if (isa<TagDecl>(TagD))
3419       Tag = cast<TagDecl>(TagD);
3420     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3421       Tag = CTD->getTemplatedDecl();
3422   }
3423 
3424   if (Tag) {
3425     HandleTagNumbering(*this, Tag, S);
3426     Tag->setFreeStanding();
3427     if (Tag->isInvalidDecl())
3428       return Tag;
3429   }
3430 
3431   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3432     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3433     // or incomplete types shall not be restrict-qualified."
3434     if (TypeQuals & DeclSpec::TQ_restrict)
3435       Diag(DS.getRestrictSpecLoc(),
3436            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3437            << DS.getSourceRange();
3438   }
3439 
3440   if (DS.isConstexprSpecified()) {
3441     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3442     // and definitions of functions and variables.
3443     if (Tag)
3444       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3445         << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3446             DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3447             DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3448             DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
3449     else
3450       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3451     // Don't emit warnings after this error.
3452     return TagD;
3453   }
3454 
3455   DiagnoseFunctionSpecifiers(DS);
3456 
3457   if (DS.isFriendSpecified()) {
3458     // If we're dealing with a decl but not a TagDecl, assume that
3459     // whatever routines created it handled the friendship aspect.
3460     if (TagD && !Tag)
3461       return nullptr;
3462     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3463   }
3464 
3465   CXXScopeSpec &SS = DS.getTypeSpecScope();
3466   bool IsExplicitSpecialization =
3467     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3468   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3469       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3470     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3471     // nested-name-specifier unless it is an explicit instantiation
3472     // or an explicit specialization.
3473     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3474     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3475       << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3476           DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3477           DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3478           DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3479       << SS.getRange();
3480     return nullptr;
3481   }
3482 
3483   // Track whether this decl-specifier declares anything.
3484   bool DeclaresAnything = true;
3485 
3486   // Handle anonymous struct definitions.
3487   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3488     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3489         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3490       if (getLangOpts().CPlusPlus ||
3491           Record->getDeclContext()->isRecord())
3492         return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
3493 
3494       DeclaresAnything = false;
3495     }
3496   }
3497 
3498   // C11 6.7.2.1p2:
3499   //   A struct-declaration that does not declare an anonymous structure or
3500   //   anonymous union shall contain a struct-declarator-list.
3501   //
3502   // This rule also existed in C89 and C99; the grammar for struct-declaration
3503   // did not permit a struct-declaration without a struct-declarator-list.
3504   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3505       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3506     // Check for Microsoft C extension: anonymous struct/union member.
3507     // Handle 2 kinds of anonymous struct/union:
3508     //   struct STRUCT;
3509     //   union UNION;
3510     // and
3511     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3512     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3513     if ((Tag && Tag->getDeclName()) ||
3514         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3515       RecordDecl *Record = nullptr;
3516       if (Tag)
3517         Record = dyn_cast<RecordDecl>(Tag);
3518       else if (const RecordType *RT =
3519                    DS.getRepAsType().get()->getAsStructureType())
3520         Record = RT->getDecl();
3521       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3522         Record = UT->getDecl();
3523 
3524       if (Record && getLangOpts().MicrosoftExt) {
3525         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3526           << Record->isUnion() << DS.getSourceRange();
3527         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3528       }
3529 
3530       DeclaresAnything = false;
3531     }
3532   }
3533 
3534   // Skip all the checks below if we have a type error.
3535   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3536       (TagD && TagD->isInvalidDecl()))
3537     return TagD;
3538 
3539   if (getLangOpts().CPlusPlus &&
3540       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3541     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3542       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3543           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3544         DeclaresAnything = false;
3545 
3546   if (!DS.isMissingDeclaratorOk()) {
3547     // Customize diagnostic for a typedef missing a name.
3548     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3549       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3550         << DS.getSourceRange();
3551     else
3552       DeclaresAnything = false;
3553   }
3554 
3555   if (DS.isModulePrivateSpecified() &&
3556       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3557     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3558       << Tag->getTagKind()
3559       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3560 
3561   ActOnDocumentableDecl(TagD);
3562 
3563   // C 6.7/2:
3564   //   A declaration [...] shall declare at least a declarator [...], a tag,
3565   //   or the members of an enumeration.
3566   // C++ [dcl.dcl]p3:
3567   //   [If there are no declarators], and except for the declaration of an
3568   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3569   //   names into the program, or shall redeclare a name introduced by a
3570   //   previous declaration.
3571   if (!DeclaresAnything) {
3572     // In C, we allow this as a (popular) extension / bug. Don't bother
3573     // producing further diagnostics for redundant qualifiers after this.
3574     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3575     return TagD;
3576   }
3577 
3578   // C++ [dcl.stc]p1:
3579   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3580   //   init-declarator-list of the declaration shall not be empty.
3581   // C++ [dcl.fct.spec]p1:
3582   //   If a cv-qualifier appears in a decl-specifier-seq, the
3583   //   init-declarator-list of the declaration shall not be empty.
3584   //
3585   // Spurious qualifiers here appear to be valid in C.
3586   unsigned DiagID = diag::warn_standalone_specifier;
3587   if (getLangOpts().CPlusPlus)
3588     DiagID = diag::ext_standalone_specifier;
3589 
3590   // Note that a linkage-specification sets a storage class, but
3591   // 'extern "C" struct foo;' is actually valid and not theoretically
3592   // useless.
3593   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3594     if (SCS == DeclSpec::SCS_mutable)
3595       // Since mutable is not a viable storage class specifier in C, there is
3596       // no reason to treat it as an extension. Instead, diagnose as an error.
3597       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3598     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3599       Diag(DS.getStorageClassSpecLoc(), DiagID)
3600         << DeclSpec::getSpecifierName(SCS);
3601   }
3602 
3603   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3604     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3605       << DeclSpec::getSpecifierName(TSCS);
3606   if (DS.getTypeQualifiers()) {
3607     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3608       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3609     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3610       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3611     // Restrict is covered above.
3612     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3613       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3614   }
3615 
3616   // Warn about ignored type attributes, for example:
3617   // __attribute__((aligned)) struct A;
3618   // Attributes should be placed after tag to apply to type declaration.
3619   if (!DS.getAttributes().empty()) {
3620     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3621     if (TypeSpecType == DeclSpec::TST_class ||
3622         TypeSpecType == DeclSpec::TST_struct ||
3623         TypeSpecType == DeclSpec::TST_interface ||
3624         TypeSpecType == DeclSpec::TST_union ||
3625         TypeSpecType == DeclSpec::TST_enum) {
3626       AttributeList* attrs = DS.getAttributes().getList();
3627       while (attrs) {
3628         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3629         << attrs->getName()
3630         << (TypeSpecType == DeclSpec::TST_class ? 0 :
3631             TypeSpecType == DeclSpec::TST_struct ? 1 :
3632             TypeSpecType == DeclSpec::TST_union ? 2 :
3633             TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
3634         attrs = attrs->getNext();
3635       }
3636     }
3637   }
3638 
3639   return TagD;
3640 }
3641 
3642 /// We are trying to inject an anonymous member into the given scope;
3643 /// check if there's an existing declaration that can't be overloaded.
3644 ///
3645 /// \return true if this is a forbidden redeclaration
3646 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3647                                          Scope *S,
3648                                          DeclContext *Owner,
3649                                          DeclarationName Name,
3650                                          SourceLocation NameLoc,
3651                                          unsigned diagnostic) {
3652   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3653                  Sema::ForRedeclaration);
3654   if (!SemaRef.LookupName(R, S)) return false;
3655 
3656   if (R.getAsSingle<TagDecl>())
3657     return false;
3658 
3659   // Pick a representative declaration.
3660   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3661   assert(PrevDecl && "Expected a non-null Decl");
3662 
3663   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3664     return false;
3665 
3666   SemaRef.Diag(NameLoc, diagnostic) << Name;
3667   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3668 
3669   return true;
3670 }
3671 
3672 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3673 /// anonymous struct or union AnonRecord into the owning context Owner
3674 /// and scope S. This routine will be invoked just after we realize
3675 /// that an unnamed union or struct is actually an anonymous union or
3676 /// struct, e.g.,
3677 ///
3678 /// @code
3679 /// union {
3680 ///   int i;
3681 ///   float f;
3682 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3683 ///    // f into the surrounding scope.x
3684 /// @endcode
3685 ///
3686 /// This routine is recursive, injecting the names of nested anonymous
3687 /// structs/unions into the owning context and scope as well.
3688 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3689                                          DeclContext *Owner,
3690                                          RecordDecl *AnonRecord,
3691                                          AccessSpecifier AS,
3692                                          SmallVectorImpl<NamedDecl *> &Chaining,
3693                                          bool MSAnonStruct) {
3694   unsigned diagKind
3695     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3696                             : diag::err_anonymous_struct_member_redecl;
3697 
3698   bool Invalid = false;
3699 
3700   // Look every FieldDecl and IndirectFieldDecl with a name.
3701   for (auto *D : AnonRecord->decls()) {
3702     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3703         cast<NamedDecl>(D)->getDeclName()) {
3704       ValueDecl *VD = cast<ValueDecl>(D);
3705       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3706                                        VD->getLocation(), diagKind)) {
3707         // C++ [class.union]p2:
3708         //   The names of the members of an anonymous union shall be
3709         //   distinct from the names of any other entity in the
3710         //   scope in which the anonymous union is declared.
3711         Invalid = true;
3712       } else {
3713         // C++ [class.union]p2:
3714         //   For the purpose of name lookup, after the anonymous union
3715         //   definition, the members of the anonymous union are
3716         //   considered to have been defined in the scope in which the
3717         //   anonymous union is declared.
3718         unsigned OldChainingSize = Chaining.size();
3719         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3720           for (auto *PI : IF->chain())
3721             Chaining.push_back(PI);
3722         else
3723           Chaining.push_back(VD);
3724 
3725         assert(Chaining.size() >= 2);
3726         NamedDecl **NamedChain =
3727           new (SemaRef.Context)NamedDecl*[Chaining.size()];
3728         for (unsigned i = 0; i < Chaining.size(); i++)
3729           NamedChain[i] = Chaining[i];
3730 
3731         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
3732             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
3733             VD->getType(), NamedChain, Chaining.size());
3734 
3735         for (const auto *Attr : VD->attrs())
3736           IndirectField->addAttr(Attr->clone(SemaRef.Context));
3737 
3738         IndirectField->setAccess(AS);
3739         IndirectField->setImplicit();
3740         SemaRef.PushOnScopeChains(IndirectField, S);
3741 
3742         // That includes picking up the appropriate access specifier.
3743         if (AS != AS_none) IndirectField->setAccess(AS);
3744 
3745         Chaining.resize(OldChainingSize);
3746       }
3747     }
3748   }
3749 
3750   return Invalid;
3751 }
3752 
3753 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3754 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
3755 /// illegal input values are mapped to SC_None.
3756 static StorageClass
3757 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3758   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3759   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3760          "Parser allowed 'typedef' as storage class VarDecl.");
3761   switch (StorageClassSpec) {
3762   case DeclSpec::SCS_unspecified:    return SC_None;
3763   case DeclSpec::SCS_extern:
3764     if (DS.isExternInLinkageSpec())
3765       return SC_None;
3766     return SC_Extern;
3767   case DeclSpec::SCS_static:         return SC_Static;
3768   case DeclSpec::SCS_auto:           return SC_Auto;
3769   case DeclSpec::SCS_register:       return SC_Register;
3770   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3771     // Illegal SCSs map to None: error reporting is up to the caller.
3772   case DeclSpec::SCS_mutable:        // Fall through.
3773   case DeclSpec::SCS_typedef:        return SC_None;
3774   }
3775   llvm_unreachable("unknown storage class specifier");
3776 }
3777 
3778 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3779   assert(Record->hasInClassInitializer());
3780 
3781   for (const auto *I : Record->decls()) {
3782     const auto *FD = dyn_cast<FieldDecl>(I);
3783     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
3784       FD = IFD->getAnonField();
3785     if (FD && FD->hasInClassInitializer())
3786       return FD->getLocation();
3787   }
3788 
3789   llvm_unreachable("couldn't find in-class initializer");
3790 }
3791 
3792 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3793                                       SourceLocation DefaultInitLoc) {
3794   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3795     return;
3796 
3797   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3798   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3799 }
3800 
3801 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3802                                       CXXRecordDecl *AnonUnion) {
3803   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3804     return;
3805 
3806   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3807 }
3808 
3809 /// BuildAnonymousStructOrUnion - Handle the declaration of an
3810 /// anonymous structure or union. Anonymous unions are a C++ feature
3811 /// (C++ [class.union]) and a C11 feature; anonymous structures
3812 /// are a C11 feature and GNU C++ extension.
3813 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3814                                         AccessSpecifier AS,
3815                                         RecordDecl *Record,
3816                                         const PrintingPolicy &Policy) {
3817   DeclContext *Owner = Record->getDeclContext();
3818 
3819   // Diagnose whether this anonymous struct/union is an extension.
3820   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
3821     Diag(Record->getLocation(), diag::ext_anonymous_union);
3822   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
3823     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3824   else if (!Record->isUnion() && !getLangOpts().C11)
3825     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3826 
3827   // C and C++ require different kinds of checks for anonymous
3828   // structs/unions.
3829   bool Invalid = false;
3830   if (getLangOpts().CPlusPlus) {
3831     const char *PrevSpec = nullptr;
3832     unsigned DiagID;
3833     if (Record->isUnion()) {
3834       // C++ [class.union]p6:
3835       //   Anonymous unions declared in a named namespace or in the
3836       //   global namespace shall be declared static.
3837       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3838           (isa<TranslationUnitDecl>(Owner) ||
3839            (isa<NamespaceDecl>(Owner) &&
3840             cast<NamespaceDecl>(Owner)->getDeclName()))) {
3841         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3842           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3843 
3844         // Recover by adding 'static'.
3845         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3846                                PrevSpec, DiagID, Policy);
3847       }
3848       // C++ [class.union]p6:
3849       //   A storage class is not allowed in a declaration of an
3850       //   anonymous union in a class scope.
3851       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3852                isa<RecordDecl>(Owner)) {
3853         Diag(DS.getStorageClassSpecLoc(),
3854              diag::err_anonymous_union_with_storage_spec)
3855           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3856 
3857         // Recover by removing the storage specifier.
3858         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3859                                SourceLocation(),
3860                                PrevSpec, DiagID, Context.getPrintingPolicy());
3861       }
3862     }
3863 
3864     // Ignore const/volatile/restrict qualifiers.
3865     if (DS.getTypeQualifiers()) {
3866       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3867         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3868           << Record->isUnion() << "const"
3869           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3870       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3871         Diag(DS.getVolatileSpecLoc(),
3872              diag::ext_anonymous_struct_union_qualified)
3873           << Record->isUnion() << "volatile"
3874           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3875       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3876         Diag(DS.getRestrictSpecLoc(),
3877              diag::ext_anonymous_struct_union_qualified)
3878           << Record->isUnion() << "restrict"
3879           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3880       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3881         Diag(DS.getAtomicSpecLoc(),
3882              diag::ext_anonymous_struct_union_qualified)
3883           << Record->isUnion() << "_Atomic"
3884           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
3885 
3886       DS.ClearTypeQualifiers();
3887     }
3888 
3889     // C++ [class.union]p2:
3890     //   The member-specification of an anonymous union shall only
3891     //   define non-static data members. [Note: nested types and
3892     //   functions cannot be declared within an anonymous union. ]
3893     for (auto *Mem : Record->decls()) {
3894       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
3895         // C++ [class.union]p3:
3896         //   An anonymous union shall not have private or protected
3897         //   members (clause 11).
3898         assert(FD->getAccess() != AS_none);
3899         if (FD->getAccess() != AS_public) {
3900           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3901             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3902           Invalid = true;
3903         }
3904 
3905         // C++ [class.union]p1
3906         //   An object of a class with a non-trivial constructor, a non-trivial
3907         //   copy constructor, a non-trivial destructor, or a non-trivial copy
3908         //   assignment operator cannot be a member of a union, nor can an
3909         //   array of such objects.
3910         if (CheckNontrivialField(FD))
3911           Invalid = true;
3912       } else if (Mem->isImplicit()) {
3913         // Any implicit members are fine.
3914       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
3915         // This is a type that showed up in an
3916         // elaborated-type-specifier inside the anonymous struct or
3917         // union, but which actually declares a type outside of the
3918         // anonymous struct or union. It's okay.
3919       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
3920         if (!MemRecord->isAnonymousStructOrUnion() &&
3921             MemRecord->getDeclName()) {
3922           // Visual C++ allows type definition in anonymous struct or union.
3923           if (getLangOpts().MicrosoftExt)
3924             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3925               << (int)Record->isUnion();
3926           else {
3927             // This is a nested type declaration.
3928             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3929               << (int)Record->isUnion();
3930             Invalid = true;
3931           }
3932         } else {
3933           // This is an anonymous type definition within another anonymous type.
3934           // This is a popular extension, provided by Plan9, MSVC and GCC, but
3935           // not part of standard C++.
3936           Diag(MemRecord->getLocation(),
3937                diag::ext_anonymous_record_with_anonymous_type)
3938             << (int)Record->isUnion();
3939         }
3940       } else if (isa<AccessSpecDecl>(Mem)) {
3941         // Any access specifier is fine.
3942       } else if (isa<StaticAssertDecl>(Mem)) {
3943         // In C++1z, static_assert declarations are also fine.
3944       } else {
3945         // We have something that isn't a non-static data
3946         // member. Complain about it.
3947         unsigned DK = diag::err_anonymous_record_bad_member;
3948         if (isa<TypeDecl>(Mem))
3949           DK = diag::err_anonymous_record_with_type;
3950         else if (isa<FunctionDecl>(Mem))
3951           DK = diag::err_anonymous_record_with_function;
3952         else if (isa<VarDecl>(Mem))
3953           DK = diag::err_anonymous_record_with_static;
3954 
3955         // Visual C++ allows type definition in anonymous struct or union.
3956         if (getLangOpts().MicrosoftExt &&
3957             DK == diag::err_anonymous_record_with_type)
3958           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
3959             << (int)Record->isUnion();
3960         else {
3961           Diag(Mem->getLocation(), DK)
3962               << (int)Record->isUnion();
3963           Invalid = true;
3964         }
3965       }
3966     }
3967 
3968     // C++11 [class.union]p8 (DR1460):
3969     //   At most one variant member of a union may have a
3970     //   brace-or-equal-initializer.
3971     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3972         Owner->isRecord())
3973       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3974                                 cast<CXXRecordDecl>(Record));
3975   }
3976 
3977   if (!Record->isUnion() && !Owner->isRecord()) {
3978     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3979       << (int)getLangOpts().CPlusPlus;
3980     Invalid = true;
3981   }
3982 
3983   // Mock up a declarator.
3984   Declarator Dc(DS, Declarator::MemberContext);
3985   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3986   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3987 
3988   // Create a declaration for this anonymous struct/union.
3989   NamedDecl *Anon = nullptr;
3990   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3991     Anon = FieldDecl::Create(Context, OwningClass,
3992                              DS.getLocStart(),
3993                              Record->getLocation(),
3994                              /*IdentifierInfo=*/nullptr,
3995                              Context.getTypeDeclType(Record),
3996                              TInfo,
3997                              /*BitWidth=*/nullptr, /*Mutable=*/false,
3998                              /*InitStyle=*/ICIS_NoInit);
3999     Anon->setAccess(AS);
4000     if (getLangOpts().CPlusPlus)
4001       FieldCollector->Add(cast<FieldDecl>(Anon));
4002   } else {
4003     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4004     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4005     if (SCSpec == DeclSpec::SCS_mutable) {
4006       // mutable can only appear on non-static class members, so it's always
4007       // an error here
4008       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4009       Invalid = true;
4010       SC = SC_None;
4011     }
4012 
4013     Anon = VarDecl::Create(Context, Owner,
4014                            DS.getLocStart(),
4015                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4016                            Context.getTypeDeclType(Record),
4017                            TInfo, SC);
4018 
4019     // Default-initialize the implicit variable. This initialization will be
4020     // trivial in almost all cases, except if a union member has an in-class
4021     // initializer:
4022     //   union { int n = 0; };
4023     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4024   }
4025   Anon->setImplicit();
4026 
4027   // Mark this as an anonymous struct/union type.
4028   Record->setAnonymousStructOrUnion(true);
4029 
4030   // Add the anonymous struct/union object to the current
4031   // context. We'll be referencing this object when we refer to one of
4032   // its members.
4033   Owner->addDecl(Anon);
4034 
4035   // Inject the members of the anonymous struct/union into the owning
4036   // context and into the identifier resolver chain for name lookup
4037   // purposes.
4038   SmallVector<NamedDecl*, 2> Chain;
4039   Chain.push_back(Anon);
4040 
4041   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
4042                                           Chain, false))
4043     Invalid = true;
4044 
4045   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4046     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4047       Decl *ManglingContextDecl;
4048       if (MangleNumberingContext *MCtx =
4049               getCurrentMangleNumberContext(NewVD->getDeclContext(),
4050                                             ManglingContextDecl)) {
4051         Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
4052         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4053       }
4054     }
4055   }
4056 
4057   if (Invalid)
4058     Anon->setInvalidDecl();
4059 
4060   return Anon;
4061 }
4062 
4063 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4064 /// Microsoft C anonymous structure.
4065 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4066 /// Example:
4067 ///
4068 /// struct A { int a; };
4069 /// struct B { struct A; int b; };
4070 ///
4071 /// void foo() {
4072 ///   B var;
4073 ///   var.a = 3;
4074 /// }
4075 ///
4076 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4077                                            RecordDecl *Record) {
4078   assert(Record && "expected a record!");
4079 
4080   // Mock up a declarator.
4081   Declarator Dc(DS, Declarator::TypeNameContext);
4082   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4083   assert(TInfo && "couldn't build declarator info for anonymous struct");
4084 
4085   auto *ParentDecl = cast<RecordDecl>(CurContext);
4086   QualType RecTy = Context.getTypeDeclType(Record);
4087 
4088   // Create a declaration for this anonymous struct.
4089   NamedDecl *Anon = FieldDecl::Create(Context,
4090                              ParentDecl,
4091                              DS.getLocStart(),
4092                              DS.getLocStart(),
4093                              /*IdentifierInfo=*/nullptr,
4094                              RecTy,
4095                              TInfo,
4096                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4097                              /*InitStyle=*/ICIS_NoInit);
4098   Anon->setImplicit();
4099 
4100   // Add the anonymous struct object to the current context.
4101   CurContext->addDecl(Anon);
4102 
4103   // Inject the members of the anonymous struct into the current
4104   // context and into the identifier resolver chain for name lookup
4105   // purposes.
4106   SmallVector<NamedDecl*, 2> Chain;
4107   Chain.push_back(Anon);
4108 
4109   RecordDecl *RecordDef = Record->getDefinition();
4110   if (RequireCompleteType(Anon->getLocation(), RecTy,
4111                           diag::err_field_incomplete) ||
4112       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4113                                           AS_none, Chain, true)) {
4114     Anon->setInvalidDecl();
4115     ParentDecl->setInvalidDecl();
4116   }
4117 
4118   return Anon;
4119 }
4120 
4121 /// GetNameForDeclarator - Determine the full declaration name for the
4122 /// given Declarator.
4123 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4124   return GetNameFromUnqualifiedId(D.getName());
4125 }
4126 
4127 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4128 DeclarationNameInfo
4129 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4130   DeclarationNameInfo NameInfo;
4131   NameInfo.setLoc(Name.StartLocation);
4132 
4133   switch (Name.getKind()) {
4134 
4135   case UnqualifiedId::IK_ImplicitSelfParam:
4136   case UnqualifiedId::IK_Identifier:
4137     NameInfo.setName(Name.Identifier);
4138     NameInfo.setLoc(Name.StartLocation);
4139     return NameInfo;
4140 
4141   case UnqualifiedId::IK_OperatorFunctionId:
4142     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4143                                            Name.OperatorFunctionId.Operator));
4144     NameInfo.setLoc(Name.StartLocation);
4145     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4146       = Name.OperatorFunctionId.SymbolLocations[0];
4147     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4148       = Name.EndLocation.getRawEncoding();
4149     return NameInfo;
4150 
4151   case UnqualifiedId::IK_LiteralOperatorId:
4152     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4153                                                            Name.Identifier));
4154     NameInfo.setLoc(Name.StartLocation);
4155     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4156     return NameInfo;
4157 
4158   case UnqualifiedId::IK_ConversionFunctionId: {
4159     TypeSourceInfo *TInfo;
4160     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4161     if (Ty.isNull())
4162       return DeclarationNameInfo();
4163     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4164                                                Context.getCanonicalType(Ty)));
4165     NameInfo.setLoc(Name.StartLocation);
4166     NameInfo.setNamedTypeInfo(TInfo);
4167     return NameInfo;
4168   }
4169 
4170   case UnqualifiedId::IK_ConstructorName: {
4171     TypeSourceInfo *TInfo;
4172     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4173     if (Ty.isNull())
4174       return DeclarationNameInfo();
4175     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4176                                               Context.getCanonicalType(Ty)));
4177     NameInfo.setLoc(Name.StartLocation);
4178     NameInfo.setNamedTypeInfo(TInfo);
4179     return NameInfo;
4180   }
4181 
4182   case UnqualifiedId::IK_ConstructorTemplateId: {
4183     // In well-formed code, we can only have a constructor
4184     // template-id that refers to the current context, so go there
4185     // to find the actual type being constructed.
4186     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4187     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4188       return DeclarationNameInfo();
4189 
4190     // Determine the type of the class being constructed.
4191     QualType CurClassType = Context.getTypeDeclType(CurClass);
4192 
4193     // FIXME: Check two things: that the template-id names the same type as
4194     // CurClassType, and that the template-id does not occur when the name
4195     // was qualified.
4196 
4197     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4198                                     Context.getCanonicalType(CurClassType)));
4199     NameInfo.setLoc(Name.StartLocation);
4200     // FIXME: should we retrieve TypeSourceInfo?
4201     NameInfo.setNamedTypeInfo(nullptr);
4202     return NameInfo;
4203   }
4204 
4205   case UnqualifiedId::IK_DestructorName: {
4206     TypeSourceInfo *TInfo;
4207     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4208     if (Ty.isNull())
4209       return DeclarationNameInfo();
4210     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4211                                               Context.getCanonicalType(Ty)));
4212     NameInfo.setLoc(Name.StartLocation);
4213     NameInfo.setNamedTypeInfo(TInfo);
4214     return NameInfo;
4215   }
4216 
4217   case UnqualifiedId::IK_TemplateId: {
4218     TemplateName TName = Name.TemplateId->Template.get();
4219     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4220     return Context.getNameForTemplate(TName, TNameLoc);
4221   }
4222 
4223   } // switch (Name.getKind())
4224 
4225   llvm_unreachable("Unknown name kind");
4226 }
4227 
4228 static QualType getCoreType(QualType Ty) {
4229   do {
4230     if (Ty->isPointerType() || Ty->isReferenceType())
4231       Ty = Ty->getPointeeType();
4232     else if (Ty->isArrayType())
4233       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4234     else
4235       return Ty.withoutLocalFastQualifiers();
4236   } while (true);
4237 }
4238 
4239 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4240 /// and Definition have "nearly" matching parameters. This heuristic is
4241 /// used to improve diagnostics in the case where an out-of-line function
4242 /// definition doesn't match any declaration within the class or namespace.
4243 /// Also sets Params to the list of indices to the parameters that differ
4244 /// between the declaration and the definition. If hasSimilarParameters
4245 /// returns true and Params is empty, then all of the parameters match.
4246 static bool hasSimilarParameters(ASTContext &Context,
4247                                      FunctionDecl *Declaration,
4248                                      FunctionDecl *Definition,
4249                                      SmallVectorImpl<unsigned> &Params) {
4250   Params.clear();
4251   if (Declaration->param_size() != Definition->param_size())
4252     return false;
4253   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4254     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4255     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4256 
4257     // The parameter types are identical
4258     if (Context.hasSameType(DefParamTy, DeclParamTy))
4259       continue;
4260 
4261     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4262     QualType DefParamBaseTy = getCoreType(DefParamTy);
4263     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4264     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4265 
4266     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4267         (DeclTyName && DeclTyName == DefTyName))
4268       Params.push_back(Idx);
4269     else  // The two parameters aren't even close
4270       return false;
4271   }
4272 
4273   return true;
4274 }
4275 
4276 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4277 /// declarator needs to be rebuilt in the current instantiation.
4278 /// Any bits of declarator which appear before the name are valid for
4279 /// consideration here.  That's specifically the type in the decl spec
4280 /// and the base type in any member-pointer chunks.
4281 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4282                                                     DeclarationName Name) {
4283   // The types we specifically need to rebuild are:
4284   //   - typenames, typeofs, and decltypes
4285   //   - types which will become injected class names
4286   // Of course, we also need to rebuild any type referencing such a
4287   // type.  It's safest to just say "dependent", but we call out a
4288   // few cases here.
4289 
4290   DeclSpec &DS = D.getMutableDeclSpec();
4291   switch (DS.getTypeSpecType()) {
4292   case DeclSpec::TST_typename:
4293   case DeclSpec::TST_typeofType:
4294   case DeclSpec::TST_underlyingType:
4295   case DeclSpec::TST_atomic: {
4296     // Grab the type from the parser.
4297     TypeSourceInfo *TSI = nullptr;
4298     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4299     if (T.isNull() || !T->isDependentType()) break;
4300 
4301     // Make sure there's a type source info.  This isn't really much
4302     // of a waste; most dependent types should have type source info
4303     // attached already.
4304     if (!TSI)
4305       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4306 
4307     // Rebuild the type in the current instantiation.
4308     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4309     if (!TSI) return true;
4310 
4311     // Store the new type back in the decl spec.
4312     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4313     DS.UpdateTypeRep(LocType);
4314     break;
4315   }
4316 
4317   case DeclSpec::TST_decltype:
4318   case DeclSpec::TST_typeofExpr: {
4319     Expr *E = DS.getRepAsExpr();
4320     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4321     if (Result.isInvalid()) return true;
4322     DS.UpdateExprRep(Result.get());
4323     break;
4324   }
4325 
4326   default:
4327     // Nothing to do for these decl specs.
4328     break;
4329   }
4330 
4331   // It doesn't matter what order we do this in.
4332   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4333     DeclaratorChunk &Chunk = D.getTypeObject(I);
4334 
4335     // The only type information in the declarator which can come
4336     // before the declaration name is the base type of a member
4337     // pointer.
4338     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4339       continue;
4340 
4341     // Rebuild the scope specifier in-place.
4342     CXXScopeSpec &SS = Chunk.Mem.Scope();
4343     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4344       return true;
4345   }
4346 
4347   return false;
4348 }
4349 
4350 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4351   D.setFunctionDefinitionKind(FDK_Declaration);
4352   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4353 
4354   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4355       Dcl && Dcl->getDeclContext()->isFileContext())
4356     Dcl->setTopLevelDeclInObjCContainer();
4357 
4358   return Dcl;
4359 }
4360 
4361 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4362 ///   If T is the name of a class, then each of the following shall have a
4363 ///   name different from T:
4364 ///     - every static data member of class T;
4365 ///     - every member function of class T
4366 ///     - every member of class T that is itself a type;
4367 /// \returns true if the declaration name violates these rules.
4368 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4369                                    DeclarationNameInfo NameInfo) {
4370   DeclarationName Name = NameInfo.getName();
4371 
4372   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4373     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4374       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4375       return true;
4376     }
4377 
4378   return false;
4379 }
4380 
4381 /// \brief Diagnose a declaration whose declarator-id has the given
4382 /// nested-name-specifier.
4383 ///
4384 /// \param SS The nested-name-specifier of the declarator-id.
4385 ///
4386 /// \param DC The declaration context to which the nested-name-specifier
4387 /// resolves.
4388 ///
4389 /// \param Name The name of the entity being declared.
4390 ///
4391 /// \param Loc The location of the name of the entity being declared.
4392 ///
4393 /// \returns true if we cannot safely recover from this error, false otherwise.
4394 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4395                                         DeclarationName Name,
4396                                         SourceLocation Loc) {
4397   DeclContext *Cur = CurContext;
4398   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4399     Cur = Cur->getParent();
4400 
4401   // If the user provided a superfluous scope specifier that refers back to the
4402   // class in which the entity is already declared, diagnose and ignore it.
4403   //
4404   // class X {
4405   //   void X::f();
4406   // };
4407   //
4408   // Note, it was once ill-formed to give redundant qualification in all
4409   // contexts, but that rule was removed by DR482.
4410   if (Cur->Equals(DC)) {
4411     if (Cur->isRecord()) {
4412       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4413                                       : diag::err_member_extra_qualification)
4414         << Name << FixItHint::CreateRemoval(SS.getRange());
4415       SS.clear();
4416     } else {
4417       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4418     }
4419     return false;
4420   }
4421 
4422   // Check whether the qualifying scope encloses the scope of the original
4423   // declaration.
4424   if (!Cur->Encloses(DC)) {
4425     if (Cur->isRecord())
4426       Diag(Loc, diag::err_member_qualification)
4427         << Name << SS.getRange();
4428     else if (isa<TranslationUnitDecl>(DC))
4429       Diag(Loc, diag::err_invalid_declarator_global_scope)
4430         << Name << SS.getRange();
4431     else if (isa<FunctionDecl>(Cur))
4432       Diag(Loc, diag::err_invalid_declarator_in_function)
4433         << Name << SS.getRange();
4434     else if (isa<BlockDecl>(Cur))
4435       Diag(Loc, diag::err_invalid_declarator_in_block)
4436         << Name << SS.getRange();
4437     else
4438       Diag(Loc, diag::err_invalid_declarator_scope)
4439       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4440 
4441     return true;
4442   }
4443 
4444   if (Cur->isRecord()) {
4445     // Cannot qualify members within a class.
4446     Diag(Loc, diag::err_member_qualification)
4447       << Name << SS.getRange();
4448     SS.clear();
4449 
4450     // C++ constructors and destructors with incorrect scopes can break
4451     // our AST invariants by having the wrong underlying types. If
4452     // that's the case, then drop this declaration entirely.
4453     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4454          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4455         !Context.hasSameType(Name.getCXXNameType(),
4456                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4457       return true;
4458 
4459     return false;
4460   }
4461 
4462   // C++11 [dcl.meaning]p1:
4463   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4464   //   not begin with a decltype-specifer"
4465   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4466   while (SpecLoc.getPrefix())
4467     SpecLoc = SpecLoc.getPrefix();
4468   if (dyn_cast_or_null<DecltypeType>(
4469         SpecLoc.getNestedNameSpecifier()->getAsType()))
4470     Diag(Loc, diag::err_decltype_in_declarator)
4471       << SpecLoc.getTypeLoc().getSourceRange();
4472 
4473   return false;
4474 }
4475 
4476 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4477                                   MultiTemplateParamsArg TemplateParamLists) {
4478   // TODO: consider using NameInfo for diagnostic.
4479   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4480   DeclarationName Name = NameInfo.getName();
4481 
4482   // All of these full declarators require an identifier.  If it doesn't have
4483   // one, the ParsedFreeStandingDeclSpec action should be used.
4484   if (!Name) {
4485     if (!D.isInvalidType())  // Reject this if we think it is valid.
4486       Diag(D.getDeclSpec().getLocStart(),
4487            diag::err_declarator_need_ident)
4488         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4489     return nullptr;
4490   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4491     return nullptr;
4492 
4493   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4494   // we find one that is.
4495   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4496          (S->getFlags() & Scope::TemplateParamScope) != 0)
4497     S = S->getParent();
4498 
4499   DeclContext *DC = CurContext;
4500   if (D.getCXXScopeSpec().isInvalid())
4501     D.setInvalidType();
4502   else if (D.getCXXScopeSpec().isSet()) {
4503     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4504                                         UPPC_DeclarationQualifier))
4505       return nullptr;
4506 
4507     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4508     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4509     if (!DC || isa<EnumDecl>(DC)) {
4510       // If we could not compute the declaration context, it's because the
4511       // declaration context is dependent but does not refer to a class,
4512       // class template, or class template partial specialization. Complain
4513       // and return early, to avoid the coming semantic disaster.
4514       Diag(D.getIdentifierLoc(),
4515            diag::err_template_qualified_declarator_no_match)
4516         << D.getCXXScopeSpec().getScopeRep()
4517         << D.getCXXScopeSpec().getRange();
4518       return nullptr;
4519     }
4520     bool IsDependentContext = DC->isDependentContext();
4521 
4522     if (!IsDependentContext &&
4523         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4524       return nullptr;
4525 
4526     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4527       Diag(D.getIdentifierLoc(),
4528            diag::err_member_def_undefined_record)
4529         << Name << DC << D.getCXXScopeSpec().getRange();
4530       D.setInvalidType();
4531     } else if (!D.getDeclSpec().isFriendSpecified()) {
4532       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4533                                       Name, D.getIdentifierLoc())) {
4534         if (DC->isRecord())
4535           return nullptr;
4536 
4537         D.setInvalidType();
4538       }
4539     }
4540 
4541     // Check whether we need to rebuild the type of the given
4542     // declaration in the current instantiation.
4543     if (EnteringContext && IsDependentContext &&
4544         TemplateParamLists.size() != 0) {
4545       ContextRAII SavedContext(*this, DC);
4546       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4547         D.setInvalidType();
4548     }
4549   }
4550 
4551   if (DiagnoseClassNameShadow(DC, NameInfo))
4552     // If this is a typedef, we'll end up spewing multiple diagnostics.
4553     // Just return early; it's safer.
4554     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4555       return nullptr;
4556 
4557   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4558   QualType R = TInfo->getType();
4559 
4560   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4561                                       UPPC_DeclarationType))
4562     D.setInvalidType();
4563 
4564   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4565                         ForRedeclaration);
4566 
4567   // See if this is a redefinition of a variable in the same scope.
4568   if (!D.getCXXScopeSpec().isSet()) {
4569     bool IsLinkageLookup = false;
4570     bool CreateBuiltins = false;
4571 
4572     // If the declaration we're planning to build will be a function
4573     // or object with linkage, then look for another declaration with
4574     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4575     //
4576     // If the declaration we're planning to build will be declared with
4577     // external linkage in the translation unit, create any builtin with
4578     // the same name.
4579     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4580       /* Do nothing*/;
4581     else if (CurContext->isFunctionOrMethod() &&
4582              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4583               R->isFunctionType())) {
4584       IsLinkageLookup = true;
4585       CreateBuiltins =
4586           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4587     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4588                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4589       CreateBuiltins = true;
4590 
4591     if (IsLinkageLookup)
4592       Previous.clear(LookupRedeclarationWithLinkage);
4593 
4594     LookupName(Previous, S, CreateBuiltins);
4595   } else { // Something like "int foo::x;"
4596     LookupQualifiedName(Previous, DC);
4597 
4598     // C++ [dcl.meaning]p1:
4599     //   When the declarator-id is qualified, the declaration shall refer to a
4600     //  previously declared member of the class or namespace to which the
4601     //  qualifier refers (or, in the case of a namespace, of an element of the
4602     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4603     //  thereof; [...]
4604     //
4605     // Note that we already checked the context above, and that we do not have
4606     // enough information to make sure that Previous contains the declaration
4607     // we want to match. For example, given:
4608     //
4609     //   class X {
4610     //     void f();
4611     //     void f(float);
4612     //   };
4613     //
4614     //   void X::f(int) { } // ill-formed
4615     //
4616     // In this case, Previous will point to the overload set
4617     // containing the two f's declared in X, but neither of them
4618     // matches.
4619 
4620     // C++ [dcl.meaning]p1:
4621     //   [...] the member shall not merely have been introduced by a
4622     //   using-declaration in the scope of the class or namespace nominated by
4623     //   the nested-name-specifier of the declarator-id.
4624     RemoveUsingDecls(Previous);
4625   }
4626 
4627   if (Previous.isSingleResult() &&
4628       Previous.getFoundDecl()->isTemplateParameter()) {
4629     // Maybe we will complain about the shadowed template parameter.
4630     if (!D.isInvalidType())
4631       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4632                                       Previous.getFoundDecl());
4633 
4634     // Just pretend that we didn't see the previous declaration.
4635     Previous.clear();
4636   }
4637 
4638   // In C++, the previous declaration we find might be a tag type
4639   // (class or enum). In this case, the new declaration will hide the
4640   // tag type. Note that this does does not apply if we're declaring a
4641   // typedef (C++ [dcl.typedef]p4).
4642   if (Previous.isSingleTagDecl() &&
4643       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4644     Previous.clear();
4645 
4646   // Check that there are no default arguments other than in the parameters
4647   // of a function declaration (C++ only).
4648   if (getLangOpts().CPlusPlus)
4649     CheckExtraCXXDefaultArguments(D);
4650 
4651   NamedDecl *New;
4652 
4653   bool AddToScope = true;
4654   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4655     if (TemplateParamLists.size()) {
4656       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4657       return nullptr;
4658     }
4659 
4660     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4661   } else if (R->isFunctionType()) {
4662     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4663                                   TemplateParamLists,
4664                                   AddToScope);
4665   } else {
4666     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4667                                   AddToScope);
4668   }
4669 
4670   if (!New)
4671     return nullptr;
4672 
4673   // If this has an identifier and is not an invalid redeclaration or
4674   // function template specialization, add it to the scope stack.
4675   if (New->getDeclName() && AddToScope &&
4676        !(D.isRedeclaration() && New->isInvalidDecl())) {
4677     // Only make a locally-scoped extern declaration visible if it is the first
4678     // declaration of this entity. Qualified lookup for such an entity should
4679     // only find this declaration if there is no visible declaration of it.
4680     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4681     PushOnScopeChains(New, S, AddToContext);
4682     if (!AddToContext)
4683       CurContext->addHiddenDecl(New);
4684   }
4685 
4686   return New;
4687 }
4688 
4689 /// Helper method to turn variable array types into constant array
4690 /// types in certain situations which would otherwise be errors (for
4691 /// GCC compatibility).
4692 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4693                                                     ASTContext &Context,
4694                                                     bool &SizeIsNegative,
4695                                                     llvm::APSInt &Oversized) {
4696   // This method tries to turn a variable array into a constant
4697   // array even when the size isn't an ICE.  This is necessary
4698   // for compatibility with code that depends on gcc's buggy
4699   // constant expression folding, like struct {char x[(int)(char*)2];}
4700   SizeIsNegative = false;
4701   Oversized = 0;
4702 
4703   if (T->isDependentType())
4704     return QualType();
4705 
4706   QualifierCollector Qs;
4707   const Type *Ty = Qs.strip(T);
4708 
4709   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4710     QualType Pointee = PTy->getPointeeType();
4711     QualType FixedType =
4712         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4713                                             Oversized);
4714     if (FixedType.isNull()) return FixedType;
4715     FixedType = Context.getPointerType(FixedType);
4716     return Qs.apply(Context, FixedType);
4717   }
4718   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4719     QualType Inner = PTy->getInnerType();
4720     QualType FixedType =
4721         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4722                                             Oversized);
4723     if (FixedType.isNull()) return FixedType;
4724     FixedType = Context.getParenType(FixedType);
4725     return Qs.apply(Context, FixedType);
4726   }
4727 
4728   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4729   if (!VLATy)
4730     return QualType();
4731   // FIXME: We should probably handle this case
4732   if (VLATy->getElementType()->isVariablyModifiedType())
4733     return QualType();
4734 
4735   llvm::APSInt Res;
4736   if (!VLATy->getSizeExpr() ||
4737       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4738     return QualType();
4739 
4740   // Check whether the array size is negative.
4741   if (Res.isSigned() && Res.isNegative()) {
4742     SizeIsNegative = true;
4743     return QualType();
4744   }
4745 
4746   // Check whether the array is too large to be addressed.
4747   unsigned ActiveSizeBits
4748     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4749                                               Res);
4750   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4751     Oversized = Res;
4752     return QualType();
4753   }
4754 
4755   return Context.getConstantArrayType(VLATy->getElementType(),
4756                                       Res, ArrayType::Normal, 0);
4757 }
4758 
4759 static void
4760 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
4761   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4762     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4763     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4764                                       DstPTL.getPointeeLoc());
4765     DstPTL.setStarLoc(SrcPTL.getStarLoc());
4766     return;
4767   }
4768   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4769     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4770     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4771                                       DstPTL.getInnerLoc());
4772     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4773     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
4774     return;
4775   }
4776   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4777   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4778   TypeLoc SrcElemTL = SrcATL.getElementLoc();
4779   TypeLoc DstElemTL = DstATL.getElementLoc();
4780   DstElemTL.initializeFullCopy(SrcElemTL);
4781   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4782   DstATL.setSizeExpr(SrcATL.getSizeExpr());
4783   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
4784 }
4785 
4786 /// Helper method to turn variable array types into constant array
4787 /// types in certain situations which would otherwise be errors (for
4788 /// GCC compatibility).
4789 static TypeSourceInfo*
4790 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4791                                               ASTContext &Context,
4792                                               bool &SizeIsNegative,
4793                                               llvm::APSInt &Oversized) {
4794   QualType FixedTy
4795     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4796                                           SizeIsNegative, Oversized);
4797   if (FixedTy.isNull())
4798     return nullptr;
4799   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4800   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4801                                     FixedTInfo->getTypeLoc());
4802   return FixedTInfo;
4803 }
4804 
4805 /// \brief Register the given locally-scoped extern "C" declaration so
4806 /// that it can be found later for redeclarations. We include any extern "C"
4807 /// declaration that is not visible in the translation unit here, not just
4808 /// function-scope declarations.
4809 void
4810 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
4811   if (!getLangOpts().CPlusPlus &&
4812       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4813     // Don't need to track declarations in the TU in C.
4814     return;
4815 
4816   // Note that we have a locally-scoped external with this name.
4817   // FIXME: There can be multiple such declarations if they are functions marked
4818   // __attribute__((overloadable)) declared in function scope in C.
4819   LocallyScopedExternCDecls[ND->getDeclName()] = ND;
4820 }
4821 
4822 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4823   if (ExternalSource) {
4824     // Load locally-scoped external decls from the external source.
4825     // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
4826     SmallVector<NamedDecl *, 4> Decls;
4827     ExternalSource->ReadLocallyScopedExternCDecls(Decls);
4828     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4829       llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4830         = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4831       if (Pos == LocallyScopedExternCDecls.end())
4832         LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
4833     }
4834   }
4835 
4836   NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
4837   return D ? D->getMostRecentDecl() : nullptr;
4838 }
4839 
4840 /// \brief Diagnose function specifiers on a declaration of an identifier that
4841 /// does not identify a function.
4842 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
4843   // FIXME: We should probably indicate the identifier in question to avoid
4844   // confusion for constructs like "inline int a(), b;"
4845   if (DS.isInlineSpecified())
4846     Diag(DS.getInlineSpecLoc(),
4847          diag::err_inline_non_function);
4848 
4849   if (DS.isVirtualSpecified())
4850     Diag(DS.getVirtualSpecLoc(),
4851          diag::err_virtual_non_function);
4852 
4853   if (DS.isExplicitSpecified())
4854     Diag(DS.getExplicitSpecLoc(),
4855          diag::err_explicit_non_function);
4856 
4857   if (DS.isNoreturnSpecified())
4858     Diag(DS.getNoreturnSpecLoc(),
4859          diag::err_noreturn_non_function);
4860 }
4861 
4862 NamedDecl*
4863 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4864                              TypeSourceInfo *TInfo, LookupResult &Previous) {
4865   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4866   if (D.getCXXScopeSpec().isSet()) {
4867     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4868       << D.getCXXScopeSpec().getRange();
4869     D.setInvalidType();
4870     // Pretend we didn't see the scope specifier.
4871     DC = CurContext;
4872     Previous.clear();
4873   }
4874 
4875   DiagnoseFunctionSpecifiers(D.getDeclSpec());
4876 
4877   if (D.getDeclSpec().isConstexprSpecified())
4878     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4879       << 1;
4880 
4881   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4882     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4883       << D.getName().getSourceRange();
4884     return nullptr;
4885   }
4886 
4887   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4888   if (!NewTD) return nullptr;
4889 
4890   // Handle attributes prior to checking for duplicates in MergeVarDecl
4891   ProcessDeclAttributes(S, NewTD, D);
4892 
4893   CheckTypedefForVariablyModifiedType(S, NewTD);
4894 
4895   bool Redeclaration = D.isRedeclaration();
4896   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4897   D.setRedeclaration(Redeclaration);
4898   return ND;
4899 }
4900 
4901 void
4902 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4903   // C99 6.7.7p2: If a typedef name specifies a variably modified type
4904   // then it shall have block scope.
4905   // Note that variably modified types must be fixed before merging the decl so
4906   // that redeclarations will match.
4907   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4908   QualType T = TInfo->getType();
4909   if (T->isVariablyModifiedType()) {
4910     getCurFunction()->setHasBranchProtectedScope();
4911 
4912     if (S->getFnParent() == nullptr) {
4913       bool SizeIsNegative;
4914       llvm::APSInt Oversized;
4915       TypeSourceInfo *FixedTInfo =
4916         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4917                                                       SizeIsNegative,
4918                                                       Oversized);
4919       if (FixedTInfo) {
4920         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4921         NewTD->setTypeSourceInfo(FixedTInfo);
4922       } else {
4923         if (SizeIsNegative)
4924           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4925         else if (T->isVariableArrayType())
4926           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4927         else if (Oversized.getBoolValue())
4928           Diag(NewTD->getLocation(), diag::err_array_too_large)
4929             << Oversized.toString(10);
4930         else
4931           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4932         NewTD->setInvalidDecl();
4933       }
4934     }
4935   }
4936 }
4937 
4938 
4939 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4940 /// declares a typedef-name, either using the 'typedef' type specifier or via
4941 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4942 NamedDecl*
4943 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4944                            LookupResult &Previous, bool &Redeclaration) {
4945   // Merge the decl with the existing one if appropriate. If the decl is
4946   // in an outer scope, it isn't the same thing.
4947   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4948                        /*AllowInlineNamespace*/false);
4949   filterNonConflictingPreviousTypedefDecls(Context, NewTD, Previous);
4950   if (!Previous.empty()) {
4951     Redeclaration = true;
4952     MergeTypedefNameDecl(NewTD, Previous);
4953   }
4954 
4955   // If this is the C FILE type, notify the AST context.
4956   if (IdentifierInfo *II = NewTD->getIdentifier())
4957     if (!NewTD->isInvalidDecl() &&
4958         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4959       if (II->isStr("FILE"))
4960         Context.setFILEDecl(NewTD);
4961       else if (II->isStr("jmp_buf"))
4962         Context.setjmp_bufDecl(NewTD);
4963       else if (II->isStr("sigjmp_buf"))
4964         Context.setsigjmp_bufDecl(NewTD);
4965       else if (II->isStr("ucontext_t"))
4966         Context.setucontext_tDecl(NewTD);
4967     }
4968 
4969   return NewTD;
4970 }
4971 
4972 /// \brief Determines whether the given declaration is an out-of-scope
4973 /// previous declaration.
4974 ///
4975 /// This routine should be invoked when name lookup has found a
4976 /// previous declaration (PrevDecl) that is not in the scope where a
4977 /// new declaration by the same name is being introduced. If the new
4978 /// declaration occurs in a local scope, previous declarations with
4979 /// linkage may still be considered previous declarations (C99
4980 /// 6.2.2p4-5, C++ [basic.link]p6).
4981 ///
4982 /// \param PrevDecl the previous declaration found by name
4983 /// lookup
4984 ///
4985 /// \param DC the context in which the new declaration is being
4986 /// declared.
4987 ///
4988 /// \returns true if PrevDecl is an out-of-scope previous declaration
4989 /// for a new delcaration with the same name.
4990 static bool
4991 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4992                                 ASTContext &Context) {
4993   if (!PrevDecl)
4994     return false;
4995 
4996   if (!PrevDecl->hasLinkage())
4997     return false;
4998 
4999   if (Context.getLangOpts().CPlusPlus) {
5000     // C++ [basic.link]p6:
5001     //   If there is a visible declaration of an entity with linkage
5002     //   having the same name and type, ignoring entities declared
5003     //   outside the innermost enclosing namespace scope, the block
5004     //   scope declaration declares that same entity and receives the
5005     //   linkage of the previous declaration.
5006     DeclContext *OuterContext = DC->getRedeclContext();
5007     if (!OuterContext->isFunctionOrMethod())
5008       // This rule only applies to block-scope declarations.
5009       return false;
5010 
5011     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5012     if (PrevOuterContext->isRecord())
5013       // We found a member function: ignore it.
5014       return false;
5015 
5016     // Find the innermost enclosing namespace for the new and
5017     // previous declarations.
5018     OuterContext = OuterContext->getEnclosingNamespaceContext();
5019     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5020 
5021     // The previous declaration is in a different namespace, so it
5022     // isn't the same function.
5023     if (!OuterContext->Equals(PrevOuterContext))
5024       return false;
5025   }
5026 
5027   return true;
5028 }
5029 
5030 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5031   CXXScopeSpec &SS = D.getCXXScopeSpec();
5032   if (!SS.isSet()) return;
5033   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5034 }
5035 
5036 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5037   QualType type = decl->getType();
5038   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5039   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5040     // Various kinds of declaration aren't allowed to be __autoreleasing.
5041     unsigned kind = -1U;
5042     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5043       if (var->hasAttr<BlocksAttr>())
5044         kind = 0; // __block
5045       else if (!var->hasLocalStorage())
5046         kind = 1; // global
5047     } else if (isa<ObjCIvarDecl>(decl)) {
5048       kind = 3; // ivar
5049     } else if (isa<FieldDecl>(decl)) {
5050       kind = 2; // field
5051     }
5052 
5053     if (kind != -1U) {
5054       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5055         << kind;
5056     }
5057   } else if (lifetime == Qualifiers::OCL_None) {
5058     // Try to infer lifetime.
5059     if (!type->isObjCLifetimeType())
5060       return false;
5061 
5062     lifetime = type->getObjCARCImplicitLifetime();
5063     type = Context.getLifetimeQualifiedType(type, lifetime);
5064     decl->setType(type);
5065   }
5066 
5067   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5068     // Thread-local variables cannot have lifetime.
5069     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5070         var->getTLSKind()) {
5071       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5072         << var->getType();
5073       return true;
5074     }
5075   }
5076 
5077   return false;
5078 }
5079 
5080 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5081   // Ensure that an auto decl is deduced otherwise the checks below might cache
5082   // the wrong linkage.
5083   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5084 
5085   // 'weak' only applies to declarations with external linkage.
5086   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5087     if (!ND.isExternallyVisible()) {
5088       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5089       ND.dropAttr<WeakAttr>();
5090     }
5091   }
5092   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5093     if (ND.isExternallyVisible()) {
5094       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5095       ND.dropAttr<WeakRefAttr>();
5096     }
5097   }
5098 
5099   // 'selectany' only applies to externally visible varable declarations.
5100   // It does not apply to functions.
5101   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5102     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5103       S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
5104       ND.dropAttr<SelectAnyAttr>();
5105     }
5106   }
5107 
5108   // dll attributes require external linkage.
5109   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5110     if (!ND.isExternallyVisible()) {
5111       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5112         << &ND << Attr;
5113       ND.setInvalidDecl();
5114     }
5115   }
5116 }
5117 
5118 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5119                                            NamedDecl *NewDecl,
5120                                            bool IsSpecialization) {
5121   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5122     OldDecl = OldTD->getTemplatedDecl();
5123   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5124     NewDecl = NewTD->getTemplatedDecl();
5125 
5126   if (!OldDecl || !NewDecl)
5127     return;
5128 
5129   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5130   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5131   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5132   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5133 
5134   // dllimport and dllexport are inheritable attributes so we have to exclude
5135   // inherited attribute instances.
5136   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5137                     (NewExportAttr && !NewExportAttr->isInherited());
5138 
5139   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5140   // the only exception being explicit specializations.
5141   // Implicitly generated declarations are also excluded for now because there
5142   // is no other way to switch these to use dllimport or dllexport.
5143   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5144 
5145   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5146     // If the declaration hasn't been used yet, allow with a warning for
5147     // free functions and global variables.
5148     bool JustWarn = false;
5149     if (!OldDecl->isUsed() && !OldDecl->isCXXClassMember()) {
5150       auto *VD = dyn_cast<VarDecl>(OldDecl);
5151       if (VD && !VD->getDescribedVarTemplate())
5152         JustWarn = true;
5153       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5154       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5155         JustWarn = true;
5156     }
5157 
5158     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5159                                : diag::err_attribute_dll_redeclaration;
5160     S.Diag(NewDecl->getLocation(), DiagID)
5161         << NewDecl
5162         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5163     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5164     if (!JustWarn) {
5165       NewDecl->setInvalidDecl();
5166       return;
5167     }
5168   }
5169 
5170   // A redeclaration is not allowed to drop a dllimport attribute, the only
5171   // exceptions being inline function definitions, local extern declarations,
5172   // and qualified friend declarations.
5173   // NB: MSVC converts such a declaration to dllexport.
5174   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5175   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5176     // Ignore static data because out-of-line definitions are diagnosed
5177     // separately.
5178     IsStaticDataMember = VD->isStaticDataMember();
5179   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5180     IsInline = FD->isInlined();
5181     IsQualifiedFriend = FD->getQualifier() &&
5182                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5183   }
5184 
5185   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5186       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5187     S.Diag(NewDecl->getLocation(),
5188            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5189       << NewDecl << OldImportAttr;
5190     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5191     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5192     OldDecl->dropAttr<DLLImportAttr>();
5193     NewDecl->dropAttr<DLLImportAttr>();
5194   } else if (IsInline && OldImportAttr &&
5195              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5196     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5197     OldDecl->dropAttr<DLLImportAttr>();
5198     NewDecl->dropAttr<DLLImportAttr>();
5199     S.Diag(NewDecl->getLocation(),
5200            diag::warn_dllimport_dropped_from_inline_function)
5201         << NewDecl << OldImportAttr;
5202   }
5203 }
5204 
5205 /// Given that we are within the definition of the given function,
5206 /// will that definition behave like C99's 'inline', where the
5207 /// definition is discarded except for optimization purposes?
5208 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5209   // Try to avoid calling GetGVALinkageForFunction.
5210 
5211   // All cases of this require the 'inline' keyword.
5212   if (!FD->isInlined()) return false;
5213 
5214   // This is only possible in C++ with the gnu_inline attribute.
5215   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5216     return false;
5217 
5218   // Okay, go ahead and call the relatively-more-expensive function.
5219 
5220 #ifndef NDEBUG
5221   // AST quite reasonably asserts that it's working on a function
5222   // definition.  We don't really have a way to tell it that we're
5223   // currently defining the function, so just lie to it in +Asserts
5224   // builds.  This is an awful hack.
5225   FD->setLazyBody(1);
5226 #endif
5227 
5228   bool isC99Inline =
5229       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5230 
5231 #ifndef NDEBUG
5232   FD->setLazyBody(0);
5233 #endif
5234 
5235   return isC99Inline;
5236 }
5237 
5238 /// Determine whether a variable is extern "C" prior to attaching
5239 /// an initializer. We can't just call isExternC() here, because that
5240 /// will also compute and cache whether the declaration is externally
5241 /// visible, which might change when we attach the initializer.
5242 ///
5243 /// This can only be used if the declaration is known to not be a
5244 /// redeclaration of an internal linkage declaration.
5245 ///
5246 /// For instance:
5247 ///
5248 ///   auto x = []{};
5249 ///
5250 /// Attaching the initializer here makes this declaration not externally
5251 /// visible, because its type has internal linkage.
5252 ///
5253 /// FIXME: This is a hack.
5254 template<typename T>
5255 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5256   if (S.getLangOpts().CPlusPlus) {
5257     // In C++, the overloadable attribute negates the effects of extern "C".
5258     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5259       return false;
5260   }
5261   return D->isExternC();
5262 }
5263 
5264 static bool shouldConsiderLinkage(const VarDecl *VD) {
5265   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5266   if (DC->isFunctionOrMethod())
5267     return VD->hasExternalStorage();
5268   if (DC->isFileContext())
5269     return true;
5270   if (DC->isRecord())
5271     return false;
5272   llvm_unreachable("Unexpected context");
5273 }
5274 
5275 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5276   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5277   if (DC->isFileContext() || DC->isFunctionOrMethod())
5278     return true;
5279   if (DC->isRecord())
5280     return false;
5281   llvm_unreachable("Unexpected context");
5282 }
5283 
5284 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5285                           AttributeList::Kind Kind) {
5286   for (const AttributeList *L = AttrList; L; L = L->getNext())
5287     if (L->getKind() == Kind)
5288       return true;
5289   return false;
5290 }
5291 
5292 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5293                           AttributeList::Kind Kind) {
5294   // Check decl attributes on the DeclSpec.
5295   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5296     return true;
5297 
5298   // Walk the declarator structure, checking decl attributes that were in a type
5299   // position to the decl itself.
5300   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5301     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5302       return true;
5303   }
5304 
5305   // Finally, check attributes on the decl itself.
5306   return hasParsedAttr(S, PD.getAttributes(), Kind);
5307 }
5308 
5309 /// Adjust the \c DeclContext for a function or variable that might be a
5310 /// function-local external declaration.
5311 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5312   if (!DC->isFunctionOrMethod())
5313     return false;
5314 
5315   // If this is a local extern function or variable declared within a function
5316   // template, don't add it into the enclosing namespace scope until it is
5317   // instantiated; it might have a dependent type right now.
5318   if (DC->isDependentContext())
5319     return true;
5320 
5321   // C++11 [basic.link]p7:
5322   //   When a block scope declaration of an entity with linkage is not found to
5323   //   refer to some other declaration, then that entity is a member of the
5324   //   innermost enclosing namespace.
5325   //
5326   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5327   // semantically-enclosing namespace, not a lexically-enclosing one.
5328   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5329     DC = DC->getParent();
5330   return true;
5331 }
5332 
5333 NamedDecl *
5334 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5335                               TypeSourceInfo *TInfo, LookupResult &Previous,
5336                               MultiTemplateParamsArg TemplateParamLists,
5337                               bool &AddToScope) {
5338   QualType R = TInfo->getType();
5339   DeclarationName Name = GetNameForDeclarator(D).getName();
5340 
5341   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5342   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5343 
5344   // dllimport globals without explicit storage class are treated as extern. We
5345   // have to change the storage class this early to get the right DeclContext.
5346   if (SC == SC_None && !DC->isRecord() &&
5347       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5348       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5349     SC = SC_Extern;
5350 
5351   DeclContext *OriginalDC = DC;
5352   bool IsLocalExternDecl = SC == SC_Extern &&
5353                            adjustContextForLocalExternDecl(DC);
5354 
5355   if (getLangOpts().OpenCL) {
5356     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5357     QualType NR = R;
5358     while (NR->isPointerType()) {
5359       if (NR->isFunctionPointerType()) {
5360         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5361         D.setInvalidType();
5362         break;
5363       }
5364       NR = NR->getPointeeType();
5365     }
5366 
5367     if (!getOpenCLOptions().cl_khr_fp16) {
5368       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5369       // half array type (unless the cl_khr_fp16 extension is enabled).
5370       if (Context.getBaseElementType(R)->isHalfType()) {
5371         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5372         D.setInvalidType();
5373       }
5374     }
5375   }
5376 
5377   if (SCSpec == DeclSpec::SCS_mutable) {
5378     // mutable can only appear on non-static class members, so it's always
5379     // an error here
5380     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5381     D.setInvalidType();
5382     SC = SC_None;
5383   }
5384 
5385   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5386       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5387                               D.getDeclSpec().getStorageClassSpecLoc())) {
5388     // In C++11, the 'register' storage class specifier is deprecated.
5389     // Suppress the warning in system macros, it's used in macros in some
5390     // popular C system headers, such as in glibc's htonl() macro.
5391     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5392          diag::warn_deprecated_register)
5393       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5394   }
5395 
5396   IdentifierInfo *II = Name.getAsIdentifierInfo();
5397   if (!II) {
5398     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5399       << Name;
5400     return nullptr;
5401   }
5402 
5403   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5404 
5405   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5406     // C99 6.9p2: The storage-class specifiers auto and register shall not
5407     // appear in the declaration specifiers in an external declaration.
5408     // Global Register+Asm is a GNU extension we support.
5409     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5410       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5411       D.setInvalidType();
5412     }
5413   }
5414 
5415   if (getLangOpts().OpenCL) {
5416     // Set up the special work-group-local storage class for variables in the
5417     // OpenCL __local address space.
5418     if (R.getAddressSpace() == LangAS::opencl_local) {
5419       SC = SC_OpenCLWorkGroupLocal;
5420     }
5421 
5422     // OpenCL v1.2 s6.9.b p4:
5423     // The sampler type cannot be used with the __local and __global address
5424     // space qualifiers.
5425     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5426       R.getAddressSpace() == LangAS::opencl_global)) {
5427       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5428     }
5429 
5430     // OpenCL 1.2 spec, p6.9 r:
5431     // The event type cannot be used to declare a program scope variable.
5432     // The event type cannot be used with the __local, __constant and __global
5433     // address space qualifiers.
5434     if (R->isEventT()) {
5435       if (S->getParent() == nullptr) {
5436         Diag(D.getLocStart(), diag::err_event_t_global_var);
5437         D.setInvalidType();
5438       }
5439 
5440       if (R.getAddressSpace()) {
5441         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5442         D.setInvalidType();
5443       }
5444     }
5445   }
5446 
5447   bool IsExplicitSpecialization = false;
5448   bool IsVariableTemplateSpecialization = false;
5449   bool IsPartialSpecialization = false;
5450   bool IsVariableTemplate = false;
5451   VarDecl *NewVD = nullptr;
5452   VarTemplateDecl *NewTemplate = nullptr;
5453   TemplateParameterList *TemplateParams = nullptr;
5454   if (!getLangOpts().CPlusPlus) {
5455     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5456                             D.getIdentifierLoc(), II,
5457                             R, TInfo, SC);
5458 
5459     if (D.isInvalidType())
5460       NewVD->setInvalidDecl();
5461   } else {
5462     bool Invalid = false;
5463 
5464     if (DC->isRecord() && !CurContext->isRecord()) {
5465       // This is an out-of-line definition of a static data member.
5466       switch (SC) {
5467       case SC_None:
5468         break;
5469       case SC_Static:
5470         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5471              diag::err_static_out_of_line)
5472           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5473         break;
5474       case SC_Auto:
5475       case SC_Register:
5476       case SC_Extern:
5477         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5478         // to names of variables declared in a block or to function parameters.
5479         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5480         // of class members
5481 
5482         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5483              diag::err_storage_class_for_static_member)
5484           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5485         break;
5486       case SC_PrivateExtern:
5487         llvm_unreachable("C storage class in c++!");
5488       case SC_OpenCLWorkGroupLocal:
5489         llvm_unreachable("OpenCL storage class in c++!");
5490       }
5491     }
5492 
5493     if (SC == SC_Static && CurContext->isRecord()) {
5494       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5495         if (RD->isLocalClass())
5496           Diag(D.getIdentifierLoc(),
5497                diag::err_static_data_member_not_allowed_in_local_class)
5498             << Name << RD->getDeclName();
5499 
5500         // C++98 [class.union]p1: If a union contains a static data member,
5501         // the program is ill-formed. C++11 drops this restriction.
5502         if (RD->isUnion())
5503           Diag(D.getIdentifierLoc(),
5504                getLangOpts().CPlusPlus11
5505                  ? diag::warn_cxx98_compat_static_data_member_in_union
5506                  : diag::ext_static_data_member_in_union) << Name;
5507         // We conservatively disallow static data members in anonymous structs.
5508         else if (!RD->getDeclName())
5509           Diag(D.getIdentifierLoc(),
5510                diag::err_static_data_member_not_allowed_in_anon_struct)
5511             << Name << RD->isUnion();
5512       }
5513     }
5514 
5515     // Match up the template parameter lists with the scope specifier, then
5516     // determine whether we have a template or a template specialization.
5517     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5518         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5519         D.getCXXScopeSpec(),
5520         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5521             ? D.getName().TemplateId
5522             : nullptr,
5523         TemplateParamLists,
5524         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5525 
5526     if (TemplateParams) {
5527       if (!TemplateParams->size() &&
5528           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5529         // There is an extraneous 'template<>' for this variable. Complain
5530         // about it, but allow the declaration of the variable.
5531         Diag(TemplateParams->getTemplateLoc(),
5532              diag::err_template_variable_noparams)
5533           << II
5534           << SourceRange(TemplateParams->getTemplateLoc(),
5535                          TemplateParams->getRAngleLoc());
5536         TemplateParams = nullptr;
5537       } else {
5538         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5539           // This is an explicit specialization or a partial specialization.
5540           // FIXME: Check that we can declare a specialization here.
5541           IsVariableTemplateSpecialization = true;
5542           IsPartialSpecialization = TemplateParams->size() > 0;
5543         } else { // if (TemplateParams->size() > 0)
5544           // This is a template declaration.
5545           IsVariableTemplate = true;
5546 
5547           // Check that we can declare a template here.
5548           if (CheckTemplateDeclScope(S, TemplateParams))
5549             return nullptr;
5550 
5551           // Only C++1y supports variable templates (N3651).
5552           Diag(D.getIdentifierLoc(),
5553                getLangOpts().CPlusPlus14
5554                    ? diag::warn_cxx11_compat_variable_template
5555                    : diag::ext_variable_template);
5556         }
5557       }
5558     } else {
5559       assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId &&
5560              "should have a 'template<>' for this decl");
5561     }
5562 
5563     if (IsVariableTemplateSpecialization) {
5564       SourceLocation TemplateKWLoc =
5565           TemplateParamLists.size() > 0
5566               ? TemplateParamLists[0]->getTemplateLoc()
5567               : SourceLocation();
5568       DeclResult Res = ActOnVarTemplateSpecialization(
5569           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5570           IsPartialSpecialization);
5571       if (Res.isInvalid())
5572         return nullptr;
5573       NewVD = cast<VarDecl>(Res.get());
5574       AddToScope = false;
5575     } else
5576       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5577                               D.getIdentifierLoc(), II, R, TInfo, SC);
5578 
5579     // If this is supposed to be a variable template, create it as such.
5580     if (IsVariableTemplate) {
5581       NewTemplate =
5582           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5583                                   TemplateParams, NewVD);
5584       NewVD->setDescribedVarTemplate(NewTemplate);
5585     }
5586 
5587     // If this decl has an auto type in need of deduction, make a note of the
5588     // Decl so we can diagnose uses of it in its own initializer.
5589     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5590       ParsingInitForAutoVars.insert(NewVD);
5591 
5592     if (D.isInvalidType() || Invalid) {
5593       NewVD->setInvalidDecl();
5594       if (NewTemplate)
5595         NewTemplate->setInvalidDecl();
5596     }
5597 
5598     SetNestedNameSpecifier(NewVD, D);
5599 
5600     // If we have any template parameter lists that don't directly belong to
5601     // the variable (matching the scope specifier), store them.
5602     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5603     if (TemplateParamLists.size() > VDTemplateParamLists)
5604       NewVD->setTemplateParameterListsInfo(
5605           Context, TemplateParamLists.size() - VDTemplateParamLists,
5606           TemplateParamLists.data());
5607 
5608     if (D.getDeclSpec().isConstexprSpecified())
5609       NewVD->setConstexpr(true);
5610   }
5611 
5612   // Set the lexical context. If the declarator has a C++ scope specifier, the
5613   // lexical context will be different from the semantic context.
5614   NewVD->setLexicalDeclContext(CurContext);
5615   if (NewTemplate)
5616     NewTemplate->setLexicalDeclContext(CurContext);
5617 
5618   if (IsLocalExternDecl)
5619     NewVD->setLocalExternDecl();
5620 
5621   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5622     // C++11 [dcl.stc]p4:
5623     //   When thread_local is applied to a variable of block scope the
5624     //   storage-class-specifier static is implied if it does not appear
5625     //   explicitly.
5626     // Core issue: 'static' is not implied if the variable is declared
5627     //   'extern'.
5628     if (NewVD->hasLocalStorage() &&
5629         (SCSpec != DeclSpec::SCS_unspecified ||
5630          TSCS != DeclSpec::TSCS_thread_local ||
5631          !DC->isFunctionOrMethod()))
5632       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5633            diag::err_thread_non_global)
5634         << DeclSpec::getSpecifierName(TSCS);
5635     else if (!Context.getTargetInfo().isTLSSupported())
5636       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5637            diag::err_thread_unsupported);
5638     else
5639       NewVD->setTSCSpec(TSCS);
5640   }
5641 
5642   // C99 6.7.4p3
5643   //   An inline definition of a function with external linkage shall
5644   //   not contain a definition of a modifiable object with static or
5645   //   thread storage duration...
5646   // We only apply this when the function is required to be defined
5647   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5648   // that a local variable with thread storage duration still has to
5649   // be marked 'static'.  Also note that it's possible to get these
5650   // semantics in C++ using __attribute__((gnu_inline)).
5651   if (SC == SC_Static && S->getFnParent() != nullptr &&
5652       !NewVD->getType().isConstQualified()) {
5653     FunctionDecl *CurFD = getCurFunctionDecl();
5654     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5655       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5656            diag::warn_static_local_in_extern_inline);
5657       MaybeSuggestAddingStaticToDecl(CurFD);
5658     }
5659   }
5660 
5661   if (D.getDeclSpec().isModulePrivateSpecified()) {
5662     if (IsVariableTemplateSpecialization)
5663       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5664           << (IsPartialSpecialization ? 1 : 0)
5665           << FixItHint::CreateRemoval(
5666                  D.getDeclSpec().getModulePrivateSpecLoc());
5667     else if (IsExplicitSpecialization)
5668       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5669         << 2
5670         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5671     else if (NewVD->hasLocalStorage())
5672       Diag(NewVD->getLocation(), diag::err_module_private_local)
5673         << 0 << NewVD->getDeclName()
5674         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5675         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5676     else {
5677       NewVD->setModulePrivate();
5678       if (NewTemplate)
5679         NewTemplate->setModulePrivate();
5680     }
5681   }
5682 
5683   // Handle attributes prior to checking for duplicates in MergeVarDecl
5684   ProcessDeclAttributes(S, NewVD, D);
5685 
5686   if (getLangOpts().CUDA) {
5687     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5688     // storage [duration]."
5689     if (SC == SC_None && S->getFnParent() != nullptr &&
5690         (NewVD->hasAttr<CUDASharedAttr>() ||
5691          NewVD->hasAttr<CUDAConstantAttr>())) {
5692       NewVD->setStorageClass(SC_Static);
5693     }
5694   }
5695 
5696   // Ensure that dllimport globals without explicit storage class are treated as
5697   // extern. The storage class is set above using parsed attributes. Now we can
5698   // check the VarDecl itself.
5699   assert(!NewVD->hasAttr<DLLImportAttr>() ||
5700          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5701          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5702 
5703   // In auto-retain/release, infer strong retension for variables of
5704   // retainable type.
5705   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5706     NewVD->setInvalidDecl();
5707 
5708   // Handle GNU asm-label extension (encoded as an attribute).
5709   if (Expr *E = (Expr*)D.getAsmLabel()) {
5710     // The parser guarantees this is a string.
5711     StringLiteral *SE = cast<StringLiteral>(E);
5712     StringRef Label = SE->getString();
5713     if (S->getFnParent() != nullptr) {
5714       switch (SC) {
5715       case SC_None:
5716       case SC_Auto:
5717         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5718         break;
5719       case SC_Register:
5720         // Local Named register
5721         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5722           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5723         break;
5724       case SC_Static:
5725       case SC_Extern:
5726       case SC_PrivateExtern:
5727       case SC_OpenCLWorkGroupLocal:
5728         break;
5729       }
5730     } else if (SC == SC_Register) {
5731       // Global Named register
5732       if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5733         Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5734       if (!R->isIntegralType(Context) && !R->isPointerType()) {
5735         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
5736         NewVD->setInvalidDecl(true);
5737       }
5738     }
5739 
5740     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
5741                                                 Context, Label, 0));
5742   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5743     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5744       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5745     if (I != ExtnameUndeclaredIdentifiers.end()) {
5746       NewVD->addAttr(I->second);
5747       ExtnameUndeclaredIdentifiers.erase(I);
5748     }
5749   }
5750 
5751   // Diagnose shadowed variables before filtering for scope.
5752   if (D.getCXXScopeSpec().isEmpty())
5753     CheckShadow(S, NewVD, Previous);
5754 
5755   // Don't consider existing declarations that are in a different
5756   // scope and are out-of-semantic-context declarations (if the new
5757   // declaration has linkage).
5758   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5759                        D.getCXXScopeSpec().isNotEmpty() ||
5760                        IsExplicitSpecialization ||
5761                        IsVariableTemplateSpecialization);
5762 
5763   // Check whether the previous declaration is in the same block scope. This
5764   // affects whether we merge types with it, per C++11 [dcl.array]p3.
5765   if (getLangOpts().CPlusPlus &&
5766       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5767     NewVD->setPreviousDeclInSameBlockScope(
5768         Previous.isSingleResult() && !Previous.isShadowed() &&
5769         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
5770 
5771   if (!getLangOpts().CPlusPlus) {
5772     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5773   } else {
5774     // If this is an explicit specialization of a static data member, check it.
5775     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5776         CheckMemberSpecialization(NewVD, Previous))
5777       NewVD->setInvalidDecl();
5778 
5779     // Merge the decl with the existing one if appropriate.
5780     if (!Previous.empty()) {
5781       if (Previous.isSingleResult() &&
5782           isa<FieldDecl>(Previous.getFoundDecl()) &&
5783           D.getCXXScopeSpec().isSet()) {
5784         // The user tried to define a non-static data member
5785         // out-of-line (C++ [dcl.meaning]p1).
5786         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5787           << D.getCXXScopeSpec().getRange();
5788         Previous.clear();
5789         NewVD->setInvalidDecl();
5790       }
5791     } else if (D.getCXXScopeSpec().isSet()) {
5792       // No previous declaration in the qualifying scope.
5793       Diag(D.getIdentifierLoc(), diag::err_no_member)
5794         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
5795         << D.getCXXScopeSpec().getRange();
5796       NewVD->setInvalidDecl();
5797     }
5798 
5799     if (!IsVariableTemplateSpecialization)
5800       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5801 
5802     if (NewTemplate) {
5803       VarTemplateDecl *PrevVarTemplate =
5804           NewVD->getPreviousDecl()
5805               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5806               : nullptr;
5807 
5808       // Check the template parameter list of this declaration, possibly
5809       // merging in the template parameter list from the previous variable
5810       // template declaration.
5811       if (CheckTemplateParameterList(
5812               TemplateParams,
5813               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5814                               : nullptr,
5815               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5816                DC->isDependentContext())
5817                   ? TPC_ClassTemplateMember
5818                   : TPC_VarTemplate))
5819         NewVD->setInvalidDecl();
5820 
5821       // If we are providing an explicit specialization of a static variable
5822       // template, make a note of that.
5823       if (PrevVarTemplate &&
5824           PrevVarTemplate->getInstantiatedFromMemberTemplate())
5825         PrevVarTemplate->setMemberSpecialization();
5826     }
5827   }
5828 
5829   ProcessPragmaWeak(S, NewVD);
5830 
5831   // If this is the first declaration of an extern C variable, update
5832   // the map of such variables.
5833   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
5834       isIncompleteDeclExternC(*this, NewVD))
5835     RegisterLocallyScopedExternCDecl(NewVD, S);
5836 
5837   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5838     Decl *ManglingContextDecl;
5839     if (MangleNumberingContext *MCtx =
5840             getCurrentMangleNumberContext(NewVD->getDeclContext(),
5841                                           ManglingContextDecl)) {
5842       Context.setManglingNumber(
5843           NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
5844       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5845     }
5846   }
5847 
5848   if (D.isRedeclaration() && !Previous.empty()) {
5849     checkDLLAttributeRedeclaration(
5850         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
5851         IsExplicitSpecialization);
5852   }
5853 
5854   if (NewTemplate) {
5855     if (NewVD->isInvalidDecl())
5856       NewTemplate->setInvalidDecl();
5857     ActOnDocumentableDecl(NewTemplate);
5858     return NewTemplate;
5859   }
5860 
5861   return NewVD;
5862 }
5863 
5864 /// \brief Diagnose variable or built-in function shadowing.  Implements
5865 /// -Wshadow.
5866 ///
5867 /// This method is called whenever a VarDecl is added to a "useful"
5868 /// scope.
5869 ///
5870 /// \param S the scope in which the shadowing name is being declared
5871 /// \param R the lookup of the name
5872 ///
5873 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
5874   // Return if warning is ignored.
5875   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
5876     return;
5877 
5878   // Don't diagnose declarations at file scope.
5879   if (D->hasGlobalStorage())
5880     return;
5881 
5882   DeclContext *NewDC = D->getDeclContext();
5883 
5884   // Only diagnose if we're shadowing an unambiguous field or variable.
5885   if (R.getResultKind() != LookupResult::Found)
5886     return;
5887 
5888   NamedDecl* ShadowedDecl = R.getFoundDecl();
5889   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5890     return;
5891 
5892   // Fields are not shadowed by variables in C++ static methods.
5893   if (isa<FieldDecl>(ShadowedDecl))
5894     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5895       if (MD->isStatic())
5896         return;
5897 
5898   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5899     if (shadowedVar->isExternC()) {
5900       // For shadowing external vars, make sure that we point to the global
5901       // declaration, not a locally scoped extern declaration.
5902       for (auto I : shadowedVar->redecls())
5903         if (I->isFileVarDecl()) {
5904           ShadowedDecl = I;
5905           break;
5906         }
5907     }
5908 
5909   DeclContext *OldDC = ShadowedDecl->getDeclContext();
5910 
5911   // Only warn about certain kinds of shadowing for class members.
5912   if (NewDC && NewDC->isRecord()) {
5913     // In particular, don't warn about shadowing non-class members.
5914     if (!OldDC->isRecord())
5915       return;
5916 
5917     // TODO: should we warn about static data members shadowing
5918     // static data members from base classes?
5919 
5920     // TODO: don't diagnose for inaccessible shadowed members.
5921     // This is hard to do perfectly because we might friend the
5922     // shadowing context, but that's just a false negative.
5923   }
5924 
5925   // Determine what kind of declaration we're shadowing.
5926   unsigned Kind;
5927   if (isa<RecordDecl>(OldDC)) {
5928     if (isa<FieldDecl>(ShadowedDecl))
5929       Kind = 3; // field
5930     else
5931       Kind = 2; // static data member
5932   } else if (OldDC->isFileContext())
5933     Kind = 1; // global
5934   else
5935     Kind = 0; // local
5936 
5937   DeclarationName Name = R.getLookupName();
5938 
5939   // Emit warning and note.
5940   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5941     return;
5942   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
5943   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5944 }
5945 
5946 /// \brief Check -Wshadow without the advantage of a previous lookup.
5947 void Sema::CheckShadow(Scope *S, VarDecl *D) {
5948   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
5949     return;
5950 
5951   LookupResult R(*this, D->getDeclName(), D->getLocation(),
5952                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5953   LookupName(R, S);
5954   CheckShadow(S, D, R);
5955 }
5956 
5957 /// Check for conflict between this global or extern "C" declaration and
5958 /// previous global or extern "C" declarations. This is only used in C++.
5959 template<typename T>
5960 static bool checkGlobalOrExternCConflict(
5961     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5962   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5963   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
5964 
5965   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5966     // The common case: this global doesn't conflict with any extern "C"
5967     // declaration.
5968     return false;
5969   }
5970 
5971   if (Prev) {
5972     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5973       // Both the old and new declarations have C language linkage. This is a
5974       // redeclaration.
5975       Previous.clear();
5976       Previous.addDecl(Prev);
5977       return true;
5978     }
5979 
5980     // This is a global, non-extern "C" declaration, and there is a previous
5981     // non-global extern "C" declaration. Diagnose if this is a variable
5982     // declaration.
5983     if (!isa<VarDecl>(ND))
5984       return false;
5985   } else {
5986     // The declaration is extern "C". Check for any declaration in the
5987     // translation unit which might conflict.
5988     if (IsGlobal) {
5989       // We have already performed the lookup into the translation unit.
5990       IsGlobal = false;
5991       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5992            I != E; ++I) {
5993         if (isa<VarDecl>(*I)) {
5994           Prev = *I;
5995           break;
5996         }
5997       }
5998     } else {
5999       DeclContext::lookup_result R =
6000           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6001       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6002            I != E; ++I) {
6003         if (isa<VarDecl>(*I)) {
6004           Prev = *I;
6005           break;
6006         }
6007         // FIXME: If we have any other entity with this name in global scope,
6008         // the declaration is ill-formed, but that is a defect: it breaks the
6009         // 'stat' hack, for instance. Only variables can have mangled name
6010         // clashes with extern "C" declarations, so only they deserve a
6011         // diagnostic.
6012       }
6013     }
6014 
6015     if (!Prev)
6016       return false;
6017   }
6018 
6019   // Use the first declaration's location to ensure we point at something which
6020   // is lexically inside an extern "C" linkage-spec.
6021   assert(Prev && "should have found a previous declaration to diagnose");
6022   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6023     Prev = FD->getFirstDecl();
6024   else
6025     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6026 
6027   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6028     << IsGlobal << ND;
6029   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6030     << IsGlobal;
6031   return false;
6032 }
6033 
6034 /// Apply special rules for handling extern "C" declarations. Returns \c true
6035 /// if we have found that this is a redeclaration of some prior entity.
6036 ///
6037 /// Per C++ [dcl.link]p6:
6038 ///   Two declarations [for a function or variable] with C language linkage
6039 ///   with the same name that appear in different scopes refer to the same
6040 ///   [entity]. An entity with C language linkage shall not be declared with
6041 ///   the same name as an entity in global scope.
6042 template<typename T>
6043 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6044                                                   LookupResult &Previous) {
6045   if (!S.getLangOpts().CPlusPlus) {
6046     // In C, when declaring a global variable, look for a corresponding 'extern'
6047     // variable declared in function scope. We don't need this in C++, because
6048     // we find local extern decls in the surrounding file-scope DeclContext.
6049     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6050       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6051         Previous.clear();
6052         Previous.addDecl(Prev);
6053         return true;
6054       }
6055     }
6056     return false;
6057   }
6058 
6059   // A declaration in the translation unit can conflict with an extern "C"
6060   // declaration.
6061   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6062     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6063 
6064   // An extern "C" declaration can conflict with a declaration in the
6065   // translation unit or can be a redeclaration of an extern "C" declaration
6066   // in another scope.
6067   if (isIncompleteDeclExternC(S,ND))
6068     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6069 
6070   // Neither global nor extern "C": nothing to do.
6071   return false;
6072 }
6073 
6074 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6075   // If the decl is already known invalid, don't check it.
6076   if (NewVD->isInvalidDecl())
6077     return;
6078 
6079   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6080   QualType T = TInfo->getType();
6081 
6082   // Defer checking an 'auto' type until its initializer is attached.
6083   if (T->isUndeducedType())
6084     return;
6085 
6086   if (NewVD->hasAttrs())
6087     CheckAlignasUnderalignment(NewVD);
6088 
6089   if (T->isObjCObjectType()) {
6090     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6091       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6092     T = Context.getObjCObjectPointerType(T);
6093     NewVD->setType(T);
6094   }
6095 
6096   // Emit an error if an address space was applied to decl with local storage.
6097   // This includes arrays of objects with address space qualifiers, but not
6098   // automatic variables that point to other address spaces.
6099   // ISO/IEC TR 18037 S5.1.2
6100   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6101     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6102     NewVD->setInvalidDecl();
6103     return;
6104   }
6105 
6106   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6107   // __constant address space.
6108   if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
6109       && T.getAddressSpace() != LangAS::opencl_constant
6110       && !T->isSamplerT()){
6111     Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
6112     NewVD->setInvalidDecl();
6113     return;
6114   }
6115 
6116   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6117   // scope.
6118   if ((getLangOpts().OpenCLVersion >= 120)
6119       && NewVD->isStaticLocal()) {
6120     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6121     NewVD->setInvalidDecl();
6122     return;
6123   }
6124 
6125   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6126       && !NewVD->hasAttr<BlocksAttr>()) {
6127     if (getLangOpts().getGC() != LangOptions::NonGC)
6128       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6129     else {
6130       assert(!getLangOpts().ObjCAutoRefCount);
6131       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6132     }
6133   }
6134 
6135   bool isVM = T->isVariablyModifiedType();
6136   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6137       NewVD->hasAttr<BlocksAttr>())
6138     getCurFunction()->setHasBranchProtectedScope();
6139 
6140   if ((isVM && NewVD->hasLinkage()) ||
6141       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6142     bool SizeIsNegative;
6143     llvm::APSInt Oversized;
6144     TypeSourceInfo *FixedTInfo =
6145       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6146                                                     SizeIsNegative, Oversized);
6147     if (!FixedTInfo && T->isVariableArrayType()) {
6148       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6149       // FIXME: This won't give the correct result for
6150       // int a[10][n];
6151       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6152 
6153       if (NewVD->isFileVarDecl())
6154         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6155         << SizeRange;
6156       else if (NewVD->isStaticLocal())
6157         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6158         << SizeRange;
6159       else
6160         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6161         << SizeRange;
6162       NewVD->setInvalidDecl();
6163       return;
6164     }
6165 
6166     if (!FixedTInfo) {
6167       if (NewVD->isFileVarDecl())
6168         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6169       else
6170         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6171       NewVD->setInvalidDecl();
6172       return;
6173     }
6174 
6175     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6176     NewVD->setType(FixedTInfo->getType());
6177     NewVD->setTypeSourceInfo(FixedTInfo);
6178   }
6179 
6180   if (T->isVoidType()) {
6181     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6182     //                    of objects and functions.
6183     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6184       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6185         << T;
6186       NewVD->setInvalidDecl();
6187       return;
6188     }
6189   }
6190 
6191   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6192     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6193     NewVD->setInvalidDecl();
6194     return;
6195   }
6196 
6197   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6198     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6199     NewVD->setInvalidDecl();
6200     return;
6201   }
6202 
6203   if (NewVD->isConstexpr() && !T->isDependentType() &&
6204       RequireLiteralType(NewVD->getLocation(), T,
6205                          diag::err_constexpr_var_non_literal)) {
6206     NewVD->setInvalidDecl();
6207     return;
6208   }
6209 }
6210 
6211 /// \brief Perform semantic checking on a newly-created variable
6212 /// declaration.
6213 ///
6214 /// This routine performs all of the type-checking required for a
6215 /// variable declaration once it has been built. It is used both to
6216 /// check variables after they have been parsed and their declarators
6217 /// have been translated into a declaration, and to check variables
6218 /// that have been instantiated from a template.
6219 ///
6220 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6221 ///
6222 /// Returns true if the variable declaration is a redeclaration.
6223 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6224   CheckVariableDeclarationType(NewVD);
6225 
6226   // If the decl is already known invalid, don't check it.
6227   if (NewVD->isInvalidDecl())
6228     return false;
6229 
6230   // If we did not find anything by this name, look for a non-visible
6231   // extern "C" declaration with the same name.
6232   if (Previous.empty() &&
6233       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6234     Previous.setShadowed();
6235 
6236   // Filter out any non-conflicting previous declarations.
6237   filterNonConflictingPreviousDecls(Context, NewVD, Previous);
6238 
6239   if (!Previous.empty()) {
6240     MergeVarDecl(NewVD, Previous);
6241     return true;
6242   }
6243   return false;
6244 }
6245 
6246 /// \brief Data used with FindOverriddenMethod
6247 struct FindOverriddenMethodData {
6248   Sema *S;
6249   CXXMethodDecl *Method;
6250 };
6251 
6252 /// \brief Member lookup function that determines whether a given C++
6253 /// method overrides a method in a base class, to be used with
6254 /// CXXRecordDecl::lookupInBases().
6255 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
6256                                  CXXBasePath &Path,
6257                                  void *UserData) {
6258   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6259 
6260   FindOverriddenMethodData *Data
6261     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
6262 
6263   DeclarationName Name = Data->Method->getDeclName();
6264 
6265   // FIXME: Do we care about other names here too?
6266   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6267     // We really want to find the base class destructor here.
6268     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
6269     CanQualType CT = Data->S->Context.getCanonicalType(T);
6270 
6271     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
6272   }
6273 
6274   for (Path.Decls = BaseRecord->lookup(Name);
6275        !Path.Decls.empty();
6276        Path.Decls = Path.Decls.slice(1)) {
6277     NamedDecl *D = Path.Decls.front();
6278     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6279       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
6280         return true;
6281     }
6282   }
6283 
6284   return false;
6285 }
6286 
6287 namespace {
6288   enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6289 }
6290 /// \brief Report an error regarding overriding, along with any relevant
6291 /// overriden methods.
6292 ///
6293 /// \param DiagID the primary error to report.
6294 /// \param MD the overriding method.
6295 /// \param OEK which overrides to include as notes.
6296 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6297                             OverrideErrorKind OEK = OEK_All) {
6298   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6299   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6300                                       E = MD->end_overridden_methods();
6301        I != E; ++I) {
6302     // This check (& the OEK parameter) could be replaced by a predicate, but
6303     // without lambdas that would be overkill. This is still nicer than writing
6304     // out the diag loop 3 times.
6305     if ((OEK == OEK_All) ||
6306         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6307         (OEK == OEK_Deleted && (*I)->isDeleted()))
6308       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6309   }
6310 }
6311 
6312 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6313 /// and if so, check that it's a valid override and remember it.
6314 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6315   // Look for methods in base classes that this method might override.
6316   CXXBasePaths Paths;
6317   FindOverriddenMethodData Data;
6318   Data.Method = MD;
6319   Data.S = this;
6320   bool hasDeletedOverridenMethods = false;
6321   bool hasNonDeletedOverridenMethods = false;
6322   bool AddedAny = false;
6323   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
6324     for (auto *I : Paths.found_decls()) {
6325       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6326         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6327         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6328             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6329             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6330             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6331           hasDeletedOverridenMethods |= OldMD->isDeleted();
6332           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6333           AddedAny = true;
6334         }
6335       }
6336     }
6337   }
6338 
6339   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6340     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6341   }
6342   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6343     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6344   }
6345 
6346   return AddedAny;
6347 }
6348 
6349 namespace {
6350   // Struct for holding all of the extra arguments needed by
6351   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6352   struct ActOnFDArgs {
6353     Scope *S;
6354     Declarator &D;
6355     MultiTemplateParamsArg TemplateParamLists;
6356     bool AddToScope;
6357   };
6358 }
6359 
6360 namespace {
6361 
6362 // Callback to only accept typo corrections that have a non-zero edit distance.
6363 // Also only accept corrections that have the same parent decl.
6364 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6365  public:
6366   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6367                             CXXRecordDecl *Parent)
6368       : Context(Context), OriginalFD(TypoFD),
6369         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6370 
6371   bool ValidateCandidate(const TypoCorrection &candidate) override {
6372     if (candidate.getEditDistance() == 0)
6373       return false;
6374 
6375     SmallVector<unsigned, 1> MismatchedParams;
6376     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6377                                           CDeclEnd = candidate.end();
6378          CDecl != CDeclEnd; ++CDecl) {
6379       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6380 
6381       if (FD && !FD->hasBody() &&
6382           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6383         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6384           CXXRecordDecl *Parent = MD->getParent();
6385           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6386             return true;
6387         } else if (!ExpectedParent) {
6388           return true;
6389         }
6390       }
6391     }
6392 
6393     return false;
6394   }
6395 
6396  private:
6397   ASTContext &Context;
6398   FunctionDecl *OriginalFD;
6399   CXXRecordDecl *ExpectedParent;
6400 };
6401 
6402 }
6403 
6404 /// \brief Generate diagnostics for an invalid function redeclaration.
6405 ///
6406 /// This routine handles generating the diagnostic messages for an invalid
6407 /// function redeclaration, including finding possible similar declarations
6408 /// or performing typo correction if there are no previous declarations with
6409 /// the same name.
6410 ///
6411 /// Returns a NamedDecl iff typo correction was performed and substituting in
6412 /// the new declaration name does not cause new errors.
6413 static NamedDecl *DiagnoseInvalidRedeclaration(
6414     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6415     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6416   DeclarationName Name = NewFD->getDeclName();
6417   DeclContext *NewDC = NewFD->getDeclContext();
6418   SmallVector<unsigned, 1> MismatchedParams;
6419   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6420   TypoCorrection Correction;
6421   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6422   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6423                                    : diag::err_member_decl_does_not_match;
6424   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6425                     IsLocalFriend ? Sema::LookupLocalFriendName
6426                                   : Sema::LookupOrdinaryName,
6427                     Sema::ForRedeclaration);
6428 
6429   NewFD->setInvalidDecl();
6430   if (IsLocalFriend)
6431     SemaRef.LookupName(Prev, S);
6432   else
6433     SemaRef.LookupQualifiedName(Prev, NewDC);
6434   assert(!Prev.isAmbiguous() &&
6435          "Cannot have an ambiguity in previous-declaration lookup");
6436   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6437   if (!Prev.empty()) {
6438     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6439          Func != FuncEnd; ++Func) {
6440       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6441       if (FD &&
6442           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6443         // Add 1 to the index so that 0 can mean the mismatch didn't
6444         // involve a parameter
6445         unsigned ParamNum =
6446             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6447         NearMatches.push_back(std::make_pair(FD, ParamNum));
6448       }
6449     }
6450   // If the qualified name lookup yielded nothing, try typo correction
6451   } else if ((Correction = SemaRef.CorrectTypo(
6452                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6453                   &ExtraArgs.D.getCXXScopeSpec(),
6454                   llvm::make_unique<DifferentNameValidatorCCC>(
6455                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6456                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6457     // Set up everything for the call to ActOnFunctionDeclarator
6458     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6459                               ExtraArgs.D.getIdentifierLoc());
6460     Previous.clear();
6461     Previous.setLookupName(Correction.getCorrection());
6462     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6463                                     CDeclEnd = Correction.end();
6464          CDecl != CDeclEnd; ++CDecl) {
6465       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6466       if (FD && !FD->hasBody() &&
6467           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6468         Previous.addDecl(FD);
6469       }
6470     }
6471     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6472 
6473     NamedDecl *Result;
6474     // Retry building the function declaration with the new previous
6475     // declarations, and with errors suppressed.
6476     {
6477       // Trap errors.
6478       Sema::SFINAETrap Trap(SemaRef);
6479 
6480       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6481       // pieces need to verify the typo-corrected C++ declaration and hopefully
6482       // eliminate the need for the parameter pack ExtraArgs.
6483       Result = SemaRef.ActOnFunctionDeclarator(
6484           ExtraArgs.S, ExtraArgs.D,
6485           Correction.getCorrectionDecl()->getDeclContext(),
6486           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6487           ExtraArgs.AddToScope);
6488 
6489       if (Trap.hasErrorOccurred())
6490         Result = nullptr;
6491     }
6492 
6493     if (Result) {
6494       // Determine which correction we picked.
6495       Decl *Canonical = Result->getCanonicalDecl();
6496       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6497            I != E; ++I)
6498         if ((*I)->getCanonicalDecl() == Canonical)
6499           Correction.setCorrectionDecl(*I);
6500 
6501       SemaRef.diagnoseTypo(
6502           Correction,
6503           SemaRef.PDiag(IsLocalFriend
6504                           ? diag::err_no_matching_local_friend_suggest
6505                           : diag::err_member_decl_does_not_match_suggest)
6506             << Name << NewDC << IsDefinition);
6507       return Result;
6508     }
6509 
6510     // Pretend the typo correction never occurred
6511     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6512                               ExtraArgs.D.getIdentifierLoc());
6513     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6514     Previous.clear();
6515     Previous.setLookupName(Name);
6516   }
6517 
6518   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6519       << Name << NewDC << IsDefinition << NewFD->getLocation();
6520 
6521   bool NewFDisConst = false;
6522   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6523     NewFDisConst = NewMD->isConst();
6524 
6525   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6526        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6527        NearMatch != NearMatchEnd; ++NearMatch) {
6528     FunctionDecl *FD = NearMatch->first;
6529     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6530     bool FDisConst = MD && MD->isConst();
6531     bool IsMember = MD || !IsLocalFriend;
6532 
6533     // FIXME: These notes are poorly worded for the local friend case.
6534     if (unsigned Idx = NearMatch->second) {
6535       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6536       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6537       if (Loc.isInvalid()) Loc = FD->getLocation();
6538       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6539                                  : diag::note_local_decl_close_param_match)
6540         << Idx << FDParam->getType()
6541         << NewFD->getParamDecl(Idx - 1)->getType();
6542     } else if (FDisConst != NewFDisConst) {
6543       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6544           << NewFDisConst << FD->getSourceRange().getEnd();
6545     } else
6546       SemaRef.Diag(FD->getLocation(),
6547                    IsMember ? diag::note_member_def_close_match
6548                             : diag::note_local_decl_close_match);
6549   }
6550   return nullptr;
6551 }
6552 
6553 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
6554   switch (D.getDeclSpec().getStorageClassSpec()) {
6555   default: llvm_unreachable("Unknown storage class!");
6556   case DeclSpec::SCS_auto:
6557   case DeclSpec::SCS_register:
6558   case DeclSpec::SCS_mutable:
6559     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6560                  diag::err_typecheck_sclass_func);
6561     D.setInvalidType();
6562     break;
6563   case DeclSpec::SCS_unspecified: break;
6564   case DeclSpec::SCS_extern:
6565     if (D.getDeclSpec().isExternInLinkageSpec())
6566       return SC_None;
6567     return SC_Extern;
6568   case DeclSpec::SCS_static: {
6569     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6570       // C99 6.7.1p5:
6571       //   The declaration of an identifier for a function that has
6572       //   block scope shall have no explicit storage-class specifier
6573       //   other than extern
6574       // See also (C++ [dcl.stc]p4).
6575       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6576                    diag::err_static_block_func);
6577       break;
6578     } else
6579       return SC_Static;
6580   }
6581   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6582   }
6583 
6584   // No explicit storage class has already been returned
6585   return SC_None;
6586 }
6587 
6588 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6589                                            DeclContext *DC, QualType &R,
6590                                            TypeSourceInfo *TInfo,
6591                                            StorageClass SC,
6592                                            bool &IsVirtualOkay) {
6593   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6594   DeclarationName Name = NameInfo.getName();
6595 
6596   FunctionDecl *NewFD = nullptr;
6597   bool isInline = D.getDeclSpec().isInlineSpecified();
6598 
6599   if (!SemaRef.getLangOpts().CPlusPlus) {
6600     // Determine whether the function was written with a
6601     // prototype. This true when:
6602     //   - there is a prototype in the declarator, or
6603     //   - the type R of the function is some kind of typedef or other reference
6604     //     to a type name (which eventually refers to a function type).
6605     bool HasPrototype =
6606       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6607       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6608 
6609     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6610                                  D.getLocStart(), NameInfo, R,
6611                                  TInfo, SC, isInline,
6612                                  HasPrototype, false);
6613     if (D.isInvalidType())
6614       NewFD->setInvalidDecl();
6615 
6616     return NewFD;
6617   }
6618 
6619   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6620   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6621 
6622   // Check that the return type is not an abstract class type.
6623   // For record types, this is done by the AbstractClassUsageDiagnoser once
6624   // the class has been completely parsed.
6625   if (!DC->isRecord() &&
6626       SemaRef.RequireNonAbstractType(
6627           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6628           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
6629     D.setInvalidType();
6630 
6631   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6632     // This is a C++ constructor declaration.
6633     assert(DC->isRecord() &&
6634            "Constructors can only be declared in a member context");
6635 
6636     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6637     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6638                                       D.getLocStart(), NameInfo,
6639                                       R, TInfo, isExplicit, isInline,
6640                                       /*isImplicitlyDeclared=*/false,
6641                                       isConstexpr);
6642 
6643   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6644     // This is a C++ destructor declaration.
6645     if (DC->isRecord()) {
6646       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6647       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6648       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6649                                         SemaRef.Context, Record,
6650                                         D.getLocStart(),
6651                                         NameInfo, R, TInfo, isInline,
6652                                         /*isImplicitlyDeclared=*/false);
6653 
6654       // If the class is complete, then we now create the implicit exception
6655       // specification. If the class is incomplete or dependent, we can't do
6656       // it yet.
6657       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6658           Record->getDefinition() && !Record->isBeingDefined() &&
6659           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6660         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6661       }
6662 
6663       IsVirtualOkay = true;
6664       return NewDD;
6665 
6666     } else {
6667       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6668       D.setInvalidType();
6669 
6670       // Create a FunctionDecl to satisfy the function definition parsing
6671       // code path.
6672       return FunctionDecl::Create(SemaRef.Context, DC,
6673                                   D.getLocStart(),
6674                                   D.getIdentifierLoc(), Name, R, TInfo,
6675                                   SC, isInline,
6676                                   /*hasPrototype=*/true, isConstexpr);
6677     }
6678 
6679   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6680     if (!DC->isRecord()) {
6681       SemaRef.Diag(D.getIdentifierLoc(),
6682            diag::err_conv_function_not_member);
6683       return nullptr;
6684     }
6685 
6686     SemaRef.CheckConversionDeclarator(D, R, SC);
6687     IsVirtualOkay = true;
6688     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6689                                      D.getLocStart(), NameInfo,
6690                                      R, TInfo, isInline, isExplicit,
6691                                      isConstexpr, SourceLocation());
6692 
6693   } else if (DC->isRecord()) {
6694     // If the name of the function is the same as the name of the record,
6695     // then this must be an invalid constructor that has a return type.
6696     // (The parser checks for a return type and makes the declarator a
6697     // constructor if it has no return type).
6698     if (Name.getAsIdentifierInfo() &&
6699         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6700       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6701         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6702         << SourceRange(D.getIdentifierLoc());
6703       return nullptr;
6704     }
6705 
6706     // This is a C++ method declaration.
6707     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6708                                                cast<CXXRecordDecl>(DC),
6709                                                D.getLocStart(), NameInfo, R,
6710                                                TInfo, SC, isInline,
6711                                                isConstexpr, SourceLocation());
6712     IsVirtualOkay = !Ret->isStatic();
6713     return Ret;
6714   } else {
6715     bool isFriend =
6716         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
6717     if (!isFriend && SemaRef.CurContext->isRecord())
6718       return nullptr;
6719 
6720     // Determine whether the function was written with a
6721     // prototype. This true when:
6722     //   - we're in C++ (where every function has a prototype),
6723     return FunctionDecl::Create(SemaRef.Context, DC,
6724                                 D.getLocStart(),
6725                                 NameInfo, R, TInfo, SC, isInline,
6726                                 true/*HasPrototype*/, isConstexpr);
6727   }
6728 }
6729 
6730 enum OpenCLParamType {
6731   ValidKernelParam,
6732   PtrPtrKernelParam,
6733   PtrKernelParam,
6734   PrivatePtrKernelParam,
6735   InvalidKernelParam,
6736   RecordKernelParam
6737 };
6738 
6739 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6740   if (PT->isPointerType()) {
6741     QualType PointeeType = PT->getPointeeType();
6742     if (PointeeType->isPointerType())
6743       return PtrPtrKernelParam;
6744     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
6745                                               : PtrKernelParam;
6746   }
6747 
6748   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6749   // be used as builtin types.
6750 
6751   if (PT->isImageType())
6752     return PtrKernelParam;
6753 
6754   if (PT->isBooleanType())
6755     return InvalidKernelParam;
6756 
6757   if (PT->isEventT())
6758     return InvalidKernelParam;
6759 
6760   if (PT->isHalfType())
6761     return InvalidKernelParam;
6762 
6763   if (PT->isRecordType())
6764     return RecordKernelParam;
6765 
6766   return ValidKernelParam;
6767 }
6768 
6769 static void checkIsValidOpenCLKernelParameter(
6770   Sema &S,
6771   Declarator &D,
6772   ParmVarDecl *Param,
6773   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
6774   QualType PT = Param->getType();
6775 
6776   // Cache the valid types we encounter to avoid rechecking structs that are
6777   // used again
6778   if (ValidTypes.count(PT.getTypePtr()))
6779     return;
6780 
6781   switch (getOpenCLKernelParameterType(PT)) {
6782   case PtrPtrKernelParam:
6783     // OpenCL v1.2 s6.9.a:
6784     // A kernel function argument cannot be declared as a
6785     // pointer to a pointer type.
6786     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6787     D.setInvalidType();
6788     return;
6789 
6790   case PrivatePtrKernelParam:
6791     // OpenCL v1.2 s6.9.a:
6792     // A kernel function argument cannot be declared as a
6793     // pointer to the private address space.
6794     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
6795     D.setInvalidType();
6796     return;
6797 
6798     // OpenCL v1.2 s6.9.k:
6799     // Arguments to kernel functions in a program cannot be declared with the
6800     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6801     // uintptr_t or a struct and/or union that contain fields declared to be
6802     // one of these built-in scalar types.
6803 
6804   case InvalidKernelParam:
6805     // OpenCL v1.2 s6.8 n:
6806     // A kernel function argument cannot be declared
6807     // of event_t type.
6808     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6809     D.setInvalidType();
6810     return;
6811 
6812   case PtrKernelParam:
6813   case ValidKernelParam:
6814     ValidTypes.insert(PT.getTypePtr());
6815     return;
6816 
6817   case RecordKernelParam:
6818     break;
6819   }
6820 
6821   // Track nested structs we will inspect
6822   SmallVector<const Decl *, 4> VisitStack;
6823 
6824   // Track where we are in the nested structs. Items will migrate from
6825   // VisitStack to HistoryStack as we do the DFS for bad field.
6826   SmallVector<const FieldDecl *, 4> HistoryStack;
6827   HistoryStack.push_back(nullptr);
6828 
6829   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6830   VisitStack.push_back(PD);
6831 
6832   assert(VisitStack.back() && "First decl null?");
6833 
6834   do {
6835     const Decl *Next = VisitStack.pop_back_val();
6836     if (!Next) {
6837       assert(!HistoryStack.empty());
6838       // Found a marker, we have gone up a level
6839       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6840         ValidTypes.insert(Hist->getType().getTypePtr());
6841 
6842       continue;
6843     }
6844 
6845     // Adds everything except the original parameter declaration (which is not a
6846     // field itself) to the history stack.
6847     const RecordDecl *RD;
6848     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6849       HistoryStack.push_back(Field);
6850       RD = Field->getType()->castAs<RecordType>()->getDecl();
6851     } else {
6852       RD = cast<RecordDecl>(Next);
6853     }
6854 
6855     // Add a null marker so we know when we've gone back up a level
6856     VisitStack.push_back(nullptr);
6857 
6858     for (const auto *FD : RD->fields()) {
6859       QualType QT = FD->getType();
6860 
6861       if (ValidTypes.count(QT.getTypePtr()))
6862         continue;
6863 
6864       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6865       if (ParamType == ValidKernelParam)
6866         continue;
6867 
6868       if (ParamType == RecordKernelParam) {
6869         VisitStack.push_back(FD);
6870         continue;
6871       }
6872 
6873       // OpenCL v1.2 s6.9.p:
6874       // Arguments to kernel functions that are declared to be a struct or union
6875       // do not allow OpenCL objects to be passed as elements of the struct or
6876       // union.
6877       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
6878           ParamType == PrivatePtrKernelParam) {
6879         S.Diag(Param->getLocation(),
6880                diag::err_record_with_pointers_kernel_param)
6881           << PT->isUnionType()
6882           << PT;
6883       } else {
6884         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6885       }
6886 
6887       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6888         << PD->getDeclName();
6889 
6890       // We have an error, now let's go back up through history and show where
6891       // the offending field came from
6892       for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6893              E = HistoryStack.end(); I != E; ++I) {
6894         const FieldDecl *OuterField = *I;
6895         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6896           << OuterField->getType();
6897       }
6898 
6899       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6900         << QT->isPointerType()
6901         << QT;
6902       D.setInvalidType();
6903       return;
6904     }
6905   } while (!VisitStack.empty());
6906 }
6907 
6908 NamedDecl*
6909 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
6910                               TypeSourceInfo *TInfo, LookupResult &Previous,
6911                               MultiTemplateParamsArg TemplateParamLists,
6912                               bool &AddToScope) {
6913   QualType R = TInfo->getType();
6914 
6915   assert(R.getTypePtr()->isFunctionType());
6916 
6917   // TODO: consider using NameInfo for diagnostic.
6918   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6919   DeclarationName Name = NameInfo.getName();
6920   StorageClass SC = getFunctionStorageClass(*this, D);
6921 
6922   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6923     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6924          diag::err_invalid_thread)
6925       << DeclSpec::getSpecifierName(TSCS);
6926 
6927   if (D.isFirstDeclarationOfMember())
6928     adjustMemberFunctionCC(R, D.isStaticMember());
6929 
6930   bool isFriend = false;
6931   FunctionTemplateDecl *FunctionTemplate = nullptr;
6932   bool isExplicitSpecialization = false;
6933   bool isFunctionTemplateSpecialization = false;
6934 
6935   bool isDependentClassScopeExplicitSpecialization = false;
6936   bool HasExplicitTemplateArgs = false;
6937   TemplateArgumentListInfo TemplateArgs;
6938 
6939   bool isVirtualOkay = false;
6940 
6941   DeclContext *OriginalDC = DC;
6942   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6943 
6944   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6945                                               isVirtualOkay);
6946   if (!NewFD) return nullptr;
6947 
6948   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6949     NewFD->setTopLevelDeclInObjCContainer();
6950 
6951   // Set the lexical context. If this is a function-scope declaration, or has a
6952   // C++ scope specifier, or is the object of a friend declaration, the lexical
6953   // context will be different from the semantic context.
6954   NewFD->setLexicalDeclContext(CurContext);
6955 
6956   if (IsLocalExternDecl)
6957     NewFD->setLocalExternDecl();
6958 
6959   if (getLangOpts().CPlusPlus) {
6960     bool isInline = D.getDeclSpec().isInlineSpecified();
6961     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6962     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6963     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6964     isFriend = D.getDeclSpec().isFriendSpecified();
6965     if (isFriend && !isInline && D.isFunctionDefinition()) {
6966       // C++ [class.friend]p5
6967       //   A function can be defined in a friend declaration of a
6968       //   class . . . . Such a function is implicitly inline.
6969       NewFD->setImplicitlyInline();
6970     }
6971 
6972     // If this is a method defined in an __interface, and is not a constructor
6973     // or an overloaded operator, then set the pure flag (isVirtual will already
6974     // return true).
6975     if (const CXXRecordDecl *Parent =
6976           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6977       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
6978         NewFD->setPure(true);
6979     }
6980 
6981     SetNestedNameSpecifier(NewFD, D);
6982     isExplicitSpecialization = false;
6983     isFunctionTemplateSpecialization = false;
6984     if (D.isInvalidType())
6985       NewFD->setInvalidDecl();
6986 
6987     // Match up the template parameter lists with the scope specifier, then
6988     // determine whether we have a template or a template specialization.
6989     bool Invalid = false;
6990     if (TemplateParameterList *TemplateParams =
6991             MatchTemplateParametersToScopeSpecifier(
6992                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6993                 D.getCXXScopeSpec(),
6994                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
6995                     ? D.getName().TemplateId
6996                     : nullptr,
6997                 TemplateParamLists, isFriend, isExplicitSpecialization,
6998                 Invalid)) {
6999       if (TemplateParams->size() > 0) {
7000         // This is a function template
7001 
7002         // Check that we can declare a template here.
7003         if (CheckTemplateDeclScope(S, TemplateParams))
7004           return nullptr;
7005 
7006         // A destructor cannot be a template.
7007         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7008           Diag(NewFD->getLocation(), diag::err_destructor_template);
7009           return nullptr;
7010         }
7011 
7012         // If we're adding a template to a dependent context, we may need to
7013         // rebuilding some of the types used within the template parameter list,
7014         // now that we know what the current instantiation is.
7015         if (DC->isDependentContext()) {
7016           ContextRAII SavedContext(*this, DC);
7017           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7018             Invalid = true;
7019         }
7020 
7021 
7022         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7023                                                         NewFD->getLocation(),
7024                                                         Name, TemplateParams,
7025                                                         NewFD);
7026         FunctionTemplate->setLexicalDeclContext(CurContext);
7027         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7028 
7029         // For source fidelity, store the other template param lists.
7030         if (TemplateParamLists.size() > 1) {
7031           NewFD->setTemplateParameterListsInfo(Context,
7032                                                TemplateParamLists.size() - 1,
7033                                                TemplateParamLists.data());
7034         }
7035       } else {
7036         // This is a function template specialization.
7037         isFunctionTemplateSpecialization = true;
7038         // For source fidelity, store all the template param lists.
7039         if (TemplateParamLists.size() > 0)
7040           NewFD->setTemplateParameterListsInfo(Context,
7041                                                TemplateParamLists.size(),
7042                                                TemplateParamLists.data());
7043 
7044         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7045         if (isFriend) {
7046           // We want to remove the "template<>", found here.
7047           SourceRange RemoveRange = TemplateParams->getSourceRange();
7048 
7049           // If we remove the template<> and the name is not a
7050           // template-id, we're actually silently creating a problem:
7051           // the friend declaration will refer to an untemplated decl,
7052           // and clearly the user wants a template specialization.  So
7053           // we need to insert '<>' after the name.
7054           SourceLocation InsertLoc;
7055           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7056             InsertLoc = D.getName().getSourceRange().getEnd();
7057             InsertLoc = getLocForEndOfToken(InsertLoc);
7058           }
7059 
7060           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7061             << Name << RemoveRange
7062             << FixItHint::CreateRemoval(RemoveRange)
7063             << FixItHint::CreateInsertion(InsertLoc, "<>");
7064         }
7065       }
7066     }
7067     else {
7068       // All template param lists were matched against the scope specifier:
7069       // this is NOT (an explicit specialization of) a template.
7070       if (TemplateParamLists.size() > 0)
7071         // For source fidelity, store all the template param lists.
7072         NewFD->setTemplateParameterListsInfo(Context,
7073                                              TemplateParamLists.size(),
7074                                              TemplateParamLists.data());
7075     }
7076 
7077     if (Invalid) {
7078       NewFD->setInvalidDecl();
7079       if (FunctionTemplate)
7080         FunctionTemplate->setInvalidDecl();
7081     }
7082 
7083     // C++ [dcl.fct.spec]p5:
7084     //   The virtual specifier shall only be used in declarations of
7085     //   nonstatic class member functions that appear within a
7086     //   member-specification of a class declaration; see 10.3.
7087     //
7088     if (isVirtual && !NewFD->isInvalidDecl()) {
7089       if (!isVirtualOkay) {
7090         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7091              diag::err_virtual_non_function);
7092       } else if (!CurContext->isRecord()) {
7093         // 'virtual' was specified outside of the class.
7094         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7095              diag::err_virtual_out_of_class)
7096           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7097       } else if (NewFD->getDescribedFunctionTemplate()) {
7098         // C++ [temp.mem]p3:
7099         //  A member function template shall not be virtual.
7100         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7101              diag::err_virtual_member_function_template)
7102           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7103       } else {
7104         // Okay: Add virtual to the method.
7105         NewFD->setVirtualAsWritten(true);
7106       }
7107 
7108       if (getLangOpts().CPlusPlus14 &&
7109           NewFD->getReturnType()->isUndeducedType())
7110         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7111     }
7112 
7113     if (getLangOpts().CPlusPlus14 &&
7114         (NewFD->isDependentContext() ||
7115          (isFriend && CurContext->isDependentContext())) &&
7116         NewFD->getReturnType()->isUndeducedType()) {
7117       // If the function template is referenced directly (for instance, as a
7118       // member of the current instantiation), pretend it has a dependent type.
7119       // This is not really justified by the standard, but is the only sane
7120       // thing to do.
7121       // FIXME: For a friend function, we have not marked the function as being
7122       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7123       const FunctionProtoType *FPT =
7124           NewFD->getType()->castAs<FunctionProtoType>();
7125       QualType Result =
7126           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7127       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7128                                              FPT->getExtProtoInfo()));
7129     }
7130 
7131     // C++ [dcl.fct.spec]p3:
7132     //  The inline specifier shall not appear on a block scope function
7133     //  declaration.
7134     if (isInline && !NewFD->isInvalidDecl()) {
7135       if (CurContext->isFunctionOrMethod()) {
7136         // 'inline' is not allowed on block scope function declaration.
7137         Diag(D.getDeclSpec().getInlineSpecLoc(),
7138              diag::err_inline_declaration_block_scope) << Name
7139           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7140       }
7141     }
7142 
7143     // C++ [dcl.fct.spec]p6:
7144     //  The explicit specifier shall be used only in the declaration of a
7145     //  constructor or conversion function within its class definition;
7146     //  see 12.3.1 and 12.3.2.
7147     if (isExplicit && !NewFD->isInvalidDecl()) {
7148       if (!CurContext->isRecord()) {
7149         // 'explicit' was specified outside of the class.
7150         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7151              diag::err_explicit_out_of_class)
7152           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7153       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7154                  !isa<CXXConversionDecl>(NewFD)) {
7155         // 'explicit' was specified on a function that wasn't a constructor
7156         // or conversion function.
7157         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7158              diag::err_explicit_non_ctor_or_conv_function)
7159           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7160       }
7161     }
7162 
7163     if (isConstexpr) {
7164       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7165       // are implicitly inline.
7166       NewFD->setImplicitlyInline();
7167 
7168       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7169       // be either constructors or to return a literal type. Therefore,
7170       // destructors cannot be declared constexpr.
7171       if (isa<CXXDestructorDecl>(NewFD))
7172         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7173     }
7174 
7175     // If __module_private__ was specified, mark the function accordingly.
7176     if (D.getDeclSpec().isModulePrivateSpecified()) {
7177       if (isFunctionTemplateSpecialization) {
7178         SourceLocation ModulePrivateLoc
7179           = D.getDeclSpec().getModulePrivateSpecLoc();
7180         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7181           << 0
7182           << FixItHint::CreateRemoval(ModulePrivateLoc);
7183       } else {
7184         NewFD->setModulePrivate();
7185         if (FunctionTemplate)
7186           FunctionTemplate->setModulePrivate();
7187       }
7188     }
7189 
7190     if (isFriend) {
7191       if (FunctionTemplate) {
7192         FunctionTemplate->setObjectOfFriendDecl();
7193         FunctionTemplate->setAccess(AS_public);
7194       }
7195       NewFD->setObjectOfFriendDecl();
7196       NewFD->setAccess(AS_public);
7197     }
7198 
7199     // If a function is defined as defaulted or deleted, mark it as such now.
7200     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7201     // definition kind to FDK_Definition.
7202     switch (D.getFunctionDefinitionKind()) {
7203       case FDK_Declaration:
7204       case FDK_Definition:
7205         break;
7206 
7207       case FDK_Defaulted:
7208         NewFD->setDefaulted();
7209         break;
7210 
7211       case FDK_Deleted:
7212         NewFD->setDeletedAsWritten();
7213         break;
7214     }
7215 
7216     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7217         D.isFunctionDefinition()) {
7218       // C++ [class.mfct]p2:
7219       //   A member function may be defined (8.4) in its class definition, in
7220       //   which case it is an inline member function (7.1.2)
7221       NewFD->setImplicitlyInline();
7222     }
7223 
7224     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7225         !CurContext->isRecord()) {
7226       // C++ [class.static]p1:
7227       //   A data or function member of a class may be declared static
7228       //   in a class definition, in which case it is a static member of
7229       //   the class.
7230 
7231       // Complain about the 'static' specifier if it's on an out-of-line
7232       // member function definition.
7233       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7234            diag::err_static_out_of_line)
7235         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7236     }
7237 
7238     // C++11 [except.spec]p15:
7239     //   A deallocation function with no exception-specification is treated
7240     //   as if it were specified with noexcept(true).
7241     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7242     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7243          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7244         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7245       NewFD->setType(Context.getFunctionType(
7246           FPT->getReturnType(), FPT->getParamTypes(),
7247           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7248   }
7249 
7250   // Filter out previous declarations that don't match the scope.
7251   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7252                        D.getCXXScopeSpec().isNotEmpty() ||
7253                        isExplicitSpecialization ||
7254                        isFunctionTemplateSpecialization);
7255 
7256   // Handle GNU asm-label extension (encoded as an attribute).
7257   if (Expr *E = (Expr*) D.getAsmLabel()) {
7258     // The parser guarantees this is a string.
7259     StringLiteral *SE = cast<StringLiteral>(E);
7260     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7261                                                 SE->getString(), 0));
7262   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7263     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7264       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7265     if (I != ExtnameUndeclaredIdentifiers.end()) {
7266       NewFD->addAttr(I->second);
7267       ExtnameUndeclaredIdentifiers.erase(I);
7268     }
7269   }
7270 
7271   // Copy the parameter declarations from the declarator D to the function
7272   // declaration NewFD, if they are available.  First scavenge them into Params.
7273   SmallVector<ParmVarDecl*, 16> Params;
7274   if (D.isFunctionDeclarator()) {
7275     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7276 
7277     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7278     // function that takes no arguments, not a function that takes a
7279     // single void argument.
7280     // We let through "const void" here because Sema::GetTypeForDeclarator
7281     // already checks for that case.
7282     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7283       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7284         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7285         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7286         Param->setDeclContext(NewFD);
7287         Params.push_back(Param);
7288 
7289         if (Param->isInvalidDecl())
7290           NewFD->setInvalidDecl();
7291       }
7292     }
7293 
7294   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7295     // When we're declaring a function with a typedef, typeof, etc as in the
7296     // following example, we'll need to synthesize (unnamed)
7297     // parameters for use in the declaration.
7298     //
7299     // @code
7300     // typedef void fn(int);
7301     // fn f;
7302     // @endcode
7303 
7304     // Synthesize a parameter for each argument type.
7305     for (const auto &AI : FT->param_types()) {
7306       ParmVarDecl *Param =
7307           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7308       Param->setScopeInfo(0, Params.size());
7309       Params.push_back(Param);
7310     }
7311   } else {
7312     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7313            "Should not need args for typedef of non-prototype fn");
7314   }
7315 
7316   // Finally, we know we have the right number of parameters, install them.
7317   NewFD->setParams(Params);
7318 
7319   // Find all anonymous symbols defined during the declaration of this function
7320   // and add to NewFD. This lets us track decls such 'enum Y' in:
7321   //
7322   //   void f(enum Y {AA} x) {}
7323   //
7324   // which would otherwise incorrectly end up in the translation unit scope.
7325   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7326   DeclsInPrototypeScope.clear();
7327 
7328   if (D.getDeclSpec().isNoreturnSpecified())
7329     NewFD->addAttr(
7330         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7331                                        Context, 0));
7332 
7333   // Functions returning a variably modified type violate C99 6.7.5.2p2
7334   // because all functions have linkage.
7335   if (!NewFD->isInvalidDecl() &&
7336       NewFD->getReturnType()->isVariablyModifiedType()) {
7337     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7338     NewFD->setInvalidDecl();
7339   }
7340 
7341   if (D.isFunctionDefinition() && CodeSegStack.CurrentValue &&
7342       !NewFD->hasAttr<SectionAttr>()) {
7343     NewFD->addAttr(
7344         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7345                                     CodeSegStack.CurrentValue->getString(),
7346                                     CodeSegStack.CurrentPragmaLocation));
7347     if (UnifySection(CodeSegStack.CurrentValue->getString(),
7348                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
7349                          ASTContext::PSF_Read,
7350                      NewFD))
7351       NewFD->dropAttr<SectionAttr>();
7352   }
7353 
7354   // Handle attributes.
7355   ProcessDeclAttributes(S, NewFD, D);
7356 
7357   QualType RetType = NewFD->getReturnType();
7358   const CXXRecordDecl *Ret = RetType->isRecordType() ?
7359       RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
7360   if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
7361       Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
7362     const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7363     // Attach WarnUnusedResult to functions returning types with that attribute.
7364     // Don't apply the attribute to that type's own non-static member functions
7365     // (to avoid warning on things like assignment operators)
7366     if (!MD || MD->getParent() != Ret)
7367       NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
7368   }
7369 
7370   if (getLangOpts().OpenCL) {
7371     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7372     // type declaration will generate a compilation error.
7373     unsigned AddressSpace = RetType.getAddressSpace();
7374     if (AddressSpace == LangAS::opencl_local ||
7375         AddressSpace == LangAS::opencl_global ||
7376         AddressSpace == LangAS::opencl_constant) {
7377       Diag(NewFD->getLocation(),
7378            diag::err_opencl_return_value_with_address_space);
7379       NewFD->setInvalidDecl();
7380     }
7381   }
7382 
7383   if (!getLangOpts().CPlusPlus) {
7384     // Perform semantic checking on the function declaration.
7385     bool isExplicitSpecialization=false;
7386     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7387       CheckMain(NewFD, D.getDeclSpec());
7388 
7389     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7390       CheckMSVCRTEntryPoint(NewFD);
7391 
7392     if (!NewFD->isInvalidDecl())
7393       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7394                                                   isExplicitSpecialization));
7395     else if (!Previous.empty())
7396       // Make graceful recovery from an invalid redeclaration.
7397       D.setRedeclaration(true);
7398     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7399             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7400            "previous declaration set still overloaded");
7401 
7402     // Diagnose no-prototype function declarations with calling conventions that
7403     // don't support variadic calls. Only do this in C and do it after merging
7404     // possibly prototyped redeclarations.
7405     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
7406     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
7407       CallingConv CC = FT->getExtInfo().getCC();
7408       if (!supportsVariadicCall(CC)) {
7409         // Windows system headers sometimes accidentally use stdcall without
7410         // (void) parameters, so we relax this to a warning.
7411         int DiagID =
7412             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
7413         Diag(NewFD->getLocation(), DiagID)
7414             << FunctionType::getNameForCallConv(CC);
7415       }
7416     }
7417   } else {
7418     // C++11 [replacement.functions]p3:
7419     //  The program's definitions shall not be specified as inline.
7420     //
7421     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7422     //
7423     // Suppress the diagnostic if the function is __attribute__((used)), since
7424     // that forces an external definition to be emitted.
7425     if (D.getDeclSpec().isInlineSpecified() &&
7426         NewFD->isReplaceableGlobalAllocationFunction() &&
7427         !NewFD->hasAttr<UsedAttr>())
7428       Diag(D.getDeclSpec().getInlineSpecLoc(),
7429            diag::ext_operator_new_delete_declared_inline)
7430         << NewFD->getDeclName();
7431 
7432     // If the declarator is a template-id, translate the parser's template
7433     // argument list into our AST format.
7434     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7435       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7436       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7437       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7438       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7439                                          TemplateId->NumArgs);
7440       translateTemplateArguments(TemplateArgsPtr,
7441                                  TemplateArgs);
7442 
7443       HasExplicitTemplateArgs = true;
7444 
7445       if (NewFD->isInvalidDecl()) {
7446         HasExplicitTemplateArgs = false;
7447       } else if (FunctionTemplate) {
7448         // Function template with explicit template arguments.
7449         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7450           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7451 
7452         HasExplicitTemplateArgs = false;
7453       } else {
7454         assert((isFunctionTemplateSpecialization ||
7455                 D.getDeclSpec().isFriendSpecified()) &&
7456                "should have a 'template<>' for this decl");
7457         // "friend void foo<>(int);" is an implicit specialization decl.
7458         isFunctionTemplateSpecialization = true;
7459       }
7460     } else if (isFriend && isFunctionTemplateSpecialization) {
7461       // This combination is only possible in a recovery case;  the user
7462       // wrote something like:
7463       //   template <> friend void foo(int);
7464       // which we're recovering from as if the user had written:
7465       //   friend void foo<>(int);
7466       // Go ahead and fake up a template id.
7467       HasExplicitTemplateArgs = true;
7468       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7469       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7470     }
7471 
7472     // If it's a friend (and only if it's a friend), it's possible
7473     // that either the specialized function type or the specialized
7474     // template is dependent, and therefore matching will fail.  In
7475     // this case, don't check the specialization yet.
7476     bool InstantiationDependent = false;
7477     if (isFunctionTemplateSpecialization && isFriend &&
7478         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7479          TemplateSpecializationType::anyDependentTemplateArguments(
7480             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7481             InstantiationDependent))) {
7482       assert(HasExplicitTemplateArgs &&
7483              "friend function specialization without template args");
7484       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7485                                                        Previous))
7486         NewFD->setInvalidDecl();
7487     } else if (isFunctionTemplateSpecialization) {
7488       if (CurContext->isDependentContext() && CurContext->isRecord()
7489           && !isFriend) {
7490         isDependentClassScopeExplicitSpecialization = true;
7491         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7492           diag::ext_function_specialization_in_class :
7493           diag::err_function_specialization_in_class)
7494           << NewFD->getDeclName();
7495       } else if (CheckFunctionTemplateSpecialization(NewFD,
7496                                   (HasExplicitTemplateArgs ? &TemplateArgs
7497                                                            : nullptr),
7498                                                      Previous))
7499         NewFD->setInvalidDecl();
7500 
7501       // C++ [dcl.stc]p1:
7502       //   A storage-class-specifier shall not be specified in an explicit
7503       //   specialization (14.7.3)
7504       FunctionTemplateSpecializationInfo *Info =
7505           NewFD->getTemplateSpecializationInfo();
7506       if (Info && SC != SC_None) {
7507         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7508           Diag(NewFD->getLocation(),
7509                diag::err_explicit_specialization_inconsistent_storage_class)
7510             << SC
7511             << FixItHint::CreateRemoval(
7512                                       D.getDeclSpec().getStorageClassSpecLoc());
7513 
7514         else
7515           Diag(NewFD->getLocation(),
7516                diag::ext_explicit_specialization_storage_class)
7517             << FixItHint::CreateRemoval(
7518                                       D.getDeclSpec().getStorageClassSpecLoc());
7519       }
7520 
7521     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7522       if (CheckMemberSpecialization(NewFD, Previous))
7523           NewFD->setInvalidDecl();
7524     }
7525 
7526     // Perform semantic checking on the function declaration.
7527     if (!isDependentClassScopeExplicitSpecialization) {
7528       if (!NewFD->isInvalidDecl() && NewFD->isMain())
7529         CheckMain(NewFD, D.getDeclSpec());
7530 
7531       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7532         CheckMSVCRTEntryPoint(NewFD);
7533 
7534       if (!NewFD->isInvalidDecl())
7535         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7536                                                     isExplicitSpecialization));
7537     }
7538 
7539     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7540             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7541            "previous declaration set still overloaded");
7542 
7543     NamedDecl *PrincipalDecl = (FunctionTemplate
7544                                 ? cast<NamedDecl>(FunctionTemplate)
7545                                 : NewFD);
7546 
7547     if (isFriend && D.isRedeclaration()) {
7548       AccessSpecifier Access = AS_public;
7549       if (!NewFD->isInvalidDecl())
7550         Access = NewFD->getPreviousDecl()->getAccess();
7551 
7552       NewFD->setAccess(Access);
7553       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7554     }
7555 
7556     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7557         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7558       PrincipalDecl->setNonMemberOperator();
7559 
7560     // If we have a function template, check the template parameter
7561     // list. This will check and merge default template arguments.
7562     if (FunctionTemplate) {
7563       FunctionTemplateDecl *PrevTemplate =
7564                                      FunctionTemplate->getPreviousDecl();
7565       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7566                        PrevTemplate ? PrevTemplate->getTemplateParameters()
7567                                     : nullptr,
7568                             D.getDeclSpec().isFriendSpecified()
7569                               ? (D.isFunctionDefinition()
7570                                    ? TPC_FriendFunctionTemplateDefinition
7571                                    : TPC_FriendFunctionTemplate)
7572                               : (D.getCXXScopeSpec().isSet() &&
7573                                  DC && DC->isRecord() &&
7574                                  DC->isDependentContext())
7575                                   ? TPC_ClassTemplateMember
7576                                   : TPC_FunctionTemplate);
7577     }
7578 
7579     if (NewFD->isInvalidDecl()) {
7580       // Ignore all the rest of this.
7581     } else if (!D.isRedeclaration()) {
7582       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7583                                        AddToScope };
7584       // Fake up an access specifier if it's supposed to be a class member.
7585       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7586         NewFD->setAccess(AS_public);
7587 
7588       // Qualified decls generally require a previous declaration.
7589       if (D.getCXXScopeSpec().isSet()) {
7590         // ...with the major exception of templated-scope or
7591         // dependent-scope friend declarations.
7592 
7593         // TODO: we currently also suppress this check in dependent
7594         // contexts because (1) the parameter depth will be off when
7595         // matching friend templates and (2) we might actually be
7596         // selecting a friend based on a dependent factor.  But there
7597         // are situations where these conditions don't apply and we
7598         // can actually do this check immediately.
7599         if (isFriend &&
7600             (TemplateParamLists.size() ||
7601              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7602              CurContext->isDependentContext())) {
7603           // ignore these
7604         } else {
7605           // The user tried to provide an out-of-line definition for a
7606           // function that is a member of a class or namespace, but there
7607           // was no such member function declared (C++ [class.mfct]p2,
7608           // C++ [namespace.memdef]p2). For example:
7609           //
7610           // class X {
7611           //   void f() const;
7612           // };
7613           //
7614           // void X::f() { } // ill-formed
7615           //
7616           // Complain about this problem, and attempt to suggest close
7617           // matches (e.g., those that differ only in cv-qualifiers and
7618           // whether the parameter types are references).
7619 
7620           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7621                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
7622             AddToScope = ExtraArgs.AddToScope;
7623             return Result;
7624           }
7625         }
7626 
7627         // Unqualified local friend declarations are required to resolve
7628         // to something.
7629       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7630         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7631                 *this, Previous, NewFD, ExtraArgs, true, S)) {
7632           AddToScope = ExtraArgs.AddToScope;
7633           return Result;
7634         }
7635       }
7636 
7637     } else if (!D.isFunctionDefinition() &&
7638                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
7639                !isFriend && !isFunctionTemplateSpecialization &&
7640                !isExplicitSpecialization) {
7641       // An out-of-line member function declaration must also be a
7642       // definition (C++ [class.mfct]p2).
7643       // Note that this is not the case for explicit specializations of
7644       // function templates or member functions of class templates, per
7645       // C++ [temp.expl.spec]p2. We also allow these declarations as an
7646       // extension for compatibility with old SWIG code which likes to
7647       // generate them.
7648       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7649         << D.getCXXScopeSpec().getRange();
7650     }
7651   }
7652 
7653   ProcessPragmaWeak(S, NewFD);
7654   checkAttributesAfterMerging(*this, *NewFD);
7655 
7656   AddKnownFunctionAttributes(NewFD);
7657 
7658   if (NewFD->hasAttr<OverloadableAttr>() &&
7659       !NewFD->getType()->getAs<FunctionProtoType>()) {
7660     Diag(NewFD->getLocation(),
7661          diag::err_attribute_overloadable_no_prototype)
7662       << NewFD;
7663 
7664     // Turn this into a variadic function with no parameters.
7665     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7666     FunctionProtoType::ExtProtoInfo EPI(
7667         Context.getDefaultCallingConvention(true, false));
7668     EPI.Variadic = true;
7669     EPI.ExtInfo = FT->getExtInfo();
7670 
7671     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
7672     NewFD->setType(R);
7673   }
7674 
7675   // If there's a #pragma GCC visibility in scope, and this isn't a class
7676   // member, set the visibility of this function.
7677   if (!DC->isRecord() && NewFD->isExternallyVisible())
7678     AddPushedVisibilityAttribute(NewFD);
7679 
7680   // If there's a #pragma clang arc_cf_code_audited in scope, consider
7681   // marking the function.
7682   AddCFAuditedAttribute(NewFD);
7683 
7684   // If this is a function definition, check if we have to apply optnone due to
7685   // a pragma.
7686   if(D.isFunctionDefinition())
7687     AddRangeBasedOptnone(NewFD);
7688 
7689   // If this is the first declaration of an extern C variable, update
7690   // the map of such variables.
7691   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7692       isIncompleteDeclExternC(*this, NewFD))
7693     RegisterLocallyScopedExternCDecl(NewFD, S);
7694 
7695   // Set this FunctionDecl's range up to the right paren.
7696   NewFD->setRangeEnd(D.getSourceRange().getEnd());
7697 
7698   if (D.isRedeclaration() && !Previous.empty()) {
7699     checkDLLAttributeRedeclaration(
7700         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
7701         isExplicitSpecialization || isFunctionTemplateSpecialization);
7702   }
7703 
7704   if (getLangOpts().CPlusPlus) {
7705     if (FunctionTemplate) {
7706       if (NewFD->isInvalidDecl())
7707         FunctionTemplate->setInvalidDecl();
7708       return FunctionTemplate;
7709     }
7710   }
7711 
7712   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7713     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7714     if ((getLangOpts().OpenCLVersion >= 120)
7715         && (SC == SC_Static)) {
7716       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7717       D.setInvalidType();
7718     }
7719 
7720     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7721     if (!NewFD->getReturnType()->isVoidType()) {
7722       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
7723       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
7724           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
7725                                 : FixItHint());
7726       D.setInvalidType();
7727     }
7728 
7729     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
7730     for (auto Param : NewFD->params())
7731       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
7732   }
7733 
7734   MarkUnusedFileScopedDecl(NewFD);
7735 
7736   if (getLangOpts().CUDA)
7737     if (IdentifierInfo *II = NewFD->getIdentifier())
7738       if (!NewFD->isInvalidDecl() &&
7739           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7740         if (II->isStr("cudaConfigureCall")) {
7741           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
7742             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7743 
7744           Context.setcudaConfigureCallDecl(NewFD);
7745         }
7746       }
7747 
7748   // Here we have an function template explicit specialization at class scope.
7749   // The actually specialization will be postponed to template instatiation
7750   // time via the ClassScopeFunctionSpecializationDecl node.
7751   if (isDependentClassScopeExplicitSpecialization) {
7752     ClassScopeFunctionSpecializationDecl *NewSpec =
7753                          ClassScopeFunctionSpecializationDecl::Create(
7754                                 Context, CurContext, SourceLocation(),
7755                                 cast<CXXMethodDecl>(NewFD),
7756                                 HasExplicitTemplateArgs, TemplateArgs);
7757     CurContext->addDecl(NewSpec);
7758     AddToScope = false;
7759   }
7760 
7761   return NewFD;
7762 }
7763 
7764 /// \brief Perform semantic checking of a new function declaration.
7765 ///
7766 /// Performs semantic analysis of the new function declaration
7767 /// NewFD. This routine performs all semantic checking that does not
7768 /// require the actual declarator involved in the declaration, and is
7769 /// used both for the declaration of functions as they are parsed
7770 /// (called via ActOnDeclarator) and for the declaration of functions
7771 /// that have been instantiated via C++ template instantiation (called
7772 /// via InstantiateDecl).
7773 ///
7774 /// \param IsExplicitSpecialization whether this new function declaration is
7775 /// an explicit specialization of the previous declaration.
7776 ///
7777 /// This sets NewFD->isInvalidDecl() to true if there was an error.
7778 ///
7779 /// \returns true if the function declaration is a redeclaration.
7780 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
7781                                     LookupResult &Previous,
7782                                     bool IsExplicitSpecialization) {
7783   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7784          "Variably modified return types are not handled here");
7785 
7786   // Determine whether the type of this function should be merged with
7787   // a previous visible declaration. This never happens for functions in C++,
7788   // and always happens in C if the previous declaration was visible.
7789   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7790                                !Previous.isShadowed();
7791 
7792   // Filter out any non-conflicting previous declarations.
7793   filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7794 
7795   bool Redeclaration = false;
7796   NamedDecl *OldDecl = nullptr;
7797 
7798   // Merge or overload the declaration with an existing declaration of
7799   // the same name, if appropriate.
7800   if (!Previous.empty()) {
7801     // Determine whether NewFD is an overload of PrevDecl or
7802     // a declaration that requires merging. If it's an overload,
7803     // there's no more work to do here; we'll just add the new
7804     // function to the scope.
7805     if (!AllowOverloadingOfFunction(Previous, Context)) {
7806       NamedDecl *Candidate = Previous.getFoundDecl();
7807       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7808         Redeclaration = true;
7809         OldDecl = Candidate;
7810       }
7811     } else {
7812       switch (CheckOverload(S, NewFD, Previous, OldDecl,
7813                             /*NewIsUsingDecl*/ false)) {
7814       case Ovl_Match:
7815         Redeclaration = true;
7816         break;
7817 
7818       case Ovl_NonFunction:
7819         Redeclaration = true;
7820         break;
7821 
7822       case Ovl_Overload:
7823         Redeclaration = false;
7824         break;
7825       }
7826 
7827       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7828         // If a function name is overloadable in C, then every function
7829         // with that name must be marked "overloadable".
7830         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7831           << Redeclaration << NewFD;
7832         NamedDecl *OverloadedDecl = nullptr;
7833         if (Redeclaration)
7834           OverloadedDecl = OldDecl;
7835         else if (!Previous.empty())
7836           OverloadedDecl = Previous.getRepresentativeDecl();
7837         if (OverloadedDecl)
7838           Diag(OverloadedDecl->getLocation(),
7839                diag::note_attribute_overloadable_prev_overload);
7840         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7841       }
7842     }
7843   }
7844 
7845   // Check for a previous extern "C" declaration with this name.
7846   if (!Redeclaration &&
7847       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7848     filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7849     if (!Previous.empty()) {
7850       // This is an extern "C" declaration with the same name as a previous
7851       // declaration, and thus redeclares that entity...
7852       Redeclaration = true;
7853       OldDecl = Previous.getFoundDecl();
7854       MergeTypeWithPrevious = false;
7855 
7856       // ... except in the presence of __attribute__((overloadable)).
7857       if (OldDecl->hasAttr<OverloadableAttr>()) {
7858         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7859           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7860             << Redeclaration << NewFD;
7861           Diag(Previous.getFoundDecl()->getLocation(),
7862                diag::note_attribute_overloadable_prev_overload);
7863           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7864         }
7865         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7866           Redeclaration = false;
7867           OldDecl = nullptr;
7868         }
7869       }
7870     }
7871   }
7872 
7873   // C++11 [dcl.constexpr]p8:
7874   //   A constexpr specifier for a non-static member function that is not
7875   //   a constructor declares that member function to be const.
7876   //
7877   // This needs to be delayed until we know whether this is an out-of-line
7878   // definition of a static member function.
7879   //
7880   // This rule is not present in C++1y, so we produce a backwards
7881   // compatibility warning whenever it happens in C++11.
7882   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7883   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
7884       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
7885       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7886     CXXMethodDecl *OldMD = nullptr;
7887     if (OldDecl)
7888       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
7889     if (!OldMD || !OldMD->isStatic()) {
7890       const FunctionProtoType *FPT =
7891         MD->getType()->castAs<FunctionProtoType>();
7892       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7893       EPI.TypeQuals |= Qualifiers::Const;
7894       MD->setType(Context.getFunctionType(FPT->getReturnType(),
7895                                           FPT->getParamTypes(), EPI));
7896 
7897       // Warn that we did this, if we're not performing template instantiation.
7898       // In that case, we'll have warned already when the template was defined.
7899       if (ActiveTemplateInstantiations.empty()) {
7900         SourceLocation AddConstLoc;
7901         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7902                 .IgnoreParens().getAs<FunctionTypeLoc>())
7903           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
7904 
7905         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
7906           << FixItHint::CreateInsertion(AddConstLoc, " const");
7907       }
7908     }
7909   }
7910 
7911   if (Redeclaration) {
7912     // NewFD and OldDecl represent declarations that need to be
7913     // merged.
7914     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
7915       NewFD->setInvalidDecl();
7916       return Redeclaration;
7917     }
7918 
7919     Previous.clear();
7920     Previous.addDecl(OldDecl);
7921 
7922     if (FunctionTemplateDecl *OldTemplateDecl
7923                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7924       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7925       FunctionTemplateDecl *NewTemplateDecl
7926         = NewFD->getDescribedFunctionTemplate();
7927       assert(NewTemplateDecl && "Template/non-template mismatch");
7928       if (CXXMethodDecl *Method
7929             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7930         Method->setAccess(OldTemplateDecl->getAccess());
7931         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
7932       }
7933 
7934       // If this is an explicit specialization of a member that is a function
7935       // template, mark it as a member specialization.
7936       if (IsExplicitSpecialization &&
7937           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7938         NewTemplateDecl->setMemberSpecialization();
7939         assert(OldTemplateDecl->isMemberSpecialization());
7940       }
7941 
7942     } else {
7943       // This needs to happen first so that 'inline' propagates.
7944       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
7945 
7946       if (isa<CXXMethodDecl>(NewFD)) {
7947         // A valid redeclaration of a C++ method must be out-of-line,
7948         // but (unfortunately) it's not necessarily a definition
7949         // because of templates, which means that the previous
7950         // declaration is not necessarily from the class definition.
7951 
7952         // For just setting the access, that doesn't matter.
7953         CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7954         NewFD->setAccess(oldMethod->getAccess());
7955 
7956         // Update the key-function state if necessary for this ABI.
7957         if (NewFD->isInlined() &&
7958             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7959           // setNonKeyFunction needs to work with the original
7960           // declaration from the class definition, and isVirtual() is
7961           // just faster in that case, so map back to that now.
7962           oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
7963           if (oldMethod->isVirtual()) {
7964             Context.setNonKeyFunction(oldMethod);
7965           }
7966         }
7967       }
7968     }
7969   }
7970 
7971   // Semantic checking for this function declaration (in isolation).
7972 
7973   if (getLangOpts().CPlusPlus) {
7974     // C++-specific checks.
7975     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7976       CheckConstructor(Constructor);
7977     } else if (CXXDestructorDecl *Destructor =
7978                 dyn_cast<CXXDestructorDecl>(NewFD)) {
7979       CXXRecordDecl *Record = Destructor->getParent();
7980       QualType ClassType = Context.getTypeDeclType(Record);
7981 
7982       // FIXME: Shouldn't we be able to perform this check even when the class
7983       // type is dependent? Both gcc and edg can handle that.
7984       if (!ClassType->isDependentType()) {
7985         DeclarationName Name
7986           = Context.DeclarationNames.getCXXDestructorName(
7987                                         Context.getCanonicalType(ClassType));
7988         if (NewFD->getDeclName() != Name) {
7989           Diag(NewFD->getLocation(), diag::err_destructor_name);
7990           NewFD->setInvalidDecl();
7991           return Redeclaration;
7992         }
7993       }
7994     } else if (CXXConversionDecl *Conversion
7995                = dyn_cast<CXXConversionDecl>(NewFD)) {
7996       ActOnConversionDeclarator(Conversion);
7997     }
7998 
7999     // Find any virtual functions that this function overrides.
8000     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8001       if (!Method->isFunctionTemplateSpecialization() &&
8002           !Method->getDescribedFunctionTemplate() &&
8003           Method->isCanonicalDecl()) {
8004         if (AddOverriddenMethods(Method->getParent(), Method)) {
8005           // If the function was marked as "static", we have a problem.
8006           if (NewFD->getStorageClass() == SC_Static) {
8007             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8008           }
8009         }
8010       }
8011 
8012       if (Method->isStatic())
8013         checkThisInStaticMemberFunctionType(Method);
8014     }
8015 
8016     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8017     if (NewFD->isOverloadedOperator() &&
8018         CheckOverloadedOperatorDeclaration(NewFD)) {
8019       NewFD->setInvalidDecl();
8020       return Redeclaration;
8021     }
8022 
8023     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8024     if (NewFD->getLiteralIdentifier() &&
8025         CheckLiteralOperatorDeclaration(NewFD)) {
8026       NewFD->setInvalidDecl();
8027       return Redeclaration;
8028     }
8029 
8030     // In C++, check default arguments now that we have merged decls. Unless
8031     // the lexical context is the class, because in this case this is done
8032     // during delayed parsing anyway.
8033     if (!CurContext->isRecord())
8034       CheckCXXDefaultArguments(NewFD);
8035 
8036     // If this function declares a builtin function, check the type of this
8037     // declaration against the expected type for the builtin.
8038     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8039       ASTContext::GetBuiltinTypeError Error;
8040       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8041       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8042       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8043         // The type of this function differs from the type of the builtin,
8044         // so forget about the builtin entirely.
8045         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
8046       }
8047     }
8048 
8049     // If this function is declared as being extern "C", then check to see if
8050     // the function returns a UDT (class, struct, or union type) that is not C
8051     // compatible, and if it does, warn the user.
8052     // But, issue any diagnostic on the first declaration only.
8053     if (NewFD->isExternC() && Previous.empty()) {
8054       QualType R = NewFD->getReturnType();
8055       if (R->isIncompleteType() && !R->isVoidType())
8056         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8057             << NewFD << R;
8058       else if (!R.isPODType(Context) && !R->isVoidType() &&
8059                !R->isObjCObjectPointerType())
8060         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8061     }
8062   }
8063   return Redeclaration;
8064 }
8065 
8066 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8067   // C++11 [basic.start.main]p3:
8068   //   A program that [...] declares main to be inline, static or
8069   //   constexpr is ill-formed.
8070   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8071   //   appear in a declaration of main.
8072   // static main is not an error under C99, but we should warn about it.
8073   // We accept _Noreturn main as an extension.
8074   if (FD->getStorageClass() == SC_Static)
8075     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8076          ? diag::err_static_main : diag::warn_static_main)
8077       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8078   if (FD->isInlineSpecified())
8079     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8080       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8081   if (DS.isNoreturnSpecified()) {
8082     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8083     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8084     Diag(NoreturnLoc, diag::ext_noreturn_main);
8085     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8086       << FixItHint::CreateRemoval(NoreturnRange);
8087   }
8088   if (FD->isConstexpr()) {
8089     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8090       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8091     FD->setConstexpr(false);
8092   }
8093 
8094   if (getLangOpts().OpenCL) {
8095     Diag(FD->getLocation(), diag::err_opencl_no_main)
8096         << FD->hasAttr<OpenCLKernelAttr>();
8097     FD->setInvalidDecl();
8098     return;
8099   }
8100 
8101   QualType T = FD->getType();
8102   assert(T->isFunctionType() && "function decl is not of function type");
8103   const FunctionType* FT = T->castAs<FunctionType>();
8104 
8105   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8106     // In C with GNU extensions we allow main() to have non-integer return
8107     // type, but we should warn about the extension, and we disable the
8108     // implicit-return-zero rule.
8109 
8110     // GCC in C mode accepts qualified 'int'.
8111     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8112       FD->setHasImplicitReturnZero(true);
8113     else {
8114       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8115       SourceRange RTRange = FD->getReturnTypeSourceRange();
8116       if (RTRange.isValid())
8117         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8118             << FixItHint::CreateReplacement(RTRange, "int");
8119     }
8120   } else {
8121     // In C and C++, main magically returns 0 if you fall off the end;
8122     // set the flag which tells us that.
8123     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8124 
8125     // All the standards say that main() should return 'int'.
8126     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8127       FD->setHasImplicitReturnZero(true);
8128     else {
8129       // Otherwise, this is just a flat-out error.
8130       SourceRange RTRange = FD->getReturnTypeSourceRange();
8131       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8132           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8133                                 : FixItHint());
8134       FD->setInvalidDecl(true);
8135     }
8136   }
8137 
8138   // Treat protoless main() as nullary.
8139   if (isa<FunctionNoProtoType>(FT)) return;
8140 
8141   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8142   unsigned nparams = FTP->getNumParams();
8143   assert(FD->getNumParams() == nparams);
8144 
8145   bool HasExtraParameters = (nparams > 3);
8146 
8147   // Darwin passes an undocumented fourth argument of type char**.  If
8148   // other platforms start sprouting these, the logic below will start
8149   // getting shifty.
8150   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8151     HasExtraParameters = false;
8152 
8153   if (HasExtraParameters) {
8154     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8155     FD->setInvalidDecl(true);
8156     nparams = 3;
8157   }
8158 
8159   // FIXME: a lot of the following diagnostics would be improved
8160   // if we had some location information about types.
8161 
8162   QualType CharPP =
8163     Context.getPointerType(Context.getPointerType(Context.CharTy));
8164   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8165 
8166   for (unsigned i = 0; i < nparams; ++i) {
8167     QualType AT = FTP->getParamType(i);
8168 
8169     bool mismatch = true;
8170 
8171     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8172       mismatch = false;
8173     else if (Expected[i] == CharPP) {
8174       // As an extension, the following forms are okay:
8175       //   char const **
8176       //   char const * const *
8177       //   char * const *
8178 
8179       QualifierCollector qs;
8180       const PointerType* PT;
8181       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8182           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8183           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8184                               Context.CharTy)) {
8185         qs.removeConst();
8186         mismatch = !qs.empty();
8187       }
8188     }
8189 
8190     if (mismatch) {
8191       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8192       // TODO: suggest replacing given type with expected type
8193       FD->setInvalidDecl(true);
8194     }
8195   }
8196 
8197   if (nparams == 1 && !FD->isInvalidDecl()) {
8198     Diag(FD->getLocation(), diag::warn_main_one_arg);
8199   }
8200 
8201   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8202     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8203     FD->setInvalidDecl();
8204   }
8205 }
8206 
8207 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8208   QualType T = FD->getType();
8209   assert(T->isFunctionType() && "function decl is not of function type");
8210   const FunctionType *FT = T->castAs<FunctionType>();
8211 
8212   // Set an implicit return of 'zero' if the function can return some integral,
8213   // enumeration, pointer or nullptr type.
8214   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8215       FT->getReturnType()->isAnyPointerType() ||
8216       FT->getReturnType()->isNullPtrType())
8217     // DllMain is exempt because a return value of zero means it failed.
8218     if (FD->getName() != "DllMain")
8219       FD->setHasImplicitReturnZero(true);
8220 
8221   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8222     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8223     FD->setInvalidDecl();
8224   }
8225 }
8226 
8227 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8228   // FIXME: Need strict checking.  In C89, we need to check for
8229   // any assignment, increment, decrement, function-calls, or
8230   // commas outside of a sizeof.  In C99, it's the same list,
8231   // except that the aforementioned are allowed in unevaluated
8232   // expressions.  Everything else falls under the
8233   // "may accept other forms of constant expressions" exception.
8234   // (We never end up here for C++, so the constant expression
8235   // rules there don't matter.)
8236   const Expr *Culprit;
8237   if (Init->isConstantInitializer(Context, false, &Culprit))
8238     return false;
8239   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8240     << Culprit->getSourceRange();
8241   return true;
8242 }
8243 
8244 namespace {
8245   // Visits an initialization expression to see if OrigDecl is evaluated in
8246   // its own initialization and throws a warning if it does.
8247   class SelfReferenceChecker
8248       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8249     Sema &S;
8250     Decl *OrigDecl;
8251     bool isRecordType;
8252     bool isPODType;
8253     bool isReferenceType;
8254 
8255     bool isInitList;
8256     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8257   public:
8258     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8259 
8260     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8261                                                     S(S), OrigDecl(OrigDecl) {
8262       isPODType = false;
8263       isRecordType = false;
8264       isReferenceType = false;
8265       isInitList = false;
8266       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8267         isPODType = VD->getType().isPODType(S.Context);
8268         isRecordType = VD->getType()->isRecordType();
8269         isReferenceType = VD->getType()->isReferenceType();
8270       }
8271     }
8272 
8273     // For most expressions, just call the visitor.  For initializer lists,
8274     // track the index of the field being initialized since fields are
8275     // initialized in order allowing use of previously initialized fields.
8276     void CheckExpr(Expr *E) {
8277       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8278       if (!InitList) {
8279         Visit(E);
8280         return;
8281       }
8282 
8283       // Track and increment the index here.
8284       isInitList = true;
8285       InitFieldIndex.push_back(0);
8286       for (auto Child : InitList->children()) {
8287         CheckExpr(cast<Expr>(Child));
8288         ++InitFieldIndex.back();
8289       }
8290       InitFieldIndex.pop_back();
8291     }
8292 
8293     // Returns true if MemberExpr is checked and no futher checking is needed.
8294     // Returns false if additional checking is required.
8295     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8296       llvm::SmallVector<FieldDecl*, 4> Fields;
8297       Expr *Base = E;
8298       bool ReferenceField = false;
8299 
8300       // Get the field memebers used.
8301       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8302         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8303         if (!FD)
8304           return false;
8305         Fields.push_back(FD);
8306         if (FD->getType()->isReferenceType())
8307           ReferenceField = true;
8308         Base = ME->getBase()->IgnoreParenImpCasts();
8309       }
8310 
8311       // Keep checking only if the base Decl is the same.
8312       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8313       if (!DRE || DRE->getDecl() != OrigDecl)
8314         return false;
8315 
8316       // A reference field can be bound to an unininitialized field.
8317       if (CheckReference && !ReferenceField)
8318         return true;
8319 
8320       // Convert FieldDecls to their index number.
8321       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8322       for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) {
8323         UsedFieldIndex.push_back((*I)->getFieldIndex());
8324       }
8325 
8326       // See if a warning is needed by checking the first difference in index
8327       // numbers.  If field being used has index less than the field being
8328       // initialized, then the use is safe.
8329       for (auto UsedIter = UsedFieldIndex.begin(),
8330                 UsedEnd = UsedFieldIndex.end(),
8331                 OrigIter = InitFieldIndex.begin(),
8332                 OrigEnd = InitFieldIndex.end();
8333            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8334         if (*UsedIter < *OrigIter)
8335           return true;
8336         if (*UsedIter > *OrigIter)
8337           break;
8338       }
8339 
8340       // TODO: Add a different warning which will print the field names.
8341       HandleDeclRefExpr(DRE);
8342       return true;
8343     }
8344 
8345     // For most expressions, the cast is directly above the DeclRefExpr.
8346     // For conditional operators, the cast can be outside the conditional
8347     // operator if both expressions are DeclRefExpr's.
8348     void HandleValue(Expr *E) {
8349       E = E->IgnoreParens();
8350       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8351         HandleDeclRefExpr(DRE);
8352         return;
8353       }
8354 
8355       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8356         Visit(CO->getCond());
8357         HandleValue(CO->getTrueExpr());
8358         HandleValue(CO->getFalseExpr());
8359         return;
8360       }
8361 
8362       if (BinaryConditionalOperator *BCO =
8363               dyn_cast<BinaryConditionalOperator>(E)) {
8364         Visit(BCO->getCond());
8365         HandleValue(BCO->getFalseExpr());
8366         return;
8367       }
8368 
8369       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8370         HandleValue(OVE->getSourceExpr());
8371         return;
8372       }
8373 
8374       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8375         if (BO->getOpcode() == BO_Comma) {
8376           Visit(BO->getLHS());
8377           HandleValue(BO->getRHS());
8378           return;
8379         }
8380       }
8381 
8382       if (isa<MemberExpr>(E)) {
8383         if (isInitList) {
8384           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8385                                       false /*CheckReference*/))
8386             return;
8387         }
8388 
8389         Expr *Base = E->IgnoreParenImpCasts();
8390         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8391           // Check for static member variables and don't warn on them.
8392           if (!isa<FieldDecl>(ME->getMemberDecl()))
8393             return;
8394           Base = ME->getBase()->IgnoreParenImpCasts();
8395         }
8396         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8397           HandleDeclRefExpr(DRE);
8398         return;
8399       }
8400 
8401       Visit(E);
8402     }
8403 
8404     // Reference types not handled in HandleValue are handled here since all
8405     // uses of references are bad, not just r-value uses.
8406     void VisitDeclRefExpr(DeclRefExpr *E) {
8407       if (isReferenceType)
8408         HandleDeclRefExpr(E);
8409     }
8410 
8411     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8412       if (E->getCastKind() == CK_LValueToRValue) {
8413         HandleValue(E->getSubExpr());
8414         return;
8415       }
8416 
8417       Inherited::VisitImplicitCastExpr(E);
8418     }
8419 
8420     void VisitMemberExpr(MemberExpr *E) {
8421       if (isInitList) {
8422         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8423           return;
8424       }
8425 
8426       // Don't warn on arrays since they can be treated as pointers.
8427       if (E->getType()->canDecayToPointerType()) return;
8428 
8429       // Warn when a non-static method call is followed by non-static member
8430       // field accesses, which is followed by a DeclRefExpr.
8431       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8432       bool Warn = (MD && !MD->isStatic());
8433       Expr *Base = E->getBase()->IgnoreParenImpCasts();
8434       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8435         if (!isa<FieldDecl>(ME->getMemberDecl()))
8436           Warn = false;
8437         Base = ME->getBase()->IgnoreParenImpCasts();
8438       }
8439 
8440       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8441         if (Warn)
8442           HandleDeclRefExpr(DRE);
8443         return;
8444       }
8445 
8446       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8447       // Visit that expression.
8448       Visit(Base);
8449     }
8450 
8451     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8452       Expr *Callee = E->getCallee();
8453 
8454       if (isa<UnresolvedLookupExpr>(Callee))
8455         return Inherited::VisitCXXOperatorCallExpr(E);
8456 
8457       Visit(Callee);
8458       for (auto Arg: E->arguments())
8459         HandleValue(Arg->IgnoreParenImpCasts());
8460     }
8461 
8462     void VisitUnaryOperator(UnaryOperator *E) {
8463       // For POD record types, addresses of its own members are well-defined.
8464       if (E->getOpcode() == UO_AddrOf && isRecordType &&
8465           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8466         if (!isPODType)
8467           HandleValue(E->getSubExpr());
8468         return;
8469       }
8470 
8471       if (E->isIncrementDecrementOp()) {
8472         HandleValue(E->getSubExpr());
8473         return;
8474       }
8475 
8476       Inherited::VisitUnaryOperator(E);
8477     }
8478 
8479     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8480 
8481     void VisitCXXConstructExpr(CXXConstructExpr *E) {
8482       if (E->getConstructor()->isCopyConstructor()) {
8483         Expr *ArgExpr = E->getArg(0);
8484         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
8485           if (ILE->getNumInits() == 1)
8486             ArgExpr = ILE->getInit(0);
8487         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8488           if (ICE->getCastKind() == CK_NoOp)
8489             ArgExpr = ICE->getSubExpr();
8490         HandleValue(ArgExpr);
8491         return;
8492       }
8493       Inherited::VisitCXXConstructExpr(E);
8494     }
8495 
8496     void VisitCallExpr(CallExpr *E) {
8497       // Treat std::move as a use.
8498       if (E->getNumArgs() == 1) {
8499         if (FunctionDecl *FD = E->getDirectCallee()) {
8500           if (FD->isInStdNamespace() && FD->getIdentifier() &&
8501               FD->getIdentifier()->isStr("move")) {
8502             HandleValue(E->getArg(0));
8503             return;
8504           }
8505         }
8506       }
8507 
8508       Inherited::VisitCallExpr(E);
8509     }
8510 
8511     void VisitBinaryOperator(BinaryOperator *E) {
8512       if (E->isCompoundAssignmentOp()) {
8513         HandleValue(E->getLHS());
8514         Visit(E->getRHS());
8515         return;
8516       }
8517 
8518       Inherited::VisitBinaryOperator(E);
8519     }
8520 
8521     // A custom visitor for BinaryConditionalOperator is needed because the
8522     // regular visitor would check the condition and true expression separately
8523     // but both point to the same place giving duplicate diagnostics.
8524     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
8525       Visit(E->getCond());
8526       Visit(E->getFalseExpr());
8527     }
8528 
8529     void HandleDeclRefExpr(DeclRefExpr *DRE) {
8530       Decl* ReferenceDecl = DRE->getDecl();
8531       if (OrigDecl != ReferenceDecl) return;
8532       unsigned diag;
8533       if (isReferenceType) {
8534         diag = diag::warn_uninit_self_reference_in_reference_init;
8535       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8536         diag = diag::warn_static_self_reference_in_init;
8537       } else {
8538         diag = diag::warn_uninit_self_reference_in_init;
8539       }
8540 
8541       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
8542                             S.PDiag(diag)
8543                               << DRE->getNameInfo().getName()
8544                               << OrigDecl->getLocation()
8545                               << DRE->getSourceRange());
8546     }
8547   };
8548 
8549   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8550   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8551                                  bool DirectInit) {
8552     // Parameters arguments are occassionially constructed with itself,
8553     // for instance, in recursive functions.  Skip them.
8554     if (isa<ParmVarDecl>(OrigDecl))
8555       return;
8556 
8557     E = E->IgnoreParens();
8558 
8559     // Skip checking T a = a where T is not a record or reference type.
8560     // Doing so is a way to silence uninitialized warnings.
8561     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8562       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8563         if (ICE->getCastKind() == CK_LValueToRValue)
8564           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8565             if (DRE->getDecl() == OrigDecl)
8566               return;
8567 
8568     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
8569   }
8570 }
8571 
8572 /// AddInitializerToDecl - Adds the initializer Init to the
8573 /// declaration dcl. If DirectInit is true, this is C++ direct
8574 /// initialization rather than copy initialization.
8575 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8576                                 bool DirectInit, bool TypeMayContainAuto) {
8577   // If there is no declaration, there was an error parsing it.  Just ignore
8578   // the initializer.
8579   if (!RealDecl || RealDecl->isInvalidDecl()) {
8580     CorrectDelayedTyposInExpr(Init);
8581     return;
8582   }
8583 
8584   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8585     // With declarators parsed the way they are, the parser cannot
8586     // distinguish between a normal initializer and a pure-specifier.
8587     // Thus this grotesque test.
8588     IntegerLiteral *IL;
8589     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
8590         Context.getCanonicalType(IL->getType()) == Context.IntTy)
8591       CheckPureMethod(Method, Init->getSourceRange());
8592     else {
8593       Diag(Method->getLocation(), diag::err_member_function_initialization)
8594         << Method->getDeclName() << Init->getSourceRange();
8595       Method->setInvalidDecl();
8596     }
8597     return;
8598   }
8599 
8600   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8601   if (!VDecl) {
8602     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8603     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8604     RealDecl->setInvalidDecl();
8605     return;
8606   }
8607   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8608 
8609   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8610   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8611     Expr *DeduceInit = Init;
8612     // Initializer could be a C++ direct-initializer. Deduction only works if it
8613     // contains exactly one expression.
8614     if (CXXDirectInit) {
8615       if (CXXDirectInit->getNumExprs() == 0) {
8616         // It isn't possible to write this directly, but it is possible to
8617         // end up in this situation with "auto x(some_pack...);"
8618         Diag(CXXDirectInit->getLocStart(),
8619              VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8620                                     : diag::err_auto_var_init_no_expression)
8621           << VDecl->getDeclName() << VDecl->getType()
8622           << VDecl->getSourceRange();
8623         RealDecl->setInvalidDecl();
8624         return;
8625       } else if (CXXDirectInit->getNumExprs() > 1) {
8626         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8627              VDecl->isInitCapture()
8628                  ? diag::err_init_capture_multiple_expressions
8629                  : diag::err_auto_var_init_multiple_expressions)
8630           << VDecl->getDeclName() << VDecl->getType()
8631           << VDecl->getSourceRange();
8632         RealDecl->setInvalidDecl();
8633         return;
8634       } else {
8635         DeduceInit = CXXDirectInit->getExpr(0);
8636         if (isa<InitListExpr>(DeduceInit))
8637           Diag(CXXDirectInit->getLocStart(),
8638                diag::err_auto_var_init_paren_braces)
8639             << VDecl->getDeclName() << VDecl->getType()
8640             << VDecl->getSourceRange();
8641       }
8642     }
8643 
8644     // Expressions default to 'id' when we're in a debugger.
8645     bool DefaultedToAuto = false;
8646     if (getLangOpts().DebuggerCastResultToId &&
8647         Init->getType() == Context.UnknownAnyTy) {
8648       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8649       if (Result.isInvalid()) {
8650         VDecl->setInvalidDecl();
8651         return;
8652       }
8653       Init = Result.get();
8654       DefaultedToAuto = true;
8655     }
8656 
8657     QualType DeducedType;
8658     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8659             DAR_Failed)
8660       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8661     if (DeducedType.isNull()) {
8662       RealDecl->setInvalidDecl();
8663       return;
8664     }
8665     VDecl->setType(DeducedType);
8666     assert(VDecl->isLinkageValid());
8667 
8668     // In ARC, infer lifetime.
8669     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8670       VDecl->setInvalidDecl();
8671 
8672     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8673     // 'id' instead of a specific object type prevents most of our usual checks.
8674     // We only want to warn outside of template instantiations, though:
8675     // inside a template, the 'id' could have come from a parameter.
8676     if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8677         DeducedType->isObjCIdType()) {
8678       SourceLocation Loc =
8679           VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8680       Diag(Loc, diag::warn_auto_var_is_id)
8681         << VDecl->getDeclName() << DeduceInit->getSourceRange();
8682     }
8683 
8684     // If this is a redeclaration, check that the type we just deduced matches
8685     // the previously declared type.
8686     if (VarDecl *Old = VDecl->getPreviousDecl()) {
8687       // We never need to merge the type, because we cannot form an incomplete
8688       // array of auto, nor deduce such a type.
8689       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8690     }
8691 
8692     // Check the deduced type is valid for a variable declaration.
8693     CheckVariableDeclarationType(VDecl);
8694     if (VDecl->isInvalidDecl())
8695       return;
8696   }
8697 
8698   // dllimport cannot be used on variable definitions.
8699   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8700     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8701     VDecl->setInvalidDecl();
8702     return;
8703   }
8704 
8705   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8706     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8707     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8708     VDecl->setInvalidDecl();
8709     return;
8710   }
8711 
8712   if (!VDecl->getType()->isDependentType()) {
8713     // A definition must end up with a complete type, which means it must be
8714     // complete with the restriction that an array type might be completed by
8715     // the initializer; note that later code assumes this restriction.
8716     QualType BaseDeclType = VDecl->getType();
8717     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8718       BaseDeclType = Array->getElementType();
8719     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8720                             diag::err_typecheck_decl_incomplete_type)) {
8721       RealDecl->setInvalidDecl();
8722       return;
8723     }
8724 
8725     // The variable can not have an abstract class type.
8726     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8727                                diag::err_abstract_type_in_decl,
8728                                AbstractVariableType))
8729       VDecl->setInvalidDecl();
8730   }
8731 
8732   const VarDecl *Def;
8733   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8734     Diag(VDecl->getLocation(), diag::err_redefinition)
8735       << VDecl->getDeclName();
8736     Diag(Def->getLocation(), diag::note_previous_definition);
8737     VDecl->setInvalidDecl();
8738     return;
8739   }
8740 
8741   const VarDecl *PrevInit = nullptr;
8742   if (getLangOpts().CPlusPlus) {
8743     // C++ [class.static.data]p4
8744     //   If a static data member is of const integral or const
8745     //   enumeration type, its declaration in the class definition can
8746     //   specify a constant-initializer which shall be an integral
8747     //   constant expression (5.19). In that case, the member can appear
8748     //   in integral constant expressions. The member shall still be
8749     //   defined in a namespace scope if it is used in the program and the
8750     //   namespace scope definition shall not contain an initializer.
8751     //
8752     // We already performed a redefinition check above, but for static
8753     // data members we also need to check whether there was an in-class
8754     // declaration with an initializer.
8755     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8756       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8757           << VDecl->getDeclName();
8758       Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
8759       return;
8760     }
8761 
8762     if (VDecl->hasLocalStorage())
8763       getCurFunction()->setHasBranchProtectedScope();
8764 
8765     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8766       VDecl->setInvalidDecl();
8767       return;
8768     }
8769   }
8770 
8771   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8772   // a kernel function cannot be initialized."
8773   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8774     Diag(VDecl->getLocation(), diag::err_local_cant_init);
8775     VDecl->setInvalidDecl();
8776     return;
8777   }
8778 
8779   // Get the decls type and save a reference for later, since
8780   // CheckInitializerTypes may change it.
8781   QualType DclT = VDecl->getType(), SavT = DclT;
8782 
8783   // Expressions default to 'id' when we're in a debugger
8784   // and we are assigning it to a variable of Objective-C pointer type.
8785   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8786       Init->getType() == Context.UnknownAnyTy) {
8787     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8788     if (Result.isInvalid()) {
8789       VDecl->setInvalidDecl();
8790       return;
8791     }
8792     Init = Result.get();
8793   }
8794 
8795   // Perform the initialization.
8796   if (!VDecl->isInvalidDecl()) {
8797     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8798     InitializationKind Kind
8799       = DirectInit ?
8800           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8801                                                            Init->getLocStart(),
8802                                                            Init->getLocEnd())
8803                         : InitializationKind::CreateDirectList(
8804                                                           VDecl->getLocation())
8805                    : InitializationKind::CreateCopy(VDecl->getLocation(),
8806                                                     Init->getLocStart());
8807 
8808     MultiExprArg Args = Init;
8809     if (CXXDirectInit)
8810       Args = MultiExprArg(CXXDirectInit->getExprs(),
8811                           CXXDirectInit->getNumExprs());
8812 
8813     // Try to correct any TypoExprs in the initialization arguments.
8814     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
8815       ExprResult Res =
8816           CorrectDelayedTyposInExpr(Args[Idx], [this, Entity, Kind](Expr *E) {
8817             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
8818             return Init.Failed() ? ExprError() : E;
8819           });
8820       if (Res.isInvalid()) {
8821         VDecl->setInvalidDecl();
8822         return;
8823       }
8824       if (Res.get() != Args[Idx])
8825         Args[Idx] = Res.get();
8826     }
8827 
8828     InitializationSequence InitSeq(*this, Entity, Kind, Args);
8829     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8830     if (Result.isInvalid()) {
8831       VDecl->setInvalidDecl();
8832       return;
8833     }
8834 
8835     Init = Result.getAs<Expr>();
8836   }
8837 
8838   // Check for self-references within variable initializers.
8839   // Variables declared within a function/method body (except for references)
8840   // are handled by a dataflow analysis.
8841   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8842       VDecl->getType()->isReferenceType()) {
8843     CheckSelfReference(*this, RealDecl, Init, DirectInit);
8844   }
8845 
8846   // If the type changed, it means we had an incomplete type that was
8847   // completed by the initializer. For example:
8848   //   int ary[] = { 1, 3, 5 };
8849   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
8850   if (!VDecl->isInvalidDecl() && (DclT != SavT))
8851     VDecl->setType(DclT);
8852 
8853   if (!VDecl->isInvalidDecl()) {
8854     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8855 
8856     if (VDecl->hasAttr<BlocksAttr>())
8857       checkRetainCycles(VDecl, Init);
8858 
8859     // It is safe to assign a weak reference into a strong variable.
8860     // Although this code can still have problems:
8861     //   id x = self.weakProp;
8862     //   id y = self.weakProp;
8863     // we do not warn to warn spuriously when 'x' and 'y' are on separate
8864     // paths through the function. This should be revisited if
8865     // -Wrepeated-use-of-weak is made flow-sensitive.
8866     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
8867         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8868                          Init->getLocStart()))
8869         getCurFunction()->markSafeWeakUse(Init);
8870   }
8871 
8872   // The initialization is usually a full-expression.
8873   //
8874   // FIXME: If this is a braced initialization of an aggregate, it is not
8875   // an expression, and each individual field initializer is a separate
8876   // full-expression. For instance, in:
8877   //
8878   //   struct Temp { ~Temp(); };
8879   //   struct S { S(Temp); };
8880   //   struct T { S a, b; } t = { Temp(), Temp() }
8881   //
8882   // we should destroy the first Temp before constructing the second.
8883   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8884                                           false,
8885                                           VDecl->isConstexpr());
8886   if (Result.isInvalid()) {
8887     VDecl->setInvalidDecl();
8888     return;
8889   }
8890   Init = Result.get();
8891 
8892   // Attach the initializer to the decl.
8893   VDecl->setInit(Init);
8894 
8895   if (VDecl->isLocalVarDecl()) {
8896     // C99 6.7.8p4: All the expressions in an initializer for an object that has
8897     // static storage duration shall be constant expressions or string literals.
8898     // C++ does not have this restriction.
8899     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8900       const Expr *Culprit;
8901       if (VDecl->getStorageClass() == SC_Static)
8902         CheckForConstantInitializer(Init, DclT);
8903       // C89 is stricter than C99 for non-static aggregate types.
8904       // C89 6.5.7p3: All the expressions [...] in an initializer list
8905       // for an object that has aggregate or union type shall be
8906       // constant expressions.
8907       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
8908                isa<InitListExpr>(Init) &&
8909                !Init->isConstantInitializer(Context, false, &Culprit))
8910         Diag(Culprit->getExprLoc(),
8911              diag::ext_aggregate_init_not_constant)
8912           << Culprit->getSourceRange();
8913     }
8914   } else if (VDecl->isStaticDataMember() &&
8915              VDecl->getLexicalDeclContext()->isRecord()) {
8916     // This is an in-class initialization for a static data member, e.g.,
8917     //
8918     // struct S {
8919     //   static const int value = 17;
8920     // };
8921 
8922     // C++ [class.mem]p4:
8923     //   A member-declarator can contain a constant-initializer only
8924     //   if it declares a static member (9.4) of const integral or
8925     //   const enumeration type, see 9.4.2.
8926     //
8927     // C++11 [class.static.data]p3:
8928     //   If a non-volatile const static data member is of integral or
8929     //   enumeration type, its declaration in the class definition can
8930     //   specify a brace-or-equal-initializer in which every initalizer-clause
8931     //   that is an assignment-expression is a constant expression. A static
8932     //   data member of literal type can be declared in the class definition
8933     //   with the constexpr specifier; if so, its declaration shall specify a
8934     //   brace-or-equal-initializer in which every initializer-clause that is
8935     //   an assignment-expression is a constant expression.
8936 
8937     // Do nothing on dependent types.
8938     if (DclT->isDependentType()) {
8939 
8940     // Allow any 'static constexpr' members, whether or not they are of literal
8941     // type. We separately check that every constexpr variable is of literal
8942     // type.
8943     } else if (VDecl->isConstexpr()) {
8944 
8945     // Require constness.
8946     } else if (!DclT.isConstQualified()) {
8947       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8948         << Init->getSourceRange();
8949       VDecl->setInvalidDecl();
8950 
8951     // We allow integer constant expressions in all cases.
8952     } else if (DclT->isIntegralOrEnumerationType()) {
8953       // Check whether the expression is a constant expression.
8954       SourceLocation Loc;
8955       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
8956         // In C++11, a non-constexpr const static data member with an
8957         // in-class initializer cannot be volatile.
8958         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8959       else if (Init->isValueDependent())
8960         ; // Nothing to check.
8961       else if (Init->isIntegerConstantExpr(Context, &Loc))
8962         ; // Ok, it's an ICE!
8963       else if (Init->isEvaluatable(Context)) {
8964         // If we can constant fold the initializer through heroics, accept it,
8965         // but report this as a use of an extension for -pedantic.
8966         Diag(Loc, diag::ext_in_class_initializer_non_constant)
8967           << Init->getSourceRange();
8968       } else {
8969         // Otherwise, this is some crazy unknown case.  Report the issue at the
8970         // location provided by the isIntegerConstantExpr failed check.
8971         Diag(Loc, diag::err_in_class_initializer_non_constant)
8972           << Init->getSourceRange();
8973         VDecl->setInvalidDecl();
8974       }
8975 
8976     // We allow foldable floating-point constants as an extension.
8977     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
8978       // In C++98, this is a GNU extension. In C++11, it is not, but we support
8979       // it anyway and provide a fixit to add the 'constexpr'.
8980       if (getLangOpts().CPlusPlus11) {
8981         Diag(VDecl->getLocation(),
8982              diag::ext_in_class_initializer_float_type_cxx11)
8983             << DclT << Init->getSourceRange();
8984         Diag(VDecl->getLocStart(),
8985              diag::note_in_class_initializer_float_type_cxx11)
8986             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8987       } else {
8988         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8989           << DclT << Init->getSourceRange();
8990 
8991         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8992           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8993             << Init->getSourceRange();
8994           VDecl->setInvalidDecl();
8995         }
8996       }
8997 
8998     // Suggest adding 'constexpr' in C++11 for literal types.
8999     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9000       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9001         << DclT << Init->getSourceRange()
9002         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9003       VDecl->setConstexpr(true);
9004 
9005     } else {
9006       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9007         << DclT << Init->getSourceRange();
9008       VDecl->setInvalidDecl();
9009     }
9010   } else if (VDecl->isFileVarDecl()) {
9011     if (VDecl->getStorageClass() == SC_Extern &&
9012         (!getLangOpts().CPlusPlus ||
9013          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9014            VDecl->isExternC())) &&
9015         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9016       Diag(VDecl->getLocation(), diag::warn_extern_init);
9017 
9018     // C99 6.7.8p4. All file scoped initializers need to be constant.
9019     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9020       CheckForConstantInitializer(Init, DclT);
9021   }
9022 
9023   // We will represent direct-initialization similarly to copy-initialization:
9024   //    int x(1);  -as-> int x = 1;
9025   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9026   //
9027   // Clients that want to distinguish between the two forms, can check for
9028   // direct initializer using VarDecl::getInitStyle().
9029   // A major benefit is that clients that don't particularly care about which
9030   // exactly form was it (like the CodeGen) can handle both cases without
9031   // special case code.
9032 
9033   // C++ 8.5p11:
9034   // The form of initialization (using parentheses or '=') is generally
9035   // insignificant, but does matter when the entity being initialized has a
9036   // class type.
9037   if (CXXDirectInit) {
9038     assert(DirectInit && "Call-style initializer must be direct init.");
9039     VDecl->setInitStyle(VarDecl::CallInit);
9040   } else if (DirectInit) {
9041     // This must be list-initialization. No other way is direct-initialization.
9042     VDecl->setInitStyle(VarDecl::ListInit);
9043   }
9044 
9045   CheckCompleteVariableDeclaration(VDecl);
9046 }
9047 
9048 /// ActOnInitializerError - Given that there was an error parsing an
9049 /// initializer for the given declaration, try to return to some form
9050 /// of sanity.
9051 void Sema::ActOnInitializerError(Decl *D) {
9052   // Our main concern here is re-establishing invariants like "a
9053   // variable's type is either dependent or complete".
9054   if (!D || D->isInvalidDecl()) return;
9055 
9056   VarDecl *VD = dyn_cast<VarDecl>(D);
9057   if (!VD) return;
9058 
9059   // Auto types are meaningless if we can't make sense of the initializer.
9060   if (ParsingInitForAutoVars.count(D)) {
9061     D->setInvalidDecl();
9062     return;
9063   }
9064 
9065   QualType Ty = VD->getType();
9066   if (Ty->isDependentType()) return;
9067 
9068   // Require a complete type.
9069   if (RequireCompleteType(VD->getLocation(),
9070                           Context.getBaseElementType(Ty),
9071                           diag::err_typecheck_decl_incomplete_type)) {
9072     VD->setInvalidDecl();
9073     return;
9074   }
9075 
9076   // Require a non-abstract type.
9077   if (RequireNonAbstractType(VD->getLocation(), Ty,
9078                              diag::err_abstract_type_in_decl,
9079                              AbstractVariableType)) {
9080     VD->setInvalidDecl();
9081     return;
9082   }
9083 
9084   // Don't bother complaining about constructors or destructors,
9085   // though.
9086 }
9087 
9088 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9089                                   bool TypeMayContainAuto) {
9090   // If there is no declaration, there was an error parsing it. Just ignore it.
9091   if (!RealDecl)
9092     return;
9093 
9094   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9095     QualType Type = Var->getType();
9096 
9097     // C++11 [dcl.spec.auto]p3
9098     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9099       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9100         << Var->getDeclName() << Type;
9101       Var->setInvalidDecl();
9102       return;
9103     }
9104 
9105     // C++11 [class.static.data]p3: A static data member can be declared with
9106     // the constexpr specifier; if so, its declaration shall specify
9107     // a brace-or-equal-initializer.
9108     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9109     // the definition of a variable [...] or the declaration of a static data
9110     // member.
9111     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9112       if (Var->isStaticDataMember())
9113         Diag(Var->getLocation(),
9114              diag::err_constexpr_static_mem_var_requires_init)
9115           << Var->getDeclName();
9116       else
9117         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9118       Var->setInvalidDecl();
9119       return;
9120     }
9121 
9122     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9123     // be initialized.
9124     if (!Var->isInvalidDecl() &&
9125         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9126         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9127       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9128       Var->setInvalidDecl();
9129       return;
9130     }
9131 
9132     switch (Var->isThisDeclarationADefinition()) {
9133     case VarDecl::Definition:
9134       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9135         break;
9136 
9137       // We have an out-of-line definition of a static data member
9138       // that has an in-class initializer, so we type-check this like
9139       // a declaration.
9140       //
9141       // Fall through
9142 
9143     case VarDecl::DeclarationOnly:
9144       // It's only a declaration.
9145 
9146       // Block scope. C99 6.7p7: If an identifier for an object is
9147       // declared with no linkage (C99 6.2.2p6), the type for the
9148       // object shall be complete.
9149       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9150           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9151           RequireCompleteType(Var->getLocation(), Type,
9152                               diag::err_typecheck_decl_incomplete_type))
9153         Var->setInvalidDecl();
9154 
9155       // Make sure that the type is not abstract.
9156       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9157           RequireNonAbstractType(Var->getLocation(), Type,
9158                                  diag::err_abstract_type_in_decl,
9159                                  AbstractVariableType))
9160         Var->setInvalidDecl();
9161       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9162           Var->getStorageClass() == SC_PrivateExtern) {
9163         Diag(Var->getLocation(), diag::warn_private_extern);
9164         Diag(Var->getLocation(), diag::note_private_extern);
9165       }
9166 
9167       return;
9168 
9169     case VarDecl::TentativeDefinition:
9170       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9171       // object that has file scope without an initializer, and without a
9172       // storage-class specifier or with the storage-class specifier "static",
9173       // constitutes a tentative definition. Note: A tentative definition with
9174       // external linkage is valid (C99 6.2.2p5).
9175       if (!Var->isInvalidDecl()) {
9176         if (const IncompleteArrayType *ArrayT
9177                                     = Context.getAsIncompleteArrayType(Type)) {
9178           if (RequireCompleteType(Var->getLocation(),
9179                                   ArrayT->getElementType(),
9180                                   diag::err_illegal_decl_array_incomplete_type))
9181             Var->setInvalidDecl();
9182         } else if (Var->getStorageClass() == SC_Static) {
9183           // C99 6.9.2p3: If the declaration of an identifier for an object is
9184           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9185           // declared type shall not be an incomplete type.
9186           // NOTE: code such as the following
9187           //     static struct s;
9188           //     struct s { int a; };
9189           // is accepted by gcc. Hence here we issue a warning instead of
9190           // an error and we do not invalidate the static declaration.
9191           // NOTE: to avoid multiple warnings, only check the first declaration.
9192           if (Var->isFirstDecl())
9193             RequireCompleteType(Var->getLocation(), Type,
9194                                 diag::ext_typecheck_decl_incomplete_type);
9195         }
9196       }
9197 
9198       // Record the tentative definition; we're done.
9199       if (!Var->isInvalidDecl())
9200         TentativeDefinitions.push_back(Var);
9201       return;
9202     }
9203 
9204     // Provide a specific diagnostic for uninitialized variable
9205     // definitions with incomplete array type.
9206     if (Type->isIncompleteArrayType()) {
9207       Diag(Var->getLocation(),
9208            diag::err_typecheck_incomplete_array_needs_initializer);
9209       Var->setInvalidDecl();
9210       return;
9211     }
9212 
9213     // Provide a specific diagnostic for uninitialized variable
9214     // definitions with reference type.
9215     if (Type->isReferenceType()) {
9216       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9217         << Var->getDeclName()
9218         << SourceRange(Var->getLocation(), Var->getLocation());
9219       Var->setInvalidDecl();
9220       return;
9221     }
9222 
9223     // Do not attempt to type-check the default initializer for a
9224     // variable with dependent type.
9225     if (Type->isDependentType())
9226       return;
9227 
9228     if (Var->isInvalidDecl())
9229       return;
9230 
9231     if (!Var->hasAttr<AliasAttr>()) {
9232       if (RequireCompleteType(Var->getLocation(),
9233                               Context.getBaseElementType(Type),
9234                               diag::err_typecheck_decl_incomplete_type)) {
9235         Var->setInvalidDecl();
9236         return;
9237       }
9238     }
9239 
9240     // The variable can not have an abstract class type.
9241     if (RequireNonAbstractType(Var->getLocation(), Type,
9242                                diag::err_abstract_type_in_decl,
9243                                AbstractVariableType)) {
9244       Var->setInvalidDecl();
9245       return;
9246     }
9247 
9248     // Check for jumps past the implicit initializer.  C++0x
9249     // clarifies that this applies to a "variable with automatic
9250     // storage duration", not a "local variable".
9251     // C++11 [stmt.dcl]p3
9252     //   A program that jumps from a point where a variable with automatic
9253     //   storage duration is not in scope to a point where it is in scope is
9254     //   ill-formed unless the variable has scalar type, class type with a
9255     //   trivial default constructor and a trivial destructor, a cv-qualified
9256     //   version of one of these types, or an array of one of the preceding
9257     //   types and is declared without an initializer.
9258     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9259       if (const RecordType *Record
9260             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9261         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9262         // Mark the function for further checking even if the looser rules of
9263         // C++11 do not require such checks, so that we can diagnose
9264         // incompatibilities with C++98.
9265         if (!CXXRecord->isPOD())
9266           getCurFunction()->setHasBranchProtectedScope();
9267       }
9268     }
9269 
9270     // C++03 [dcl.init]p9:
9271     //   If no initializer is specified for an object, and the
9272     //   object is of (possibly cv-qualified) non-POD class type (or
9273     //   array thereof), the object shall be default-initialized; if
9274     //   the object is of const-qualified type, the underlying class
9275     //   type shall have a user-declared default
9276     //   constructor. Otherwise, if no initializer is specified for
9277     //   a non- static object, the object and its subobjects, if
9278     //   any, have an indeterminate initial value); if the object
9279     //   or any of its subobjects are of const-qualified type, the
9280     //   program is ill-formed.
9281     // C++0x [dcl.init]p11:
9282     //   If no initializer is specified for an object, the object is
9283     //   default-initialized; [...].
9284     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9285     InitializationKind Kind
9286       = InitializationKind::CreateDefault(Var->getLocation());
9287 
9288     InitializationSequence InitSeq(*this, Entity, Kind, None);
9289     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9290     if (Init.isInvalid())
9291       Var->setInvalidDecl();
9292     else if (Init.get()) {
9293       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9294       // This is important for template substitution.
9295       Var->setInitStyle(VarDecl::CallInit);
9296     }
9297 
9298     CheckCompleteVariableDeclaration(Var);
9299   }
9300 }
9301 
9302 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9303   VarDecl *VD = dyn_cast<VarDecl>(D);
9304   if (!VD) {
9305     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9306     D->setInvalidDecl();
9307     return;
9308   }
9309 
9310   VD->setCXXForRangeDecl(true);
9311 
9312   // for-range-declaration cannot be given a storage class specifier.
9313   int Error = -1;
9314   switch (VD->getStorageClass()) {
9315   case SC_None:
9316     break;
9317   case SC_Extern:
9318     Error = 0;
9319     break;
9320   case SC_Static:
9321     Error = 1;
9322     break;
9323   case SC_PrivateExtern:
9324     Error = 2;
9325     break;
9326   case SC_Auto:
9327     Error = 3;
9328     break;
9329   case SC_Register:
9330     Error = 4;
9331     break;
9332   case SC_OpenCLWorkGroupLocal:
9333     llvm_unreachable("Unexpected storage class");
9334   }
9335   if (VD->isConstexpr())
9336     Error = 5;
9337   if (Error != -1) {
9338     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9339       << VD->getDeclName() << Error;
9340     D->setInvalidDecl();
9341   }
9342 }
9343 
9344 StmtResult
9345 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9346                                  IdentifierInfo *Ident,
9347                                  ParsedAttributes &Attrs,
9348                                  SourceLocation AttrEnd) {
9349   // C++1y [stmt.iter]p1:
9350   //   A range-based for statement of the form
9351   //      for ( for-range-identifier : for-range-initializer ) statement
9352   //   is equivalent to
9353   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
9354   DeclSpec DS(Attrs.getPool().getFactory());
9355 
9356   const char *PrevSpec;
9357   unsigned DiagID;
9358   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9359                      getPrintingPolicy());
9360 
9361   Declarator D(DS, Declarator::ForContext);
9362   D.SetIdentifier(Ident, IdentLoc);
9363   D.takeAttributes(Attrs, AttrEnd);
9364 
9365   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9366   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9367                 EmptyAttrs, IdentLoc);
9368   Decl *Var = ActOnDeclarator(S, D);
9369   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9370   FinalizeDeclaration(Var);
9371   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9372                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
9373 }
9374 
9375 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9376   if (var->isInvalidDecl()) return;
9377 
9378   // In ARC, don't allow jumps past the implicit initialization of a
9379   // local retaining variable.
9380   if (getLangOpts().ObjCAutoRefCount &&
9381       var->hasLocalStorage()) {
9382     switch (var->getType().getObjCLifetime()) {
9383     case Qualifiers::OCL_None:
9384     case Qualifiers::OCL_ExplicitNone:
9385     case Qualifiers::OCL_Autoreleasing:
9386       break;
9387 
9388     case Qualifiers::OCL_Weak:
9389     case Qualifiers::OCL_Strong:
9390       getCurFunction()->setHasBranchProtectedScope();
9391       break;
9392     }
9393   }
9394 
9395   // Warn about externally-visible variables being defined without a
9396   // prior declaration.  We only want to do this for global
9397   // declarations, but we also specifically need to avoid doing it for
9398   // class members because the linkage of an anonymous class can
9399   // change if it's later given a typedef name.
9400   if (var->isThisDeclarationADefinition() &&
9401       var->getDeclContext()->getRedeclContext()->isFileContext() &&
9402       var->isExternallyVisible() && var->hasLinkage() &&
9403       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9404                                   var->getLocation())) {
9405     // Find a previous declaration that's not a definition.
9406     VarDecl *prev = var->getPreviousDecl();
9407     while (prev && prev->isThisDeclarationADefinition())
9408       prev = prev->getPreviousDecl();
9409 
9410     if (!prev)
9411       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9412   }
9413 
9414   if (var->getTLSKind() == VarDecl::TLS_Static) {
9415     const Expr *Culprit;
9416     if (var->getType().isDestructedType()) {
9417       // GNU C++98 edits for __thread, [basic.start.term]p3:
9418       //   The type of an object with thread storage duration shall not
9419       //   have a non-trivial destructor.
9420       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9421       if (getLangOpts().CPlusPlus11)
9422         Diag(var->getLocation(), diag::note_use_thread_local);
9423     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9424                !var->getInit()->isConstantInitializer(
9425                    Context, var->getType()->isReferenceType(), &Culprit)) {
9426       // GNU C++98 edits for __thread, [basic.start.init]p4:
9427       //   An object of thread storage duration shall not require dynamic
9428       //   initialization.
9429       // FIXME: Need strict checking here.
9430       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9431         << Culprit->getSourceRange();
9432       if (getLangOpts().CPlusPlus11)
9433         Diag(var->getLocation(), diag::note_use_thread_local);
9434     }
9435 
9436   }
9437 
9438   if (var->isThisDeclarationADefinition() &&
9439       ActiveTemplateInstantiations.empty()) {
9440     PragmaStack<StringLiteral *> *Stack = nullptr;
9441     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
9442     if (var->getType().isConstQualified())
9443       Stack = &ConstSegStack;
9444     else if (!var->getInit()) {
9445       Stack = &BSSSegStack;
9446       SectionFlags |= ASTContext::PSF_Write;
9447     } else {
9448       Stack = &DataSegStack;
9449       SectionFlags |= ASTContext::PSF_Write;
9450     }
9451     if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue)
9452       var->addAttr(
9453           SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
9454                                       Stack->CurrentValue->getString(),
9455                                       Stack->CurrentPragmaLocation));
9456     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
9457       if (UnifySection(SA->getName(), SectionFlags, var))
9458         var->dropAttr<SectionAttr>();
9459 
9460     // Apply the init_seg attribute if this has an initializer.  If the
9461     // initializer turns out to not be dynamic, we'll end up ignoring this
9462     // attribute.
9463     if (CurInitSeg && var->getInit())
9464       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
9465                                                CurInitSegLoc));
9466   }
9467 
9468   // All the following checks are C++ only.
9469   if (!getLangOpts().CPlusPlus) return;
9470 
9471   QualType type = var->getType();
9472   if (type->isDependentType()) return;
9473 
9474   // __block variables might require us to capture a copy-initializer.
9475   if (var->hasAttr<BlocksAttr>()) {
9476     // It's currently invalid to ever have a __block variable with an
9477     // array type; should we diagnose that here?
9478 
9479     // Regardless, we don't want to ignore array nesting when
9480     // constructing this copy.
9481     if (type->isStructureOrClassType()) {
9482       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
9483       SourceLocation poi = var->getLocation();
9484       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
9485       ExprResult result
9486         = PerformMoveOrCopyInitialization(
9487             InitializedEntity::InitializeBlock(poi, type, false),
9488             var, var->getType(), varRef, /*AllowNRVO=*/true);
9489       if (!result.isInvalid()) {
9490         result = MaybeCreateExprWithCleanups(result);
9491         Expr *init = result.getAs<Expr>();
9492         Context.setBlockVarCopyInits(var, init);
9493       }
9494     }
9495   }
9496 
9497   Expr *Init = var->getInit();
9498   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
9499   QualType baseType = Context.getBaseElementType(type);
9500 
9501   if (!var->getDeclContext()->isDependentContext() &&
9502       Init && !Init->isValueDependent()) {
9503     if (IsGlobal && !var->isConstexpr() &&
9504         !getDiagnostics().isIgnored(diag::warn_global_constructor,
9505                                     var->getLocation())) {
9506       // Warn about globals which don't have a constant initializer.  Don't
9507       // warn about globals with a non-trivial destructor because we already
9508       // warned about them.
9509       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
9510       if (!(RD && !RD->hasTrivialDestructor()) &&
9511           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
9512         Diag(var->getLocation(), diag::warn_global_constructor)
9513           << Init->getSourceRange();
9514     }
9515 
9516     if (var->isConstexpr()) {
9517       SmallVector<PartialDiagnosticAt, 8> Notes;
9518       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
9519         SourceLocation DiagLoc = var->getLocation();
9520         // If the note doesn't add any useful information other than a source
9521         // location, fold it into the primary diagnostic.
9522         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9523               diag::note_invalid_subexpr_in_const_expr) {
9524           DiagLoc = Notes[0].first;
9525           Notes.clear();
9526         }
9527         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
9528           << var << Init->getSourceRange();
9529         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9530           Diag(Notes[I].first, Notes[I].second);
9531       }
9532     } else if (var->isUsableInConstantExpressions(Context)) {
9533       // Check whether the initializer of a const variable of integral or
9534       // enumeration type is an ICE now, since we can't tell whether it was
9535       // initialized by a constant expression if we check later.
9536       var->checkInitIsICE();
9537     }
9538   }
9539 
9540   // Require the destructor.
9541   if (const RecordType *recordType = baseType->getAs<RecordType>())
9542     FinalizeVarWithDestructor(var, recordType);
9543 }
9544 
9545 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9546 /// any semantic actions necessary after any initializer has been attached.
9547 void
9548 Sema::FinalizeDeclaration(Decl *ThisDecl) {
9549   // Note that we are no longer parsing the initializer for this declaration.
9550   ParsingInitForAutoVars.erase(ThisDecl);
9551 
9552   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
9553   if (!VD)
9554     return;
9555 
9556   checkAttributesAfterMerging(*this, *VD);
9557 
9558   // Static locals inherit dll attributes from their function.
9559   if (VD->isStaticLocal()) {
9560     if (FunctionDecl *FD =
9561             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
9562       if (Attr *A = getDLLAttr(FD)) {
9563         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
9564         NewAttr->setInherited(true);
9565         VD->addAttr(NewAttr);
9566       }
9567     }
9568   }
9569 
9570   // Grab the dllimport or dllexport attribute off of the VarDecl.
9571   const InheritableAttr *DLLAttr = getDLLAttr(VD);
9572 
9573   // Imported static data members cannot be defined out-of-line.
9574   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
9575     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
9576         VD->isThisDeclarationADefinition()) {
9577       // We allow definitions of dllimport class template static data members
9578       // with a warning.
9579       CXXRecordDecl *Context =
9580         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
9581       bool IsClassTemplateMember =
9582           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
9583           Context->getDescribedClassTemplate();
9584 
9585       Diag(VD->getLocation(),
9586            IsClassTemplateMember
9587                ? diag::warn_attribute_dllimport_static_field_definition
9588                : diag::err_attribute_dllimport_static_field_definition);
9589       Diag(IA->getLocation(), diag::note_attribute);
9590       if (!IsClassTemplateMember)
9591         VD->setInvalidDecl();
9592     }
9593   }
9594 
9595   // dllimport/dllexport variables cannot be thread local, their TLS index
9596   // isn't exported with the variable.
9597   if (DLLAttr && VD->getTLSKind()) {
9598     Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
9599                                                                   << DLLAttr;
9600     VD->setInvalidDecl();
9601   }
9602 
9603   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9604     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
9605       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
9606       VD->dropAttr<UsedAttr>();
9607     }
9608   }
9609 
9610   if (!VD->isInvalidDecl() &&
9611       VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
9612     if (const VarDecl *Def = VD->getDefinition()) {
9613       if (Def->hasAttr<AliasAttr>()) {
9614         Diag(VD->getLocation(), diag::err_tentative_after_alias)
9615             << VD->getDeclName();
9616         Diag(Def->getLocation(), diag::note_previous_definition);
9617         VD->setInvalidDecl();
9618       }
9619     }
9620   }
9621 
9622   const DeclContext *DC = VD->getDeclContext();
9623   // If there's a #pragma GCC visibility in scope, and this isn't a class
9624   // member, set the visibility of this variable.
9625   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
9626     AddPushedVisibilityAttribute(VD);
9627 
9628   // FIXME: Warn on unused templates.
9629   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
9630       !isa<VarTemplatePartialSpecializationDecl>(VD))
9631     MarkUnusedFileScopedDecl(VD);
9632 
9633   // Now we have parsed the initializer and can update the table of magic
9634   // tag values.
9635   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
9636       !VD->getType()->isIntegralOrEnumerationType())
9637     return;
9638 
9639   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
9640     const Expr *MagicValueExpr = VD->getInit();
9641     if (!MagicValueExpr) {
9642       continue;
9643     }
9644     llvm::APSInt MagicValueInt;
9645     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9646       Diag(I->getRange().getBegin(),
9647            diag::err_type_tag_for_datatype_not_ice)
9648         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9649       continue;
9650     }
9651     if (MagicValueInt.getActiveBits() > 64) {
9652       Diag(I->getRange().getBegin(),
9653            diag::err_type_tag_for_datatype_too_large)
9654         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9655       continue;
9656     }
9657     uint64_t MagicValue = MagicValueInt.getZExtValue();
9658     RegisterTypeTagForDatatype(I->getArgumentKind(),
9659                                MagicValue,
9660                                I->getMatchingCType(),
9661                                I->getLayoutCompatible(),
9662                                I->getMustBeNull());
9663   }
9664 }
9665 
9666 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
9667                                                    ArrayRef<Decl *> Group) {
9668   SmallVector<Decl*, 8> Decls;
9669 
9670   if (DS.isTypeSpecOwned())
9671     Decls.push_back(DS.getRepAsDecl());
9672 
9673   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
9674   for (unsigned i = 0, e = Group.size(); i != e; ++i)
9675     if (Decl *D = Group[i]) {
9676       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9677         if (!FirstDeclaratorInGroup)
9678           FirstDeclaratorInGroup = DD;
9679       Decls.push_back(D);
9680     }
9681 
9682   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
9683     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
9684       HandleTagNumbering(*this, Tag, S);
9685       if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9686         Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9687     }
9688   }
9689 
9690   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
9691 }
9692 
9693 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
9694 /// group, performing any necessary semantic checking.
9695 Sema::DeclGroupPtrTy
9696 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
9697                            bool TypeMayContainAuto) {
9698   // C++0x [dcl.spec.auto]p7:
9699   //   If the type deduced for the template parameter U is not the same in each
9700   //   deduction, the program is ill-formed.
9701   // FIXME: When initializer-list support is added, a distinction is needed
9702   // between the deduced type U and the deduced type which 'auto' stands for.
9703   //   auto a = 0, b = { 1, 2, 3 };
9704   // is legal because the deduced type U is 'int' in both cases.
9705   if (TypeMayContainAuto && Group.size() > 1) {
9706     QualType Deduced;
9707     CanQualType DeducedCanon;
9708     VarDecl *DeducedDecl = nullptr;
9709     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
9710       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9711         AutoType *AT = D->getType()->getContainedAutoType();
9712         // Don't reissue diagnostics when instantiating a template.
9713         if (AT && D->isInvalidDecl())
9714           break;
9715         QualType U = AT ? AT->getDeducedType() : QualType();
9716         if (!U.isNull()) {
9717           CanQualType UCanon = Context.getCanonicalType(U);
9718           if (Deduced.isNull()) {
9719             Deduced = U;
9720             DeducedCanon = UCanon;
9721             DeducedDecl = D;
9722           } else if (DeducedCanon != UCanon) {
9723             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9724                  diag::err_auto_different_deductions)
9725               << (AT->isDecltypeAuto() ? 1 : 0)
9726               << Deduced << DeducedDecl->getDeclName()
9727               << U << D->getDeclName()
9728               << DeducedDecl->getInit()->getSourceRange()
9729               << D->getInit()->getSourceRange();
9730             D->setInvalidDecl();
9731             break;
9732           }
9733         }
9734       }
9735     }
9736   }
9737 
9738   ActOnDocumentableDecls(Group);
9739 
9740   return DeclGroupPtrTy::make(
9741       DeclGroupRef::Create(Context, Group.data(), Group.size()));
9742 }
9743 
9744 void Sema::ActOnDocumentableDecl(Decl *D) {
9745   ActOnDocumentableDecls(D);
9746 }
9747 
9748 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
9749   // Don't parse the comment if Doxygen diagnostics are ignored.
9750   if (Group.empty() || !Group[0])
9751    return;
9752 
9753   if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation()))
9754     return;
9755 
9756   if (Group.size() >= 2) {
9757     // This is a decl group.  Normally it will contain only declarations
9758     // produced from declarator list.  But in case we have any definitions or
9759     // additional declaration references:
9760     //   'typedef struct S {} S;'
9761     //   'typedef struct S *S;'
9762     //   'struct S *pS;'
9763     // FinalizeDeclaratorGroup adds these as separate declarations.
9764     Decl *MaybeTagDecl = Group[0];
9765     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
9766       Group = Group.slice(1);
9767     }
9768   }
9769 
9770   // See if there are any new comments that are not attached to a decl.
9771   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9772   if (!Comments.empty() &&
9773       !Comments.back()->isAttached()) {
9774     // There is at least one comment that not attached to a decl.
9775     // Maybe it should be attached to one of these decls?
9776     //
9777     // Note that this way we pick up not only comments that precede the
9778     // declaration, but also comments that *follow* the declaration -- thanks to
9779     // the lookahead in the lexer: we've consumed the semicolon and looked
9780     // ahead through comments.
9781     for (unsigned i = 0, e = Group.size(); i != e; ++i)
9782       Context.getCommentForDecl(Group[i], &PP);
9783   }
9784 }
9785 
9786 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9787 /// to introduce parameters into function prototype scope.
9788 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
9789   const DeclSpec &DS = D.getDeclSpec();
9790 
9791   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
9792 
9793   // C++03 [dcl.stc]p2 also permits 'auto'.
9794   StorageClass SC = SC_None;
9795   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
9796     SC = SC_Register;
9797   } else if (getLangOpts().CPlusPlus &&
9798              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9799     SC = SC_Auto;
9800   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
9801     Diag(DS.getStorageClassSpecLoc(),
9802          diag::err_invalid_storage_class_in_func_decl);
9803     D.getMutableDeclSpec().ClearStorageClassSpecs();
9804   }
9805 
9806   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9807     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9808       << DeclSpec::getSpecifierName(TSCS);
9809   if (DS.isConstexprSpecified())
9810     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
9811       << 0;
9812 
9813   DiagnoseFunctionSpecifiers(DS);
9814 
9815   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9816   QualType parmDeclType = TInfo->getType();
9817 
9818   if (getLangOpts().CPlusPlus) {
9819     // Check that there are no default arguments inside the type of this
9820     // parameter.
9821     CheckExtraCXXDefaultArguments(D);
9822 
9823     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9824     if (D.getCXXScopeSpec().isSet()) {
9825       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9826         << D.getCXXScopeSpec().getRange();
9827       D.getCXXScopeSpec().clear();
9828     }
9829   }
9830 
9831   // Ensure we have a valid name
9832   IdentifierInfo *II = nullptr;
9833   if (D.hasName()) {
9834     II = D.getIdentifier();
9835     if (!II) {
9836       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9837         << GetNameForDeclarator(D).getName();
9838       D.setInvalidType(true);
9839     }
9840   }
9841 
9842   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
9843   if (II) {
9844     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9845                    ForRedeclaration);
9846     LookupName(R, S);
9847     if (R.isSingleResult()) {
9848       NamedDecl *PrevDecl = R.getFoundDecl();
9849       if (PrevDecl->isTemplateParameter()) {
9850         // Maybe we will complain about the shadowed template parameter.
9851         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9852         // Just pretend that we didn't see the previous declaration.
9853         PrevDecl = nullptr;
9854       } else if (S->isDeclScope(PrevDecl)) {
9855         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
9856         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9857 
9858         // Recover by removing the name
9859         II = nullptr;
9860         D.SetIdentifier(nullptr, D.getIdentifierLoc());
9861         D.setInvalidType(true);
9862       }
9863     }
9864   }
9865 
9866   // Temporarily put parameter variables in the translation unit, not
9867   // the enclosing context.  This prevents them from accidentally
9868   // looking like class members in C++.
9869   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
9870                                     D.getLocStart(),
9871                                     D.getIdentifierLoc(), II,
9872                                     parmDeclType, TInfo,
9873                                     SC);
9874 
9875   if (D.isInvalidType())
9876     New->setInvalidDecl();
9877 
9878   assert(S->isFunctionPrototypeScope());
9879   assert(S->getFunctionPrototypeDepth() >= 1);
9880   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9881                     S->getNextFunctionPrototypeIndex());
9882 
9883   // Add the parameter declaration into this scope.
9884   S->AddDecl(New);
9885   if (II)
9886     IdResolver.AddDecl(New);
9887 
9888   ProcessDeclAttributes(S, New, D);
9889 
9890   if (D.getDeclSpec().isModulePrivateSpecified())
9891     Diag(New->getLocation(), diag::err_module_private_local)
9892       << 1 << New->getDeclName()
9893       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9894       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9895 
9896   if (New->hasAttr<BlocksAttr>()) {
9897     Diag(New->getLocation(), diag::err_block_on_nonlocal);
9898   }
9899   return New;
9900 }
9901 
9902 /// \brief Synthesizes a variable for a parameter arising from a
9903 /// typedef.
9904 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9905                                               SourceLocation Loc,
9906                                               QualType T) {
9907   /* FIXME: setting StartLoc == Loc.
9908      Would it be worth to modify callers so as to provide proper source
9909      location for the unnamed parameters, embedding the parameter's type? */
9910   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
9911                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
9912                                            SC_None, nullptr);
9913   Param->setImplicit();
9914   return Param;
9915 }
9916 
9917 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9918                                     ParmVarDecl * const *ParamEnd) {
9919   // Don't diagnose unused-parameter errors in template instantiations; we
9920   // will already have done so in the template itself.
9921   if (!ActiveTemplateInstantiations.empty())
9922     return;
9923 
9924   for (; Param != ParamEnd; ++Param) {
9925     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
9926         !(*Param)->hasAttr<UnusedAttr>()) {
9927       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9928         << (*Param)->getDeclName();
9929     }
9930   }
9931 }
9932 
9933 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9934                                                   ParmVarDecl * const *ParamEnd,
9935                                                   QualType ReturnTy,
9936                                                   NamedDecl *D) {
9937   if (LangOpts.NumLargeByValueCopy == 0) // No check.
9938     return;
9939 
9940   // Warn if the return value is pass-by-value and larger than the specified
9941   // threshold.
9942   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
9943     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
9944     if (Size > LangOpts.NumLargeByValueCopy)
9945       Diag(D->getLocation(), diag::warn_return_value_size)
9946           << D->getDeclName() << Size;
9947   }
9948 
9949   // Warn if any parameter is pass-by-value and larger than the specified
9950   // threshold.
9951   for (; Param != ParamEnd; ++Param) {
9952     QualType T = (*Param)->getType();
9953     if (T->isDependentType() || !T.isPODType(Context))
9954       continue;
9955     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
9956     if (Size > LangOpts.NumLargeByValueCopy)
9957       Diag((*Param)->getLocation(), diag::warn_parameter_size)
9958           << (*Param)->getDeclName() << Size;
9959   }
9960 }
9961 
9962 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9963                                   SourceLocation NameLoc, IdentifierInfo *Name,
9964                                   QualType T, TypeSourceInfo *TSInfo,
9965                                   StorageClass SC) {
9966   // In ARC, infer a lifetime qualifier for appropriate parameter types.
9967   if (getLangOpts().ObjCAutoRefCount &&
9968       T.getObjCLifetime() == Qualifiers::OCL_None &&
9969       T->isObjCLifetimeType()) {
9970 
9971     Qualifiers::ObjCLifetime lifetime;
9972 
9973     // Special cases for arrays:
9974     //   - if it's const, use __unsafe_unretained
9975     //   - otherwise, it's an error
9976     if (T->isArrayType()) {
9977       if (!T.isConstQualified()) {
9978         DelayedDiagnostics.add(
9979             sema::DelayedDiagnostic::makeForbiddenType(
9980             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
9981       }
9982       lifetime = Qualifiers::OCL_ExplicitNone;
9983     } else {
9984       lifetime = T->getObjCARCImplicitLifetime();
9985     }
9986     T = Context.getLifetimeQualifiedType(T, lifetime);
9987   }
9988 
9989   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
9990                                          Context.getAdjustedParameterType(T),
9991                                          TSInfo, SC, nullptr);
9992 
9993   // Parameters can not be abstract class types.
9994   // For record types, this is done by the AbstractClassUsageDiagnoser once
9995   // the class has been completely parsed.
9996   if (!CurContext->isRecord() &&
9997       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9998                              AbstractParamType))
9999     New->setInvalidDecl();
10000 
10001   // Parameter declarators cannot be interface types. All ObjC objects are
10002   // passed by reference.
10003   if (T->isObjCObjectType()) {
10004     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10005     Diag(NameLoc,
10006          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10007       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10008     T = Context.getObjCObjectPointerType(T);
10009     New->setType(T);
10010   }
10011 
10012   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10013   // duration shall not be qualified by an address-space qualifier."
10014   // Since all parameters have automatic store duration, they can not have
10015   // an address space.
10016   if (T.getAddressSpace() != 0) {
10017     // OpenCL allows function arguments declared to be an array of a type
10018     // to be qualified with an address space.
10019     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10020       Diag(NameLoc, diag::err_arg_with_address_space);
10021       New->setInvalidDecl();
10022     }
10023   }
10024 
10025   return New;
10026 }
10027 
10028 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10029                                            SourceLocation LocAfterDecls) {
10030   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10031 
10032   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10033   // for a K&R function.
10034   if (!FTI.hasPrototype) {
10035     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10036       --i;
10037       if (FTI.Params[i].Param == nullptr) {
10038         SmallString<256> Code;
10039         llvm::raw_svector_ostream(Code)
10040             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10041         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10042             << FTI.Params[i].Ident
10043             << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
10044 
10045         // Implicitly declare the argument as type 'int' for lack of a better
10046         // type.
10047         AttributeFactory attrs;
10048         DeclSpec DS(attrs);
10049         const char* PrevSpec; // unused
10050         unsigned DiagID; // unused
10051         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10052                            DiagID, Context.getPrintingPolicy());
10053         // Use the identifier location for the type source range.
10054         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10055         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10056         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10057         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10058         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10059       }
10060     }
10061   }
10062 }
10063 
10064 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
10065   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10066   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10067   Scope *ParentScope = FnBodyScope->getParent();
10068 
10069   D.setFunctionDefinitionKind(FDK_Definition);
10070   Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
10071   return ActOnStartOfFunctionDef(FnBodyScope, DP);
10072 }
10073 
10074 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10075   Consumer.HandleInlineMethodDefinition(D);
10076 }
10077 
10078 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10079                              const FunctionDecl*& PossibleZeroParamPrototype) {
10080   // Don't warn about invalid declarations.
10081   if (FD->isInvalidDecl())
10082     return false;
10083 
10084   // Or declarations that aren't global.
10085   if (!FD->isGlobal())
10086     return false;
10087 
10088   // Don't warn about C++ member functions.
10089   if (isa<CXXMethodDecl>(FD))
10090     return false;
10091 
10092   // Don't warn about 'main'.
10093   if (FD->isMain())
10094     return false;
10095 
10096   // Don't warn about inline functions.
10097   if (FD->isInlined())
10098     return false;
10099 
10100   // Don't warn about function templates.
10101   if (FD->getDescribedFunctionTemplate())
10102     return false;
10103 
10104   // Don't warn about function template specializations.
10105   if (FD->isFunctionTemplateSpecialization())
10106     return false;
10107 
10108   // Don't warn for OpenCL kernels.
10109   if (FD->hasAttr<OpenCLKernelAttr>())
10110     return false;
10111 
10112   bool MissingPrototype = true;
10113   for (const FunctionDecl *Prev = FD->getPreviousDecl();
10114        Prev; Prev = Prev->getPreviousDecl()) {
10115     // Ignore any declarations that occur in function or method
10116     // scope, because they aren't visible from the header.
10117     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10118       continue;
10119 
10120     MissingPrototype = !Prev->getType()->isFunctionProtoType();
10121     if (FD->getNumParams() == 0)
10122       PossibleZeroParamPrototype = Prev;
10123     break;
10124   }
10125 
10126   return MissingPrototype;
10127 }
10128 
10129 void
10130 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10131                                    const FunctionDecl *EffectiveDefinition) {
10132   // Don't complain if we're in GNU89 mode and the previous definition
10133   // was an extern inline function.
10134   const FunctionDecl *Definition = EffectiveDefinition;
10135   if (!Definition)
10136     if (!FD->isDefined(Definition))
10137       return;
10138 
10139   if (canRedefineFunction(Definition, getLangOpts()))
10140     return;
10141 
10142   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10143       Definition->getStorageClass() == SC_Extern)
10144     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10145         << FD->getDeclName() << getLangOpts().CPlusPlus;
10146   else
10147     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10148 
10149   Diag(Definition->getLocation(), diag::note_previous_definition);
10150   FD->setInvalidDecl();
10151 }
10152 
10153 
10154 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10155                                    Sema &S) {
10156   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10157 
10158   LambdaScopeInfo *LSI = S.PushLambdaScope();
10159   LSI->CallOperator = CallOperator;
10160   LSI->Lambda = LambdaClass;
10161   LSI->ReturnType = CallOperator->getReturnType();
10162   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10163 
10164   if (LCD == LCD_None)
10165     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10166   else if (LCD == LCD_ByCopy)
10167     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10168   else if (LCD == LCD_ByRef)
10169     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10170   DeclarationNameInfo DNI = CallOperator->getNameInfo();
10171 
10172   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10173   LSI->Mutable = !CallOperator->isConst();
10174 
10175   // Add the captures to the LSI so they can be noted as already
10176   // captured within tryCaptureVar.
10177   auto I = LambdaClass->field_begin();
10178   for (const auto &C : LambdaClass->captures()) {
10179     if (C.capturesVariable()) {
10180       VarDecl *VD = C.getCapturedVar();
10181       if (VD->isInitCapture())
10182         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10183       QualType CaptureType = VD->getType();
10184       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10185       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10186           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
10187           /*EllipsisLoc*/C.isPackExpansion()
10188                          ? C.getEllipsisLoc() : SourceLocation(),
10189           CaptureType, /*Expr*/ nullptr);
10190 
10191     } else if (C.capturesThis()) {
10192       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10193                               S.getCurrentThisType(), /*Expr*/ nullptr);
10194     } else {
10195       LSI->addVLATypeCapture(C.getLocation(), I->getType());
10196     }
10197     ++I;
10198   }
10199 }
10200 
10201 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
10202   // Clear the last template instantiation error context.
10203   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10204 
10205   if (!D)
10206     return D;
10207   FunctionDecl *FD = nullptr;
10208 
10209   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10210     FD = FunTmpl->getTemplatedDecl();
10211   else
10212     FD = cast<FunctionDecl>(D);
10213   // If we are instantiating a generic lambda call operator, push
10214   // a LambdaScopeInfo onto the function stack.  But use the information
10215   // that's already been calculated (ActOnLambdaExpr) to prime the current
10216   // LambdaScopeInfo.
10217   // When the template operator is being specialized, the LambdaScopeInfo,
10218   // has to be properly restored so that tryCaptureVariable doesn't try
10219   // and capture any new variables. In addition when calculating potential
10220   // captures during transformation of nested lambdas, it is necessary to
10221   // have the LSI properly restored.
10222   if (isGenericLambdaCallOperatorSpecialization(FD)) {
10223     assert(ActiveTemplateInstantiations.size() &&
10224       "There should be an active template instantiation on the stack "
10225       "when instantiating a generic lambda!");
10226     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10227   }
10228   else
10229     // Enter a new function scope
10230     PushFunctionScope();
10231 
10232   // See if this is a redefinition.
10233   if (!FD->isLateTemplateParsed())
10234     CheckForFunctionRedefinition(FD);
10235 
10236   // Builtin functions cannot be defined.
10237   if (unsigned BuiltinID = FD->getBuiltinID()) {
10238     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10239         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10240       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10241       FD->setInvalidDecl();
10242     }
10243   }
10244 
10245   // The return type of a function definition must be complete
10246   // (C99 6.9.1p3, C++ [dcl.fct]p6).
10247   QualType ResultType = FD->getReturnType();
10248   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10249       !FD->isInvalidDecl() &&
10250       RequireCompleteType(FD->getLocation(), ResultType,
10251                           diag::err_func_def_incomplete_result))
10252     FD->setInvalidDecl();
10253 
10254   // GNU warning -Wmissing-prototypes:
10255   //   Warn if a global function is defined without a previous
10256   //   prototype declaration. This warning is issued even if the
10257   //   definition itself provides a prototype. The aim is to detect
10258   //   global functions that fail to be declared in header files.
10259   const FunctionDecl *PossibleZeroParamPrototype = nullptr;
10260   if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
10261     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
10262 
10263     if (PossibleZeroParamPrototype) {
10264       // We found a declaration that is not a prototype,
10265       // but that could be a zero-parameter prototype
10266       if (TypeSourceInfo *TI =
10267               PossibleZeroParamPrototype->getTypeSourceInfo()) {
10268         TypeLoc TL = TI->getTypeLoc();
10269         if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
10270           Diag(PossibleZeroParamPrototype->getLocation(),
10271                diag::note_declaration_not_a_prototype)
10272             << PossibleZeroParamPrototype
10273             << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
10274       }
10275     }
10276   }
10277 
10278   if (FnBodyScope)
10279     PushDeclContext(FnBodyScope, FD);
10280 
10281   // Check the validity of our function parameters
10282   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10283                            /*CheckParameterNames=*/true);
10284 
10285   // Introduce our parameters into the function scope
10286   for (auto Param : FD->params()) {
10287     Param->setOwningFunction(FD);
10288 
10289     // If this has an identifier, add it to the scope stack.
10290     if (Param->getIdentifier() && FnBodyScope) {
10291       CheckShadow(FnBodyScope, Param);
10292 
10293       PushOnScopeChains(Param, FnBodyScope);
10294     }
10295   }
10296 
10297   // If we had any tags defined in the function prototype,
10298   // introduce them into the function scope.
10299   if (FnBodyScope) {
10300     for (ArrayRef<NamedDecl *>::iterator
10301              I = FD->getDeclsInPrototypeScope().begin(),
10302              E = FD->getDeclsInPrototypeScope().end();
10303          I != E; ++I) {
10304       NamedDecl *D = *I;
10305 
10306       // Some of these decls (like enums) may have been pinned to the translation unit
10307       // for lack of a real context earlier. If so, remove from the translation unit
10308       // and reattach to the current context.
10309       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10310         // Is the decl actually in the context?
10311         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10312           if (DI == D) {
10313             Context.getTranslationUnitDecl()->removeDecl(D);
10314             break;
10315           }
10316         }
10317         // Either way, reassign the lexical decl context to our FunctionDecl.
10318         D->setLexicalDeclContext(CurContext);
10319       }
10320 
10321       // If the decl has a non-null name, make accessible in the current scope.
10322       if (!D->getName().empty())
10323         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10324 
10325       // Similarly, dive into enums and fish their constants out, making them
10326       // accessible in this scope.
10327       if (auto *ED = dyn_cast<EnumDecl>(D)) {
10328         for (auto *EI : ED->enumerators())
10329           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10330       }
10331     }
10332   }
10333 
10334   // Ensure that the function's exception specification is instantiated.
10335   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10336     ResolveExceptionSpec(D->getLocation(), FPT);
10337 
10338   // dllimport cannot be applied to non-inline function definitions.
10339   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10340       !FD->isTemplateInstantiation()) {
10341     assert(!FD->hasAttr<DLLExportAttr>());
10342     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10343     FD->setInvalidDecl();
10344     return D;
10345   }
10346   // We want to attach documentation to original Decl (which might be
10347   // a function template).
10348   ActOnDocumentableDecl(D);
10349   if (getCurLexicalContext()->isObjCContainer() &&
10350       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10351       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10352     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10353 
10354   return D;
10355 }
10356 
10357 /// \brief Given the set of return statements within a function body,
10358 /// compute the variables that are subject to the named return value
10359 /// optimization.
10360 ///
10361 /// Each of the variables that is subject to the named return value
10362 /// optimization will be marked as NRVO variables in the AST, and any
10363 /// return statement that has a marked NRVO variable as its NRVO candidate can
10364 /// use the named return value optimization.
10365 ///
10366 /// This function applies a very simplistic algorithm for NRVO: if every return
10367 /// statement in the scope of a variable has the same NRVO candidate, that
10368 /// candidate is an NRVO variable.
10369 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
10370   ReturnStmt **Returns = Scope->Returns.data();
10371 
10372   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10373     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10374       if (!NRVOCandidate->isNRVOVariable())
10375         Returns[I]->setNRVOCandidate(nullptr);
10376     }
10377   }
10378 }
10379 
10380 bool Sema::canDelayFunctionBody(const Declarator &D) {
10381   // We can't delay parsing the body of a constexpr function template (yet).
10382   if (D.getDeclSpec().isConstexprSpecified())
10383     return false;
10384 
10385   // We can't delay parsing the body of a function template with a deduced
10386   // return type (yet).
10387   if (D.getDeclSpec().containsPlaceholderType()) {
10388     // If the placeholder introduces a non-deduced trailing return type,
10389     // we can still delay parsing it.
10390     if (D.getNumTypeObjects()) {
10391       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10392       if (Outer.Kind == DeclaratorChunk::Function &&
10393           Outer.Fun.hasTrailingReturnType()) {
10394         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10395         return Ty.isNull() || !Ty->isUndeducedType();
10396       }
10397     }
10398     return false;
10399   }
10400 
10401   return true;
10402 }
10403 
10404 bool Sema::canSkipFunctionBody(Decl *D) {
10405   // We cannot skip the body of a function (or function template) which is
10406   // constexpr, since we may need to evaluate its body in order to parse the
10407   // rest of the file.
10408   // We cannot skip the body of a function with an undeduced return type,
10409   // because any callers of that function need to know the type.
10410   if (const FunctionDecl *FD = D->getAsFunction())
10411     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
10412       return false;
10413   return Consumer.shouldSkipFunctionBody(D);
10414 }
10415 
10416 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
10417   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
10418     FD->setHasSkippedBody();
10419   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
10420     MD->setHasSkippedBody();
10421   return ActOnFinishFunctionBody(Decl, nullptr);
10422 }
10423 
10424 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
10425   return ActOnFinishFunctionBody(D, BodyArg, false);
10426 }
10427 
10428 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
10429                                     bool IsInstantiation) {
10430   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
10431 
10432   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10433   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
10434 
10435   if (FD) {
10436     FD->setBody(Body);
10437 
10438     if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
10439         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
10440       // If the function has a deduced result type but contains no 'return'
10441       // statements, the result type as written must be exactly 'auto', and
10442       // the deduced result type is 'void'.
10443       if (!FD->getReturnType()->getAs<AutoType>()) {
10444         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
10445             << FD->getReturnType();
10446         FD->setInvalidDecl();
10447       } else {
10448         // Substitute 'void' for the 'auto' in the type.
10449         TypeLoc ResultType = getReturnTypeLoc(FD);
10450         Context.adjustDeducedFunctionResultType(
10451             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
10452       }
10453     }
10454 
10455     // The only way to be included in UndefinedButUsed is if there is an
10456     // ODR use before the definition. Avoid the expensive map lookup if this
10457     // is the first declaration.
10458     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
10459       if (!FD->isExternallyVisible())
10460         UndefinedButUsed.erase(FD);
10461       else if (FD->isInlined() &&
10462                (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10463                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
10464         UndefinedButUsed.erase(FD);
10465     }
10466 
10467     // If the function implicitly returns zero (like 'main') or is naked,
10468     // don't complain about missing return statements.
10469     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
10470       WP.disableCheckFallThrough();
10471 
10472     // MSVC permits the use of pure specifier (=0) on function definition,
10473     // defined at class scope, warn about this non-standard construct.
10474     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
10475       Diag(FD->getLocation(), diag::ext_pure_function_definition);
10476 
10477     if (!FD->isInvalidDecl()) {
10478       // Don't diagnose unused parameters of defaulted or deleted functions.
10479       if (Body)
10480         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
10481       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
10482                                              FD->getReturnType(), FD);
10483 
10484       // If this is a structor, we need a vtable.
10485       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
10486         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
10487       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
10488         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
10489 
10490       // Try to apply the named return value optimization. We have to check
10491       // if we can do this here because lambdas keep return statements around
10492       // to deduce an implicit return type.
10493       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
10494           !FD->isDependentContext())
10495         computeNRVO(Body, getCurFunction());
10496     }
10497 
10498     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
10499            "Function parsing confused");
10500   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
10501     assert(MD == getCurMethodDecl() && "Method parsing confused");
10502     MD->setBody(Body);
10503     if (!MD->isInvalidDecl()) {
10504       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
10505       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
10506                                              MD->getReturnType(), MD);
10507 
10508       if (Body)
10509         computeNRVO(Body, getCurFunction());
10510     }
10511     if (getCurFunction()->ObjCShouldCallSuper) {
10512       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
10513         << MD->getSelector().getAsString();
10514       getCurFunction()->ObjCShouldCallSuper = false;
10515     }
10516     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
10517       const ObjCMethodDecl *InitMethod = nullptr;
10518       bool isDesignated =
10519           MD->isDesignatedInitializerForTheInterface(&InitMethod);
10520       assert(isDesignated && InitMethod);
10521       (void)isDesignated;
10522 
10523       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
10524         auto IFace = MD->getClassInterface();
10525         if (!IFace)
10526           return false;
10527         auto SuperD = IFace->getSuperClass();
10528         if (!SuperD)
10529           return false;
10530         return SuperD->getIdentifier() ==
10531             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
10532       };
10533       // Don't issue this warning for unavailable inits or direct subclasses
10534       // of NSObject.
10535       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
10536         Diag(MD->getLocation(),
10537              diag::warn_objc_designated_init_missing_super_call);
10538         Diag(InitMethod->getLocation(),
10539              diag::note_objc_designated_init_marked_here);
10540       }
10541       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
10542     }
10543     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
10544       // Don't issue this warning for unavaialable inits.
10545       if (!MD->isUnavailable())
10546         Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
10547       getCurFunction()->ObjCWarnForNoInitDelegation = false;
10548     }
10549   } else {
10550     return nullptr;
10551   }
10552 
10553   assert(!getCurFunction()->ObjCShouldCallSuper &&
10554          "This should only be set for ObjC methods, which should have been "
10555          "handled in the block above.");
10556 
10557   // Verify and clean out per-function state.
10558   if (Body) {
10559     // C++ constructors that have function-try-blocks can't have return
10560     // statements in the handlers of that block. (C++ [except.handle]p14)
10561     // Verify this.
10562     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
10563       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
10564 
10565     // Verify that gotos and switch cases don't jump into scopes illegally.
10566     if (getCurFunction()->NeedsScopeChecking() &&
10567         !PP.isCodeCompletionEnabled())
10568       DiagnoseInvalidJumps(Body);
10569 
10570     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
10571       if (!Destructor->getParent()->isDependentType())
10572         CheckDestructor(Destructor);
10573 
10574       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10575                                              Destructor->getParent());
10576     }
10577 
10578     // If any errors have occurred, clear out any temporaries that may have
10579     // been leftover. This ensures that these temporaries won't be picked up for
10580     // deletion in some later function.
10581     if (getDiagnostics().hasErrorOccurred() ||
10582         getDiagnostics().getSuppressAllDiagnostics()) {
10583       DiscardCleanupsInEvaluationContext();
10584     }
10585     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
10586         !isa<FunctionTemplateDecl>(dcl)) {
10587       // Since the body is valid, issue any analysis-based warnings that are
10588       // enabled.
10589       ActivePolicy = &WP;
10590     }
10591 
10592     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10593         (!CheckConstexprFunctionDecl(FD) ||
10594          !CheckConstexprFunctionBody(FD, Body)))
10595       FD->setInvalidDecl();
10596 
10597     if (FD && FD->hasAttr<NakedAttr>()) {
10598       for (const Stmt *S : Body->children()) {
10599         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
10600           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
10601           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
10602           FD->setInvalidDecl();
10603           break;
10604         }
10605       }
10606     }
10607 
10608     assert(ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
10609            && "Leftover temporaries in function");
10610     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
10611     assert(MaybeODRUseExprs.empty() &&
10612            "Leftover expressions for odr-use checking");
10613   }
10614 
10615   if (!IsInstantiation)
10616     PopDeclContext();
10617 
10618   PopFunctionScopeInfo(ActivePolicy, dcl);
10619   // If any errors have occurred, clear out any temporaries that may have
10620   // been leftover. This ensures that these temporaries won't be picked up for
10621   // deletion in some later function.
10622   if (getDiagnostics().hasErrorOccurred()) {
10623     DiscardCleanupsInEvaluationContext();
10624   }
10625 
10626   return dcl;
10627 }
10628 
10629 
10630 /// When we finish delayed parsing of an attribute, we must attach it to the
10631 /// relevant Decl.
10632 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
10633                                        ParsedAttributes &Attrs) {
10634   // Always attach attributes to the underlying decl.
10635   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
10636     D = TD->getTemplatedDecl();
10637   ProcessDeclAttributeList(S, D, Attrs.getList());
10638 
10639   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
10640     if (Method->isStatic())
10641       checkThisInStaticMemberFunctionAttributes(Method);
10642 }
10643 
10644 
10645 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
10646 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
10647 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
10648                                           IdentifierInfo &II, Scope *S) {
10649   // Before we produce a declaration for an implicitly defined
10650   // function, see whether there was a locally-scoped declaration of
10651   // this name as a function or variable. If so, use that
10652   // (non-visible) declaration, and complain about it.
10653   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
10654     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
10655     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
10656     return ExternCPrev;
10657   }
10658 
10659   // Extension in C99.  Legal in C90, but warn about it.
10660   unsigned diag_id;
10661   if (II.getName().startswith("__builtin_"))
10662     diag_id = diag::warn_builtin_unknown;
10663   else if (getLangOpts().C99)
10664     diag_id = diag::ext_implicit_function_decl;
10665   else
10666     diag_id = diag::warn_implicit_function_decl;
10667   Diag(Loc, diag_id) << &II;
10668 
10669   // Because typo correction is expensive, only do it if the implicit
10670   // function declaration is going to be treated as an error.
10671   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
10672     TypoCorrection Corrected;
10673     if (S &&
10674         (Corrected = CorrectTypo(
10675              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
10676              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
10677       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
10678                    /*ErrorRecovery*/false);
10679   }
10680 
10681   // Set a Declarator for the implicit definition: int foo();
10682   const char *Dummy;
10683   AttributeFactory attrFactory;
10684   DeclSpec DS(attrFactory);
10685   unsigned DiagID;
10686   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
10687                                   Context.getPrintingPolicy());
10688   (void)Error; // Silence warning.
10689   assert(!Error && "Error setting up implicit decl!");
10690   SourceLocation NoLoc;
10691   Declarator D(DS, Declarator::BlockContext);
10692   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
10693                                              /*IsAmbiguous=*/false,
10694                                              /*LParenLoc=*/NoLoc,
10695                                              /*Params=*/nullptr,
10696                                              /*NumParams=*/0,
10697                                              /*EllipsisLoc=*/NoLoc,
10698                                              /*RParenLoc=*/NoLoc,
10699                                              /*TypeQuals=*/0,
10700                                              /*RefQualifierIsLvalueRef=*/true,
10701                                              /*RefQualifierLoc=*/NoLoc,
10702                                              /*ConstQualifierLoc=*/NoLoc,
10703                                              /*VolatileQualifierLoc=*/NoLoc,
10704                                              /*RestrictQualifierLoc=*/NoLoc,
10705                                              /*MutableLoc=*/NoLoc,
10706                                              EST_None,
10707                                              /*ESpecLoc=*/NoLoc,
10708                                              /*Exceptions=*/nullptr,
10709                                              /*ExceptionRanges=*/nullptr,
10710                                              /*NumExceptions=*/0,
10711                                              /*NoexceptExpr=*/nullptr,
10712                                              /*ExceptionSpecTokens=*/nullptr,
10713                                              Loc, Loc, D),
10714                 DS.getAttributes(),
10715                 SourceLocation());
10716   D.SetIdentifier(&II, Loc);
10717 
10718   // Insert this function into translation-unit scope.
10719 
10720   DeclContext *PrevDC = CurContext;
10721   CurContext = Context.getTranslationUnitDecl();
10722 
10723   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
10724   FD->setImplicit();
10725 
10726   CurContext = PrevDC;
10727 
10728   AddKnownFunctionAttributes(FD);
10729 
10730   return FD;
10731 }
10732 
10733 /// \brief Adds any function attributes that we know a priori based on
10734 /// the declaration of this function.
10735 ///
10736 /// These attributes can apply both to implicitly-declared builtins
10737 /// (like __builtin___printf_chk) or to library-declared functions
10738 /// like NSLog or printf.
10739 ///
10740 /// We need to check for duplicate attributes both here and where user-written
10741 /// attributes are applied to declarations.
10742 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10743   if (FD->isInvalidDecl())
10744     return;
10745 
10746   // If this is a built-in function, map its builtin attributes to
10747   // actual attributes.
10748   if (unsigned BuiltinID = FD->getBuiltinID()) {
10749     // Handle printf-formatting attributes.
10750     unsigned FormatIdx;
10751     bool HasVAListArg;
10752     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
10753       if (!FD->hasAttr<FormatAttr>()) {
10754         const char *fmt = "printf";
10755         unsigned int NumParams = FD->getNumParams();
10756         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10757             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10758           fmt = "NSString";
10759         FD->addAttr(FormatAttr::CreateImplicit(Context,
10760                                                &Context.Idents.get(fmt),
10761                                                FormatIdx+1,
10762                                                HasVAListArg ? 0 : FormatIdx+2,
10763                                                FD->getLocation()));
10764       }
10765     }
10766     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10767                                              HasVAListArg)) {
10768      if (!FD->hasAttr<FormatAttr>())
10769        FD->addAttr(FormatAttr::CreateImplicit(Context,
10770                                               &Context.Idents.get("scanf"),
10771                                               FormatIdx+1,
10772                                               HasVAListArg ? 0 : FormatIdx+2,
10773                                               FD->getLocation()));
10774     }
10775 
10776     // Mark const if we don't care about errno and that is the only
10777     // thing preventing the function from being const. This allows
10778     // IRgen to use LLVM intrinsics for such functions.
10779     if (!getLangOpts().MathErrno &&
10780         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
10781       if (!FD->hasAttr<ConstAttr>())
10782         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10783     }
10784 
10785     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10786         !FD->hasAttr<ReturnsTwiceAttr>())
10787       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10788                                          FD->getLocation()));
10789     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
10790       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
10791     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
10792       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10793   }
10794 
10795   IdentifierInfo *Name = FD->getIdentifier();
10796   if (!Name)
10797     return;
10798   if ((!getLangOpts().CPlusPlus &&
10799        FD->getDeclContext()->isTranslationUnit()) ||
10800       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
10801        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
10802        LinkageSpecDecl::lang_c)) {
10803     // Okay: this could be a libc/libm/Objective-C function we know
10804     // about.
10805   } else
10806     return;
10807 
10808   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
10809     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
10810     // target-specific builtins, perhaps?
10811     if (!FD->hasAttr<FormatAttr>())
10812       FD->addAttr(FormatAttr::CreateImplicit(Context,
10813                                              &Context.Idents.get("printf"), 2,
10814                                              Name->isStr("vasprintf") ? 0 : 3,
10815                                              FD->getLocation()));
10816   }
10817 
10818   if (Name->isStr("__CFStringMakeConstantString")) {
10819     // We already have a __builtin___CFStringMakeConstantString,
10820     // but builds that use -fno-constant-cfstrings don't go through that.
10821     if (!FD->hasAttr<FormatArgAttr>())
10822       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10823                                                 FD->getLocation()));
10824   }
10825 }
10826 
10827 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
10828                                     TypeSourceInfo *TInfo) {
10829   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
10830   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
10831 
10832   if (!TInfo) {
10833     assert(D.isInvalidType() && "no declarator info for valid type");
10834     TInfo = Context.getTrivialTypeSourceInfo(T);
10835   }
10836 
10837   // Scope manipulation handled by caller.
10838   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
10839                                            D.getLocStart(),
10840                                            D.getIdentifierLoc(),
10841                                            D.getIdentifier(),
10842                                            TInfo);
10843 
10844   // Bail out immediately if we have an invalid declaration.
10845   if (D.isInvalidType()) {
10846     NewTD->setInvalidDecl();
10847     return NewTD;
10848   }
10849 
10850   if (D.getDeclSpec().isModulePrivateSpecified()) {
10851     if (CurContext->isFunctionOrMethod())
10852       Diag(NewTD->getLocation(), diag::err_module_private_local)
10853         << 2 << NewTD->getDeclName()
10854         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10855         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10856     else
10857       NewTD->setModulePrivate();
10858   }
10859 
10860   // C++ [dcl.typedef]p8:
10861   //   If the typedef declaration defines an unnamed class (or
10862   //   enum), the first typedef-name declared by the declaration
10863   //   to be that class type (or enum type) is used to denote the
10864   //   class type (or enum type) for linkage purposes only.
10865   // We need to check whether the type was declared in the declaration.
10866   switch (D.getDeclSpec().getTypeSpecType()) {
10867   case TST_enum:
10868   case TST_struct:
10869   case TST_interface:
10870   case TST_union:
10871   case TST_class: {
10872     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10873 
10874     // Do nothing if the tag is not anonymous or already has an
10875     // associated typedef (from an earlier typedef in this decl group).
10876     if (tagFromDeclSpec->getIdentifier()) break;
10877     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
10878 
10879     // A well-formed anonymous tag must always be a TUK_Definition.
10880     assert(tagFromDeclSpec->isThisDeclarationADefinition());
10881 
10882     // The type must match the tag exactly;  no qualifiers allowed.
10883     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10884       break;
10885 
10886     // If we've already computed linkage for the anonymous tag, then
10887     // adding a typedef name for the anonymous decl can change that
10888     // linkage, which might be a serious problem.  Diagnose this as
10889     // unsupported and ignore the typedef name.  TODO: we should
10890     // pursue this as a language defect and establish a formal rule
10891     // for how to handle it.
10892     if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10893       Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10894 
10895       SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
10896       tagLoc = getLocForEndOfToken(tagLoc);
10897 
10898       llvm::SmallString<40> textToInsert;
10899       textToInsert += ' ';
10900       textToInsert += D.getIdentifier()->getName();
10901       Diag(tagLoc, diag::note_typedef_changes_linkage)
10902         << FixItHint::CreateInsertion(tagLoc, textToInsert);
10903       break;
10904     }
10905 
10906     // Otherwise, set this is the anon-decl typedef for the tag.
10907     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
10908     break;
10909   }
10910 
10911   default:
10912     break;
10913   }
10914 
10915   return NewTD;
10916 }
10917 
10918 
10919 /// \brief Check that this is a valid underlying type for an enum declaration.
10920 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10921   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10922   QualType T = TI->getType();
10923 
10924   if (T->isDependentType())
10925     return false;
10926 
10927   if (const BuiltinType *BT = T->getAs<BuiltinType>())
10928     if (BT->isInteger())
10929       return false;
10930 
10931   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10932   return true;
10933 }
10934 
10935 /// Check whether this is a valid redeclaration of a previous enumeration.
10936 /// \return true if the redeclaration was invalid.
10937 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10938                                   QualType EnumUnderlyingTy,
10939                                   const EnumDecl *Prev) {
10940   bool IsFixed = !EnumUnderlyingTy.isNull();
10941 
10942   if (IsScoped != Prev->isScoped()) {
10943     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10944       << Prev->isScoped();
10945     Diag(Prev->getLocation(), diag::note_previous_declaration);
10946     return true;
10947   }
10948 
10949   if (IsFixed && Prev->isFixed()) {
10950     if (!EnumUnderlyingTy->isDependentType() &&
10951         !Prev->getIntegerType()->isDependentType() &&
10952         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
10953                                         Prev->getIntegerType())) {
10954       // TODO: Highlight the underlying type of the redeclaration.
10955       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10956         << EnumUnderlyingTy << Prev->getIntegerType();
10957       Diag(Prev->getLocation(), diag::note_previous_declaration)
10958           << Prev->getIntegerTypeRange();
10959       return true;
10960     }
10961   } else if (IsFixed != Prev->isFixed()) {
10962     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10963       << Prev->isFixed();
10964     Diag(Prev->getLocation(), diag::note_previous_declaration);
10965     return true;
10966   }
10967 
10968   return false;
10969 }
10970 
10971 /// \brief Get diagnostic %select index for tag kind for
10972 /// redeclaration diagnostic message.
10973 /// WARNING: Indexes apply to particular diagnostics only!
10974 ///
10975 /// \returns diagnostic %select index.
10976 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
10977   switch (Tag) {
10978   case TTK_Struct: return 0;
10979   case TTK_Interface: return 1;
10980   case TTK_Class:  return 2;
10981   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
10982   }
10983 }
10984 
10985 /// \brief Determine if tag kind is a class-key compatible with
10986 /// class for redeclaration (class, struct, or __interface).
10987 ///
10988 /// \returns true iff the tag kind is compatible.
10989 static bool isClassCompatTagKind(TagTypeKind Tag)
10990 {
10991   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10992 }
10993 
10994 /// \brief Determine whether a tag with a given kind is acceptable
10995 /// as a redeclaration of the given tag declaration.
10996 ///
10997 /// \returns true if the new tag kind is acceptable, false otherwise.
10998 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
10999                                         TagTypeKind NewTag, bool isDefinition,
11000                                         SourceLocation NewTagLoc,
11001                                         const IdentifierInfo &Name) {
11002   // C++ [dcl.type.elab]p3:
11003   //   The class-key or enum keyword present in the
11004   //   elaborated-type-specifier shall agree in kind with the
11005   //   declaration to which the name in the elaborated-type-specifier
11006   //   refers. This rule also applies to the form of
11007   //   elaborated-type-specifier that declares a class-name or
11008   //   friend class since it can be construed as referring to the
11009   //   definition of the class. Thus, in any
11010   //   elaborated-type-specifier, the enum keyword shall be used to
11011   //   refer to an enumeration (7.2), the union class-key shall be
11012   //   used to refer to a union (clause 9), and either the class or
11013   //   struct class-key shall be used to refer to a class (clause 9)
11014   //   declared using the class or struct class-key.
11015   TagTypeKind OldTag = Previous->getTagKind();
11016   if (!isDefinition || !isClassCompatTagKind(NewTag))
11017     if (OldTag == NewTag)
11018       return true;
11019 
11020   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11021     // Warn about the struct/class tag mismatch.
11022     bool isTemplate = false;
11023     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11024       isTemplate = Record->getDescribedClassTemplate();
11025 
11026     if (!ActiveTemplateInstantiations.empty()) {
11027       // In a template instantiation, do not offer fix-its for tag mismatches
11028       // since they usually mess up the template instead of fixing the problem.
11029       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11030         << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11031         << getRedeclDiagFromTagKind(OldTag);
11032       return true;
11033     }
11034 
11035     if (isDefinition) {
11036       // On definitions, check previous tags and issue a fix-it for each
11037       // one that doesn't match the current tag.
11038       if (Previous->getDefinition()) {
11039         // Don't suggest fix-its for redefinitions.
11040         return true;
11041       }
11042 
11043       bool previousMismatch = false;
11044       for (auto I : Previous->redecls()) {
11045         if (I->getTagKind() != NewTag) {
11046           if (!previousMismatch) {
11047             previousMismatch = true;
11048             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11049               << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11050               << getRedeclDiagFromTagKind(I->getTagKind());
11051           }
11052           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11053             << getRedeclDiagFromTagKind(NewTag)
11054             << FixItHint::CreateReplacement(I->getInnerLocStart(),
11055                  TypeWithKeyword::getTagTypeKindName(NewTag));
11056         }
11057       }
11058       return true;
11059     }
11060 
11061     // Check for a previous definition.  If current tag and definition
11062     // are same type, do nothing.  If no definition, but disagree with
11063     // with previous tag type, give a warning, but no fix-it.
11064     const TagDecl *Redecl = Previous->getDefinition() ?
11065                             Previous->getDefinition() : Previous;
11066     if (Redecl->getTagKind() == NewTag) {
11067       return true;
11068     }
11069 
11070     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11071       << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11072       << getRedeclDiagFromTagKind(OldTag);
11073     Diag(Redecl->getLocation(), diag::note_previous_use);
11074 
11075     // If there is a previous definition, suggest a fix-it.
11076     if (Previous->getDefinition()) {
11077         Diag(NewTagLoc, diag::note_struct_class_suggestion)
11078           << getRedeclDiagFromTagKind(Redecl->getTagKind())
11079           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11080                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11081     }
11082 
11083     return true;
11084   }
11085   return false;
11086 }
11087 
11088 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11089 /// from an outer enclosing namespace or file scope inside a friend declaration.
11090 /// This should provide the commented out code in the following snippet:
11091 ///   namespace N {
11092 ///     struct X;
11093 ///     namespace M {
11094 ///       struct Y { friend struct /*N::*/ X; };
11095 ///     }
11096 ///   }
11097 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11098                                          SourceLocation NameLoc) {
11099   // While the decl is in a namespace, do repeated lookup of that name and see
11100   // if we get the same namespace back.  If we do not, continue until
11101   // translation unit scope, at which point we have a fully qualified NNS.
11102   SmallVector<IdentifierInfo *, 4> Namespaces;
11103   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11104   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11105     // This tag should be declared in a namespace, which can only be enclosed by
11106     // other namespaces.  Bail if there's an anonymous namespace in the chain.
11107     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11108     if (!Namespace || Namespace->isAnonymousNamespace())
11109       return FixItHint();
11110     IdentifierInfo *II = Namespace->getIdentifier();
11111     Namespaces.push_back(II);
11112     NamedDecl *Lookup = SemaRef.LookupSingleName(
11113         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11114     if (Lookup == Namespace)
11115       break;
11116   }
11117 
11118   // Once we have all the namespaces, reverse them to go outermost first, and
11119   // build an NNS.
11120   SmallString<64> Insertion;
11121   llvm::raw_svector_ostream OS(Insertion);
11122   if (DC->isTranslationUnit())
11123     OS << "::";
11124   std::reverse(Namespaces.begin(), Namespaces.end());
11125   for (auto *II : Namespaces)
11126     OS << II->getName() << "::";
11127   OS.flush();
11128   return FixItHint::CreateInsertion(NameLoc, Insertion);
11129 }
11130 
11131 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
11132 /// former case, Name will be non-null.  In the later case, Name will be null.
11133 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11134 /// reference/declaration/definition of a tag.
11135 ///
11136 /// IsTypeSpecifier is true if this is a type-specifier (or
11137 /// trailing-type-specifier) other than one in an alias-declaration.
11138 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11139                      SourceLocation KWLoc, CXXScopeSpec &SS,
11140                      IdentifierInfo *Name, SourceLocation NameLoc,
11141                      AttributeList *Attr, AccessSpecifier AS,
11142                      SourceLocation ModulePrivateLoc,
11143                      MultiTemplateParamsArg TemplateParameterLists,
11144                      bool &OwnedDecl, bool &IsDependent,
11145                      SourceLocation ScopedEnumKWLoc,
11146                      bool ScopedEnumUsesClassTag,
11147                      TypeResult UnderlyingType,
11148                      bool IsTypeSpecifier) {
11149   // If this is not a definition, it must have a name.
11150   IdentifierInfo *OrigName = Name;
11151   assert((Name != nullptr || TUK == TUK_Definition) &&
11152          "Nameless record must be a definition!");
11153   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11154 
11155   OwnedDecl = false;
11156   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11157   bool ScopedEnum = ScopedEnumKWLoc.isValid();
11158 
11159   // FIXME: Check explicit specializations more carefully.
11160   bool isExplicitSpecialization = false;
11161   bool Invalid = false;
11162 
11163   // We only need to do this matching if we have template parameters
11164   // or a scope specifier, which also conveniently avoids this work
11165   // for non-C++ cases.
11166   if (TemplateParameterLists.size() > 0 ||
11167       (SS.isNotEmpty() && TUK != TUK_Reference)) {
11168     if (TemplateParameterList *TemplateParams =
11169             MatchTemplateParametersToScopeSpecifier(
11170                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11171                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11172       if (Kind == TTK_Enum) {
11173         Diag(KWLoc, diag::err_enum_template);
11174         return nullptr;
11175       }
11176 
11177       if (TemplateParams->size() > 0) {
11178         // This is a declaration or definition of a class template (which may
11179         // be a member of another template).
11180 
11181         if (Invalid)
11182           return nullptr;
11183 
11184         OwnedDecl = false;
11185         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11186                                                SS, Name, NameLoc, Attr,
11187                                                TemplateParams, AS,
11188                                                ModulePrivateLoc,
11189                                                /*FriendLoc*/SourceLocation(),
11190                                                TemplateParameterLists.size()-1,
11191                                                TemplateParameterLists.data());
11192         return Result.get();
11193       } else {
11194         // The "template<>" header is extraneous.
11195         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11196           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11197         isExplicitSpecialization = true;
11198       }
11199     }
11200   }
11201 
11202   // Figure out the underlying type if this a enum declaration. We need to do
11203   // this early, because it's needed to detect if this is an incompatible
11204   // redeclaration.
11205   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11206 
11207   if (Kind == TTK_Enum) {
11208     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11209       // No underlying type explicitly specified, or we failed to parse the
11210       // type, default to int.
11211       EnumUnderlying = Context.IntTy.getTypePtr();
11212     else if (UnderlyingType.get()) {
11213       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11214       // integral type; any cv-qualification is ignored.
11215       TypeSourceInfo *TI = nullptr;
11216       GetTypeFromParser(UnderlyingType.get(), &TI);
11217       EnumUnderlying = TI;
11218 
11219       if (CheckEnumUnderlyingType(TI))
11220         // Recover by falling back to int.
11221         EnumUnderlying = Context.IntTy.getTypePtr();
11222 
11223       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11224                                           UPPC_FixedUnderlyingType))
11225         EnumUnderlying = Context.IntTy.getTypePtr();
11226 
11227     } else if (getLangOpts().MSVCCompat)
11228       // Microsoft enums are always of int type.
11229       EnumUnderlying = Context.IntTy.getTypePtr();
11230   }
11231 
11232   DeclContext *SearchDC = CurContext;
11233   DeclContext *DC = CurContext;
11234   bool isStdBadAlloc = false;
11235 
11236   RedeclarationKind Redecl = ForRedeclaration;
11237   if (TUK == TUK_Friend || TUK == TUK_Reference)
11238     Redecl = NotForRedeclaration;
11239 
11240   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11241   if (Name && SS.isNotEmpty()) {
11242     // We have a nested-name tag ('struct foo::bar').
11243 
11244     // Check for invalid 'foo::'.
11245     if (SS.isInvalid()) {
11246       Name = nullptr;
11247       goto CreateNewDecl;
11248     }
11249 
11250     // If this is a friend or a reference to a class in a dependent
11251     // context, don't try to make a decl for it.
11252     if (TUK == TUK_Friend || TUK == TUK_Reference) {
11253       DC = computeDeclContext(SS, false);
11254       if (!DC) {
11255         IsDependent = true;
11256         return nullptr;
11257       }
11258     } else {
11259       DC = computeDeclContext(SS, true);
11260       if (!DC) {
11261         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11262           << SS.getRange();
11263         return nullptr;
11264       }
11265     }
11266 
11267     if (RequireCompleteDeclContext(SS, DC))
11268       return nullptr;
11269 
11270     SearchDC = DC;
11271     // Look-up name inside 'foo::'.
11272     LookupQualifiedName(Previous, DC);
11273 
11274     if (Previous.isAmbiguous())
11275       return nullptr;
11276 
11277     if (Previous.empty()) {
11278       // Name lookup did not find anything. However, if the
11279       // nested-name-specifier refers to the current instantiation,
11280       // and that current instantiation has any dependent base
11281       // classes, we might find something at instantiation time: treat
11282       // this as a dependent elaborated-type-specifier.
11283       // But this only makes any sense for reference-like lookups.
11284       if (Previous.wasNotFoundInCurrentInstantiation() &&
11285           (TUK == TUK_Reference || TUK == TUK_Friend)) {
11286         IsDependent = true;
11287         return nullptr;
11288       }
11289 
11290       // A tag 'foo::bar' must already exist.
11291       Diag(NameLoc, diag::err_not_tag_in_scope)
11292         << Kind << Name << DC << SS.getRange();
11293       Name = nullptr;
11294       Invalid = true;
11295       goto CreateNewDecl;
11296     }
11297   } else if (Name) {
11298     // If this is a named struct, check to see if there was a previous forward
11299     // declaration or definition.
11300     // FIXME: We're looking into outer scopes here, even when we
11301     // shouldn't be. Doing so can result in ambiguities that we
11302     // shouldn't be diagnosing.
11303     LookupName(Previous, S);
11304 
11305     // When declaring or defining a tag, ignore ambiguities introduced
11306     // by types using'ed into this scope.
11307     if (Previous.isAmbiguous() &&
11308         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
11309       LookupResult::Filter F = Previous.makeFilter();
11310       while (F.hasNext()) {
11311         NamedDecl *ND = F.next();
11312         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
11313           F.erase();
11314       }
11315       F.done();
11316     }
11317 
11318     // C++11 [namespace.memdef]p3:
11319     //   If the name in a friend declaration is neither qualified nor
11320     //   a template-id and the declaration is a function or an
11321     //   elaborated-type-specifier, the lookup to determine whether
11322     //   the entity has been previously declared shall not consider
11323     //   any scopes outside the innermost enclosing namespace.
11324     //
11325     // MSVC doesn't implement the above rule for types, so a friend tag
11326     // declaration may be a redeclaration of a type declared in an enclosing
11327     // scope.  They do implement this rule for friend functions.
11328     //
11329     // Does it matter that this should be by scope instead of by
11330     // semantic context?
11331     if (!Previous.empty() && TUK == TUK_Friend) {
11332       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
11333       LookupResult::Filter F = Previous.makeFilter();
11334       bool FriendSawTagOutsideEnclosingNamespace = false;
11335       while (F.hasNext()) {
11336         NamedDecl *ND = F.next();
11337         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11338         if (DC->isFileContext() &&
11339             !EnclosingNS->Encloses(ND->getDeclContext())) {
11340           if (getLangOpts().MSVCCompat)
11341             FriendSawTagOutsideEnclosingNamespace = true;
11342           else
11343             F.erase();
11344         }
11345       }
11346       F.done();
11347 
11348       // Diagnose this MSVC extension in the easy case where lookup would have
11349       // unambiguously found something outside the enclosing namespace.
11350       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
11351         NamedDecl *ND = Previous.getFoundDecl();
11352         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
11353             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
11354       }
11355     }
11356 
11357     // Note:  there used to be some attempt at recovery here.
11358     if (Previous.isAmbiguous())
11359       return nullptr;
11360 
11361     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
11362       // FIXME: This makes sure that we ignore the contexts associated
11363       // with C structs, unions, and enums when looking for a matching
11364       // tag declaration or definition. See the similar lookup tweak
11365       // in Sema::LookupName; is there a better way to deal with this?
11366       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
11367         SearchDC = SearchDC->getParent();
11368     }
11369   }
11370 
11371   if (Previous.isSingleResult() &&
11372       Previous.getFoundDecl()->isTemplateParameter()) {
11373     // Maybe we will complain about the shadowed template parameter.
11374     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
11375     // Just pretend that we didn't see the previous declaration.
11376     Previous.clear();
11377   }
11378 
11379   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
11380       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
11381     // This is a declaration of or a reference to "std::bad_alloc".
11382     isStdBadAlloc = true;
11383 
11384     if (Previous.empty() && StdBadAlloc) {
11385       // std::bad_alloc has been implicitly declared (but made invisible to
11386       // name lookup). Fill in this implicit declaration as the previous
11387       // declaration, so that the declarations get chained appropriately.
11388       Previous.addDecl(getStdBadAlloc());
11389     }
11390   }
11391 
11392   // If we didn't find a previous declaration, and this is a reference
11393   // (or friend reference), move to the correct scope.  In C++, we
11394   // also need to do a redeclaration lookup there, just in case
11395   // there's a shadow friend decl.
11396   if (Name && Previous.empty() &&
11397       (TUK == TUK_Reference || TUK == TUK_Friend)) {
11398     if (Invalid) goto CreateNewDecl;
11399     assert(SS.isEmpty());
11400 
11401     if (TUK == TUK_Reference) {
11402       // C++ [basic.scope.pdecl]p5:
11403       //   -- for an elaborated-type-specifier of the form
11404       //
11405       //          class-key identifier
11406       //
11407       //      if the elaborated-type-specifier is used in the
11408       //      decl-specifier-seq or parameter-declaration-clause of a
11409       //      function defined in namespace scope, the identifier is
11410       //      declared as a class-name in the namespace that contains
11411       //      the declaration; otherwise, except as a friend
11412       //      declaration, the identifier is declared in the smallest
11413       //      non-class, non-function-prototype scope that contains the
11414       //      declaration.
11415       //
11416       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
11417       // C structs and unions.
11418       //
11419       // It is an error in C++ to declare (rather than define) an enum
11420       // type, including via an elaborated type specifier.  We'll
11421       // diagnose that later; for now, declare the enum in the same
11422       // scope as we would have picked for any other tag type.
11423       //
11424       // GNU C also supports this behavior as part of its incomplete
11425       // enum types extension, while GNU C++ does not.
11426       //
11427       // Find the context where we'll be declaring the tag.
11428       // FIXME: We would like to maintain the current DeclContext as the
11429       // lexical context,
11430       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
11431         SearchDC = SearchDC->getParent();
11432 
11433       // Find the scope where we'll be declaring the tag.
11434       while (S->isClassScope() ||
11435              (getLangOpts().CPlusPlus &&
11436               S->isFunctionPrototypeScope()) ||
11437              ((S->getFlags() & Scope::DeclScope) == 0) ||
11438              (S->getEntity() && S->getEntity()->isTransparentContext()))
11439         S = S->getParent();
11440     } else {
11441       assert(TUK == TUK_Friend);
11442       // C++ [namespace.memdef]p3:
11443       //   If a friend declaration in a non-local class first declares a
11444       //   class or function, the friend class or function is a member of
11445       //   the innermost enclosing namespace.
11446       SearchDC = SearchDC->getEnclosingNamespaceContext();
11447     }
11448 
11449     // In C++, we need to do a redeclaration lookup to properly
11450     // diagnose some problems.
11451     if (getLangOpts().CPlusPlus) {
11452       Previous.setRedeclarationKind(ForRedeclaration);
11453       LookupQualifiedName(Previous, SearchDC);
11454     }
11455   }
11456 
11457   if (!Previous.empty()) {
11458     NamedDecl *PrevDecl = Previous.getFoundDecl();
11459     NamedDecl *DirectPrevDecl =
11460         getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
11461 
11462     // It's okay to have a tag decl in the same scope as a typedef
11463     // which hides a tag decl in the same scope.  Finding this
11464     // insanity with a redeclaration lookup can only actually happen
11465     // in C++.
11466     //
11467     // This is also okay for elaborated-type-specifiers, which is
11468     // technically forbidden by the current standard but which is
11469     // okay according to the likely resolution of an open issue;
11470     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
11471     if (getLangOpts().CPlusPlus) {
11472       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11473         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
11474           TagDecl *Tag = TT->getDecl();
11475           if (Tag->getDeclName() == Name &&
11476               Tag->getDeclContext()->getRedeclContext()
11477                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
11478             PrevDecl = Tag;
11479             Previous.clear();
11480             Previous.addDecl(Tag);
11481             Previous.resolveKind();
11482           }
11483         }
11484       }
11485     }
11486 
11487     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
11488       // If this is a use of a previous tag, or if the tag is already declared
11489       // in the same scope (so that the definition/declaration completes or
11490       // rementions the tag), reuse the decl.
11491       if (TUK == TUK_Reference || TUK == TUK_Friend ||
11492           isDeclInScope(DirectPrevDecl, SearchDC, S,
11493                         SS.isNotEmpty() || isExplicitSpecialization)) {
11494         // Make sure that this wasn't declared as an enum and now used as a
11495         // struct or something similar.
11496         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
11497                                           TUK == TUK_Definition, KWLoc,
11498                                           *Name)) {
11499           bool SafeToContinue
11500             = (PrevTagDecl->getTagKind() != TTK_Enum &&
11501                Kind != TTK_Enum);
11502           if (SafeToContinue)
11503             Diag(KWLoc, diag::err_use_with_wrong_tag)
11504               << Name
11505               << FixItHint::CreateReplacement(SourceRange(KWLoc),
11506                                               PrevTagDecl->getKindName());
11507           else
11508             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
11509           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
11510 
11511           if (SafeToContinue)
11512             Kind = PrevTagDecl->getTagKind();
11513           else {
11514             // Recover by making this an anonymous redefinition.
11515             Name = nullptr;
11516             Previous.clear();
11517             Invalid = true;
11518           }
11519         }
11520 
11521         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
11522           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
11523 
11524           // If this is an elaborated-type-specifier for a scoped enumeration,
11525           // the 'class' keyword is not necessary and not permitted.
11526           if (TUK == TUK_Reference || TUK == TUK_Friend) {
11527             if (ScopedEnum)
11528               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
11529                 << PrevEnum->isScoped()
11530                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
11531             return PrevTagDecl;
11532           }
11533 
11534           QualType EnumUnderlyingTy;
11535           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11536             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
11537           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
11538             EnumUnderlyingTy = QualType(T, 0);
11539 
11540           // All conflicts with previous declarations are recovered by
11541           // returning the previous declaration, unless this is a definition,
11542           // in which case we want the caller to bail out.
11543           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
11544                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
11545             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
11546         }
11547 
11548         // C++11 [class.mem]p1:
11549         //   A member shall not be declared twice in the member-specification,
11550         //   except that a nested class or member class template can be declared
11551         //   and then later defined.
11552         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
11553             S->isDeclScope(PrevDecl)) {
11554           Diag(NameLoc, diag::ext_member_redeclared);
11555           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
11556         }
11557 
11558         if (!Invalid) {
11559           // If this is a use, just return the declaration we found, unless
11560           // we have attributes.
11561 
11562           // FIXME: In the future, return a variant or some other clue
11563           // for the consumer of this Decl to know it doesn't own it.
11564           // For our current ASTs this shouldn't be a problem, but will
11565           // need to be changed with DeclGroups.
11566           if (!Attr &&
11567               ((TUK == TUK_Reference &&
11568                 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
11569                || TUK == TUK_Friend))
11570             return PrevTagDecl;
11571 
11572           // Diagnose attempts to redefine a tag.
11573           if (TUK == TUK_Definition) {
11574             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
11575               // If we're defining a specialization and the previous definition
11576               // is from an implicit instantiation, don't emit an error
11577               // here; we'll catch this in the general case below.
11578               bool IsExplicitSpecializationAfterInstantiation = false;
11579               if (isExplicitSpecialization) {
11580                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
11581                   IsExplicitSpecializationAfterInstantiation =
11582                     RD->getTemplateSpecializationKind() !=
11583                     TSK_ExplicitSpecialization;
11584                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
11585                   IsExplicitSpecializationAfterInstantiation =
11586                     ED->getTemplateSpecializationKind() !=
11587                     TSK_ExplicitSpecialization;
11588               }
11589 
11590               if (!IsExplicitSpecializationAfterInstantiation) {
11591                 // A redeclaration in function prototype scope in C isn't
11592                 // visible elsewhere, so merely issue a warning.
11593                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
11594                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
11595                 else
11596                   Diag(NameLoc, diag::err_redefinition) << Name;
11597                 Diag(Def->getLocation(), diag::note_previous_definition);
11598                 // If this is a redefinition, recover by making this
11599                 // struct be anonymous, which will make any later
11600                 // references get the previous definition.
11601                 Name = nullptr;
11602                 Previous.clear();
11603                 Invalid = true;
11604               }
11605             } else {
11606               // If the type is currently being defined, complain
11607               // about a nested redefinition.
11608               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
11609               if (TD->isBeingDefined()) {
11610                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
11611                 Diag(PrevTagDecl->getLocation(),
11612                      diag::note_previous_definition);
11613                 Name = nullptr;
11614                 Previous.clear();
11615                 Invalid = true;
11616               }
11617             }
11618 
11619             // Okay, this is definition of a previously declared or referenced
11620             // tag. We're going to create a new Decl for it.
11621           }
11622 
11623           // Okay, we're going to make a redeclaration.  If this is some kind
11624           // of reference, make sure we build the redeclaration in the same DC
11625           // as the original, and ignore the current access specifier.
11626           if (TUK == TUK_Friend || TUK == TUK_Reference) {
11627             SearchDC = PrevTagDecl->getDeclContext();
11628             AS = AS_none;
11629           }
11630         }
11631         // If we get here we have (another) forward declaration or we
11632         // have a definition.  Just create a new decl.
11633 
11634       } else {
11635         // If we get here, this is a definition of a new tag type in a nested
11636         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
11637         // new decl/type.  We set PrevDecl to NULL so that the entities
11638         // have distinct types.
11639         Previous.clear();
11640       }
11641       // If we get here, we're going to create a new Decl. If PrevDecl
11642       // is non-NULL, it's a definition of the tag declared by
11643       // PrevDecl. If it's NULL, we have a new definition.
11644 
11645 
11646     // Otherwise, PrevDecl is not a tag, but was found with tag
11647     // lookup.  This is only actually possible in C++, where a few
11648     // things like templates still live in the tag namespace.
11649     } else {
11650       // Use a better diagnostic if an elaborated-type-specifier
11651       // found the wrong kind of type on the first
11652       // (non-redeclaration) lookup.
11653       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
11654           !Previous.isForRedeclaration()) {
11655         unsigned Kind = 0;
11656         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11657         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11658         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11659         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
11660         Diag(PrevDecl->getLocation(), diag::note_declared_at);
11661         Invalid = true;
11662 
11663       // Otherwise, only diagnose if the declaration is in scope.
11664       } else if (!isDeclInScope(PrevDecl, SearchDC, S,
11665                                 SS.isNotEmpty() || isExplicitSpecialization)) {
11666         // do nothing
11667 
11668       // Diagnose implicit declarations introduced by elaborated types.
11669       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
11670         unsigned Kind = 0;
11671         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11672         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11673         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11674         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
11675         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11676         Invalid = true;
11677 
11678       // Otherwise it's a declaration.  Call out a particularly common
11679       // case here.
11680       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11681         unsigned Kind = 0;
11682         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
11683         Diag(NameLoc, diag::err_tag_definition_of_typedef)
11684           << Name << Kind << TND->getUnderlyingType();
11685         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11686         Invalid = true;
11687 
11688       // Otherwise, diagnose.
11689       } else {
11690         // The tag name clashes with something else in the target scope,
11691         // issue an error and recover by making this tag be anonymous.
11692         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
11693         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11694         Name = nullptr;
11695         Invalid = true;
11696       }
11697 
11698       // The existing declaration isn't relevant to us; we're in a
11699       // new scope, so clear out the previous declaration.
11700       Previous.clear();
11701     }
11702   }
11703 
11704 CreateNewDecl:
11705 
11706   TagDecl *PrevDecl = nullptr;
11707   if (Previous.isSingleResult())
11708     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
11709 
11710   // If there is an identifier, use the location of the identifier as the
11711   // location of the decl, otherwise use the location of the struct/union
11712   // keyword.
11713   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
11714 
11715   // Otherwise, create a new declaration. If there is a previous
11716   // declaration of the same entity, the two will be linked via
11717   // PrevDecl.
11718   TagDecl *New;
11719 
11720   bool IsForwardReference = false;
11721   if (Kind == TTK_Enum) {
11722     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11723     // enum X { A, B, C } D;    D should chain to X.
11724     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
11725                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
11726                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
11727     // If this is an undefined enum, warn.
11728     if (TUK != TUK_Definition && !Invalid) {
11729       TagDecl *Def;
11730       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
11731           cast<EnumDecl>(New)->isFixed()) {
11732         // C++0x: 7.2p2: opaque-enum-declaration.
11733         // Conflicts are diagnosed above. Do nothing.
11734       }
11735       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
11736         Diag(Loc, diag::ext_forward_ref_enum_def)
11737           << New;
11738         Diag(Def->getLocation(), diag::note_previous_definition);
11739       } else {
11740         unsigned DiagID = diag::ext_forward_ref_enum;
11741         if (getLangOpts().MSVCCompat)
11742           DiagID = diag::ext_ms_forward_ref_enum;
11743         else if (getLangOpts().CPlusPlus)
11744           DiagID = diag::err_forward_ref_enum;
11745         Diag(Loc, DiagID);
11746 
11747         // If this is a forward-declared reference to an enumeration, make a
11748         // note of it; we won't actually be introducing the declaration into
11749         // the declaration context.
11750         if (TUK == TUK_Reference)
11751           IsForwardReference = true;
11752       }
11753     }
11754 
11755     if (EnumUnderlying) {
11756       EnumDecl *ED = cast<EnumDecl>(New);
11757       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11758         ED->setIntegerTypeSourceInfo(TI);
11759       else
11760         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
11761       ED->setPromotionType(ED->getIntegerType());
11762     }
11763 
11764   } else {
11765     // struct/union/class
11766 
11767     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11768     // struct X { int A; } D;    D should chain to X.
11769     if (getLangOpts().CPlusPlus) {
11770       // FIXME: Look for a way to use RecordDecl for simple structs.
11771       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11772                                   cast_or_null<CXXRecordDecl>(PrevDecl));
11773 
11774       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
11775         StdBadAlloc = cast<CXXRecordDecl>(New);
11776     } else
11777       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11778                                cast_or_null<RecordDecl>(PrevDecl));
11779   }
11780 
11781   // C++11 [dcl.type]p3:
11782   //   A type-specifier-seq shall not define a class or enumeration [...].
11783   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11784     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11785       << Context.getTagDeclType(New);
11786     Invalid = true;
11787   }
11788 
11789   // Maybe add qualifier info.
11790   if (SS.isNotEmpty()) {
11791     if (SS.isSet()) {
11792       // If this is either a declaration or a definition, check the
11793       // nested-name-specifier against the current context. We don't do this
11794       // for explicit specializations, because they have similar checking
11795       // (with more specific diagnostics) in the call to
11796       // CheckMemberSpecialization, below.
11797       if (!isExplicitSpecialization &&
11798           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11799           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
11800         Invalid = true;
11801 
11802       New->setQualifierInfo(SS.getWithLocInContext(Context));
11803       if (TemplateParameterLists.size() > 0) {
11804         New->setTemplateParameterListsInfo(Context,
11805                                            TemplateParameterLists.size(),
11806                                            TemplateParameterLists.data());
11807       }
11808     }
11809     else
11810       Invalid = true;
11811   }
11812 
11813   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11814     // Add alignment attributes if necessary; these attributes are checked when
11815     // the ASTContext lays out the structure.
11816     //
11817     // It is important for implementing the correct semantics that this
11818     // happen here (in act on tag decl). The #pragma pack stack is
11819     // maintained as a result of parser callbacks which can occur at
11820     // many points during the parsing of a struct declaration (because
11821     // the #pragma tokens are effectively skipped over during the
11822     // parsing of the struct).
11823     if (TUK == TUK_Definition) {
11824       AddAlignmentAttributesForRecord(RD);
11825       AddMsStructLayoutForRecord(RD);
11826     }
11827   }
11828 
11829   if (ModulePrivateLoc.isValid()) {
11830     if (isExplicitSpecialization)
11831       Diag(New->getLocation(), diag::err_module_private_specialization)
11832         << 2
11833         << FixItHint::CreateRemoval(ModulePrivateLoc);
11834     // __module_private__ does not apply to local classes. However, we only
11835     // diagnose this as an error when the declaration specifiers are
11836     // freestanding. Here, we just ignore the __module_private__.
11837     else if (!SearchDC->isFunctionOrMethod())
11838       New->setModulePrivate();
11839   }
11840 
11841   // If this is a specialization of a member class (of a class template),
11842   // check the specialization.
11843   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
11844     Invalid = true;
11845 
11846   // If we're declaring or defining a tag in function prototype scope in C,
11847   // note that this type can only be used within the function and add it to
11848   // the list of decls to inject into the function definition scope.
11849   if ((Name || Kind == TTK_Enum) &&
11850       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
11851     if (getLangOpts().CPlusPlus) {
11852       // C++ [dcl.fct]p6:
11853       //   Types shall not be defined in return or parameter types.
11854       if (TUK == TUK_Definition && !IsTypeSpecifier) {
11855         Diag(Loc, diag::err_type_defined_in_param_type)
11856             << Name;
11857         Invalid = true;
11858       }
11859     } else {
11860       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11861     }
11862     DeclsInPrototypeScope.push_back(New);
11863   }
11864 
11865   if (Invalid)
11866     New->setInvalidDecl();
11867 
11868   if (Attr)
11869     ProcessDeclAttributeList(S, New, Attr);
11870 
11871   // Set the lexical context. If the tag has a C++ scope specifier, the
11872   // lexical context will be different from the semantic context.
11873   New->setLexicalDeclContext(CurContext);
11874 
11875   // Mark this as a friend decl if applicable.
11876   // In Microsoft mode, a friend declaration also acts as a forward
11877   // declaration so we always pass true to setObjectOfFriendDecl to make
11878   // the tag name visible.
11879   if (TUK == TUK_Friend)
11880     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
11881 
11882   // Set the access specifier.
11883   if (!Invalid && SearchDC->isRecord())
11884     SetMemberAccessSpecifier(New, PrevDecl, AS);
11885 
11886   if (TUK == TUK_Definition)
11887     New->startDefinition();
11888 
11889   // If this has an identifier, add it to the scope stack.
11890   if (TUK == TUK_Friend) {
11891     // We might be replacing an existing declaration in the lookup tables;
11892     // if so, borrow its access specifier.
11893     if (PrevDecl)
11894       New->setAccess(PrevDecl->getAccess());
11895 
11896     DeclContext *DC = New->getDeclContext()->getRedeclContext();
11897     DC->makeDeclVisibleInContext(New);
11898     if (Name) // can be null along some error paths
11899       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11900         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
11901   } else if (Name) {
11902     S = getNonFieldDeclScope(S);
11903     PushOnScopeChains(New, S, !IsForwardReference);
11904     if (IsForwardReference)
11905       SearchDC->makeDeclVisibleInContext(New);
11906 
11907   } else {
11908     CurContext->addDecl(New);
11909   }
11910 
11911   // If this is the C FILE type, notify the AST context.
11912   if (IdentifierInfo *II = New->getIdentifier())
11913     if (!New->isInvalidDecl() &&
11914         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
11915         II->isStr("FILE"))
11916       Context.setFILEDecl(New);
11917 
11918   if (PrevDecl)
11919     mergeDeclAttributes(New, PrevDecl);
11920 
11921   // If there's a #pragma GCC visibility in scope, set the visibility of this
11922   // record.
11923   AddPushedVisibilityAttribute(New);
11924 
11925   OwnedDecl = true;
11926   // In C++, don't return an invalid declaration. We can't recover well from
11927   // the cases where we make the type anonymous.
11928   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
11929 }
11930 
11931 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
11932   AdjustDeclIfTemplate(TagD);
11933   TagDecl *Tag = cast<TagDecl>(TagD);
11934 
11935   // Enter the tag context.
11936   PushDeclContext(S, Tag);
11937 
11938   ActOnDocumentableDecl(TagD);
11939 
11940   // If there's a #pragma GCC visibility in scope, set the visibility of this
11941   // record.
11942   AddPushedVisibilityAttribute(Tag);
11943 }
11944 
11945 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
11946   assert(isa<ObjCContainerDecl>(IDecl) &&
11947          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11948   DeclContext *OCD = cast<DeclContext>(IDecl);
11949   assert(getContainingDC(OCD) == CurContext &&
11950       "The next DeclContext should be lexically contained in the current one.");
11951   CurContext = OCD;
11952   return IDecl;
11953 }
11954 
11955 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
11956                                            SourceLocation FinalLoc,
11957                                            bool IsFinalSpelledSealed,
11958                                            SourceLocation LBraceLoc) {
11959   AdjustDeclIfTemplate(TagD);
11960   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
11961 
11962   FieldCollector->StartClass();
11963 
11964   if (!Record->getIdentifier())
11965     return;
11966 
11967   if (FinalLoc.isValid())
11968     Record->addAttr(new (Context)
11969                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11970 
11971   // C++ [class]p2:
11972   //   [...] The class-name is also inserted into the scope of the
11973   //   class itself; this is known as the injected-class-name. For
11974   //   purposes of access checking, the injected-class-name is treated
11975   //   as if it were a public member name.
11976   CXXRecordDecl *InjectedClassName
11977     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11978                             Record->getLocStart(), Record->getLocation(),
11979                             Record->getIdentifier(),
11980                             /*PrevDecl=*/nullptr,
11981                             /*DelayTypeCreation=*/true);
11982   Context.getTypeDeclType(InjectedClassName, Record);
11983   InjectedClassName->setImplicit();
11984   InjectedClassName->setAccess(AS_public);
11985   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11986       InjectedClassName->setDescribedClassTemplate(Template);
11987   PushOnScopeChains(InjectedClassName, S);
11988   assert(InjectedClassName->isInjectedClassName() &&
11989          "Broken injected-class-name");
11990 }
11991 
11992 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
11993                                     SourceLocation RBraceLoc) {
11994   AdjustDeclIfTemplate(TagD);
11995   TagDecl *Tag = cast<TagDecl>(TagD);
11996   Tag->setRBraceLoc(RBraceLoc);
11997 
11998   // Make sure we "complete" the definition even it is invalid.
11999   if (Tag->isBeingDefined()) {
12000     assert(Tag->isInvalidDecl() && "We should already have completed it");
12001     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12002       RD->completeDefinition();
12003   }
12004 
12005   if (isa<CXXRecordDecl>(Tag))
12006     FieldCollector->FinishClass();
12007 
12008   // Exit this scope of this tag's definition.
12009   PopDeclContext();
12010 
12011   if (getCurLexicalContext()->isObjCContainer() &&
12012       Tag->getDeclContext()->isFileContext())
12013     Tag->setTopLevelDeclInObjCContainer();
12014 
12015   // Notify the consumer that we've defined a tag.
12016   if (!Tag->isInvalidDecl())
12017     Consumer.HandleTagDeclDefinition(Tag);
12018 }
12019 
12020 void Sema::ActOnObjCContainerFinishDefinition() {
12021   // Exit this scope of this interface definition.
12022   PopDeclContext();
12023 }
12024 
12025 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12026   assert(DC == CurContext && "Mismatch of container contexts");
12027   OriginalLexicalContext = DC;
12028   ActOnObjCContainerFinishDefinition();
12029 }
12030 
12031 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12032   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12033   OriginalLexicalContext = nullptr;
12034 }
12035 
12036 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12037   AdjustDeclIfTemplate(TagD);
12038   TagDecl *Tag = cast<TagDecl>(TagD);
12039   Tag->setInvalidDecl();
12040 
12041   // Make sure we "complete" the definition even it is invalid.
12042   if (Tag->isBeingDefined()) {
12043     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12044       RD->completeDefinition();
12045   }
12046 
12047   // We're undoing ActOnTagStartDefinition here, not
12048   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12049   // the FieldCollector.
12050 
12051   PopDeclContext();
12052 }
12053 
12054 // Note that FieldName may be null for anonymous bitfields.
12055 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12056                                 IdentifierInfo *FieldName,
12057                                 QualType FieldTy, bool IsMsStruct,
12058                                 Expr *BitWidth, bool *ZeroWidth) {
12059   // Default to true; that shouldn't confuse checks for emptiness
12060   if (ZeroWidth)
12061     *ZeroWidth = true;
12062 
12063   // C99 6.7.2.1p4 - verify the field type.
12064   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12065   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12066     // Handle incomplete types with specific error.
12067     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12068       return ExprError();
12069     if (FieldName)
12070       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12071         << FieldName << FieldTy << BitWidth->getSourceRange();
12072     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12073       << FieldTy << BitWidth->getSourceRange();
12074   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12075                                              UPPC_BitFieldWidth))
12076     return ExprError();
12077 
12078   // If the bit-width is type- or value-dependent, don't try to check
12079   // it now.
12080   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12081     return BitWidth;
12082 
12083   llvm::APSInt Value;
12084   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12085   if (ICE.isInvalid())
12086     return ICE;
12087   BitWidth = ICE.get();
12088 
12089   if (Value != 0 && ZeroWidth)
12090     *ZeroWidth = false;
12091 
12092   // Zero-width bitfield is ok for anonymous field.
12093   if (Value == 0 && FieldName)
12094     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12095 
12096   if (Value.isSigned() && Value.isNegative()) {
12097     if (FieldName)
12098       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12099                << FieldName << Value.toString(10);
12100     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12101       << Value.toString(10);
12102   }
12103 
12104   if (!FieldTy->isDependentType()) {
12105     uint64_t TypeSize = Context.getTypeSize(FieldTy);
12106     if (Value.getZExtValue() > TypeSize) {
12107       if (!getLangOpts().CPlusPlus || IsMsStruct ||
12108           Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12109         if (FieldName)
12110           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
12111             << FieldName << (unsigned)Value.getZExtValue()
12112             << (unsigned)TypeSize;
12113 
12114         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
12115           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12116       }
12117 
12118       if (FieldName)
12119         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
12120           << FieldName << (unsigned)Value.getZExtValue()
12121           << (unsigned)TypeSize;
12122       else
12123         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
12124           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12125     }
12126   }
12127 
12128   return BitWidth;
12129 }
12130 
12131 /// ActOnField - Each field of a C struct/union is passed into this in order
12132 /// to create a FieldDecl object for it.
12133 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
12134                        Declarator &D, Expr *BitfieldWidth) {
12135   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12136                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12137                                /*InitStyle=*/ICIS_NoInit, AS_public);
12138   return Res;
12139 }
12140 
12141 /// HandleField - Analyze a field of a C struct or a C++ data member.
12142 ///
12143 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12144                              SourceLocation DeclStart,
12145                              Declarator &D, Expr *BitWidth,
12146                              InClassInitStyle InitStyle,
12147                              AccessSpecifier AS) {
12148   IdentifierInfo *II = D.getIdentifier();
12149   SourceLocation Loc = DeclStart;
12150   if (II) Loc = D.getIdentifierLoc();
12151 
12152   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12153   QualType T = TInfo->getType();
12154   if (getLangOpts().CPlusPlus) {
12155     CheckExtraCXXDefaultArguments(D);
12156 
12157     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12158                                         UPPC_DataMemberType)) {
12159       D.setInvalidType();
12160       T = Context.IntTy;
12161       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12162     }
12163   }
12164 
12165   // TR 18037 does not allow fields to be declared with address spaces.
12166   if (T.getQualifiers().hasAddressSpace()) {
12167     Diag(Loc, diag::err_field_with_address_space);
12168     D.setInvalidType();
12169   }
12170 
12171   // OpenCL 1.2 spec, s6.9 r:
12172   // The event type cannot be used to declare a structure or union field.
12173   if (LangOpts.OpenCL && T->isEventT()) {
12174     Diag(Loc, diag::err_event_t_struct_field);
12175     D.setInvalidType();
12176   }
12177 
12178   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12179 
12180   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12181     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12182          diag::err_invalid_thread)
12183       << DeclSpec::getSpecifierName(TSCS);
12184 
12185   // Check to see if this name was declared as a member previously
12186   NamedDecl *PrevDecl = nullptr;
12187   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12188   LookupName(Previous, S);
12189   switch (Previous.getResultKind()) {
12190     case LookupResult::Found:
12191     case LookupResult::FoundUnresolvedValue:
12192       PrevDecl = Previous.getAsSingle<NamedDecl>();
12193       break;
12194 
12195     case LookupResult::FoundOverloaded:
12196       PrevDecl = Previous.getRepresentativeDecl();
12197       break;
12198 
12199     case LookupResult::NotFound:
12200     case LookupResult::NotFoundInCurrentInstantiation:
12201     case LookupResult::Ambiguous:
12202       break;
12203   }
12204   Previous.suppressDiagnostics();
12205 
12206   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12207     // Maybe we will complain about the shadowed template parameter.
12208     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12209     // Just pretend that we didn't see the previous declaration.
12210     PrevDecl = nullptr;
12211   }
12212 
12213   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12214     PrevDecl = nullptr;
12215 
12216   bool Mutable
12217     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
12218   SourceLocation TSSL = D.getLocStart();
12219   FieldDecl *NewFD
12220     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
12221                      TSSL, AS, PrevDecl, &D);
12222 
12223   if (NewFD->isInvalidDecl())
12224     Record->setInvalidDecl();
12225 
12226   if (D.getDeclSpec().isModulePrivateSpecified())
12227     NewFD->setModulePrivate();
12228 
12229   if (NewFD->isInvalidDecl() && PrevDecl) {
12230     // Don't introduce NewFD into scope; there's already something
12231     // with the same name in the same scope.
12232   } else if (II) {
12233     PushOnScopeChains(NewFD, S);
12234   } else
12235     Record->addDecl(NewFD);
12236 
12237   return NewFD;
12238 }
12239 
12240 /// \brief Build a new FieldDecl and check its well-formedness.
12241 ///
12242 /// This routine builds a new FieldDecl given the fields name, type,
12243 /// record, etc. \p PrevDecl should refer to any previous declaration
12244 /// with the same name and in the same scope as the field to be
12245 /// created.
12246 ///
12247 /// \returns a new FieldDecl.
12248 ///
12249 /// \todo The Declarator argument is a hack. It will be removed once
12250 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
12251                                 TypeSourceInfo *TInfo,
12252                                 RecordDecl *Record, SourceLocation Loc,
12253                                 bool Mutable, Expr *BitWidth,
12254                                 InClassInitStyle InitStyle,
12255                                 SourceLocation TSSL,
12256                                 AccessSpecifier AS, NamedDecl *PrevDecl,
12257                                 Declarator *D) {
12258   IdentifierInfo *II = Name.getAsIdentifierInfo();
12259   bool InvalidDecl = false;
12260   if (D) InvalidDecl = D->isInvalidType();
12261 
12262   // If we receive a broken type, recover by assuming 'int' and
12263   // marking this declaration as invalid.
12264   if (T.isNull()) {
12265     InvalidDecl = true;
12266     T = Context.IntTy;
12267   }
12268 
12269   QualType EltTy = Context.getBaseElementType(T);
12270   if (!EltTy->isDependentType()) {
12271     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
12272       // Fields of incomplete type force their record to be invalid.
12273       Record->setInvalidDecl();
12274       InvalidDecl = true;
12275     } else {
12276       NamedDecl *Def;
12277       EltTy->isIncompleteType(&Def);
12278       if (Def && Def->isInvalidDecl()) {
12279         Record->setInvalidDecl();
12280         InvalidDecl = true;
12281       }
12282     }
12283   }
12284 
12285   // OpenCL v1.2 s6.9.c: bitfields are not supported.
12286   if (BitWidth && getLangOpts().OpenCL) {
12287     Diag(Loc, diag::err_opencl_bitfields);
12288     InvalidDecl = true;
12289   }
12290 
12291   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12292   // than a variably modified type.
12293   if (!InvalidDecl && T->isVariablyModifiedType()) {
12294     bool SizeIsNegative;
12295     llvm::APSInt Oversized;
12296 
12297     TypeSourceInfo *FixedTInfo =
12298       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
12299                                                     SizeIsNegative,
12300                                                     Oversized);
12301     if (FixedTInfo) {
12302       Diag(Loc, diag::warn_illegal_constant_array_size);
12303       TInfo = FixedTInfo;
12304       T = FixedTInfo->getType();
12305     } else {
12306       if (SizeIsNegative)
12307         Diag(Loc, diag::err_typecheck_negative_array_size);
12308       else if (Oversized.getBoolValue())
12309         Diag(Loc, diag::err_array_too_large)
12310           << Oversized.toString(10);
12311       else
12312         Diag(Loc, diag::err_typecheck_field_variable_size);
12313       InvalidDecl = true;
12314     }
12315   }
12316 
12317   // Fields can not have abstract class types
12318   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
12319                                              diag::err_abstract_type_in_decl,
12320                                              AbstractFieldType))
12321     InvalidDecl = true;
12322 
12323   bool ZeroWidth = false;
12324   // If this is declared as a bit-field, check the bit-field.
12325   if (!InvalidDecl && BitWidth) {
12326     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
12327                               &ZeroWidth).get();
12328     if (!BitWidth) {
12329       InvalidDecl = true;
12330       BitWidth = nullptr;
12331       ZeroWidth = false;
12332     }
12333   }
12334 
12335   // Check that 'mutable' is consistent with the type of the declaration.
12336   if (!InvalidDecl && Mutable) {
12337     unsigned DiagID = 0;
12338     if (T->isReferenceType())
12339       DiagID = diag::err_mutable_reference;
12340     else if (T.isConstQualified())
12341       DiagID = diag::err_mutable_const;
12342 
12343     if (DiagID) {
12344       SourceLocation ErrLoc = Loc;
12345       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
12346         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
12347       Diag(ErrLoc, DiagID);
12348       Mutable = false;
12349       InvalidDecl = true;
12350     }
12351   }
12352 
12353   // C++11 [class.union]p8 (DR1460):
12354   //   At most one variant member of a union may have a
12355   //   brace-or-equal-initializer.
12356   if (InitStyle != ICIS_NoInit)
12357     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
12358 
12359   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
12360                                        BitWidth, Mutable, InitStyle);
12361   if (InvalidDecl)
12362     NewFD->setInvalidDecl();
12363 
12364   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
12365     Diag(Loc, diag::err_duplicate_member) << II;
12366     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12367     NewFD->setInvalidDecl();
12368   }
12369 
12370   if (!InvalidDecl && getLangOpts().CPlusPlus) {
12371     if (Record->isUnion()) {
12372       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12373         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
12374         if (RDecl->getDefinition()) {
12375           // C++ [class.union]p1: An object of a class with a non-trivial
12376           // constructor, a non-trivial copy constructor, a non-trivial
12377           // destructor, or a non-trivial copy assignment operator
12378           // cannot be a member of a union, nor can an array of such
12379           // objects.
12380           if (CheckNontrivialField(NewFD))
12381             NewFD->setInvalidDecl();
12382         }
12383       }
12384 
12385       // C++ [class.union]p1: If a union contains a member of reference type,
12386       // the program is ill-formed, except when compiling with MSVC extensions
12387       // enabled.
12388       if (EltTy->isReferenceType()) {
12389         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
12390                                     diag::ext_union_member_of_reference_type :
12391                                     diag::err_union_member_of_reference_type)
12392           << NewFD->getDeclName() << EltTy;
12393         if (!getLangOpts().MicrosoftExt)
12394           NewFD->setInvalidDecl();
12395       }
12396     }
12397   }
12398 
12399   // FIXME: We need to pass in the attributes given an AST
12400   // representation, not a parser representation.
12401   if (D) {
12402     // FIXME: The current scope is almost... but not entirely... correct here.
12403     ProcessDeclAttributes(getCurScope(), NewFD, *D);
12404 
12405     if (NewFD->hasAttrs())
12406       CheckAlignasUnderalignment(NewFD);
12407   }
12408 
12409   // In auto-retain/release, infer strong retension for fields of
12410   // retainable type.
12411   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
12412     NewFD->setInvalidDecl();
12413 
12414   if (T.isObjCGCWeak())
12415     Diag(Loc, diag::warn_attribute_weak_on_field);
12416 
12417   NewFD->setAccess(AS);
12418   return NewFD;
12419 }
12420 
12421 bool Sema::CheckNontrivialField(FieldDecl *FD) {
12422   assert(FD);
12423   assert(getLangOpts().CPlusPlus && "valid check only for C++");
12424 
12425   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
12426     return false;
12427 
12428   QualType EltTy = Context.getBaseElementType(FD->getType());
12429   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12430     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
12431     if (RDecl->getDefinition()) {
12432       // We check for copy constructors before constructors
12433       // because otherwise we'll never get complaints about
12434       // copy constructors.
12435 
12436       CXXSpecialMember member = CXXInvalid;
12437       // We're required to check for any non-trivial constructors. Since the
12438       // implicit default constructor is suppressed if there are any
12439       // user-declared constructors, we just need to check that there is a
12440       // trivial default constructor and a trivial copy constructor. (We don't
12441       // worry about move constructors here, since this is a C++98 check.)
12442       if (RDecl->hasNonTrivialCopyConstructor())
12443         member = CXXCopyConstructor;
12444       else if (!RDecl->hasTrivialDefaultConstructor())
12445         member = CXXDefaultConstructor;
12446       else if (RDecl->hasNonTrivialCopyAssignment())
12447         member = CXXCopyAssignment;
12448       else if (RDecl->hasNonTrivialDestructor())
12449         member = CXXDestructor;
12450 
12451       if (member != CXXInvalid) {
12452         if (!getLangOpts().CPlusPlus11 &&
12453             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
12454           // Objective-C++ ARC: it is an error to have a non-trivial field of
12455           // a union. However, system headers in Objective-C programs
12456           // occasionally have Objective-C lifetime objects within unions,
12457           // and rather than cause the program to fail, we make those
12458           // members unavailable.
12459           SourceLocation Loc = FD->getLocation();
12460           if (getSourceManager().isInSystemHeader(Loc)) {
12461             if (!FD->hasAttr<UnavailableAttr>())
12462               FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12463                                   "this system field has retaining ownership",
12464                                   Loc));
12465             return false;
12466           }
12467         }
12468 
12469         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
12470                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
12471                diag::err_illegal_union_or_anon_struct_member)
12472           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
12473         DiagnoseNontrivial(RDecl, member);
12474         return !getLangOpts().CPlusPlus11;
12475       }
12476     }
12477   }
12478 
12479   return false;
12480 }
12481 
12482 /// TranslateIvarVisibility - Translate visibility from a token ID to an
12483 ///  AST enum value.
12484 static ObjCIvarDecl::AccessControl
12485 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
12486   switch (ivarVisibility) {
12487   default: llvm_unreachable("Unknown visitibility kind");
12488   case tok::objc_private: return ObjCIvarDecl::Private;
12489   case tok::objc_public: return ObjCIvarDecl::Public;
12490   case tok::objc_protected: return ObjCIvarDecl::Protected;
12491   case tok::objc_package: return ObjCIvarDecl::Package;
12492   }
12493 }
12494 
12495 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
12496 /// in order to create an IvarDecl object for it.
12497 Decl *Sema::ActOnIvar(Scope *S,
12498                                 SourceLocation DeclStart,
12499                                 Declarator &D, Expr *BitfieldWidth,
12500                                 tok::ObjCKeywordKind Visibility) {
12501 
12502   IdentifierInfo *II = D.getIdentifier();
12503   Expr *BitWidth = (Expr*)BitfieldWidth;
12504   SourceLocation Loc = DeclStart;
12505   if (II) Loc = D.getIdentifierLoc();
12506 
12507   // FIXME: Unnamed fields can be handled in various different ways, for
12508   // example, unnamed unions inject all members into the struct namespace!
12509 
12510   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12511   QualType T = TInfo->getType();
12512 
12513   if (BitWidth) {
12514     // 6.7.2.1p3, 6.7.2.1p4
12515     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
12516     if (!BitWidth)
12517       D.setInvalidType();
12518   } else {
12519     // Not a bitfield.
12520 
12521     // validate II.
12522 
12523   }
12524   if (T->isReferenceType()) {
12525     Diag(Loc, diag::err_ivar_reference_type);
12526     D.setInvalidType();
12527   }
12528   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12529   // than a variably modified type.
12530   else if (T->isVariablyModifiedType()) {
12531     Diag(Loc, diag::err_typecheck_ivar_variable_size);
12532     D.setInvalidType();
12533   }
12534 
12535   // Get the visibility (access control) for this ivar.
12536   ObjCIvarDecl::AccessControl ac =
12537     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
12538                                         : ObjCIvarDecl::None;
12539   // Must set ivar's DeclContext to its enclosing interface.
12540   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
12541   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
12542     return nullptr;
12543   ObjCContainerDecl *EnclosingContext;
12544   if (ObjCImplementationDecl *IMPDecl =
12545       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12546     if (LangOpts.ObjCRuntime.isFragile()) {
12547     // Case of ivar declared in an implementation. Context is that of its class.
12548       EnclosingContext = IMPDecl->getClassInterface();
12549       assert(EnclosingContext && "Implementation has no class interface!");
12550     }
12551     else
12552       EnclosingContext = EnclosingDecl;
12553   } else {
12554     if (ObjCCategoryDecl *CDecl =
12555         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12556       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
12557         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
12558         return nullptr;
12559       }
12560     }
12561     EnclosingContext = EnclosingDecl;
12562   }
12563 
12564   // Construct the decl.
12565   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
12566                                              DeclStart, Loc, II, T,
12567                                              TInfo, ac, (Expr *)BitfieldWidth);
12568 
12569   if (II) {
12570     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
12571                                            ForRedeclaration);
12572     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
12573         && !isa<TagDecl>(PrevDecl)) {
12574       Diag(Loc, diag::err_duplicate_member) << II;
12575       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12576       NewID->setInvalidDecl();
12577     }
12578   }
12579 
12580   // Process attributes attached to the ivar.
12581   ProcessDeclAttributes(S, NewID, D);
12582 
12583   if (D.isInvalidType())
12584     NewID->setInvalidDecl();
12585 
12586   // In ARC, infer 'retaining' for ivars of retainable type.
12587   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
12588     NewID->setInvalidDecl();
12589 
12590   if (D.getDeclSpec().isModulePrivateSpecified())
12591     NewID->setModulePrivate();
12592 
12593   if (II) {
12594     // FIXME: When interfaces are DeclContexts, we'll need to add
12595     // these to the interface.
12596     S->AddDecl(NewID);
12597     IdResolver.AddDecl(NewID);
12598   }
12599 
12600   if (LangOpts.ObjCRuntime.isNonFragile() &&
12601       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
12602     Diag(Loc, diag::warn_ivars_in_interface);
12603 
12604   return NewID;
12605 }
12606 
12607 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
12608 /// class and class extensions. For every class \@interface and class
12609 /// extension \@interface, if the last ivar is a bitfield of any type,
12610 /// then add an implicit `char :0` ivar to the end of that interface.
12611 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
12612                              SmallVectorImpl<Decl *> &AllIvarDecls) {
12613   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
12614     return;
12615 
12616   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
12617   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
12618 
12619   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
12620     return;
12621   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
12622   if (!ID) {
12623     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
12624       if (!CD->IsClassExtension())
12625         return;
12626     }
12627     // No need to add this to end of @implementation.
12628     else
12629       return;
12630   }
12631   // All conditions are met. Add a new bitfield to the tail end of ivars.
12632   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
12633   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
12634 
12635   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
12636                               DeclLoc, DeclLoc, nullptr,
12637                               Context.CharTy,
12638                               Context.getTrivialTypeSourceInfo(Context.CharTy,
12639                                                                DeclLoc),
12640                               ObjCIvarDecl::Private, BW,
12641                               true);
12642   AllIvarDecls.push_back(Ivar);
12643 }
12644 
12645 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
12646                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
12647                        SourceLocation RBrac, AttributeList *Attr) {
12648   assert(EnclosingDecl && "missing record or interface decl");
12649 
12650   // If this is an Objective-C @implementation or category and we have
12651   // new fields here we should reset the layout of the interface since
12652   // it will now change.
12653   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
12654     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
12655     switch (DC->getKind()) {
12656     default: break;
12657     case Decl::ObjCCategory:
12658       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
12659       break;
12660     case Decl::ObjCImplementation:
12661       Context.
12662         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
12663       break;
12664     }
12665   }
12666 
12667   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
12668 
12669   // Start counting up the number of named members; make sure to include
12670   // members of anonymous structs and unions in the total.
12671   unsigned NumNamedMembers = 0;
12672   if (Record) {
12673     for (const auto *I : Record->decls()) {
12674       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
12675         if (IFD->getDeclName())
12676           ++NumNamedMembers;
12677     }
12678   }
12679 
12680   // Verify that all the fields are okay.
12681   SmallVector<FieldDecl*, 32> RecFields;
12682 
12683   bool ARCErrReported = false;
12684   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
12685        i != end; ++i) {
12686     FieldDecl *FD = cast<FieldDecl>(*i);
12687 
12688     // Get the type for the field.
12689     const Type *FDTy = FD->getType().getTypePtr();
12690 
12691     if (!FD->isAnonymousStructOrUnion()) {
12692       // Remember all fields written by the user.
12693       RecFields.push_back(FD);
12694     }
12695 
12696     // If the field is already invalid for some reason, don't emit more
12697     // diagnostics about it.
12698     if (FD->isInvalidDecl()) {
12699       EnclosingDecl->setInvalidDecl();
12700       continue;
12701     }
12702 
12703     // C99 6.7.2.1p2:
12704     //   A structure or union shall not contain a member with
12705     //   incomplete or function type (hence, a structure shall not
12706     //   contain an instance of itself, but may contain a pointer to
12707     //   an instance of itself), except that the last member of a
12708     //   structure with more than one named member may have incomplete
12709     //   array type; such a structure (and any union containing,
12710     //   possibly recursively, a member that is such a structure)
12711     //   shall not be a member of a structure or an element of an
12712     //   array.
12713     if (FDTy->isFunctionType()) {
12714       // Field declared as a function.
12715       Diag(FD->getLocation(), diag::err_field_declared_as_function)
12716         << FD->getDeclName();
12717       FD->setInvalidDecl();
12718       EnclosingDecl->setInvalidDecl();
12719       continue;
12720     } else if (FDTy->isIncompleteArrayType() && Record &&
12721                ((i + 1 == Fields.end() && !Record->isUnion()) ||
12722                 ((getLangOpts().MicrosoftExt ||
12723                   getLangOpts().CPlusPlus) &&
12724                  (i + 1 == Fields.end() || Record->isUnion())))) {
12725       // Flexible array member.
12726       // Microsoft and g++ is more permissive regarding flexible array.
12727       // It will accept flexible array in union and also
12728       // as the sole element of a struct/class.
12729       unsigned DiagID = 0;
12730       if (Record->isUnion())
12731         DiagID = getLangOpts().MicrosoftExt
12732                      ? diag::ext_flexible_array_union_ms
12733                      : getLangOpts().CPlusPlus
12734                            ? diag::ext_flexible_array_union_gnu
12735                            : diag::err_flexible_array_union;
12736       else if (Fields.size() == 1)
12737         DiagID = getLangOpts().MicrosoftExt
12738                      ? diag::ext_flexible_array_empty_aggregate_ms
12739                      : getLangOpts().CPlusPlus
12740                            ? diag::ext_flexible_array_empty_aggregate_gnu
12741                            : NumNamedMembers < 1
12742                                  ? diag::err_flexible_array_empty_aggregate
12743                                  : 0;
12744 
12745       if (DiagID)
12746         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
12747                                         << Record->getTagKind();
12748       // While the layout of types that contain virtual bases is not specified
12749       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
12750       // virtual bases after the derived members.  This would make a flexible
12751       // array member declared at the end of an object not adjacent to the end
12752       // of the type.
12753       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
12754         if (RD->getNumVBases() != 0)
12755           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
12756             << FD->getDeclName() << Record->getTagKind();
12757       if (!getLangOpts().C99)
12758         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
12759           << FD->getDeclName() << Record->getTagKind();
12760 
12761       // If the element type has a non-trivial destructor, we would not
12762       // implicitly destroy the elements, so disallow it for now.
12763       //
12764       // FIXME: GCC allows this. We should probably either implicitly delete
12765       // the destructor of the containing class, or just allow this.
12766       QualType BaseElem = Context.getBaseElementType(FD->getType());
12767       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
12768         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
12769           << FD->getDeclName() << FD->getType();
12770         FD->setInvalidDecl();
12771         EnclosingDecl->setInvalidDecl();
12772         continue;
12773       }
12774       // Okay, we have a legal flexible array member at the end of the struct.
12775       Record->setHasFlexibleArrayMember(true);
12776     } else if (!FDTy->isDependentType() &&
12777                RequireCompleteType(FD->getLocation(), FD->getType(),
12778                                    diag::err_field_incomplete)) {
12779       // Incomplete type
12780       FD->setInvalidDecl();
12781       EnclosingDecl->setInvalidDecl();
12782       continue;
12783     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
12784       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
12785         // A type which contains a flexible array member is considered to be a
12786         // flexible array member.
12787         Record->setHasFlexibleArrayMember(true);
12788         if (!Record->isUnion()) {
12789           // If this is a struct/class and this is not the last element, reject
12790           // it.  Note that GCC supports variable sized arrays in the middle of
12791           // structures.
12792           if (i + 1 != Fields.end())
12793             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
12794               << FD->getDeclName() << FD->getType();
12795           else {
12796             // We support flexible arrays at the end of structs in
12797             // other structs as an extension.
12798             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12799               << FD->getDeclName();
12800           }
12801         }
12802       }
12803       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12804           RequireNonAbstractType(FD->getLocation(), FD->getType(),
12805                                  diag::err_abstract_type_in_decl,
12806                                  AbstractIvarType)) {
12807         // Ivars can not have abstract class types
12808         FD->setInvalidDecl();
12809       }
12810       if (Record && FDTTy->getDecl()->hasObjectMember())
12811         Record->setHasObjectMember(true);
12812       if (Record && FDTTy->getDecl()->hasVolatileMember())
12813         Record->setHasVolatileMember(true);
12814     } else if (FDTy->isObjCObjectType()) {
12815       /// A field cannot be an Objective-c object
12816       Diag(FD->getLocation(), diag::err_statically_allocated_object)
12817         << FixItHint::CreateInsertion(FD->getLocation(), "*");
12818       QualType T = Context.getObjCObjectPointerType(FD->getType());
12819       FD->setType(T);
12820     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12821                (!getLangOpts().CPlusPlus || Record->isUnion())) {
12822       // It's an error in ARC if a field has lifetime.
12823       // We don't want to report this in a system header, though,
12824       // so we just make the field unavailable.
12825       // FIXME: that's really not sufficient; we need to make the type
12826       // itself invalid to, say, initialize or copy.
12827       QualType T = FD->getType();
12828       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12829       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12830         SourceLocation loc = FD->getLocation();
12831         if (getSourceManager().isInSystemHeader(loc)) {
12832           if (!FD->hasAttr<UnavailableAttr>()) {
12833             FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12834                               "this system field has retaining ownership",
12835                               loc));
12836           }
12837         } else {
12838           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
12839             << T->isBlockPointerType() << Record->getTagKind();
12840         }
12841         ARCErrReported = true;
12842       }
12843     } else if (getLangOpts().ObjC1 &&
12844                getLangOpts().getGC() != LangOptions::NonGC &&
12845                Record && !Record->hasObjectMember()) {
12846       if (FD->getType()->isObjCObjectPointerType() ||
12847           FD->getType().isObjCGCStrong())
12848         Record->setHasObjectMember(true);
12849       else if (Context.getAsArrayType(FD->getType())) {
12850         QualType BaseType = Context.getBaseElementType(FD->getType());
12851         if (BaseType->isRecordType() &&
12852             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
12853           Record->setHasObjectMember(true);
12854         else if (BaseType->isObjCObjectPointerType() ||
12855                  BaseType.isObjCGCStrong())
12856                Record->setHasObjectMember(true);
12857       }
12858     }
12859     if (Record && FD->getType().isVolatileQualified())
12860       Record->setHasVolatileMember(true);
12861     // Keep track of the number of named members.
12862     if (FD->getIdentifier())
12863       ++NumNamedMembers;
12864   }
12865 
12866   // Okay, we successfully defined 'Record'.
12867   if (Record) {
12868     bool Completed = false;
12869     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12870       if (!CXXRecord->isInvalidDecl()) {
12871         // Set access bits correctly on the directly-declared conversions.
12872         for (CXXRecordDecl::conversion_iterator
12873                I = CXXRecord->conversion_begin(),
12874                E = CXXRecord->conversion_end(); I != E; ++I)
12875           I.setAccess((*I)->getAccess());
12876 
12877         if (!CXXRecord->isDependentType()) {
12878           if (CXXRecord->hasUserDeclaredDestructor()) {
12879             // Adjust user-defined destructor exception spec.
12880             if (getLangOpts().CPlusPlus11)
12881               AdjustDestructorExceptionSpec(CXXRecord,
12882                                             CXXRecord->getDestructor());
12883           }
12884 
12885           // Add any implicitly-declared members to this class.
12886           AddImplicitlyDeclaredMembersToClass(CXXRecord);
12887 
12888           // If we have virtual base classes, we may end up finding multiple
12889           // final overriders for a given virtual function. Check for this
12890           // problem now.
12891           if (CXXRecord->getNumVBases()) {
12892             CXXFinalOverriderMap FinalOverriders;
12893             CXXRecord->getFinalOverriders(FinalOverriders);
12894 
12895             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12896                                              MEnd = FinalOverriders.end();
12897                  M != MEnd; ++M) {
12898               for (OverridingMethods::iterator SO = M->second.begin(),
12899                                             SOEnd = M->second.end();
12900                    SO != SOEnd; ++SO) {
12901                 assert(SO->second.size() > 0 &&
12902                        "Virtual function without overridding functions?");
12903                 if (SO->second.size() == 1)
12904                   continue;
12905 
12906                 // C++ [class.virtual]p2:
12907                 //   In a derived class, if a virtual member function of a base
12908                 //   class subobject has more than one final overrider the
12909                 //   program is ill-formed.
12910                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
12911                   << (const NamedDecl *)M->first << Record;
12912                 Diag(M->first->getLocation(),
12913                      diag::note_overridden_virtual_function);
12914                 for (OverridingMethods::overriding_iterator
12915                           OM = SO->second.begin(),
12916                        OMEnd = SO->second.end();
12917                      OM != OMEnd; ++OM)
12918                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
12919                     << (const NamedDecl *)M->first << OM->Method->getParent();
12920 
12921                 Record->setInvalidDecl();
12922               }
12923             }
12924             CXXRecord->completeDefinition(&FinalOverriders);
12925             Completed = true;
12926           }
12927         }
12928       }
12929     }
12930 
12931     if (!Completed)
12932       Record->completeDefinition();
12933 
12934     if (Record->hasAttrs()) {
12935       CheckAlignasUnderalignment(Record);
12936 
12937       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
12938         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
12939                                            IA->getRange(), IA->getBestCase(),
12940                                            IA->getSemanticSpelling());
12941     }
12942 
12943     // Check if the structure/union declaration is a type that can have zero
12944     // size in C. For C this is a language extension, for C++ it may cause
12945     // compatibility problems.
12946     bool CheckForZeroSize;
12947     if (!getLangOpts().CPlusPlus) {
12948       CheckForZeroSize = true;
12949     } else {
12950       // For C++ filter out types that cannot be referenced in C code.
12951       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12952       CheckForZeroSize =
12953           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12954           !CXXRecord->isDependentType() &&
12955           CXXRecord->isCLike();
12956     }
12957     if (CheckForZeroSize) {
12958       bool ZeroSize = true;
12959       bool IsEmpty = true;
12960       unsigned NonBitFields = 0;
12961       for (RecordDecl::field_iterator I = Record->field_begin(),
12962                                       E = Record->field_end();
12963            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12964         IsEmpty = false;
12965         if (I->isUnnamedBitfield()) {
12966           if (I->getBitWidthValue(Context) > 0)
12967             ZeroSize = false;
12968         } else {
12969           ++NonBitFields;
12970           QualType FieldType = I->getType();
12971           if (FieldType->isIncompleteType() ||
12972               !Context.getTypeSizeInChars(FieldType).isZero())
12973             ZeroSize = false;
12974         }
12975       }
12976 
12977       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12978       // allowed in C++, but warn if its declaration is inside
12979       // extern "C" block.
12980       if (ZeroSize) {
12981         Diag(RecLoc, getLangOpts().CPlusPlus ?
12982                          diag::warn_zero_size_struct_union_in_extern_c :
12983                          diag::warn_zero_size_struct_union_compat)
12984           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12985       }
12986 
12987       // Structs without named members are extension in C (C99 6.7.2.1p7),
12988       // but are accepted by GCC.
12989       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12990         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12991                                diag::ext_no_named_members_in_struct_union)
12992           << Record->isUnion();
12993       }
12994     }
12995   } else {
12996     ObjCIvarDecl **ClsFields =
12997       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
12998     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
12999       ID->setEndOfDefinitionLoc(RBrac);
13000       // Add ivar's to class's DeclContext.
13001       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13002         ClsFields[i]->setLexicalDeclContext(ID);
13003         ID->addDecl(ClsFields[i]);
13004       }
13005       // Must enforce the rule that ivars in the base classes may not be
13006       // duplicates.
13007       if (ID->getSuperClass())
13008         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13009     } else if (ObjCImplementationDecl *IMPDecl =
13010                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13011       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13012       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13013         // Ivar declared in @implementation never belongs to the implementation.
13014         // Only it is in implementation's lexical context.
13015         ClsFields[I]->setLexicalDeclContext(IMPDecl);
13016       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13017       IMPDecl->setIvarLBraceLoc(LBrac);
13018       IMPDecl->setIvarRBraceLoc(RBrac);
13019     } else if (ObjCCategoryDecl *CDecl =
13020                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13021       // case of ivars in class extension; all other cases have been
13022       // reported as errors elsewhere.
13023       // FIXME. Class extension does not have a LocEnd field.
13024       // CDecl->setLocEnd(RBrac);
13025       // Add ivar's to class extension's DeclContext.
13026       // Diagnose redeclaration of private ivars.
13027       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13028       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13029         if (IDecl) {
13030           if (const ObjCIvarDecl *ClsIvar =
13031               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13032             Diag(ClsFields[i]->getLocation(),
13033                  diag::err_duplicate_ivar_declaration);
13034             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13035             continue;
13036           }
13037           for (const auto *Ext : IDecl->known_extensions()) {
13038             if (const ObjCIvarDecl *ClsExtIvar
13039                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13040               Diag(ClsFields[i]->getLocation(),
13041                    diag::err_duplicate_ivar_declaration);
13042               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13043               continue;
13044             }
13045           }
13046         }
13047         ClsFields[i]->setLexicalDeclContext(CDecl);
13048         CDecl->addDecl(ClsFields[i]);
13049       }
13050       CDecl->setIvarLBraceLoc(LBrac);
13051       CDecl->setIvarRBraceLoc(RBrac);
13052     }
13053   }
13054 
13055   if (Attr)
13056     ProcessDeclAttributeList(S, Record, Attr);
13057 }
13058 
13059 /// \brief Determine whether the given integral value is representable within
13060 /// the given type T.
13061 static bool isRepresentableIntegerValue(ASTContext &Context,
13062                                         llvm::APSInt &Value,
13063                                         QualType T) {
13064   assert(T->isIntegralType(Context) && "Integral type required!");
13065   unsigned BitWidth = Context.getIntWidth(T);
13066 
13067   if (Value.isUnsigned() || Value.isNonNegative()) {
13068     if (T->isSignedIntegerOrEnumerationType())
13069       --BitWidth;
13070     return Value.getActiveBits() <= BitWidth;
13071   }
13072   return Value.getMinSignedBits() <= BitWidth;
13073 }
13074 
13075 // \brief Given an integral type, return the next larger integral type
13076 // (or a NULL type of no such type exists).
13077 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13078   // FIXME: Int128/UInt128 support, which also needs to be introduced into
13079   // enum checking below.
13080   assert(T->isIntegralType(Context) && "Integral type required!");
13081   const unsigned NumTypes = 4;
13082   QualType SignedIntegralTypes[NumTypes] = {
13083     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13084   };
13085   QualType UnsignedIntegralTypes[NumTypes] = {
13086     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
13087     Context.UnsignedLongLongTy
13088   };
13089 
13090   unsigned BitWidth = Context.getTypeSize(T);
13091   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13092                                                         : UnsignedIntegralTypes;
13093   for (unsigned I = 0; I != NumTypes; ++I)
13094     if (Context.getTypeSize(Types[I]) > BitWidth)
13095       return Types[I];
13096 
13097   return QualType();
13098 }
13099 
13100 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13101                                           EnumConstantDecl *LastEnumConst,
13102                                           SourceLocation IdLoc,
13103                                           IdentifierInfo *Id,
13104                                           Expr *Val) {
13105   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13106   llvm::APSInt EnumVal(IntWidth);
13107   QualType EltTy;
13108 
13109   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13110     Val = nullptr;
13111 
13112   if (Val)
13113     Val = DefaultLvalueConversion(Val).get();
13114 
13115   if (Val) {
13116     if (Enum->isDependentType() || Val->isTypeDependent())
13117       EltTy = Context.DependentTy;
13118     else {
13119       SourceLocation ExpLoc;
13120       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13121           !getLangOpts().MSVCCompat) {
13122         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13123         // constant-expression in the enumerator-definition shall be a converted
13124         // constant expression of the underlying type.
13125         EltTy = Enum->getIntegerType();
13126         ExprResult Converted =
13127           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13128                                            CCEK_Enumerator);
13129         if (Converted.isInvalid())
13130           Val = nullptr;
13131         else
13132           Val = Converted.get();
13133       } else if (!Val->isValueDependent() &&
13134                  !(Val = VerifyIntegerConstantExpression(Val,
13135                                                          &EnumVal).get())) {
13136         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13137       } else {
13138         if (Enum->isFixed()) {
13139           EltTy = Enum->getIntegerType();
13140 
13141           // In Obj-C and Microsoft mode, require the enumeration value to be
13142           // representable in the underlying type of the enumeration. In C++11,
13143           // we perform a non-narrowing conversion as part of converted constant
13144           // expression checking.
13145           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13146             if (getLangOpts().MSVCCompat) {
13147               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13148               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13149             } else
13150               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13151           } else
13152             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13153         } else if (getLangOpts().CPlusPlus) {
13154           // C++11 [dcl.enum]p5:
13155           //   If the underlying type is not fixed, the type of each enumerator
13156           //   is the type of its initializing value:
13157           //     - If an initializer is specified for an enumerator, the
13158           //       initializing value has the same type as the expression.
13159           EltTy = Val->getType();
13160         } else {
13161           // C99 6.7.2.2p2:
13162           //   The expression that defines the value of an enumeration constant
13163           //   shall be an integer constant expression that has a value
13164           //   representable as an int.
13165 
13166           // Complain if the value is not representable in an int.
13167           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13168             Diag(IdLoc, diag::ext_enum_value_not_int)
13169               << EnumVal.toString(10) << Val->getSourceRange()
13170               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13171           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13172             // Force the type of the expression to 'int'.
13173             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13174           }
13175           EltTy = Val->getType();
13176         }
13177       }
13178     }
13179   }
13180 
13181   if (!Val) {
13182     if (Enum->isDependentType())
13183       EltTy = Context.DependentTy;
13184     else if (!LastEnumConst) {
13185       // C++0x [dcl.enum]p5:
13186       //   If the underlying type is not fixed, the type of each enumerator
13187       //   is the type of its initializing value:
13188       //     - If no initializer is specified for the first enumerator, the
13189       //       initializing value has an unspecified integral type.
13190       //
13191       // GCC uses 'int' for its unspecified integral type, as does
13192       // C99 6.7.2.2p3.
13193       if (Enum->isFixed()) {
13194         EltTy = Enum->getIntegerType();
13195       }
13196       else {
13197         EltTy = Context.IntTy;
13198       }
13199     } else {
13200       // Assign the last value + 1.
13201       EnumVal = LastEnumConst->getInitVal();
13202       ++EnumVal;
13203       EltTy = LastEnumConst->getType();
13204 
13205       // Check for overflow on increment.
13206       if (EnumVal < LastEnumConst->getInitVal()) {
13207         // C++0x [dcl.enum]p5:
13208         //   If the underlying type is not fixed, the type of each enumerator
13209         //   is the type of its initializing value:
13210         //
13211         //     - Otherwise the type of the initializing value is the same as
13212         //       the type of the initializing value of the preceding enumerator
13213         //       unless the incremented value is not representable in that type,
13214         //       in which case the type is an unspecified integral type
13215         //       sufficient to contain the incremented value. If no such type
13216         //       exists, the program is ill-formed.
13217         QualType T = getNextLargerIntegralType(Context, EltTy);
13218         if (T.isNull() || Enum->isFixed()) {
13219           // There is no integral type larger enough to represent this
13220           // value. Complain, then allow the value to wrap around.
13221           EnumVal = LastEnumConst->getInitVal();
13222           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
13223           ++EnumVal;
13224           if (Enum->isFixed())
13225             // When the underlying type is fixed, this is ill-formed.
13226             Diag(IdLoc, diag::err_enumerator_wrapped)
13227               << EnumVal.toString(10)
13228               << EltTy;
13229           else
13230             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
13231               << EnumVal.toString(10);
13232         } else {
13233           EltTy = T;
13234         }
13235 
13236         // Retrieve the last enumerator's value, extent that type to the
13237         // type that is supposed to be large enough to represent the incremented
13238         // value, then increment.
13239         EnumVal = LastEnumConst->getInitVal();
13240         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13241         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
13242         ++EnumVal;
13243 
13244         // If we're not in C++, diagnose the overflow of enumerator values,
13245         // which in C99 means that the enumerator value is not representable in
13246         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13247         // permits enumerator values that are representable in some larger
13248         // integral type.
13249         if (!getLangOpts().CPlusPlus && !T.isNull())
13250           Diag(IdLoc, diag::warn_enum_value_overflow);
13251       } else if (!getLangOpts().CPlusPlus &&
13252                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13253         // Enforce C99 6.7.2.2p2 even when we compute the next value.
13254         Diag(IdLoc, diag::ext_enum_value_not_int)
13255           << EnumVal.toString(10) << 1;
13256       }
13257     }
13258   }
13259 
13260   if (!EltTy->isDependentType()) {
13261     // Make the enumerator value match the signedness and size of the
13262     // enumerator's type.
13263     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
13264     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13265   }
13266 
13267   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
13268                                   Val, EnumVal);
13269 }
13270 
13271 
13272 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
13273                               SourceLocation IdLoc, IdentifierInfo *Id,
13274                               AttributeList *Attr,
13275                               SourceLocation EqualLoc, Expr *Val) {
13276   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
13277   EnumConstantDecl *LastEnumConst =
13278     cast_or_null<EnumConstantDecl>(lastEnumConst);
13279 
13280   // The scope passed in may not be a decl scope.  Zip up the scope tree until
13281   // we find one that is.
13282   S = getNonFieldDeclScope(S);
13283 
13284   // Verify that there isn't already something declared with this name in this
13285   // scope.
13286   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
13287                                          ForRedeclaration);
13288   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13289     // Maybe we will complain about the shadowed template parameter.
13290     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
13291     // Just pretend that we didn't see the previous declaration.
13292     PrevDecl = nullptr;
13293   }
13294 
13295   if (PrevDecl) {
13296     // When in C++, we may get a TagDecl with the same name; in this case the
13297     // enum constant will 'hide' the tag.
13298     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
13299            "Received TagDecl when not in C++!");
13300     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
13301       if (isa<EnumConstantDecl>(PrevDecl))
13302         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
13303       else
13304         Diag(IdLoc, diag::err_redefinition) << Id;
13305       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13306       return nullptr;
13307     }
13308   }
13309 
13310   // C++ [class.mem]p15:
13311   // If T is the name of a class, then each of the following shall have a name
13312   // different from T:
13313   // - every enumerator of every member of class T that is an unscoped
13314   // enumerated type
13315   if (CXXRecordDecl *Record
13316                       = dyn_cast<CXXRecordDecl>(
13317                              TheEnumDecl->getDeclContext()->getRedeclContext()))
13318     if (!TheEnumDecl->isScoped() &&
13319         Record->getIdentifier() && Record->getIdentifier() == Id)
13320       Diag(IdLoc, diag::err_member_name_of_class) << Id;
13321 
13322   EnumConstantDecl *New =
13323     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
13324 
13325   if (New) {
13326     // Process attributes.
13327     if (Attr) ProcessDeclAttributeList(S, New, Attr);
13328 
13329     // Register this decl in the current scope stack.
13330     New->setAccess(TheEnumDecl->getAccess());
13331     PushOnScopeChains(New, S);
13332   }
13333 
13334   ActOnDocumentableDecl(New);
13335 
13336   return New;
13337 }
13338 
13339 // Returns true when the enum initial expression does not trigger the
13340 // duplicate enum warning.  A few common cases are exempted as follows:
13341 // Element2 = Element1
13342 // Element2 = Element1 + 1
13343 // Element2 = Element1 - 1
13344 // Where Element2 and Element1 are from the same enum.
13345 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
13346   Expr *InitExpr = ECD->getInitExpr();
13347   if (!InitExpr)
13348     return true;
13349   InitExpr = InitExpr->IgnoreImpCasts();
13350 
13351   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
13352     if (!BO->isAdditiveOp())
13353       return true;
13354     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
13355     if (!IL)
13356       return true;
13357     if (IL->getValue() != 1)
13358       return true;
13359 
13360     InitExpr = BO->getLHS();
13361   }
13362 
13363   // This checks if the elements are from the same enum.
13364   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
13365   if (!DRE)
13366     return true;
13367 
13368   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
13369   if (!EnumConstant)
13370     return true;
13371 
13372   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
13373       Enum)
13374     return true;
13375 
13376   return false;
13377 }
13378 
13379 struct DupKey {
13380   int64_t val;
13381   bool isTombstoneOrEmptyKey;
13382   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
13383     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
13384 };
13385 
13386 static DupKey GetDupKey(const llvm::APSInt& Val) {
13387   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
13388                 false);
13389 }
13390 
13391 struct DenseMapInfoDupKey {
13392   static DupKey getEmptyKey() { return DupKey(0, true); }
13393   static DupKey getTombstoneKey() { return DupKey(1, true); }
13394   static unsigned getHashValue(const DupKey Key) {
13395     return (unsigned)(Key.val * 37);
13396   }
13397   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
13398     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
13399            LHS.val == RHS.val;
13400   }
13401 };
13402 
13403 // Emits a warning when an element is implicitly set a value that
13404 // a previous element has already been set to.
13405 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
13406                                         EnumDecl *Enum,
13407                                         QualType EnumType) {
13408   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
13409     return;
13410   // Avoid anonymous enums
13411   if (!Enum->getIdentifier())
13412     return;
13413 
13414   // Only check for small enums.
13415   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
13416     return;
13417 
13418   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
13419   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
13420 
13421   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
13422   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
13423           ValueToVectorMap;
13424 
13425   DuplicatesVector DupVector;
13426   ValueToVectorMap EnumMap;
13427 
13428   // Populate the EnumMap with all values represented by enum constants without
13429   // an initialier.
13430   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13431     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
13432 
13433     // Null EnumConstantDecl means a previous diagnostic has been emitted for
13434     // this constant.  Skip this enum since it may be ill-formed.
13435     if (!ECD) {
13436       return;
13437     }
13438 
13439     if (ECD->getInitExpr())
13440       continue;
13441 
13442     DupKey Key = GetDupKey(ECD->getInitVal());
13443     DeclOrVector &Entry = EnumMap[Key];
13444 
13445     // First time encountering this value.
13446     if (Entry.isNull())
13447       Entry = ECD;
13448   }
13449 
13450   // Create vectors for any values that has duplicates.
13451   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13452     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
13453     if (!ValidDuplicateEnum(ECD, Enum))
13454       continue;
13455 
13456     DupKey Key = GetDupKey(ECD->getInitVal());
13457 
13458     DeclOrVector& Entry = EnumMap[Key];
13459     if (Entry.isNull())
13460       continue;
13461 
13462     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
13463       // Ensure constants are different.
13464       if (D == ECD)
13465         continue;
13466 
13467       // Create new vector and push values onto it.
13468       ECDVector *Vec = new ECDVector();
13469       Vec->push_back(D);
13470       Vec->push_back(ECD);
13471 
13472       // Update entry to point to the duplicates vector.
13473       Entry = Vec;
13474 
13475       // Store the vector somewhere we can consult later for quick emission of
13476       // diagnostics.
13477       DupVector.push_back(Vec);
13478       continue;
13479     }
13480 
13481     ECDVector *Vec = Entry.get<ECDVector*>();
13482     // Make sure constants are not added more than once.
13483     if (*Vec->begin() == ECD)
13484       continue;
13485 
13486     Vec->push_back(ECD);
13487   }
13488 
13489   // Emit diagnostics.
13490   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
13491                                   DupVectorEnd = DupVector.end();
13492        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
13493     ECDVector *Vec = *DupVectorIter;
13494     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
13495 
13496     // Emit warning for one enum constant.
13497     ECDVector::iterator I = Vec->begin();
13498     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
13499       << (*I)->getName() << (*I)->getInitVal().toString(10)
13500       << (*I)->getSourceRange();
13501     ++I;
13502 
13503     // Emit one note for each of the remaining enum constants with
13504     // the same value.
13505     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
13506       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
13507         << (*I)->getName() << (*I)->getInitVal().toString(10)
13508         << (*I)->getSourceRange();
13509     delete Vec;
13510   }
13511 }
13512 
13513 bool
13514 Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
13515                         bool AllowMask) const {
13516   FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>();
13517   assert(FEAttr && "looking for value in non-flag enum");
13518 
13519   llvm::APInt FlagMask = ~FEAttr->getFlagBits();
13520   unsigned Width = FlagMask.getBitWidth();
13521 
13522   // We will try a zero-extended value for the regular check first.
13523   llvm::APInt ExtVal = Val.zextOrSelf(Width);
13524 
13525   // A value is in a flag enum if either its bits are a subset of the enum's
13526   // flag bits (the first condition) or we are allowing masks and the same is
13527   // true of its complement (the second condition). When masks are allowed, we
13528   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
13529   //
13530   // While it's true that any value could be used as a mask, the assumption is
13531   // that a mask will have all of the insignificant bits set. Anything else is
13532   // likely a logic error.
13533   if (!(FlagMask & ExtVal))
13534     return true;
13535 
13536   if (AllowMask) {
13537     // Try a one-extended value instead. This can happen if the enum is wider
13538     // than the constant used, in C with extensions to allow for wider enums.
13539     // The mask will still have the correct behaviour, so we give the user the
13540     // benefit of the doubt.
13541     //
13542     // FIXME: This heuristic can cause weird results if the enum was extended
13543     // to a larger type and is signed, because then bit-masks of smaller types
13544     // that get extended will fall out of range (e.g. ~0x1u). We currently don't
13545     // detect that case and will get a false positive for it. In most cases,
13546     // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may
13547     // be fine just to accept this as a warning.
13548     ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth());
13549     if (!(FlagMask & ~ExtVal))
13550       return true;
13551   }
13552 
13553   return false;
13554 }
13555 
13556 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
13557                          SourceLocation RBraceLoc, Decl *EnumDeclX,
13558                          ArrayRef<Decl *> Elements,
13559                          Scope *S, AttributeList *Attr) {
13560   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
13561   QualType EnumType = Context.getTypeDeclType(Enum);
13562 
13563   if (Attr)
13564     ProcessDeclAttributeList(S, Enum, Attr);
13565 
13566   if (Enum->isDependentType()) {
13567     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13568       EnumConstantDecl *ECD =
13569         cast_or_null<EnumConstantDecl>(Elements[i]);
13570       if (!ECD) continue;
13571 
13572       ECD->setType(EnumType);
13573     }
13574 
13575     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
13576     return;
13577   }
13578 
13579   // TODO: If the result value doesn't fit in an int, it must be a long or long
13580   // long value.  ISO C does not support this, but GCC does as an extension,
13581   // emit a warning.
13582   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13583   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
13584   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
13585 
13586   // Verify that all the values are okay, compute the size of the values, and
13587   // reverse the list.
13588   unsigned NumNegativeBits = 0;
13589   unsigned NumPositiveBits = 0;
13590 
13591   // Keep track of whether all elements have type int.
13592   bool AllElementsInt = true;
13593 
13594   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13595     EnumConstantDecl *ECD =
13596       cast_or_null<EnumConstantDecl>(Elements[i]);
13597     if (!ECD) continue;  // Already issued a diagnostic.
13598 
13599     const llvm::APSInt &InitVal = ECD->getInitVal();
13600 
13601     // Keep track of the size of positive and negative values.
13602     if (InitVal.isUnsigned() || InitVal.isNonNegative())
13603       NumPositiveBits = std::max(NumPositiveBits,
13604                                  (unsigned)InitVal.getActiveBits());
13605     else
13606       NumNegativeBits = std::max(NumNegativeBits,
13607                                  (unsigned)InitVal.getMinSignedBits());
13608 
13609     // Keep track of whether every enum element has type int (very commmon).
13610     if (AllElementsInt)
13611       AllElementsInt = ECD->getType() == Context.IntTy;
13612   }
13613 
13614   // Figure out the type that should be used for this enum.
13615   QualType BestType;
13616   unsigned BestWidth;
13617 
13618   // C++0x N3000 [conv.prom]p3:
13619   //   An rvalue of an unscoped enumeration type whose underlying
13620   //   type is not fixed can be converted to an rvalue of the first
13621   //   of the following types that can represent all the values of
13622   //   the enumeration: int, unsigned int, long int, unsigned long
13623   //   int, long long int, or unsigned long long int.
13624   // C99 6.4.4.3p2:
13625   //   An identifier declared as an enumeration constant has type int.
13626   // The C99 rule is modified by a gcc extension
13627   QualType BestPromotionType;
13628 
13629   bool Packed = Enum->hasAttr<PackedAttr>();
13630   // -fshort-enums is the equivalent to specifying the packed attribute on all
13631   // enum definitions.
13632   if (LangOpts.ShortEnums)
13633     Packed = true;
13634 
13635   if (Enum->isFixed()) {
13636     BestType = Enum->getIntegerType();
13637     if (BestType->isPromotableIntegerType())
13638       BestPromotionType = Context.getPromotedIntegerType(BestType);
13639     else
13640       BestPromotionType = BestType;
13641 
13642     BestWidth = Context.getIntWidth(BestType);
13643   }
13644   else if (NumNegativeBits) {
13645     // If there is a negative value, figure out the smallest integer type (of
13646     // int/long/longlong) that fits.
13647     // If it's packed, check also if it fits a char or a short.
13648     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
13649       BestType = Context.SignedCharTy;
13650       BestWidth = CharWidth;
13651     } else if (Packed && NumNegativeBits <= ShortWidth &&
13652                NumPositiveBits < ShortWidth) {
13653       BestType = Context.ShortTy;
13654       BestWidth = ShortWidth;
13655     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
13656       BestType = Context.IntTy;
13657       BestWidth = IntWidth;
13658     } else {
13659       BestWidth = Context.getTargetInfo().getLongWidth();
13660 
13661       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
13662         BestType = Context.LongTy;
13663       } else {
13664         BestWidth = Context.getTargetInfo().getLongLongWidth();
13665 
13666         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
13667           Diag(Enum->getLocation(), diag::ext_enum_too_large);
13668         BestType = Context.LongLongTy;
13669       }
13670     }
13671     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
13672   } else {
13673     // If there is no negative value, figure out the smallest type that fits
13674     // all of the enumerator values.
13675     // If it's packed, check also if it fits a char or a short.
13676     if (Packed && NumPositiveBits <= CharWidth) {
13677       BestType = Context.UnsignedCharTy;
13678       BestPromotionType = Context.IntTy;
13679       BestWidth = CharWidth;
13680     } else if (Packed && NumPositiveBits <= ShortWidth) {
13681       BestType = Context.UnsignedShortTy;
13682       BestPromotionType = Context.IntTy;
13683       BestWidth = ShortWidth;
13684     } else if (NumPositiveBits <= IntWidth) {
13685       BestType = Context.UnsignedIntTy;
13686       BestWidth = IntWidth;
13687       BestPromotionType
13688         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13689                            ? Context.UnsignedIntTy : Context.IntTy;
13690     } else if (NumPositiveBits <=
13691                (BestWidth = Context.getTargetInfo().getLongWidth())) {
13692       BestType = Context.UnsignedLongTy;
13693       BestPromotionType
13694         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13695                            ? Context.UnsignedLongTy : Context.LongTy;
13696     } else {
13697       BestWidth = Context.getTargetInfo().getLongLongWidth();
13698       assert(NumPositiveBits <= BestWidth &&
13699              "How could an initializer get larger than ULL?");
13700       BestType = Context.UnsignedLongLongTy;
13701       BestPromotionType
13702         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13703                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
13704     }
13705   }
13706 
13707   FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>();
13708   if (FEAttr)
13709     FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0);
13710 
13711   // Loop over all of the enumerator constants, changing their types to match
13712   // the type of the enum if needed. If we have a flag type, we also prepare the
13713   // FlagBits cache.
13714   for (auto *D : Elements) {
13715     auto *ECD = cast_or_null<EnumConstantDecl>(D);
13716     if (!ECD) continue;  // Already issued a diagnostic.
13717 
13718     // Standard C says the enumerators have int type, but we allow, as an
13719     // extension, the enumerators to be larger than int size.  If each
13720     // enumerator value fits in an int, type it as an int, otherwise type it the
13721     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
13722     // that X has type 'int', not 'unsigned'.
13723 
13724     // Determine whether the value fits into an int.
13725     llvm::APSInt InitVal = ECD->getInitVal();
13726 
13727     // If it fits into an integer type, force it.  Otherwise force it to match
13728     // the enum decl type.
13729     QualType NewTy;
13730     unsigned NewWidth;
13731     bool NewSign;
13732     if (!getLangOpts().CPlusPlus &&
13733         !Enum->isFixed() &&
13734         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
13735       NewTy = Context.IntTy;
13736       NewWidth = IntWidth;
13737       NewSign = true;
13738     } else if (ECD->getType() == BestType) {
13739       // Already the right type!
13740       if (getLangOpts().CPlusPlus)
13741         // C++ [dcl.enum]p4: Following the closing brace of an
13742         // enum-specifier, each enumerator has the type of its
13743         // enumeration.
13744         ECD->setType(EnumType);
13745       goto flagbits;
13746     } else {
13747       NewTy = BestType;
13748       NewWidth = BestWidth;
13749       NewSign = BestType->isSignedIntegerOrEnumerationType();
13750     }
13751 
13752     // Adjust the APSInt value.
13753     InitVal = InitVal.extOrTrunc(NewWidth);
13754     InitVal.setIsSigned(NewSign);
13755     ECD->setInitVal(InitVal);
13756 
13757     // Adjust the Expr initializer and type.
13758     if (ECD->getInitExpr() &&
13759         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
13760       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
13761                                                 CK_IntegralCast,
13762                                                 ECD->getInitExpr(),
13763                                                 /*base paths*/ nullptr,
13764                                                 VK_RValue));
13765     if (getLangOpts().CPlusPlus)
13766       // C++ [dcl.enum]p4: Following the closing brace of an
13767       // enum-specifier, each enumerator has the type of its
13768       // enumeration.
13769       ECD->setType(EnumType);
13770     else
13771       ECD->setType(NewTy);
13772 
13773 flagbits:
13774     // Check to see if we have a constant with exactly one bit set. Note that x
13775     // & (x - 1) will be nonzero if and only if x has more than one bit set.
13776     if (FEAttr) {
13777       llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth);
13778       if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) {
13779         FEAttr->getFlagBits() |= ExtVal;
13780       }
13781     }
13782   }
13783 
13784   if (FEAttr) {
13785     for (Decl *D : Elements) {
13786       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
13787       if (!ECD) continue;  // Already issued a diagnostic.
13788 
13789       llvm::APSInt InitVal = ECD->getInitVal();
13790       if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true))
13791         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
13792           << ECD << Enum;
13793     }
13794   }
13795 
13796 
13797 
13798   Enum->completeDefinition(BestType, BestPromotionType,
13799                            NumPositiveBits, NumNegativeBits);
13800 
13801   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
13802 
13803   // Now that the enum type is defined, ensure it's not been underaligned.
13804   if (Enum->hasAttrs())
13805     CheckAlignasUnderalignment(Enum);
13806 }
13807 
13808 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
13809                                   SourceLocation StartLoc,
13810                                   SourceLocation EndLoc) {
13811   StringLiteral *AsmString = cast<StringLiteral>(expr);
13812 
13813   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
13814                                                    AsmString, StartLoc,
13815                                                    EndLoc);
13816   CurContext->addDecl(New);
13817   return New;
13818 }
13819 
13820 static void checkModuleImportContext(Sema &S, Module *M,
13821                                      SourceLocation ImportLoc,
13822                                      DeclContext *DC) {
13823   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
13824     switch (LSD->getLanguage()) {
13825     case LinkageSpecDecl::lang_c:
13826       if (!M->IsExternC) {
13827         S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
13828           << M->getFullModuleName();
13829         S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
13830         return;
13831       }
13832       break;
13833     case LinkageSpecDecl::lang_cxx:
13834       break;
13835     }
13836     DC = LSD->getParent();
13837   }
13838 
13839   while (isa<LinkageSpecDecl>(DC))
13840     DC = DC->getParent();
13841   if (!isa<TranslationUnitDecl>(DC)) {
13842     S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
13843       << M->getFullModuleName() << DC;
13844     S.Diag(cast<Decl>(DC)->getLocStart(),
13845            diag::note_module_import_not_at_top_level)
13846       << DC;
13847   }
13848 }
13849 
13850 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
13851                                    SourceLocation ImportLoc,
13852                                    ModuleIdPath Path) {
13853   Module *Mod =
13854       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
13855                                    /*IsIncludeDirective=*/false);
13856   if (!Mod)
13857     return true;
13858 
13859   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13860 
13861   // FIXME: we should support importing a submodule within a different submodule
13862   // of the same top-level module. Until we do, make it an error rather than
13863   // silently ignoring the import.
13864   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
13865     Diag(ImportLoc, diag::err_module_self_import)
13866         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
13867   else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
13868     Diag(ImportLoc, diag::err_module_import_in_implementation)
13869         << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
13870 
13871   SmallVector<SourceLocation, 2> IdentifierLocs;
13872   Module *ModCheck = Mod;
13873   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13874     // If we've run out of module parents, just drop the remaining identifiers.
13875     // We need the length to be consistent.
13876     if (!ModCheck)
13877       break;
13878     ModCheck = ModCheck->Parent;
13879 
13880     IdentifierLocs.push_back(Path[I].second);
13881   }
13882 
13883   ImportDecl *Import = ImportDecl::Create(Context,
13884                                           Context.getTranslationUnitDecl(),
13885                                           AtLoc.isValid()? AtLoc : ImportLoc,
13886                                           Mod, IdentifierLocs);
13887   Context.getTranslationUnitDecl()->addDecl(Import);
13888   return Import;
13889 }
13890 
13891 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
13892   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13893 
13894   // FIXME: Should we synthesize an ImportDecl here?
13895   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13896                                       /*Complain=*/true);
13897 }
13898 
13899 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
13900                                                       Module *Mod) {
13901   // Bail if we're not allowed to implicitly import a module here.
13902   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
13903     return;
13904 
13905   // Create the implicit import declaration.
13906   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13907   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13908                                                    Loc, Mod, Loc);
13909   TU->addDecl(ImportD);
13910   Consumer.HandleImplicitImportDecl(ImportD);
13911 
13912   // Make the module visible.
13913   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13914                                       /*Complain=*/false);
13915 }
13916 
13917 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13918                                       IdentifierInfo* AliasName,
13919                                       SourceLocation PragmaLoc,
13920                                       SourceLocation NameLoc,
13921                                       SourceLocation AliasNameLoc) {
13922   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13923                                     LookupOrdinaryName);
13924   AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13925                                                     AliasName->getName(), 0);
13926 
13927   if (PrevDecl)
13928     PrevDecl->addAttr(Attr);
13929   else
13930     (void)ExtnameUndeclaredIdentifiers.insert(
13931       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13932 }
13933 
13934 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13935                              SourceLocation PragmaLoc,
13936                              SourceLocation NameLoc) {
13937   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
13938 
13939   if (PrevDecl) {
13940     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
13941   } else {
13942     (void)WeakUndeclaredIdentifiers.insert(
13943       std::pair<IdentifierInfo*,WeakInfo>
13944         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
13945   }
13946 }
13947 
13948 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13949                                 IdentifierInfo* AliasName,
13950                                 SourceLocation PragmaLoc,
13951                                 SourceLocation NameLoc,
13952                                 SourceLocation AliasNameLoc) {
13953   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13954                                     LookupOrdinaryName);
13955   WeakInfo W = WeakInfo(Name, NameLoc);
13956 
13957   if (PrevDecl) {
13958     if (!PrevDecl->hasAttr<AliasAttr>())
13959       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
13960         DeclApplyPragmaWeak(TUScope, ND, W);
13961   } else {
13962     (void)WeakUndeclaredIdentifiers.insert(
13963       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
13964   }
13965 }
13966 
13967 Decl *Sema::getObjCDeclContext() const {
13968   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13969 }
13970 
13971 AvailabilityResult Sema::getCurContextAvailability() const {
13972   const Decl *D = cast<Decl>(getCurObjCLexicalContext());
13973   // If we are within an Objective-C method, we should consult
13974   // both the availability of the method as well as the
13975   // enclosing class.  If the class is (say) deprecated,
13976   // the entire method is considered deprecated from the
13977   // purpose of checking if the current context is deprecated.
13978   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13979     AvailabilityResult R = MD->getAvailability();
13980     if (R != AR_Available)
13981       return R;
13982     D = MD->getClassInterface();
13983   }
13984   // If we are within an Objective-c @implementation, it
13985   // gets the same availability context as the @interface.
13986   else if (const ObjCImplementationDecl *ID =
13987             dyn_cast<ObjCImplementationDecl>(D)) {
13988     D = ID->getClassInterface();
13989   }
13990   // Recover from user error.
13991   return D ? D->getAvailability() : AR_Available;
13992 }
13993