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 /// \brief If the identifier refers to a type name within this scope,
132 /// return the declaration of that type.
133 ///
134 /// This routine performs ordinary name lookup of the identifier II
135 /// within the given scope, with optional C++ scope specifier SS, to
136 /// determine whether the name refers to a type. If so, returns an
137 /// opaque pointer (actually a QualType) corresponding to that
138 /// type. Otherwise, returns NULL.
139 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
140                              Scope *S, CXXScopeSpec *SS,
141                              bool isClassName, bool HasTrailingDot,
142                              ParsedType ObjectTypePtr,
143                              bool IsCtorOrDtorName,
144                              bool WantNontrivialTypeSourceInfo,
145                              IdentifierInfo **CorrectedII) {
146   // Determine where we will perform name lookup.
147   DeclContext *LookupCtx = nullptr;
148   if (ObjectTypePtr) {
149     QualType ObjectType = ObjectTypePtr.get();
150     if (ObjectType->isRecordType())
151       LookupCtx = computeDeclContext(ObjectType);
152   } else if (SS && SS->isNotEmpty()) {
153     LookupCtx = computeDeclContext(*SS, false);
154 
155     if (!LookupCtx) {
156       if (isDependentScopeSpecifier(*SS)) {
157         // C++ [temp.res]p3:
158         //   A qualified-id that refers to a type and in which the
159         //   nested-name-specifier depends on a template-parameter (14.6.2)
160         //   shall be prefixed by the keyword typename to indicate that the
161         //   qualified-id denotes a type, forming an
162         //   elaborated-type-specifier (7.1.5.3).
163         //
164         // We therefore do not perform any name lookup if the result would
165         // refer to a member of an unknown specialization.
166         if (!isClassName && !IsCtorOrDtorName)
167           return ParsedType();
168 
169         // We know from the grammar that this name refers to a type,
170         // so build a dependent node to describe the type.
171         if (WantNontrivialTypeSourceInfo)
172           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
173 
174         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
175         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
176                                        II, NameLoc);
177         return ParsedType::make(T);
178       }
179 
180       return ParsedType();
181     }
182 
183     if (!LookupCtx->isDependentContext() &&
184         RequireCompleteDeclContext(*SS, LookupCtx))
185       return ParsedType();
186   }
187 
188   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
189   // lookup for class-names.
190   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
191                                       LookupOrdinaryName;
192   LookupResult Result(*this, &II, NameLoc, Kind);
193   if (LookupCtx) {
194     // Perform "qualified" name lookup into the declaration context we
195     // computed, which is either the type of the base of a member access
196     // expression or the declaration context associated with a prior
197     // nested-name-specifier.
198     LookupQualifiedName(Result, LookupCtx);
199 
200     if (ObjectTypePtr && Result.empty()) {
201       // C++ [basic.lookup.classref]p3:
202       //   If the unqualified-id is ~type-name, the type-name is looked up
203       //   in the context of the entire postfix-expression. If the type T of
204       //   the object expression is of a class type C, the type-name is also
205       //   looked up in the scope of class C. At least one of the lookups shall
206       //   find a name that refers to (possibly cv-qualified) T.
207       LookupName(Result, S);
208     }
209   } else {
210     // Perform unqualified name lookup.
211     LookupName(Result, S);
212   }
213 
214   NamedDecl *IIDecl = nullptr;
215   switch (Result.getResultKind()) {
216   case LookupResult::NotFound:
217   case LookupResult::NotFoundInCurrentInstantiation:
218     if (CorrectedII) {
219       TypeNameValidatorCCC Validator(true, isClassName);
220       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
221                                               Kind, S, SS, Validator,
222                                               CTK_ErrorRecovery);
223       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
224       TemplateTy Template;
225       bool MemberOfUnknownSpecialization;
226       UnqualifiedId TemplateName;
227       TemplateName.setIdentifier(NewII, NameLoc);
228       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
229       CXXScopeSpec NewSS, *NewSSPtr = SS;
230       if (SS && NNS) {
231         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
232         NewSSPtr = &NewSS;
233       }
234       if (Correction && (NNS || NewII != &II) &&
235           // Ignore a correction to a template type as the to-be-corrected
236           // identifier is not a template (typo correction for template names
237           // is handled elsewhere).
238           !(getLangOpts().CPlusPlus && NewSSPtr &&
239             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
240                            false, Template, MemberOfUnknownSpecialization))) {
241         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
242                                     isClassName, HasTrailingDot, ObjectTypePtr,
243                                     IsCtorOrDtorName,
244                                     WantNontrivialTypeSourceInfo);
245         if (Ty) {
246           diagnoseTypo(Correction,
247                        PDiag(diag::err_unknown_type_or_class_name_suggest)
248                          << Result.getLookupName() << isClassName);
249           if (SS && NNS)
250             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
251           *CorrectedII = NewII;
252           return Ty;
253         }
254       }
255     }
256     // If typo correction failed or was not performed, fall through
257   case LookupResult::FoundOverloaded:
258   case LookupResult::FoundUnresolvedValue:
259     Result.suppressDiagnostics();
260     return ParsedType();
261 
262   case LookupResult::Ambiguous:
263     // Recover from type-hiding ambiguities by hiding the type.  We'll
264     // do the lookup again when looking for an object, and we can
265     // diagnose the error then.  If we don't do this, then the error
266     // about hiding the type will be immediately followed by an error
267     // that only makes sense if the identifier was treated like a type.
268     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
269       Result.suppressDiagnostics();
270       return ParsedType();
271     }
272 
273     // Look to see if we have a type anywhere in the list of results.
274     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
275          Res != ResEnd; ++Res) {
276       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
277         if (!IIDecl ||
278             (*Res)->getLocation().getRawEncoding() <
279               IIDecl->getLocation().getRawEncoding())
280           IIDecl = *Res;
281       }
282     }
283 
284     if (!IIDecl) {
285       // None of the entities we found is a type, so there is no way
286       // to even assume that the result is a type. In this case, don't
287       // complain about the ambiguity. The parser will either try to
288       // perform this lookup again (e.g., as an object name), which
289       // will produce the ambiguity, or will complain that it expected
290       // a type name.
291       Result.suppressDiagnostics();
292       return ParsedType();
293     }
294 
295     // We found a type within the ambiguous lookup; diagnose the
296     // ambiguity and then return that type. This might be the right
297     // answer, or it might not be, but it suppresses any attempt to
298     // perform the name lookup again.
299     break;
300 
301   case LookupResult::Found:
302     IIDecl = Result.getFoundDecl();
303     break;
304   }
305 
306   assert(IIDecl && "Didn't find decl");
307 
308   QualType T;
309   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
310     DiagnoseUseOfDecl(IIDecl, NameLoc);
311 
312     T = Context.getTypeDeclType(TD);
313 
314     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
315     // constructor or destructor name (in such a case, the scope specifier
316     // will be attached to the enclosing Expr or Decl node).
317     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
318       if (WantNontrivialTypeSourceInfo) {
319         // Construct a type with type-source information.
320         TypeLocBuilder Builder;
321         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
322 
323         T = getElaboratedType(ETK_None, *SS, T);
324         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
325         ElabTL.setElaboratedKeywordLoc(SourceLocation());
326         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
327         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
328       } else {
329         T = getElaboratedType(ETK_None, *SS, T);
330       }
331     }
332   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
333     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
334     if (!HasTrailingDot)
335       T = Context.getObjCInterfaceType(IDecl);
336   }
337 
338   if (T.isNull()) {
339     // If it's not plausibly a type, suppress diagnostics.
340     Result.suppressDiagnostics();
341     return ParsedType();
342   }
343   return ParsedType::make(T);
344 }
345 
346 // Builds a fake NNS for the given decl context.
347 static NestedNameSpecifier *
348 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
349   for (;; DC = DC->getLookupParent()) {
350     DC = DC->getPrimaryContext();
351     auto *ND = dyn_cast<NamespaceDecl>(DC);
352     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
353       return NestedNameSpecifier::Create(Context, nullptr, ND);
354     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
355       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
356                                          RD->getTypeForDecl());
357     else if (isa<TranslationUnitDecl>(DC))
358       return NestedNameSpecifier::GlobalSpecifier(Context);
359   }
360   llvm_unreachable("something isn't in TU scope?");
361 }
362 
363 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
364                                                 SourceLocation NameLoc) {
365   // Accepting an undeclared identifier as a default argument for a template
366   // type parameter is a Microsoft extension.
367   Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
368 
369   // Build a fake DependentNameType that will perform lookup into CurContext at
370   // instantiation time.  The name specifier isn't dependent, so template
371   // instantiation won't transform it.  It will retry the lookup, however.
372   NestedNameSpecifier *NNS =
373       synthesizeCurrentNestedNameSpecifier(Context, CurContext);
374   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
375 
376   // Build type location information.  We synthesized the qualifier, so we have
377   // to build a fake NestedNameSpecifierLoc.
378   NestedNameSpecifierLocBuilder NNSLocBuilder;
379   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
380   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
381 
382   TypeLocBuilder Builder;
383   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
384   DepTL.setNameLoc(NameLoc);
385   DepTL.setElaboratedKeywordLoc(SourceLocation());
386   DepTL.setQualifierLoc(QualifierLoc);
387   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
388 }
389 
390 /// isTagName() - This method is called *for error recovery purposes only*
391 /// to determine if the specified name is a valid tag name ("struct foo").  If
392 /// so, this returns the TST for the tag corresponding to it (TST_enum,
393 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
394 /// cases in C where the user forgot to specify the tag.
395 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
396   // Do a tag name lookup in this scope.
397   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
398   LookupName(R, S, false);
399   R.suppressDiagnostics();
400   if (R.getResultKind() == LookupResult::Found)
401     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
402       switch (TD->getTagKind()) {
403       case TTK_Struct: return DeclSpec::TST_struct;
404       case TTK_Interface: return DeclSpec::TST_interface;
405       case TTK_Union:  return DeclSpec::TST_union;
406       case TTK_Class:  return DeclSpec::TST_class;
407       case TTK_Enum:   return DeclSpec::TST_enum;
408       }
409     }
410 
411   return DeclSpec::TST_unspecified;
412 }
413 
414 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
415 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
416 /// then downgrade the missing typename error to a warning.
417 /// This is needed for MSVC compatibility; Example:
418 /// @code
419 /// template<class T> class A {
420 /// public:
421 ///   typedef int TYPE;
422 /// };
423 /// template<class T> class B : public A<T> {
424 /// public:
425 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
426 /// };
427 /// @endcode
428 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
429   if (CurContext->isRecord()) {
430     const Type *Ty = SS->getScopeRep()->getAsType();
431 
432     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
433     for (const auto &Base : RD->bases())
434       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
435         return true;
436     return S->isFunctionPrototypeScope();
437   }
438   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
439 }
440 
441 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
442                                    SourceLocation IILoc,
443                                    Scope *S,
444                                    CXXScopeSpec *SS,
445                                    ParsedType &SuggestedType,
446                                    bool AllowClassTemplates) {
447   // We don't have anything to suggest (yet).
448   SuggestedType = ParsedType();
449 
450   // There may have been a typo in the name of the type. Look up typo
451   // results, in case we have something that we can suggest.
452   TypeNameValidatorCCC Validator(false, false, AllowClassTemplates);
453   if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
454                                              LookupOrdinaryName, S, SS,
455                                              Validator, CTK_ErrorRecovery)) {
456     if (Corrected.isKeyword()) {
457       // We corrected to a keyword.
458       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
459       II = Corrected.getCorrectionAsIdentifierInfo();
460     } else {
461       // We found a similarly-named type or interface; suggest that.
462       if (!SS || !SS->isSet()) {
463         diagnoseTypo(Corrected,
464                      PDiag(diag::err_unknown_typename_suggest) << II);
465       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
466         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
467         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
468                                 II->getName().equals(CorrectedStr);
469         diagnoseTypo(Corrected,
470                      PDiag(diag::err_unknown_nested_typename_suggest)
471                        << II << DC << DroppedSpecifier << SS->getRange());
472       } else {
473         llvm_unreachable("could not have corrected a typo here");
474       }
475 
476       CXXScopeSpec tmpSS;
477       if (Corrected.getCorrectionSpecifier())
478         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
479                           SourceRange(IILoc));
480       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
481                                   IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
482                                   false, ParsedType(),
483                                   /*IsCtorOrDtorName=*/false,
484                                   /*NonTrivialTypeSourceInfo=*/true);
485     }
486     return;
487   }
488 
489   if (getLangOpts().CPlusPlus) {
490     // See if II is a class template that the user forgot to pass arguments to.
491     UnqualifiedId Name;
492     Name.setIdentifier(II, IILoc);
493     CXXScopeSpec EmptySS;
494     TemplateTy TemplateResult;
495     bool MemberOfUnknownSpecialization;
496     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
497                        Name, ParsedType(), true, TemplateResult,
498                        MemberOfUnknownSpecialization) == TNK_Type_template) {
499       TemplateName TplName = TemplateResult.get();
500       Diag(IILoc, diag::err_template_missing_args) << TplName;
501       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
502         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
503           << TplDecl->getTemplateParameters()->getSourceRange();
504       }
505       return;
506     }
507   }
508 
509   // FIXME: Should we move the logic that tries to recover from a missing tag
510   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
511 
512   if (!SS || (!SS->isSet() && !SS->isInvalid()))
513     Diag(IILoc, diag::err_unknown_typename) << II;
514   else if (DeclContext *DC = computeDeclContext(*SS, false))
515     Diag(IILoc, diag::err_typename_nested_not_found)
516       << II << DC << SS->getRange();
517   else if (isDependentScopeSpecifier(*SS)) {
518     unsigned DiagID = diag::err_typename_missing;
519     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
520       DiagID = diag::ext_typename_missing;
521 
522     Diag(SS->getRange().getBegin(), DiagID)
523       << SS->getScopeRep() << II->getName()
524       << SourceRange(SS->getRange().getBegin(), IILoc)
525       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
526     SuggestedType = ActOnTypenameType(S, SourceLocation(),
527                                       *SS, *II, IILoc).get();
528   } else {
529     assert(SS && SS->isInvalid() &&
530            "Invalid scope specifier has already been diagnosed");
531   }
532 }
533 
534 /// \brief Determine whether the given result set contains either a type name
535 /// or
536 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
537   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
538                        NextToken.is(tok::less);
539 
540   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
541     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
542       return true;
543 
544     if (CheckTemplate && isa<TemplateDecl>(*I))
545       return true;
546   }
547 
548   return false;
549 }
550 
551 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
552                                     Scope *S, CXXScopeSpec &SS,
553                                     IdentifierInfo *&Name,
554                                     SourceLocation NameLoc) {
555   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
556   SemaRef.LookupParsedName(R, S, &SS);
557   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
558     StringRef FixItTagName;
559     switch (Tag->getTagKind()) {
560       case TTK_Class:
561         FixItTagName = "class ";
562         break;
563 
564       case TTK_Enum:
565         FixItTagName = "enum ";
566         break;
567 
568       case TTK_Struct:
569         FixItTagName = "struct ";
570         break;
571 
572       case TTK_Interface:
573         FixItTagName = "__interface ";
574         break;
575 
576       case TTK_Union:
577         FixItTagName = "union ";
578         break;
579     }
580 
581     StringRef TagName = FixItTagName.drop_back();
582     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
583       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
584       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
585 
586     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
587          I != IEnd; ++I)
588       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
589         << Name << TagName;
590 
591     // Replace lookup results with just the tag decl.
592     Result.clear(Sema::LookupTagName);
593     SemaRef.LookupParsedName(Result, S, &SS);
594     return true;
595   }
596 
597   return false;
598 }
599 
600 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
601 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
602                                   QualType T, SourceLocation NameLoc) {
603   ASTContext &Context = S.Context;
604 
605   TypeLocBuilder Builder;
606   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
607 
608   T = S.getElaboratedType(ETK_None, SS, T);
609   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
610   ElabTL.setElaboratedKeywordLoc(SourceLocation());
611   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
612   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
613 }
614 
615 Sema::NameClassification Sema::ClassifyName(Scope *S,
616                                             CXXScopeSpec &SS,
617                                             IdentifierInfo *&Name,
618                                             SourceLocation NameLoc,
619                                             const Token &NextToken,
620                                             bool IsAddressOfOperand,
621                                             CorrectionCandidateCallback *CCC) {
622   DeclarationNameInfo NameInfo(Name, NameLoc);
623   ObjCMethodDecl *CurMethod = getCurMethodDecl();
624 
625   if (NextToken.is(tok::coloncolon)) {
626     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
627                                 QualType(), false, SS, nullptr, false);
628   }
629 
630   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
631   LookupParsedName(Result, S, &SS, !CurMethod);
632 
633   // Perform lookup for Objective-C instance variables (including automatically
634   // synthesized instance variables), if we're in an Objective-C method.
635   // FIXME: This lookup really, really needs to be folded in to the normal
636   // unqualified lookup mechanism.
637   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
638     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
639     if (E.get() || E.isInvalid())
640       return E;
641   }
642 
643   bool SecondTry = false;
644   bool IsFilteredTemplateName = false;
645 
646 Corrected:
647   switch (Result.getResultKind()) {
648   case LookupResult::NotFound:
649     // If an unqualified-id is followed by a '(', then we have a function
650     // call.
651     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
652       // In C++, this is an ADL-only call.
653       // FIXME: Reference?
654       if (getLangOpts().CPlusPlus)
655         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
656 
657       // C90 6.3.2.2:
658       //   If the expression that precedes the parenthesized argument list in a
659       //   function call consists solely of an identifier, and if no
660       //   declaration is visible for this identifier, the identifier is
661       //   implicitly declared exactly as if, in the innermost block containing
662       //   the function call, the declaration
663       //
664       //     extern int identifier ();
665       //
666       //   appeared.
667       //
668       // We also allow this in C99 as an extension.
669       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
670         Result.addDecl(D);
671         Result.resolveKind();
672         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
673       }
674     }
675 
676     // In C, we first see whether there is a tag type by the same name, in
677     // which case it's likely that the user just forget to write "enum",
678     // "struct", or "union".
679     if (!getLangOpts().CPlusPlus && !SecondTry &&
680         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
681       break;
682     }
683 
684     // Perform typo correction to determine if there is another name that is
685     // close to this name.
686     if (!SecondTry && CCC) {
687       SecondTry = true;
688       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
689                                                  Result.getLookupKind(), S,
690                                                  &SS, *CCC,
691                                                  CTK_ErrorRecovery)) {
692         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
693         unsigned QualifiedDiag = diag::err_no_member_suggest;
694 
695         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
696         NamedDecl *UnderlyingFirstDecl
697           = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
698         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
699             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
700           UnqualifiedDiag = diag::err_no_template_suggest;
701           QualifiedDiag = diag::err_no_member_template_suggest;
702         } else if (UnderlyingFirstDecl &&
703                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
704                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
705                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
706           UnqualifiedDiag = diag::err_unknown_typename_suggest;
707           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
708         }
709 
710         if (SS.isEmpty()) {
711           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
712         } else {// FIXME: is this even reachable? Test it.
713           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
714           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
715                                   Name->getName().equals(CorrectedStr);
716           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
717                                     << Name << computeDeclContext(SS, false)
718                                     << DroppedSpecifier << SS.getRange());
719         }
720 
721         // Update the name, so that the caller has the new name.
722         Name = Corrected.getCorrectionAsIdentifierInfo();
723 
724         // Typo correction corrected to a keyword.
725         if (Corrected.isKeyword())
726           return Name;
727 
728         // Also update the LookupResult...
729         // FIXME: This should probably go away at some point
730         Result.clear();
731         Result.setLookupName(Corrected.getCorrection());
732         if (FirstDecl)
733           Result.addDecl(FirstDecl);
734 
735         // If we found an Objective-C instance variable, let
736         // LookupInObjCMethod build the appropriate expression to
737         // reference the ivar.
738         // FIXME: This is a gross hack.
739         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
740           Result.clear();
741           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
742           return E;
743         }
744 
745         goto Corrected;
746       }
747     }
748 
749     // We failed to correct; just fall through and let the parser deal with it.
750     Result.suppressDiagnostics();
751     return NameClassification::Unknown();
752 
753   case LookupResult::NotFoundInCurrentInstantiation: {
754     // We performed name lookup into the current instantiation, and there were
755     // dependent bases, so we treat this result the same way as any other
756     // dependent nested-name-specifier.
757 
758     // C++ [temp.res]p2:
759     //   A name used in a template declaration or definition and that is
760     //   dependent on a template-parameter is assumed not to name a type
761     //   unless the applicable name lookup finds a type name or the name is
762     //   qualified by the keyword typename.
763     //
764     // FIXME: If the next token is '<', we might want to ask the parser to
765     // perform some heroics to see if we actually have a
766     // template-argument-list, which would indicate a missing 'template'
767     // keyword here.
768     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
769                                       NameInfo, IsAddressOfOperand,
770                                       /*TemplateArgs=*/nullptr);
771   }
772 
773   case LookupResult::Found:
774   case LookupResult::FoundOverloaded:
775   case LookupResult::FoundUnresolvedValue:
776     break;
777 
778   case LookupResult::Ambiguous:
779     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
780         hasAnyAcceptableTemplateNames(Result)) {
781       // C++ [temp.local]p3:
782       //   A lookup that finds an injected-class-name (10.2) can result in an
783       //   ambiguity in certain cases (for example, if it is found in more than
784       //   one base class). If all of the injected-class-names that are found
785       //   refer to specializations of the same class template, and if the name
786       //   is followed by a template-argument-list, the reference refers to the
787       //   class template itself and not a specialization thereof, and is not
788       //   ambiguous.
789       //
790       // This filtering can make an ambiguous result into an unambiguous one,
791       // so try again after filtering out template names.
792       FilterAcceptableTemplateNames(Result);
793       if (!Result.isAmbiguous()) {
794         IsFilteredTemplateName = true;
795         break;
796       }
797     }
798 
799     // Diagnose the ambiguity and return an error.
800     return NameClassification::Error();
801   }
802 
803   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
804       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
805     // C++ [temp.names]p3:
806     //   After name lookup (3.4) finds that a name is a template-name or that
807     //   an operator-function-id or a literal- operator-id refers to a set of
808     //   overloaded functions any member of which is a function template if
809     //   this is followed by a <, the < is always taken as the delimiter of a
810     //   template-argument-list and never as the less-than operator.
811     if (!IsFilteredTemplateName)
812       FilterAcceptableTemplateNames(Result);
813 
814     if (!Result.empty()) {
815       bool IsFunctionTemplate;
816       bool IsVarTemplate;
817       TemplateName Template;
818       if (Result.end() - Result.begin() > 1) {
819         IsFunctionTemplate = true;
820         Template = Context.getOverloadedTemplateName(Result.begin(),
821                                                      Result.end());
822       } else {
823         TemplateDecl *TD
824           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
825         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
826         IsVarTemplate = isa<VarTemplateDecl>(TD);
827 
828         if (SS.isSet() && !SS.isInvalid())
829           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
830                                                     /*TemplateKeyword=*/false,
831                                                       TD);
832         else
833           Template = TemplateName(TD);
834       }
835 
836       if (IsFunctionTemplate) {
837         // Function templates always go through overload resolution, at which
838         // point we'll perform the various checks (e.g., accessibility) we need
839         // to based on which function we selected.
840         Result.suppressDiagnostics();
841 
842         return NameClassification::FunctionTemplate(Template);
843       }
844 
845       return IsVarTemplate ? NameClassification::VarTemplate(Template)
846                            : NameClassification::TypeTemplate(Template);
847     }
848   }
849 
850   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
851   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
852     DiagnoseUseOfDecl(Type, NameLoc);
853     QualType T = Context.getTypeDeclType(Type);
854     if (SS.isNotEmpty())
855       return buildNestedType(*this, SS, T, NameLoc);
856     return ParsedType::make(T);
857   }
858 
859   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
860   if (!Class) {
861     // FIXME: It's unfortunate that we don't have a Type node for handling this.
862     if (ObjCCompatibleAliasDecl *Alias =
863             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
864       Class = Alias->getClassInterface();
865   }
866 
867   if (Class) {
868     DiagnoseUseOfDecl(Class, NameLoc);
869 
870     if (NextToken.is(tok::period)) {
871       // Interface. <something> is parsed as a property reference expression.
872       // Just return "unknown" as a fall-through for now.
873       Result.suppressDiagnostics();
874       return NameClassification::Unknown();
875     }
876 
877     QualType T = Context.getObjCInterfaceType(Class);
878     return ParsedType::make(T);
879   }
880 
881   // We can have a type template here if we're classifying a template argument.
882   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
883     return NameClassification::TypeTemplate(
884         TemplateName(cast<TemplateDecl>(FirstDecl)));
885 
886   // Check for a tag type hidden by a non-type decl in a few cases where it
887   // seems likely a type is wanted instead of the non-type that was found.
888   bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
889   if ((NextToken.is(tok::identifier) ||
890        (NextIsOp &&
891         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
892       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
893     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
894     DiagnoseUseOfDecl(Type, NameLoc);
895     QualType T = Context.getTypeDeclType(Type);
896     if (SS.isNotEmpty())
897       return buildNestedType(*this, SS, T, NameLoc);
898     return ParsedType::make(T);
899   }
900 
901   if (FirstDecl->isCXXClassMember())
902     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
903                                            nullptr);
904 
905   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
906   return BuildDeclarationNameExpr(SS, Result, ADL);
907 }
908 
909 // Determines the context to return to after temporarily entering a
910 // context.  This depends in an unnecessarily complicated way on the
911 // exact ordering of callbacks from the parser.
912 DeclContext *Sema::getContainingDC(DeclContext *DC) {
913 
914   // Functions defined inline within classes aren't parsed until we've
915   // finished parsing the top-level class, so the top-level class is
916   // the context we'll need to return to.
917   // A Lambda call operator whose parent is a class must not be treated
918   // as an inline member function.  A Lambda can be used legally
919   // either as an in-class member initializer or a default argument.  These
920   // are parsed once the class has been marked complete and so the containing
921   // context would be the nested class (when the lambda is defined in one);
922   // If the class is not complete, then the lambda is being used in an
923   // ill-formed fashion (such as to specify the width of a bit-field, or
924   // in an array-bound) - in which case we still want to return the
925   // lexically containing DC (which could be a nested class).
926   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
927     DC = DC->getLexicalParent();
928 
929     // A function not defined within a class will always return to its
930     // lexical context.
931     if (!isa<CXXRecordDecl>(DC))
932       return DC;
933 
934     // A C++ inline method/friend is parsed *after* the topmost class
935     // it was declared in is fully parsed ("complete");  the topmost
936     // class is the context we need to return to.
937     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
938       DC = RD;
939 
940     // Return the declaration context of the topmost class the inline method is
941     // declared in.
942     return DC;
943   }
944 
945   return DC->getLexicalParent();
946 }
947 
948 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
949   assert(getContainingDC(DC) == CurContext &&
950       "The next DeclContext should be lexically contained in the current one.");
951   CurContext = DC;
952   S->setEntity(DC);
953 }
954 
955 void Sema::PopDeclContext() {
956   assert(CurContext && "DeclContext imbalance!");
957 
958   CurContext = getContainingDC(CurContext);
959   assert(CurContext && "Popped translation unit!");
960 }
961 
962 /// EnterDeclaratorContext - Used when we must lookup names in the context
963 /// of a declarator's nested name specifier.
964 ///
965 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
966   // C++0x [basic.lookup.unqual]p13:
967   //   A name used in the definition of a static data member of class
968   //   X (after the qualified-id of the static member) is looked up as
969   //   if the name was used in a member function of X.
970   // C++0x [basic.lookup.unqual]p14:
971   //   If a variable member of a namespace is defined outside of the
972   //   scope of its namespace then any name used in the definition of
973   //   the variable member (after the declarator-id) is looked up as
974   //   if the definition of the variable member occurred in its
975   //   namespace.
976   // Both of these imply that we should push a scope whose context
977   // is the semantic context of the declaration.  We can't use
978   // PushDeclContext here because that context is not necessarily
979   // lexically contained in the current context.  Fortunately,
980   // the containing scope should have the appropriate information.
981 
982   assert(!S->getEntity() && "scope already has entity");
983 
984 #ifndef NDEBUG
985   Scope *Ancestor = S->getParent();
986   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
987   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
988 #endif
989 
990   CurContext = DC;
991   S->setEntity(DC);
992 }
993 
994 void Sema::ExitDeclaratorContext(Scope *S) {
995   assert(S->getEntity() == CurContext && "Context imbalance!");
996 
997   // Switch back to the lexical context.  The safety of this is
998   // enforced by an assert in EnterDeclaratorContext.
999   Scope *Ancestor = S->getParent();
1000   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1001   CurContext = Ancestor->getEntity();
1002 
1003   // We don't need to do anything with the scope, which is going to
1004   // disappear.
1005 }
1006 
1007 
1008 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1009   // We assume that the caller has already called
1010   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1011   FunctionDecl *FD = D->getAsFunction();
1012   if (!FD)
1013     return;
1014 
1015   // Same implementation as PushDeclContext, but enters the context
1016   // from the lexical parent, rather than the top-level class.
1017   assert(CurContext == FD->getLexicalParent() &&
1018     "The next DeclContext should be lexically contained in the current one.");
1019   CurContext = FD;
1020   S->setEntity(CurContext);
1021 
1022   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1023     ParmVarDecl *Param = FD->getParamDecl(P);
1024     // If the parameter has an identifier, then add it to the scope
1025     if (Param->getIdentifier()) {
1026       S->AddDecl(Param);
1027       IdResolver.AddDecl(Param);
1028     }
1029   }
1030 }
1031 
1032 
1033 void Sema::ActOnExitFunctionContext() {
1034   // Same implementation as PopDeclContext, but returns to the lexical parent,
1035   // rather than the top-level class.
1036   assert(CurContext && "DeclContext imbalance!");
1037   CurContext = CurContext->getLexicalParent();
1038   assert(CurContext && "Popped translation unit!");
1039 }
1040 
1041 
1042 /// \brief Determine whether we allow overloading of the function
1043 /// PrevDecl with another declaration.
1044 ///
1045 /// This routine determines whether overloading is possible, not
1046 /// whether some new function is actually an overload. It will return
1047 /// true in C++ (where we can always provide overloads) or, as an
1048 /// extension, in C when the previous function is already an
1049 /// overloaded function declaration or has the "overloadable"
1050 /// attribute.
1051 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1052                                        ASTContext &Context) {
1053   if (Context.getLangOpts().CPlusPlus)
1054     return true;
1055 
1056   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1057     return true;
1058 
1059   return (Previous.getResultKind() == LookupResult::Found
1060           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1061 }
1062 
1063 /// Add this decl to the scope shadowed decl chains.
1064 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1065   // Move up the scope chain until we find the nearest enclosing
1066   // non-transparent context. The declaration will be introduced into this
1067   // scope.
1068   while (S->getEntity() && S->getEntity()->isTransparentContext())
1069     S = S->getParent();
1070 
1071   // Add scoped declarations into their context, so that they can be
1072   // found later. Declarations without a context won't be inserted
1073   // into any context.
1074   if (AddToContext)
1075     CurContext->addDecl(D);
1076 
1077   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1078   // are function-local declarations.
1079   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1080       !D->getDeclContext()->getRedeclContext()->Equals(
1081         D->getLexicalDeclContext()->getRedeclContext()) &&
1082       !D->getLexicalDeclContext()->isFunctionOrMethod())
1083     return;
1084 
1085   // Template instantiations should also not be pushed into scope.
1086   if (isa<FunctionDecl>(D) &&
1087       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1088     return;
1089 
1090   // If this replaces anything in the current scope,
1091   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1092                                IEnd = IdResolver.end();
1093   for (; I != IEnd; ++I) {
1094     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1095       S->RemoveDecl(*I);
1096       IdResolver.RemoveDecl(*I);
1097 
1098       // Should only need to replace one decl.
1099       break;
1100     }
1101   }
1102 
1103   S->AddDecl(D);
1104 
1105   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1106     // Implicitly-generated labels may end up getting generated in an order that
1107     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1108     // the label at the appropriate place in the identifier chain.
1109     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1110       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1111       if (IDC == CurContext) {
1112         if (!S->isDeclScope(*I))
1113           continue;
1114       } else if (IDC->Encloses(CurContext))
1115         break;
1116     }
1117 
1118     IdResolver.InsertDeclAfter(I, D);
1119   } else {
1120     IdResolver.AddDecl(D);
1121   }
1122 }
1123 
1124 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1125   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1126     TUScope->AddDecl(D);
1127 }
1128 
1129 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1130                          bool AllowInlineNamespace) {
1131   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1132 }
1133 
1134 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1135   DeclContext *TargetDC = DC->getPrimaryContext();
1136   do {
1137     if (DeclContext *ScopeDC = S->getEntity())
1138       if (ScopeDC->getPrimaryContext() == TargetDC)
1139         return S;
1140   } while ((S = S->getParent()));
1141 
1142   return nullptr;
1143 }
1144 
1145 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1146                                             DeclContext*,
1147                                             ASTContext&);
1148 
1149 /// Filters out lookup results that don't fall within the given scope
1150 /// as determined by isDeclInScope.
1151 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1152                                 bool ConsiderLinkage,
1153                                 bool AllowInlineNamespace) {
1154   LookupResult::Filter F = R.makeFilter();
1155   while (F.hasNext()) {
1156     NamedDecl *D = F.next();
1157 
1158     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1159       continue;
1160 
1161     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1162       continue;
1163 
1164     F.erase();
1165   }
1166 
1167   F.done();
1168 }
1169 
1170 static bool isUsingDecl(NamedDecl *D) {
1171   return isa<UsingShadowDecl>(D) ||
1172          isa<UnresolvedUsingTypenameDecl>(D) ||
1173          isa<UnresolvedUsingValueDecl>(D);
1174 }
1175 
1176 /// Removes using shadow declarations from the lookup results.
1177 static void RemoveUsingDecls(LookupResult &R) {
1178   LookupResult::Filter F = R.makeFilter();
1179   while (F.hasNext())
1180     if (isUsingDecl(F.next()))
1181       F.erase();
1182 
1183   F.done();
1184 }
1185 
1186 /// \brief Check for this common pattern:
1187 /// @code
1188 /// class S {
1189 ///   S(const S&); // DO NOT IMPLEMENT
1190 ///   void operator=(const S&); // DO NOT IMPLEMENT
1191 /// };
1192 /// @endcode
1193 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1194   // FIXME: Should check for private access too but access is set after we get
1195   // the decl here.
1196   if (D->doesThisDeclarationHaveABody())
1197     return false;
1198 
1199   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1200     return CD->isCopyConstructor();
1201   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1202     return Method->isCopyAssignmentOperator();
1203   return false;
1204 }
1205 
1206 // We need this to handle
1207 //
1208 // typedef struct {
1209 //   void *foo() { return 0; }
1210 // } A;
1211 //
1212 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1213 // for example. If 'A', foo will have external linkage. If we have '*A',
1214 // foo will have no linkage. Since we can't know until we get to the end
1215 // of the typedef, this function finds out if D might have non-external linkage.
1216 // Callers should verify at the end of the TU if it D has external linkage or
1217 // not.
1218 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1219   const DeclContext *DC = D->getDeclContext();
1220   while (!DC->isTranslationUnit()) {
1221     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1222       if (!RD->hasNameForLinkage())
1223         return true;
1224     }
1225     DC = DC->getParent();
1226   }
1227 
1228   return !D->isExternallyVisible();
1229 }
1230 
1231 // FIXME: This needs to be refactored; some other isInMainFile users want
1232 // these semantics.
1233 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1234   if (S.TUKind != TU_Complete)
1235     return false;
1236   return S.SourceMgr.isInMainFile(Loc);
1237 }
1238 
1239 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1240   assert(D);
1241 
1242   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1243     return false;
1244 
1245   // Ignore all entities declared within templates, and out-of-line definitions
1246   // of members of class templates.
1247   if (D->getDeclContext()->isDependentContext() ||
1248       D->getLexicalDeclContext()->isDependentContext())
1249     return false;
1250 
1251   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1252     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1253       return false;
1254 
1255     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1256       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1257         return false;
1258     } else {
1259       // 'static inline' functions are defined in headers; don't warn.
1260       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1261         return false;
1262     }
1263 
1264     if (FD->doesThisDeclarationHaveABody() &&
1265         Context.DeclMustBeEmitted(FD))
1266       return false;
1267   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1268     // Constants and utility variables are defined in headers with internal
1269     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1270     // like "inline".)
1271     if (!isMainFileLoc(*this, VD->getLocation()))
1272       return false;
1273 
1274     if (Context.DeclMustBeEmitted(VD))
1275       return false;
1276 
1277     if (VD->isStaticDataMember() &&
1278         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1279       return false;
1280   } else {
1281     return false;
1282   }
1283 
1284   // Only warn for unused decls internal to the translation unit.
1285   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1286   // for inline functions defined in the main source file, for instance.
1287   return mightHaveNonExternalLinkage(D);
1288 }
1289 
1290 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1291   if (!D)
1292     return;
1293 
1294   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1295     const FunctionDecl *First = FD->getFirstDecl();
1296     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1297       return; // First should already be in the vector.
1298   }
1299 
1300   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1301     const VarDecl *First = VD->getFirstDecl();
1302     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1303       return; // First should already be in the vector.
1304   }
1305 
1306   if (ShouldWarnIfUnusedFileScopedDecl(D))
1307     UnusedFileScopedDecls.push_back(D);
1308 }
1309 
1310 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1311   if (D->isInvalidDecl())
1312     return false;
1313 
1314   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1315       D->hasAttr<ObjCPreciseLifetimeAttr>())
1316     return false;
1317 
1318   if (isa<LabelDecl>(D))
1319     return true;
1320 
1321   // White-list anything that isn't a local variable.
1322   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1323       !D->getDeclContext()->isFunctionOrMethod())
1324     return false;
1325 
1326   // Types of valid local variables should be complete, so this should succeed.
1327   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1328 
1329     // White-list anything with an __attribute__((unused)) type.
1330     QualType Ty = VD->getType();
1331 
1332     // Only look at the outermost level of typedef.
1333     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1334       if (TT->getDecl()->hasAttr<UnusedAttr>())
1335         return false;
1336     }
1337 
1338     // If we failed to complete the type for some reason, or if the type is
1339     // dependent, don't diagnose the variable.
1340     if (Ty->isIncompleteType() || Ty->isDependentType())
1341       return false;
1342 
1343     if (const TagType *TT = Ty->getAs<TagType>()) {
1344       const TagDecl *Tag = TT->getDecl();
1345       if (Tag->hasAttr<UnusedAttr>())
1346         return false;
1347 
1348       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1349         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1350           return false;
1351 
1352         if (const Expr *Init = VD->getInit()) {
1353           if (const ExprWithCleanups *Cleanups =
1354                   dyn_cast<ExprWithCleanups>(Init))
1355             Init = Cleanups->getSubExpr();
1356           const CXXConstructExpr *Construct =
1357             dyn_cast<CXXConstructExpr>(Init);
1358           if (Construct && !Construct->isElidable()) {
1359             CXXConstructorDecl *CD = Construct->getConstructor();
1360             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1361               return false;
1362           }
1363         }
1364       }
1365     }
1366 
1367     // TODO: __attribute__((unused)) templates?
1368   }
1369 
1370   return true;
1371 }
1372 
1373 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1374                                      FixItHint &Hint) {
1375   if (isa<LabelDecl>(D)) {
1376     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1377                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1378     if (AfterColon.isInvalid())
1379       return;
1380     Hint = FixItHint::CreateRemoval(CharSourceRange::
1381                                     getCharRange(D->getLocStart(), AfterColon));
1382   }
1383   return;
1384 }
1385 
1386 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1387 /// unless they are marked attr(unused).
1388 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1389   if (!ShouldDiagnoseUnusedDecl(D))
1390     return;
1391 
1392   FixItHint Hint;
1393   GenerateFixForUnusedDecl(D, Context, Hint);
1394 
1395   unsigned DiagID;
1396   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1397     DiagID = diag::warn_unused_exception_param;
1398   else if (isa<LabelDecl>(D))
1399     DiagID = diag::warn_unused_label;
1400   else
1401     DiagID = diag::warn_unused_variable;
1402 
1403   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1404 }
1405 
1406 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1407   // Verify that we have no forward references left.  If so, there was a goto
1408   // or address of a label taken, but no definition of it.  Label fwd
1409   // definitions are indicated with a null substmt.
1410   if (L->getStmt() == nullptr)
1411     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1412 }
1413 
1414 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1415   S->mergeNRVOIntoParent();
1416 
1417   if (S->decl_empty()) return;
1418   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1419          "Scope shouldn't contain decls!");
1420 
1421   for (auto *TmpD : S->decls()) {
1422     assert(TmpD && "This decl didn't get pushed??");
1423 
1424     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1425     NamedDecl *D = cast<NamedDecl>(TmpD);
1426 
1427     if (!D->getDeclName()) continue;
1428 
1429     // Diagnose unused variables in this scope.
1430     if (!S->hasUnrecoverableErrorOccurred())
1431       DiagnoseUnusedDecl(D);
1432 
1433     // If this was a forward reference to a label, verify it was defined.
1434     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1435       CheckPoppedLabel(LD, *this);
1436 
1437     // Remove this name from our lexical scope.
1438     IdResolver.RemoveDecl(D);
1439   }
1440 }
1441 
1442 /// \brief Look for an Objective-C class in the translation unit.
1443 ///
1444 /// \param Id The name of the Objective-C class we're looking for. If
1445 /// typo-correction fixes this name, the Id will be updated
1446 /// to the fixed name.
1447 ///
1448 /// \param IdLoc The location of the name in the translation unit.
1449 ///
1450 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1451 /// if there is no class with the given name.
1452 ///
1453 /// \returns The declaration of the named Objective-C class, or NULL if the
1454 /// class could not be found.
1455 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1456                                               SourceLocation IdLoc,
1457                                               bool DoTypoCorrection) {
1458   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1459   // creation from this context.
1460   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1461 
1462   if (!IDecl && DoTypoCorrection) {
1463     // Perform typo correction at the given location, but only if we
1464     // find an Objective-C class name.
1465     DeclFilterCCC<ObjCInterfaceDecl> Validator;
1466     if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1467                                        LookupOrdinaryName, TUScope, nullptr,
1468                                        Validator, CTK_ErrorRecovery)) {
1469       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1470       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1471       Id = IDecl->getIdentifier();
1472     }
1473   }
1474   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1475   // This routine must always return a class definition, if any.
1476   if (Def && Def->getDefinition())
1477       Def = Def->getDefinition();
1478   return Def;
1479 }
1480 
1481 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1482 /// from S, where a non-field would be declared. This routine copes
1483 /// with the difference between C and C++ scoping rules in structs and
1484 /// unions. For example, the following code is well-formed in C but
1485 /// ill-formed in C++:
1486 /// @code
1487 /// struct S6 {
1488 ///   enum { BAR } e;
1489 /// };
1490 ///
1491 /// void test_S6() {
1492 ///   struct S6 a;
1493 ///   a.e = BAR;
1494 /// }
1495 /// @endcode
1496 /// For the declaration of BAR, this routine will return a different
1497 /// scope. The scope S will be the scope of the unnamed enumeration
1498 /// within S6. In C++, this routine will return the scope associated
1499 /// with S6, because the enumeration's scope is a transparent
1500 /// context but structures can contain non-field names. In C, this
1501 /// routine will return the translation unit scope, since the
1502 /// enumeration's scope is a transparent context and structures cannot
1503 /// contain non-field names.
1504 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1505   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1506          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1507          (S->isClassScope() && !getLangOpts().CPlusPlus))
1508     S = S->getParent();
1509   return S;
1510 }
1511 
1512 /// \brief Looks up the declaration of "struct objc_super" and
1513 /// saves it for later use in building builtin declaration of
1514 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1515 /// pre-existing declaration exists no action takes place.
1516 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1517                                         IdentifierInfo *II) {
1518   if (!II->isStr("objc_msgSendSuper"))
1519     return;
1520   ASTContext &Context = ThisSema.Context;
1521 
1522   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1523                       SourceLocation(), Sema::LookupTagName);
1524   ThisSema.LookupName(Result, S);
1525   if (Result.getResultKind() == LookupResult::Found)
1526     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1527       Context.setObjCSuperType(Context.getTagDeclType(TD));
1528 }
1529 
1530 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1531 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1532 /// if we're creating this built-in in anticipation of redeclaring the
1533 /// built-in.
1534 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1535                                      Scope *S, bool ForRedeclaration,
1536                                      SourceLocation Loc) {
1537   LookupPredefedObjCSuperType(*this, S, II);
1538 
1539   Builtin::ID BID = (Builtin::ID)bid;
1540 
1541   ASTContext::GetBuiltinTypeError Error;
1542   QualType R = Context.GetBuiltinType(BID, Error);
1543   switch (Error) {
1544   case ASTContext::GE_None:
1545     // Okay
1546     break;
1547 
1548   case ASTContext::GE_Missing_stdio:
1549     if (ForRedeclaration)
1550       Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1551         << Context.BuiltinInfo.GetName(BID);
1552     return nullptr;
1553 
1554   case ASTContext::GE_Missing_setjmp:
1555     if (ForRedeclaration)
1556       Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1557         << Context.BuiltinInfo.GetName(BID);
1558     return nullptr;
1559 
1560   case ASTContext::GE_Missing_ucontext:
1561     if (ForRedeclaration)
1562       Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1563         << Context.BuiltinInfo.GetName(BID);
1564     return nullptr;
1565   }
1566 
1567   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1568     Diag(Loc, diag::ext_implicit_lib_function_decl)
1569       << Context.BuiltinInfo.GetName(BID)
1570       << R;
1571     if (Context.BuiltinInfo.getHeaderName(BID) &&
1572         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1573       Diag(Loc, diag::note_please_include_header)
1574         << Context.BuiltinInfo.getHeaderName(BID)
1575         << Context.BuiltinInfo.GetName(BID);
1576   }
1577 
1578   DeclContext *Parent = Context.getTranslationUnitDecl();
1579   if (getLangOpts().CPlusPlus) {
1580     LinkageSpecDecl *CLinkageDecl =
1581         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1582                                 LinkageSpecDecl::lang_c, false);
1583     CLinkageDecl->setImplicit();
1584     Parent->addDecl(CLinkageDecl);
1585     Parent = CLinkageDecl;
1586   }
1587 
1588   FunctionDecl *New = FunctionDecl::Create(Context,
1589                                            Parent,
1590                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1591                                            SC_Extern,
1592                                            false,
1593                                            /*hasPrototype=*/true);
1594   New->setImplicit();
1595 
1596   // Create Decl objects for each parameter, adding them to the
1597   // FunctionDecl.
1598   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1599     SmallVector<ParmVarDecl*, 16> Params;
1600     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1601       ParmVarDecl *parm =
1602           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1603                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1604                               SC_None, nullptr);
1605       parm->setScopeInfo(0, i);
1606       Params.push_back(parm);
1607     }
1608     New->setParams(Params);
1609   }
1610 
1611   AddKnownFunctionAttributes(New);
1612   RegisterLocallyScopedExternCDecl(New, S);
1613 
1614   // TUScope is the translation-unit scope to insert this function into.
1615   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1616   // relate Scopes to DeclContexts, and probably eliminate CurContext
1617   // entirely, but we're not there yet.
1618   DeclContext *SavedContext = CurContext;
1619   CurContext = Parent;
1620   PushOnScopeChains(New, TUScope);
1621   CurContext = SavedContext;
1622   return New;
1623 }
1624 
1625 /// \brief Filter out any previous declarations that the given declaration
1626 /// should not consider because they are not permitted to conflict, e.g.,
1627 /// because they come from hidden sub-modules and do not refer to the same
1628 /// entity.
1629 static void filterNonConflictingPreviousDecls(ASTContext &context,
1630                                               NamedDecl *decl,
1631                                               LookupResult &previous){
1632   // This is only interesting when modules are enabled.
1633   if (!context.getLangOpts().Modules)
1634     return;
1635 
1636   // Empty sets are uninteresting.
1637   if (previous.empty())
1638     return;
1639 
1640   LookupResult::Filter filter = previous.makeFilter();
1641   while (filter.hasNext()) {
1642     NamedDecl *old = filter.next();
1643 
1644     // Non-hidden declarations are never ignored.
1645     if (!old->isHidden())
1646       continue;
1647 
1648     if (!old->isExternallyVisible())
1649       filter.erase();
1650   }
1651 
1652   filter.done();
1653 }
1654 
1655 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1656   QualType OldType;
1657   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1658     OldType = OldTypedef->getUnderlyingType();
1659   else
1660     OldType = Context.getTypeDeclType(Old);
1661   QualType NewType = New->getUnderlyingType();
1662 
1663   if (NewType->isVariablyModifiedType()) {
1664     // Must not redefine a typedef with a variably-modified type.
1665     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1666     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1667       << Kind << NewType;
1668     if (Old->getLocation().isValid())
1669       Diag(Old->getLocation(), diag::note_previous_definition);
1670     New->setInvalidDecl();
1671     return true;
1672   }
1673 
1674   if (OldType != NewType &&
1675       !OldType->isDependentType() &&
1676       !NewType->isDependentType() &&
1677       !Context.hasSameType(OldType, NewType)) {
1678     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1679     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1680       << Kind << NewType << OldType;
1681     if (Old->getLocation().isValid())
1682       Diag(Old->getLocation(), diag::note_previous_definition);
1683     New->setInvalidDecl();
1684     return true;
1685   }
1686   return false;
1687 }
1688 
1689 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1690 /// same name and scope as a previous declaration 'Old'.  Figure out
1691 /// how to resolve this situation, merging decls or emitting
1692 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1693 ///
1694 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1695   // If the new decl is known invalid already, don't bother doing any
1696   // merging checks.
1697   if (New->isInvalidDecl()) return;
1698 
1699   // Allow multiple definitions for ObjC built-in typedefs.
1700   // FIXME: Verify the underlying types are equivalent!
1701   if (getLangOpts().ObjC1) {
1702     const IdentifierInfo *TypeID = New->getIdentifier();
1703     switch (TypeID->getLength()) {
1704     default: break;
1705     case 2:
1706       {
1707         if (!TypeID->isStr("id"))
1708           break;
1709         QualType T = New->getUnderlyingType();
1710         if (!T->isPointerType())
1711           break;
1712         if (!T->isVoidPointerType()) {
1713           QualType PT = T->getAs<PointerType>()->getPointeeType();
1714           if (!PT->isStructureType())
1715             break;
1716         }
1717         Context.setObjCIdRedefinitionType(T);
1718         // Install the built-in type for 'id', ignoring the current definition.
1719         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1720         return;
1721       }
1722     case 5:
1723       if (!TypeID->isStr("Class"))
1724         break;
1725       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1726       // Install the built-in type for 'Class', ignoring the current definition.
1727       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1728       return;
1729     case 3:
1730       if (!TypeID->isStr("SEL"))
1731         break;
1732       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1733       // Install the built-in type for 'SEL', ignoring the current definition.
1734       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1735       return;
1736     }
1737     // Fall through - the typedef name was not a builtin type.
1738   }
1739 
1740   // Verify the old decl was also a type.
1741   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1742   if (!Old) {
1743     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1744       << New->getDeclName();
1745 
1746     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1747     if (OldD->getLocation().isValid())
1748       Diag(OldD->getLocation(), diag::note_previous_definition);
1749 
1750     return New->setInvalidDecl();
1751   }
1752 
1753   // If the old declaration is invalid, just give up here.
1754   if (Old->isInvalidDecl())
1755     return New->setInvalidDecl();
1756 
1757   // If the typedef types are not identical, reject them in all languages and
1758   // with any extensions enabled.
1759   if (isIncompatibleTypedef(Old, New))
1760     return;
1761 
1762   // The types match.  Link up the redeclaration chain and merge attributes if
1763   // the old declaration was a typedef.
1764   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1765     New->setPreviousDecl(Typedef);
1766     mergeDeclAttributes(New, Old);
1767   }
1768 
1769   if (getLangOpts().MicrosoftExt)
1770     return;
1771 
1772   if (getLangOpts().CPlusPlus) {
1773     // C++ [dcl.typedef]p2:
1774     //   In a given non-class scope, a typedef specifier can be used to
1775     //   redefine the name of any type declared in that scope to refer
1776     //   to the type to which it already refers.
1777     if (!isa<CXXRecordDecl>(CurContext))
1778       return;
1779 
1780     // C++0x [dcl.typedef]p4:
1781     //   In a given class scope, a typedef specifier can be used to redefine
1782     //   any class-name declared in that scope that is not also a typedef-name
1783     //   to refer to the type to which it already refers.
1784     //
1785     // This wording came in via DR424, which was a correction to the
1786     // wording in DR56, which accidentally banned code like:
1787     //
1788     //   struct S {
1789     //     typedef struct A { } A;
1790     //   };
1791     //
1792     // in the C++03 standard. We implement the C++0x semantics, which
1793     // allow the above but disallow
1794     //
1795     //   struct S {
1796     //     typedef int I;
1797     //     typedef int I;
1798     //   };
1799     //
1800     // since that was the intent of DR56.
1801     if (!isa<TypedefNameDecl>(Old))
1802       return;
1803 
1804     Diag(New->getLocation(), diag::err_redefinition)
1805       << New->getDeclName();
1806     Diag(Old->getLocation(), diag::note_previous_definition);
1807     return New->setInvalidDecl();
1808   }
1809 
1810   // Modules always permit redefinition of typedefs, as does C11.
1811   if (getLangOpts().Modules || getLangOpts().C11)
1812     return;
1813 
1814   // If we have a redefinition of a typedef in C, emit a warning.  This warning
1815   // is normally mapped to an error, but can be controlled with
1816   // -Wtypedef-redefinition.  If either the original or the redefinition is
1817   // in a system header, don't emit this for compatibility with GCC.
1818   if (getDiagnostics().getSuppressSystemWarnings() &&
1819       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1820        Context.getSourceManager().isInSystemHeader(New->getLocation())))
1821     return;
1822 
1823   Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1824     << New->getDeclName();
1825   Diag(Old->getLocation(), diag::note_previous_definition);
1826   return;
1827 }
1828 
1829 /// DeclhasAttr - returns true if decl Declaration already has the target
1830 /// attribute.
1831 static bool DeclHasAttr(const Decl *D, const Attr *A) {
1832   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1833   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1834   for (const auto *i : D->attrs())
1835     if (i->getKind() == A->getKind()) {
1836       if (Ann) {
1837         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
1838           return true;
1839         continue;
1840       }
1841       // FIXME: Don't hardcode this check
1842       if (OA && isa<OwnershipAttr>(i))
1843         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
1844       return true;
1845     }
1846 
1847   return false;
1848 }
1849 
1850 static bool isAttributeTargetADefinition(Decl *D) {
1851   if (VarDecl *VD = dyn_cast<VarDecl>(D))
1852     return VD->isThisDeclarationADefinition();
1853   if (TagDecl *TD = dyn_cast<TagDecl>(D))
1854     return TD->isCompleteDefinition() || TD->isBeingDefined();
1855   return true;
1856 }
1857 
1858 /// Merge alignment attributes from \p Old to \p New, taking into account the
1859 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1860 ///
1861 /// \return \c true if any attributes were added to \p New.
1862 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1863   // Look for alignas attributes on Old, and pick out whichever attribute
1864   // specifies the strictest alignment requirement.
1865   AlignedAttr *OldAlignasAttr = nullptr;
1866   AlignedAttr *OldStrictestAlignAttr = nullptr;
1867   unsigned OldAlign = 0;
1868   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
1869     // FIXME: We have no way of representing inherited dependent alignments
1870     // in a case like:
1871     //   template<int A, int B> struct alignas(A) X;
1872     //   template<int A, int B> struct alignas(B) X {};
1873     // For now, we just ignore any alignas attributes which are not on the
1874     // definition in such a case.
1875     if (I->isAlignmentDependent())
1876       return false;
1877 
1878     if (I->isAlignas())
1879       OldAlignasAttr = I;
1880 
1881     unsigned Align = I->getAlignment(S.Context);
1882     if (Align > OldAlign) {
1883       OldAlign = Align;
1884       OldStrictestAlignAttr = I;
1885     }
1886   }
1887 
1888   // Look for alignas attributes on New.
1889   AlignedAttr *NewAlignasAttr = nullptr;
1890   unsigned NewAlign = 0;
1891   for (auto *I : New->specific_attrs<AlignedAttr>()) {
1892     if (I->isAlignmentDependent())
1893       return false;
1894 
1895     if (I->isAlignas())
1896       NewAlignasAttr = I;
1897 
1898     unsigned Align = I->getAlignment(S.Context);
1899     if (Align > NewAlign)
1900       NewAlign = Align;
1901   }
1902 
1903   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1904     // Both declarations have 'alignas' attributes. We require them to match.
1905     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1906     // fall short. (If two declarations both have alignas, they must both match
1907     // every definition, and so must match each other if there is a definition.)
1908 
1909     // If either declaration only contains 'alignas(0)' specifiers, then it
1910     // specifies the natural alignment for the type.
1911     if (OldAlign == 0 || NewAlign == 0) {
1912       QualType Ty;
1913       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1914         Ty = VD->getType();
1915       else
1916         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1917 
1918       if (OldAlign == 0)
1919         OldAlign = S.Context.getTypeAlign(Ty);
1920       if (NewAlign == 0)
1921         NewAlign = S.Context.getTypeAlign(Ty);
1922     }
1923 
1924     if (OldAlign != NewAlign) {
1925       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1926         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1927         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1928       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1929     }
1930   }
1931 
1932   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1933     // C++11 [dcl.align]p6:
1934     //   if any declaration of an entity has an alignment-specifier,
1935     //   every defining declaration of that entity shall specify an
1936     //   equivalent alignment.
1937     // C11 6.7.5/7:
1938     //   If the definition of an object does not have an alignment
1939     //   specifier, any other declaration of that object shall also
1940     //   have no alignment specifier.
1941     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1942       << OldAlignasAttr;
1943     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1944       << OldAlignasAttr;
1945   }
1946 
1947   bool AnyAdded = false;
1948 
1949   // Ensure we have an attribute representing the strictest alignment.
1950   if (OldAlign > NewAlign) {
1951     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1952     Clone->setInherited(true);
1953     New->addAttr(Clone);
1954     AnyAdded = true;
1955   }
1956 
1957   // Ensure we have an alignas attribute if the old declaration had one.
1958   if (OldAlignasAttr && !NewAlignasAttr &&
1959       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1960     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1961     Clone->setInherited(true);
1962     New->addAttr(Clone);
1963     AnyAdded = true;
1964   }
1965 
1966   return AnyAdded;
1967 }
1968 
1969 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
1970                                const InheritableAttr *Attr, bool Override) {
1971   InheritableAttr *NewAttr = nullptr;
1972   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
1973   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
1974     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1975                                       AA->getIntroduced(), AA->getDeprecated(),
1976                                       AA->getObsoleted(), AA->getUnavailable(),
1977                                       AA->getMessage(), Override,
1978                                       AttrSpellingListIndex);
1979   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
1980     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1981                                     AttrSpellingListIndex);
1982   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1983     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1984                                         AttrSpellingListIndex);
1985   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
1986     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1987                                    AttrSpellingListIndex);
1988   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
1989     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1990                                    AttrSpellingListIndex);
1991   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
1992     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1993                                 FA->getFormatIdx(), FA->getFirstArg(),
1994                                 AttrSpellingListIndex);
1995   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
1996     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1997                                  AttrSpellingListIndex);
1998   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
1999     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2000                                        AttrSpellingListIndex,
2001                                        IA->getSemanticSpelling());
2002   else if (isa<AlignedAttr>(Attr))
2003     // AlignedAttrs are handled separately, because we need to handle all
2004     // such attributes on a declaration at the same time.
2005     NewAttr = nullptr;
2006   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2007     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2008 
2009   if (NewAttr) {
2010     NewAttr->setInherited(true);
2011     D->addAttr(NewAttr);
2012     return true;
2013   }
2014 
2015   return false;
2016 }
2017 
2018 static const Decl *getDefinition(const Decl *D) {
2019   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2020     return TD->getDefinition();
2021   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2022     const VarDecl *Def = VD->getDefinition();
2023     if (Def)
2024       return Def;
2025     return VD->getActingDefinition();
2026   }
2027   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2028     const FunctionDecl* Def;
2029     if (FD->isDefined(Def))
2030       return Def;
2031   }
2032   return nullptr;
2033 }
2034 
2035 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2036   for (const auto *Attribute : D->attrs())
2037     if (Attribute->getKind() == Kind)
2038       return true;
2039   return false;
2040 }
2041 
2042 /// checkNewAttributesAfterDef - If we already have a definition, check that
2043 /// there are no new attributes in this declaration.
2044 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2045   if (!New->hasAttrs())
2046     return;
2047 
2048   const Decl *Def = getDefinition(Old);
2049   if (!Def || Def == New)
2050     return;
2051 
2052   AttrVec &NewAttributes = New->getAttrs();
2053   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2054     const Attr *NewAttribute = NewAttributes[I];
2055 
2056     if (isa<AliasAttr>(NewAttribute)) {
2057       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2058         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2059       else {
2060         VarDecl *VD = cast<VarDecl>(New);
2061         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2062                                 VarDecl::TentativeDefinition
2063                             ? diag::err_alias_after_tentative
2064                             : diag::err_redefinition;
2065         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2066         S.Diag(Def->getLocation(), diag::note_previous_definition);
2067         VD->setInvalidDecl();
2068       }
2069       ++I;
2070       continue;
2071     }
2072 
2073     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2074       // Tentative definitions are only interesting for the alias check above.
2075       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2076         ++I;
2077         continue;
2078       }
2079     }
2080 
2081     if (hasAttribute(Def, NewAttribute->getKind())) {
2082       ++I;
2083       continue; // regular attr merging will take care of validating this.
2084     }
2085 
2086     if (isa<C11NoReturnAttr>(NewAttribute)) {
2087       // C's _Noreturn is allowed to be added to a function after it is defined.
2088       ++I;
2089       continue;
2090     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2091       if (AA->isAlignas()) {
2092         // C++11 [dcl.align]p6:
2093         //   if any declaration of an entity has an alignment-specifier,
2094         //   every defining declaration of that entity shall specify an
2095         //   equivalent alignment.
2096         // C11 6.7.5/7:
2097         //   If the definition of an object does not have an alignment
2098         //   specifier, any other declaration of that object shall also
2099         //   have no alignment specifier.
2100         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2101           << AA;
2102         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2103           << AA;
2104         NewAttributes.erase(NewAttributes.begin() + I);
2105         --E;
2106         continue;
2107       }
2108     }
2109 
2110     S.Diag(NewAttribute->getLocation(),
2111            diag::warn_attribute_precede_definition);
2112     S.Diag(Def->getLocation(), diag::note_previous_definition);
2113     NewAttributes.erase(NewAttributes.begin() + I);
2114     --E;
2115   }
2116 }
2117 
2118 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2119 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2120                                AvailabilityMergeKind AMK) {
2121   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2122     UsedAttr *NewAttr = OldAttr->clone(Context);
2123     NewAttr->setInherited(true);
2124     New->addAttr(NewAttr);
2125   }
2126 
2127   if (!Old->hasAttrs() && !New->hasAttrs())
2128     return;
2129 
2130   // attributes declared post-definition are currently ignored
2131   checkNewAttributesAfterDef(*this, New, Old);
2132 
2133   if (!Old->hasAttrs())
2134     return;
2135 
2136   bool foundAny = New->hasAttrs();
2137 
2138   // Ensure that any moving of objects within the allocated map is done before
2139   // we process them.
2140   if (!foundAny) New->setAttrs(AttrVec());
2141 
2142   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2143     bool Override = false;
2144     // Ignore deprecated/unavailable/availability attributes if requested.
2145     if (isa<DeprecatedAttr>(I) ||
2146         isa<UnavailableAttr>(I) ||
2147         isa<AvailabilityAttr>(I)) {
2148       switch (AMK) {
2149       case AMK_None:
2150         continue;
2151 
2152       case AMK_Redeclaration:
2153         break;
2154 
2155       case AMK_Override:
2156         Override = true;
2157         break;
2158       }
2159     }
2160 
2161     // Already handled.
2162     if (isa<UsedAttr>(I))
2163       continue;
2164 
2165     if (mergeDeclAttribute(*this, New, I, Override))
2166       foundAny = true;
2167   }
2168 
2169   if (mergeAlignedAttrs(*this, New, Old))
2170     foundAny = true;
2171 
2172   if (!foundAny) New->dropAttrs();
2173 }
2174 
2175 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2176 /// to the new one.
2177 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2178                                      const ParmVarDecl *oldDecl,
2179                                      Sema &S) {
2180   // C++11 [dcl.attr.depend]p2:
2181   //   The first declaration of a function shall specify the
2182   //   carries_dependency attribute for its declarator-id if any declaration
2183   //   of the function specifies the carries_dependency attribute.
2184   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2185   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2186     S.Diag(CDA->getLocation(),
2187            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2188     // Find the first declaration of the parameter.
2189     // FIXME: Should we build redeclaration chains for function parameters?
2190     const FunctionDecl *FirstFD =
2191       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2192     const ParmVarDecl *FirstVD =
2193       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2194     S.Diag(FirstVD->getLocation(),
2195            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2196   }
2197 
2198   if (!oldDecl->hasAttrs())
2199     return;
2200 
2201   bool foundAny = newDecl->hasAttrs();
2202 
2203   // Ensure that any moving of objects within the allocated map is
2204   // done before we process them.
2205   if (!foundAny) newDecl->setAttrs(AttrVec());
2206 
2207   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2208     if (!DeclHasAttr(newDecl, I)) {
2209       InheritableAttr *newAttr =
2210         cast<InheritableParamAttr>(I->clone(S.Context));
2211       newAttr->setInherited(true);
2212       newDecl->addAttr(newAttr);
2213       foundAny = true;
2214     }
2215   }
2216 
2217   if (!foundAny) newDecl->dropAttrs();
2218 }
2219 
2220 namespace {
2221 
2222 /// Used in MergeFunctionDecl to keep track of function parameters in
2223 /// C.
2224 struct GNUCompatibleParamWarning {
2225   ParmVarDecl *OldParm;
2226   ParmVarDecl *NewParm;
2227   QualType PromotedType;
2228 };
2229 
2230 }
2231 
2232 /// getSpecialMember - get the special member enum for a method.
2233 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2234   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2235     if (Ctor->isDefaultConstructor())
2236       return Sema::CXXDefaultConstructor;
2237 
2238     if (Ctor->isCopyConstructor())
2239       return Sema::CXXCopyConstructor;
2240 
2241     if (Ctor->isMoveConstructor())
2242       return Sema::CXXMoveConstructor;
2243   } else if (isa<CXXDestructorDecl>(MD)) {
2244     return Sema::CXXDestructor;
2245   } else if (MD->isCopyAssignmentOperator()) {
2246     return Sema::CXXCopyAssignment;
2247   } else if (MD->isMoveAssignmentOperator()) {
2248     return Sema::CXXMoveAssignment;
2249   }
2250 
2251   return Sema::CXXInvalid;
2252 }
2253 
2254 // Determine whether the previous declaration was a definition, implicit
2255 // declaration, or a declaration.
2256 template <typename T>
2257 static std::pair<diag::kind, SourceLocation>
2258 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2259   diag::kind PrevDiag;
2260   SourceLocation OldLocation = Old->getLocation();
2261   if (Old->isThisDeclarationADefinition())
2262     PrevDiag = diag::note_previous_definition;
2263   else if (Old->isImplicit()) {
2264     PrevDiag = diag::note_previous_implicit_declaration;
2265     if (OldLocation.isInvalid())
2266       OldLocation = New->getLocation();
2267   } else
2268     PrevDiag = diag::note_previous_declaration;
2269   return std::make_pair(PrevDiag, OldLocation);
2270 }
2271 
2272 /// canRedefineFunction - checks if a function can be redefined. Currently,
2273 /// only extern inline functions can be redefined, and even then only in
2274 /// GNU89 mode.
2275 static bool canRedefineFunction(const FunctionDecl *FD,
2276                                 const LangOptions& LangOpts) {
2277   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2278           !LangOpts.CPlusPlus &&
2279           FD->isInlineSpecified() &&
2280           FD->getStorageClass() == SC_Extern);
2281 }
2282 
2283 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2284   const AttributedType *AT = T->getAs<AttributedType>();
2285   while (AT && !AT->isCallingConv())
2286     AT = AT->getModifiedType()->getAs<AttributedType>();
2287   return AT;
2288 }
2289 
2290 template <typename T>
2291 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2292   const DeclContext *DC = Old->getDeclContext();
2293   if (DC->isRecord())
2294     return false;
2295 
2296   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2297   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2298     return true;
2299   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2300     return true;
2301   return false;
2302 }
2303 
2304 /// MergeFunctionDecl - We just parsed a function 'New' from
2305 /// declarator D which has the same name and scope as a previous
2306 /// declaration 'Old'.  Figure out how to resolve this situation,
2307 /// merging decls or emitting diagnostics as appropriate.
2308 ///
2309 /// In C++, New and Old must be declarations that are not
2310 /// overloaded. Use IsOverload to determine whether New and Old are
2311 /// overloaded, and to select the Old declaration that New should be
2312 /// merged with.
2313 ///
2314 /// Returns true if there was an error, false otherwise.
2315 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2316                              Scope *S, bool MergeTypeWithOld) {
2317   // Verify the old decl was also a function.
2318   FunctionDecl *Old = OldD->getAsFunction();
2319   if (!Old) {
2320     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2321       if (New->getFriendObjectKind()) {
2322         Diag(New->getLocation(), diag::err_using_decl_friend);
2323         Diag(Shadow->getTargetDecl()->getLocation(),
2324              diag::note_using_decl_target);
2325         Diag(Shadow->getUsingDecl()->getLocation(),
2326              diag::note_using_decl) << 0;
2327         return true;
2328       }
2329 
2330       // C++11 [namespace.udecl]p14:
2331       //   If a function declaration in namespace scope or block scope has the
2332       //   same name and the same parameter-type-list as a function introduced
2333       //   by a using-declaration, and the declarations do not declare the same
2334       //   function, the program is ill-formed.
2335 
2336       // Check whether the two declarations might declare the same function.
2337       Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2338       if (Old &&
2339           !Old->getDeclContext()->getRedeclContext()->Equals(
2340               New->getDeclContext()->getRedeclContext()) &&
2341           !(Old->isExternC() && New->isExternC()))
2342         Old = nullptr;
2343 
2344       if (!Old) {
2345         Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2346         Diag(Shadow->getTargetDecl()->getLocation(),
2347              diag::note_using_decl_target);
2348         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2349         return true;
2350       }
2351       OldD = Old;
2352     } else {
2353       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2354         << New->getDeclName();
2355       Diag(OldD->getLocation(), diag::note_previous_definition);
2356       return true;
2357     }
2358   }
2359 
2360   // If the old declaration is invalid, just give up here.
2361   if (Old->isInvalidDecl())
2362     return true;
2363 
2364   diag::kind PrevDiag;
2365   SourceLocation OldLocation;
2366   std::tie(PrevDiag, OldLocation) =
2367       getNoteDiagForInvalidRedeclaration(Old, New);
2368 
2369   // Don't complain about this if we're in GNU89 mode and the old function
2370   // is an extern inline function.
2371   // Don't complain about specializations. They are not supposed to have
2372   // storage classes.
2373   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2374       New->getStorageClass() == SC_Static &&
2375       Old->hasExternalFormalLinkage() &&
2376       !New->getTemplateSpecializationInfo() &&
2377       !canRedefineFunction(Old, getLangOpts())) {
2378     if (getLangOpts().MicrosoftExt) {
2379       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2380       Diag(OldLocation, PrevDiag);
2381     } else {
2382       Diag(New->getLocation(), diag::err_static_non_static) << New;
2383       Diag(OldLocation, PrevDiag);
2384       return true;
2385     }
2386   }
2387 
2388 
2389   // If a function is first declared with a calling convention, but is later
2390   // declared or defined without one, all following decls assume the calling
2391   // convention of the first.
2392   //
2393   // It's OK if a function is first declared without a calling convention,
2394   // but is later declared or defined with the default calling convention.
2395   //
2396   // To test if either decl has an explicit calling convention, we look for
2397   // AttributedType sugar nodes on the type as written.  If they are missing or
2398   // were canonicalized away, we assume the calling convention was implicit.
2399   //
2400   // Note also that we DO NOT return at this point, because we still have
2401   // other tests to run.
2402   QualType OldQType = Context.getCanonicalType(Old->getType());
2403   QualType NewQType = Context.getCanonicalType(New->getType());
2404   const FunctionType *OldType = cast<FunctionType>(OldQType);
2405   const FunctionType *NewType = cast<FunctionType>(NewQType);
2406   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2407   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2408   bool RequiresAdjustment = false;
2409 
2410   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2411     FunctionDecl *First = Old->getFirstDecl();
2412     const FunctionType *FT =
2413         First->getType().getCanonicalType()->castAs<FunctionType>();
2414     FunctionType::ExtInfo FI = FT->getExtInfo();
2415     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2416     if (!NewCCExplicit) {
2417       // Inherit the CC from the previous declaration if it was specified
2418       // there but not here.
2419       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2420       RequiresAdjustment = true;
2421     } else {
2422       // Calling conventions aren't compatible, so complain.
2423       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2424       Diag(New->getLocation(), diag::err_cconv_change)
2425         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2426         << !FirstCCExplicit
2427         << (!FirstCCExplicit ? "" :
2428             FunctionType::getNameForCallConv(FI.getCC()));
2429 
2430       // Put the note on the first decl, since it is the one that matters.
2431       Diag(First->getLocation(), diag::note_previous_declaration);
2432       return true;
2433     }
2434   }
2435 
2436   // FIXME: diagnose the other way around?
2437   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2438     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2439     RequiresAdjustment = true;
2440   }
2441 
2442   // Merge regparm attribute.
2443   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2444       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2445     if (NewTypeInfo.getHasRegParm()) {
2446       Diag(New->getLocation(), diag::err_regparm_mismatch)
2447         << NewType->getRegParmType()
2448         << OldType->getRegParmType();
2449       Diag(OldLocation, diag::note_previous_declaration);
2450       return true;
2451     }
2452 
2453     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2454     RequiresAdjustment = true;
2455   }
2456 
2457   // Merge ns_returns_retained attribute.
2458   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2459     if (NewTypeInfo.getProducesResult()) {
2460       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2461       Diag(OldLocation, diag::note_previous_declaration);
2462       return true;
2463     }
2464 
2465     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2466     RequiresAdjustment = true;
2467   }
2468 
2469   if (RequiresAdjustment) {
2470     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2471     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2472     New->setType(QualType(AdjustedType, 0));
2473     NewQType = Context.getCanonicalType(New->getType());
2474     NewType = cast<FunctionType>(NewQType);
2475   }
2476 
2477   // If this redeclaration makes the function inline, we may need to add it to
2478   // UndefinedButUsed.
2479   if (!Old->isInlined() && New->isInlined() &&
2480       !New->hasAttr<GNUInlineAttr>() &&
2481       (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2482       Old->isUsed(false) &&
2483       !Old->isDefined() && !New->isThisDeclarationADefinition())
2484     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2485                                            SourceLocation()));
2486 
2487   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2488   // about it.
2489   if (New->hasAttr<GNUInlineAttr>() &&
2490       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2491     UndefinedButUsed.erase(Old->getCanonicalDecl());
2492   }
2493 
2494   if (getLangOpts().CPlusPlus) {
2495     // (C++98 13.1p2):
2496     //   Certain function declarations cannot be overloaded:
2497     //     -- Function declarations that differ only in the return type
2498     //        cannot be overloaded.
2499 
2500     // Go back to the type source info to compare the declared return types,
2501     // per C++1y [dcl.type.auto]p13:
2502     //   Redeclarations or specializations of a function or function template
2503     //   with a declared return type that uses a placeholder type shall also
2504     //   use that placeholder, not a deduced type.
2505     QualType OldDeclaredReturnType =
2506         (Old->getTypeSourceInfo()
2507              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2508              : OldType)->getReturnType();
2509     QualType NewDeclaredReturnType =
2510         (New->getTypeSourceInfo()
2511              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2512              : NewType)->getReturnType();
2513     QualType ResQT;
2514     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2515         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2516           New->isLocalExternDecl())) {
2517       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2518           OldDeclaredReturnType->isObjCObjectPointerType())
2519         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2520       if (ResQT.isNull()) {
2521         if (New->isCXXClassMember() && New->isOutOfLine())
2522           Diag(New->getLocation(),
2523                diag::err_member_def_does_not_match_ret_type) << New;
2524         else
2525           Diag(New->getLocation(), diag::err_ovl_diff_return_type);
2526         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2527         return true;
2528       }
2529       else
2530         NewQType = ResQT;
2531     }
2532 
2533     QualType OldReturnType = OldType->getReturnType();
2534     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2535     if (OldReturnType != NewReturnType) {
2536       // If this function has a deduced return type and has already been
2537       // defined, copy the deduced value from the old declaration.
2538       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2539       if (OldAT && OldAT->isDeduced()) {
2540         New->setType(
2541             SubstAutoType(New->getType(),
2542                           OldAT->isDependentType() ? Context.DependentTy
2543                                                    : OldAT->getDeducedType()));
2544         NewQType = Context.getCanonicalType(
2545             SubstAutoType(NewQType,
2546                           OldAT->isDependentType() ? Context.DependentTy
2547                                                    : OldAT->getDeducedType()));
2548       }
2549     }
2550 
2551     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2552     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2553     if (OldMethod && NewMethod) {
2554       // Preserve triviality.
2555       NewMethod->setTrivial(OldMethod->isTrivial());
2556 
2557       // MSVC allows explicit template specialization at class scope:
2558       // 2 CXXMethodDecls referring to the same function will be injected.
2559       // We don't want a redeclaration error.
2560       bool IsClassScopeExplicitSpecialization =
2561                               OldMethod->isFunctionTemplateSpecialization() &&
2562                               NewMethod->isFunctionTemplateSpecialization();
2563       bool isFriend = NewMethod->getFriendObjectKind();
2564 
2565       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2566           !IsClassScopeExplicitSpecialization) {
2567         //    -- Member function declarations with the same name and the
2568         //       same parameter types cannot be overloaded if any of them
2569         //       is a static member function declaration.
2570         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2571           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2572           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2573           return true;
2574         }
2575 
2576         // C++ [class.mem]p1:
2577         //   [...] A member shall not be declared twice in the
2578         //   member-specification, except that a nested class or member
2579         //   class template can be declared and then later defined.
2580         if (ActiveTemplateInstantiations.empty()) {
2581           unsigned NewDiag;
2582           if (isa<CXXConstructorDecl>(OldMethod))
2583             NewDiag = diag::err_constructor_redeclared;
2584           else if (isa<CXXDestructorDecl>(NewMethod))
2585             NewDiag = diag::err_destructor_redeclared;
2586           else if (isa<CXXConversionDecl>(NewMethod))
2587             NewDiag = diag::err_conv_function_redeclared;
2588           else
2589             NewDiag = diag::err_member_redeclared;
2590 
2591           Diag(New->getLocation(), NewDiag);
2592         } else {
2593           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2594             << New << New->getType();
2595         }
2596         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2597 
2598       // Complain if this is an explicit declaration of a special
2599       // member that was initially declared implicitly.
2600       //
2601       // As an exception, it's okay to befriend such methods in order
2602       // to permit the implicit constructor/destructor/operator calls.
2603       } else if (OldMethod->isImplicit()) {
2604         if (isFriend) {
2605           NewMethod->setImplicit();
2606         } else {
2607           Diag(NewMethod->getLocation(),
2608                diag::err_definition_of_implicitly_declared_member)
2609             << New << getSpecialMember(OldMethod);
2610           return true;
2611         }
2612       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2613         Diag(NewMethod->getLocation(),
2614              diag::err_definition_of_explicitly_defaulted_member)
2615           << getSpecialMember(OldMethod);
2616         return true;
2617       }
2618     }
2619 
2620     // C++11 [dcl.attr.noreturn]p1:
2621     //   The first declaration of a function shall specify the noreturn
2622     //   attribute if any declaration of that function specifies the noreturn
2623     //   attribute.
2624     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2625     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2626       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2627       Diag(Old->getFirstDecl()->getLocation(),
2628            diag::note_noreturn_missing_first_decl);
2629     }
2630 
2631     // C++11 [dcl.attr.depend]p2:
2632     //   The first declaration of a function shall specify the
2633     //   carries_dependency attribute for its declarator-id if any declaration
2634     //   of the function specifies the carries_dependency attribute.
2635     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2636     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2637       Diag(CDA->getLocation(),
2638            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2639       Diag(Old->getFirstDecl()->getLocation(),
2640            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2641     }
2642 
2643     // (C++98 8.3.5p3):
2644     //   All declarations for a function shall agree exactly in both the
2645     //   return type and the parameter-type-list.
2646     // We also want to respect all the extended bits except noreturn.
2647 
2648     // noreturn should now match unless the old type info didn't have it.
2649     QualType OldQTypeForComparison = OldQType;
2650     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2651       assert(OldQType == QualType(OldType, 0));
2652       const FunctionType *OldTypeForComparison
2653         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2654       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2655       assert(OldQTypeForComparison.isCanonical());
2656     }
2657 
2658     if (haveIncompatibleLanguageLinkages(Old, New)) {
2659       // As a special case, retain the language linkage from previous
2660       // declarations of a friend function as an extension.
2661       //
2662       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2663       // and is useful because there's otherwise no way to specify language
2664       // linkage within class scope.
2665       //
2666       // Check cautiously as the friend object kind isn't yet complete.
2667       if (New->getFriendObjectKind() != Decl::FOK_None) {
2668         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2669         Diag(OldLocation, PrevDiag);
2670       } else {
2671         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2672         Diag(OldLocation, PrevDiag);
2673         return true;
2674       }
2675     }
2676 
2677     if (OldQTypeForComparison == NewQType)
2678       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2679 
2680     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2681         New->isLocalExternDecl()) {
2682       // It's OK if we couldn't merge types for a local function declaraton
2683       // if either the old or new type is dependent. We'll merge the types
2684       // when we instantiate the function.
2685       return false;
2686     }
2687 
2688     // Fall through for conflicting redeclarations and redefinitions.
2689   }
2690 
2691   // C: Function types need to be compatible, not identical. This handles
2692   // duplicate function decls like "void f(int); void f(enum X);" properly.
2693   if (!getLangOpts().CPlusPlus &&
2694       Context.typesAreCompatible(OldQType, NewQType)) {
2695     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2696     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2697     const FunctionProtoType *OldProto = nullptr;
2698     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
2699         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2700       // The old declaration provided a function prototype, but the
2701       // new declaration does not. Merge in the prototype.
2702       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2703       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
2704       NewQType =
2705           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2706                                   OldProto->getExtProtoInfo());
2707       New->setType(NewQType);
2708       New->setHasInheritedPrototype();
2709 
2710       // Synthesize parameters with the same types.
2711       SmallVector<ParmVarDecl*, 16> Params;
2712       for (const auto &ParamType : OldProto->param_types()) {
2713         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
2714                                                  SourceLocation(), nullptr,
2715                                                  ParamType, /*TInfo=*/nullptr,
2716                                                  SC_None, nullptr);
2717         Param->setScopeInfo(0, Params.size());
2718         Param->setImplicit();
2719         Params.push_back(Param);
2720       }
2721 
2722       New->setParams(Params);
2723     }
2724 
2725     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2726   }
2727 
2728   // GNU C permits a K&R definition to follow a prototype declaration
2729   // if the declared types of the parameters in the K&R definition
2730   // match the types in the prototype declaration, even when the
2731   // promoted types of the parameters from the K&R definition differ
2732   // from the types in the prototype. GCC then keeps the types from
2733   // the prototype.
2734   //
2735   // If a variadic prototype is followed by a non-variadic K&R definition,
2736   // the K&R definition becomes variadic.  This is sort of an edge case, but
2737   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2738   // C99 6.9.1p8.
2739   if (!getLangOpts().CPlusPlus &&
2740       Old->hasPrototype() && !New->hasPrototype() &&
2741       New->getType()->getAs<FunctionProtoType>() &&
2742       Old->getNumParams() == New->getNumParams()) {
2743     SmallVector<QualType, 16> ArgTypes;
2744     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2745     const FunctionProtoType *OldProto
2746       = Old->getType()->getAs<FunctionProtoType>();
2747     const FunctionProtoType *NewProto
2748       = New->getType()->getAs<FunctionProtoType>();
2749 
2750     // Determine whether this is the GNU C extension.
2751     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2752                                                NewProto->getReturnType());
2753     bool LooseCompatible = !MergedReturn.isNull();
2754     for (unsigned Idx = 0, End = Old->getNumParams();
2755          LooseCompatible && Idx != End; ++Idx) {
2756       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2757       ParmVarDecl *NewParm = New->getParamDecl(Idx);
2758       if (Context.typesAreCompatible(OldParm->getType(),
2759                                      NewProto->getParamType(Idx))) {
2760         ArgTypes.push_back(NewParm->getType());
2761       } else if (Context.typesAreCompatible(OldParm->getType(),
2762                                             NewParm->getType(),
2763                                             /*CompareUnqualified=*/true)) {
2764         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2765                                            NewProto->getParamType(Idx) };
2766         Warnings.push_back(Warn);
2767         ArgTypes.push_back(NewParm->getType());
2768       } else
2769         LooseCompatible = false;
2770     }
2771 
2772     if (LooseCompatible) {
2773       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2774         Diag(Warnings[Warn].NewParm->getLocation(),
2775              diag::ext_param_promoted_not_compatible_with_prototype)
2776           << Warnings[Warn].PromotedType
2777           << Warnings[Warn].OldParm->getType();
2778         if (Warnings[Warn].OldParm->getLocation().isValid())
2779           Diag(Warnings[Warn].OldParm->getLocation(),
2780                diag::note_previous_declaration);
2781       }
2782 
2783       if (MergeTypeWithOld)
2784         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2785                                              OldProto->getExtProtoInfo()));
2786       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2787     }
2788 
2789     // Fall through to diagnose conflicting types.
2790   }
2791 
2792   // A function that has already been declared has been redeclared or
2793   // defined with a different type; show an appropriate diagnostic.
2794 
2795   // If the previous declaration was an implicitly-generated builtin
2796   // declaration, then at the very least we should use a specialized note.
2797   unsigned BuiltinID;
2798   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2799     // If it's actually a library-defined builtin function like 'malloc'
2800     // or 'printf', just warn about the incompatible redeclaration.
2801     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2802       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2803       Diag(OldLocation, diag::note_previous_builtin_declaration)
2804         << Old << Old->getType();
2805 
2806       // If this is a global redeclaration, just forget hereafter
2807       // about the "builtin-ness" of the function.
2808       //
2809       // Doing this for local extern declarations is problematic.  If
2810       // the builtin declaration remains visible, a second invalid
2811       // local declaration will produce a hard error; if it doesn't
2812       // remain visible, a single bogus local redeclaration (which is
2813       // actually only a warning) could break all the downstream code.
2814       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
2815         New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2816 
2817       return false;
2818     }
2819 
2820     PrevDiag = diag::note_previous_builtin_declaration;
2821   }
2822 
2823   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2824   Diag(OldLocation, PrevDiag) << Old << Old->getType();
2825   return true;
2826 }
2827 
2828 /// \brief Completes the merge of two function declarations that are
2829 /// known to be compatible.
2830 ///
2831 /// This routine handles the merging of attributes and other
2832 /// properties of function declarations from the old declaration to
2833 /// the new declaration, once we know that New is in fact a
2834 /// redeclaration of Old.
2835 ///
2836 /// \returns false
2837 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2838                                         Scope *S, bool MergeTypeWithOld) {
2839   // Merge the attributes
2840   mergeDeclAttributes(New, Old);
2841 
2842   // Merge "pure" flag.
2843   if (Old->isPure())
2844     New->setPure();
2845 
2846   // Merge "used" flag.
2847   if (Old->getMostRecentDecl()->isUsed(false))
2848     New->setIsUsed();
2849 
2850   // Merge attributes from the parameters.  These can mismatch with K&R
2851   // declarations.
2852   if (New->getNumParams() == Old->getNumParams())
2853     for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2854       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2855                                *this);
2856 
2857   if (getLangOpts().CPlusPlus)
2858     return MergeCXXFunctionDecl(New, Old, S);
2859 
2860   // Merge the function types so the we get the composite types for the return
2861   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2862   // was visible.
2863   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
2864   if (!Merged.isNull() && MergeTypeWithOld)
2865     New->setType(Merged);
2866 
2867   return false;
2868 }
2869 
2870 
2871 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2872                                 ObjCMethodDecl *oldMethod) {
2873 
2874   // Merge the attributes, including deprecated/unavailable
2875   AvailabilityMergeKind MergeKind =
2876     isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2877                                                    : AMK_Override;
2878   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
2879 
2880   // Merge attributes from the parameters.
2881   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2882                                        oe = oldMethod->param_end();
2883   for (ObjCMethodDecl::param_iterator
2884          ni = newMethod->param_begin(), ne = newMethod->param_end();
2885        ni != ne && oi != oe; ++ni, ++oi)
2886     mergeParamDeclAttributes(*ni, *oi, *this);
2887 
2888   CheckObjCMethodOverride(newMethod, oldMethod);
2889 }
2890 
2891 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2892 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
2893 /// emitting diagnostics as appropriate.
2894 ///
2895 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2896 /// to here in AddInitializerToDecl. We can't check them before the initializer
2897 /// is attached.
2898 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2899                              bool MergeTypeWithOld) {
2900   if (New->isInvalidDecl() || Old->isInvalidDecl())
2901     return;
2902 
2903   QualType MergedT;
2904   if (getLangOpts().CPlusPlus) {
2905     if (New->getType()->isUndeducedType()) {
2906       // We don't know what the new type is until the initializer is attached.
2907       return;
2908     } else if (Context.hasSameType(New->getType(), Old->getType())) {
2909       // These could still be something that needs exception specs checked.
2910       return MergeVarDeclExceptionSpecs(New, Old);
2911     }
2912     // C++ [basic.link]p10:
2913     //   [...] the types specified by all declarations referring to a given
2914     //   object or function shall be identical, except that declarations for an
2915     //   array object can specify array types that differ by the presence or
2916     //   absence of a major array bound (8.3.4).
2917     else if (Old->getType()->isIncompleteArrayType() &&
2918              New->getType()->isArrayType()) {
2919       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2920       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2921       if (Context.hasSameType(OldArray->getElementType(),
2922                               NewArray->getElementType()))
2923         MergedT = New->getType();
2924     } else if (Old->getType()->isArrayType() &&
2925                New->getType()->isIncompleteArrayType()) {
2926       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2927       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2928       if (Context.hasSameType(OldArray->getElementType(),
2929                               NewArray->getElementType()))
2930         MergedT = Old->getType();
2931     } else if (New->getType()->isObjCObjectPointerType() &&
2932                Old->getType()->isObjCObjectPointerType()) {
2933       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2934                                               Old->getType());
2935     }
2936   } else {
2937     // C 6.2.7p2:
2938     //   All declarations that refer to the same object or function shall have
2939     //   compatible type.
2940     MergedT = Context.mergeTypes(New->getType(), Old->getType());
2941   }
2942   if (MergedT.isNull()) {
2943     // It's OK if we couldn't merge types if either type is dependent, for a
2944     // block-scope variable. In other cases (static data members of class
2945     // templates, variable templates, ...), we require the types to be
2946     // equivalent.
2947     // FIXME: The C++ standard doesn't say anything about this.
2948     if ((New->getType()->isDependentType() ||
2949          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2950       // If the old type was dependent, we can't merge with it, so the new type
2951       // becomes dependent for now. We'll reproduce the original type when we
2952       // instantiate the TypeSourceInfo for the variable.
2953       if (!New->getType()->isDependentType() && MergeTypeWithOld)
2954         New->setType(Context.DependentTy);
2955       return;
2956     }
2957 
2958     // FIXME: Even if this merging succeeds, some other non-visible declaration
2959     // of this variable might have an incompatible type. For instance:
2960     //
2961     //   extern int arr[];
2962     //   void f() { extern int arr[2]; }
2963     //   void g() { extern int arr[3]; }
2964     //
2965     // Neither C nor C++ requires a diagnostic for this, but we should still try
2966     // to diagnose it.
2967     Diag(New->getLocation(), diag::err_redefinition_different_type)
2968       << New->getDeclName() << New->getType() << Old->getType();
2969     Diag(Old->getLocation(), diag::note_previous_definition);
2970     return New->setInvalidDecl();
2971   }
2972 
2973   // Don't actually update the type on the new declaration if the old
2974   // declaration was an extern declaration in a different scope.
2975   if (MergeTypeWithOld)
2976     New->setType(MergedT);
2977 }
2978 
2979 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2980                                   LookupResult &Previous) {
2981   // C11 6.2.7p4:
2982   //   For an identifier with internal or external linkage declared
2983   //   in a scope in which a prior declaration of that identifier is
2984   //   visible, if the prior declaration specifies internal or
2985   //   external linkage, the type of the identifier at the later
2986   //   declaration becomes the composite type.
2987   //
2988   // If the variable isn't visible, we do not merge with its type.
2989   if (Previous.isShadowed())
2990     return false;
2991 
2992   if (S.getLangOpts().CPlusPlus) {
2993     // C++11 [dcl.array]p3:
2994     //   If there is a preceding declaration of the entity in the same
2995     //   scope in which the bound was specified, an omitted array bound
2996     //   is taken to be the same as in that earlier declaration.
2997     return NewVD->isPreviousDeclInSameBlockScope() ||
2998            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2999             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3000   } else {
3001     // If the old declaration was function-local, don't merge with its
3002     // type unless we're in the same function.
3003     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3004            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3005   }
3006 }
3007 
3008 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3009 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3010 /// situation, merging decls or emitting diagnostics as appropriate.
3011 ///
3012 /// Tentative definition rules (C99 6.9.2p2) are checked by
3013 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3014 /// definitions here, since the initializer hasn't been attached.
3015 ///
3016 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3017   // If the new decl is already invalid, don't do any other checking.
3018   if (New->isInvalidDecl())
3019     return;
3020 
3021   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3022 
3023   // Verify the old decl was also a variable or variable template.
3024   VarDecl *Old = nullptr;
3025   VarTemplateDecl *OldTemplate = nullptr;
3026   if (Previous.isSingleResult()) {
3027     if (NewTemplate) {
3028       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3029       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3030     } else
3031       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3032   }
3033   if (!Old) {
3034     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3035       << New->getDeclName();
3036     Diag(Previous.getRepresentativeDecl()->getLocation(),
3037          diag::note_previous_definition);
3038     return New->setInvalidDecl();
3039   }
3040 
3041   if (!shouldLinkPossiblyHiddenDecl(Old, New))
3042     return;
3043 
3044   // Ensure the template parameters are compatible.
3045   if (NewTemplate &&
3046       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3047                                       OldTemplate->getTemplateParameters(),
3048                                       /*Complain=*/true, TPL_TemplateMatch))
3049     return;
3050 
3051   // C++ [class.mem]p1:
3052   //   A member shall not be declared twice in the member-specification [...]
3053   //
3054   // Here, we need only consider static data members.
3055   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3056     Diag(New->getLocation(), diag::err_duplicate_member)
3057       << New->getIdentifier();
3058     Diag(Old->getLocation(), diag::note_previous_declaration);
3059     New->setInvalidDecl();
3060   }
3061 
3062   mergeDeclAttributes(New, Old);
3063   // Warn if an already-declared variable is made a weak_import in a subsequent
3064   // declaration
3065   if (New->hasAttr<WeakImportAttr>() &&
3066       Old->getStorageClass() == SC_None &&
3067       !Old->hasAttr<WeakImportAttr>()) {
3068     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3069     Diag(Old->getLocation(), diag::note_previous_definition);
3070     // Remove weak_import attribute on new declaration.
3071     New->dropAttr<WeakImportAttr>();
3072   }
3073 
3074   // Merge the types.
3075   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3076 
3077   if (New->isInvalidDecl())
3078     return;
3079 
3080   diag::kind PrevDiag;
3081   SourceLocation OldLocation;
3082   std::tie(PrevDiag, OldLocation) =
3083       getNoteDiagForInvalidRedeclaration(Old, New);
3084 
3085   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3086   if (New->getStorageClass() == SC_Static &&
3087       !New->isStaticDataMember() &&
3088       Old->hasExternalFormalLinkage()) {
3089     if (getLangOpts().MicrosoftExt) {
3090       Diag(New->getLocation(), diag::ext_static_non_static)
3091           << New->getDeclName();
3092       Diag(OldLocation, PrevDiag);
3093     } else {
3094       Diag(New->getLocation(), diag::err_static_non_static)
3095           << New->getDeclName();
3096       Diag(OldLocation, PrevDiag);
3097       return New->setInvalidDecl();
3098     }
3099   }
3100   // C99 6.2.2p4:
3101   //   For an identifier declared with the storage-class specifier
3102   //   extern in a scope in which a prior declaration of that
3103   //   identifier is visible,23) if the prior declaration specifies
3104   //   internal or external linkage, the linkage of the identifier at
3105   //   the later declaration is the same as the linkage specified at
3106   //   the prior declaration. If no prior declaration is visible, or
3107   //   if the prior declaration specifies no linkage, then the
3108   //   identifier has external linkage.
3109   if (New->hasExternalStorage() && Old->hasLinkage())
3110     /* Okay */;
3111   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3112            !New->isStaticDataMember() &&
3113            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3114     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3115     Diag(OldLocation, PrevDiag);
3116     return New->setInvalidDecl();
3117   }
3118 
3119   // Check if extern is followed by non-extern and vice-versa.
3120   if (New->hasExternalStorage() &&
3121       !Old->hasLinkage() && Old->isLocalVarDecl()) {
3122     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3123     Diag(OldLocation, PrevDiag);
3124     return New->setInvalidDecl();
3125   }
3126   if (Old->hasLinkage() && New->isLocalVarDecl() &&
3127       !New->hasExternalStorage()) {
3128     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3129     Diag(OldLocation, PrevDiag);
3130     return New->setInvalidDecl();
3131   }
3132 
3133   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3134 
3135   // FIXME: The test for external storage here seems wrong? We still
3136   // need to check for mismatches.
3137   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3138       // Don't complain about out-of-line definitions of static members.
3139       !(Old->getLexicalDeclContext()->isRecord() &&
3140         !New->getLexicalDeclContext()->isRecord())) {
3141     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3142     Diag(OldLocation, PrevDiag);
3143     return New->setInvalidDecl();
3144   }
3145 
3146   if (New->getTLSKind() != Old->getTLSKind()) {
3147     if (!Old->getTLSKind()) {
3148       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3149       Diag(OldLocation, PrevDiag);
3150     } else if (!New->getTLSKind()) {
3151       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3152       Diag(OldLocation, PrevDiag);
3153     } else {
3154       // Do not allow redeclaration to change the variable between requiring
3155       // static and dynamic initialization.
3156       // FIXME: GCC allows this, but uses the TLS keyword on the first
3157       // declaration to determine the kind. Do we need to be compatible here?
3158       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3159         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3160       Diag(OldLocation, PrevDiag);
3161     }
3162   }
3163 
3164   // C++ doesn't have tentative definitions, so go right ahead and check here.
3165   const VarDecl *Def;
3166   if (getLangOpts().CPlusPlus &&
3167       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3168       (Def = Old->getDefinition())) {
3169     Diag(New->getLocation(), diag::err_redefinition) << New;
3170     Diag(Def->getLocation(), diag::note_previous_definition);
3171     New->setInvalidDecl();
3172     return;
3173   }
3174 
3175   if (haveIncompatibleLanguageLinkages(Old, New)) {
3176     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3177     Diag(OldLocation, PrevDiag);
3178     New->setInvalidDecl();
3179     return;
3180   }
3181 
3182   // Merge "used" flag.
3183   if (Old->getMostRecentDecl()->isUsed(false))
3184     New->setIsUsed();
3185 
3186   // Keep a chain of previous declarations.
3187   New->setPreviousDecl(Old);
3188   if (NewTemplate)
3189     NewTemplate->setPreviousDecl(OldTemplate);
3190 
3191   // Inherit access appropriately.
3192   New->setAccess(Old->getAccess());
3193   if (NewTemplate)
3194     NewTemplate->setAccess(New->getAccess());
3195 }
3196 
3197 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3198 /// no declarator (e.g. "struct foo;") is parsed.
3199 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3200                                        DeclSpec &DS) {
3201   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3202 }
3203 
3204 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
3205   if (!S.Context.getLangOpts().CPlusPlus)
3206     return;
3207 
3208   if (isa<CXXRecordDecl>(Tag->getParent())) {
3209     // If this tag is the direct child of a class, number it if
3210     // it is anonymous.
3211     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3212       return;
3213     MangleNumberingContext &MCtx =
3214         S.Context.getManglingNumberContext(Tag->getParent());
3215     S.Context.setManglingNumber(
3216         Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
3217     return;
3218   }
3219 
3220   // If this tag isn't a direct child of a class, number it if it is local.
3221   Decl *ManglingContextDecl;
3222   if (MangleNumberingContext *MCtx =
3223           S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3224                                           ManglingContextDecl)) {
3225     S.Context.setManglingNumber(
3226         Tag,
3227         MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
3228   }
3229 }
3230 
3231 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3232 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3233 /// parameters to cope with template friend declarations.
3234 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3235                                        DeclSpec &DS,
3236                                        MultiTemplateParamsArg TemplateParams,
3237                                        bool IsExplicitInstantiation) {
3238   Decl *TagD = nullptr;
3239   TagDecl *Tag = nullptr;
3240   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3241       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3242       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3243       DS.getTypeSpecType() == DeclSpec::TST_union ||
3244       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3245     TagD = DS.getRepAsDecl();
3246 
3247     if (!TagD) // We probably had an error
3248       return nullptr;
3249 
3250     // Note that the above type specs guarantee that the
3251     // type rep is a Decl, whereas in many of the others
3252     // it's a Type.
3253     if (isa<TagDecl>(TagD))
3254       Tag = cast<TagDecl>(TagD);
3255     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3256       Tag = CTD->getTemplatedDecl();
3257   }
3258 
3259   if (Tag) {
3260     HandleTagNumbering(*this, Tag, S);
3261     Tag->setFreeStanding();
3262     if (Tag->isInvalidDecl())
3263       return Tag;
3264   }
3265 
3266   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3267     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3268     // or incomplete types shall not be restrict-qualified."
3269     if (TypeQuals & DeclSpec::TQ_restrict)
3270       Diag(DS.getRestrictSpecLoc(),
3271            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3272            << DS.getSourceRange();
3273   }
3274 
3275   if (DS.isConstexprSpecified()) {
3276     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3277     // and definitions of functions and variables.
3278     if (Tag)
3279       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3280         << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3281             DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3282             DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3283             DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
3284     else
3285       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3286     // Don't emit warnings after this error.
3287     return TagD;
3288   }
3289 
3290   DiagnoseFunctionSpecifiers(DS);
3291 
3292   if (DS.isFriendSpecified()) {
3293     // If we're dealing with a decl but not a TagDecl, assume that
3294     // whatever routines created it handled the friendship aspect.
3295     if (TagD && !Tag)
3296       return nullptr;
3297     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3298   }
3299 
3300   CXXScopeSpec &SS = DS.getTypeSpecScope();
3301   bool IsExplicitSpecialization =
3302     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3303   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3304       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3305     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3306     // nested-name-specifier unless it is an explicit instantiation
3307     // or an explicit specialization.
3308     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3309     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3310       << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3311           DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3312           DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3313           DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3314       << SS.getRange();
3315     return nullptr;
3316   }
3317 
3318   // Track whether this decl-specifier declares anything.
3319   bool DeclaresAnything = true;
3320 
3321   // Handle anonymous struct definitions.
3322   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3323     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3324         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3325       if (getLangOpts().CPlusPlus ||
3326           Record->getDeclContext()->isRecord())
3327         return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
3328 
3329       DeclaresAnything = false;
3330     }
3331   }
3332 
3333   // Check for Microsoft C extension: anonymous struct member.
3334   if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
3335       CurContext->isRecord() &&
3336       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3337     // Handle 2 kinds of anonymous struct:
3338     //   struct STRUCT;
3339     // and
3340     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3341     RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
3342     if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
3343         (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3344          DS.getRepAsType().get()->isStructureType())) {
3345       Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
3346         << DS.getSourceRange();
3347       return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3348     }
3349   }
3350 
3351   // Skip all the checks below if we have a type error.
3352   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3353       (TagD && TagD->isInvalidDecl()))
3354     return TagD;
3355 
3356   if (getLangOpts().CPlusPlus &&
3357       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3358     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3359       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3360           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3361         DeclaresAnything = false;
3362 
3363   if (!DS.isMissingDeclaratorOk()) {
3364     // Customize diagnostic for a typedef missing a name.
3365     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3366       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3367         << DS.getSourceRange();
3368     else
3369       DeclaresAnything = false;
3370   }
3371 
3372   if (DS.isModulePrivateSpecified() &&
3373       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3374     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3375       << Tag->getTagKind()
3376       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3377 
3378   ActOnDocumentableDecl(TagD);
3379 
3380   // C 6.7/2:
3381   //   A declaration [...] shall declare at least a declarator [...], a tag,
3382   //   or the members of an enumeration.
3383   // C++ [dcl.dcl]p3:
3384   //   [If there are no declarators], and except for the declaration of an
3385   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3386   //   names into the program, or shall redeclare a name introduced by a
3387   //   previous declaration.
3388   if (!DeclaresAnything) {
3389     // In C, we allow this as a (popular) extension / bug. Don't bother
3390     // producing further diagnostics for redundant qualifiers after this.
3391     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3392     return TagD;
3393   }
3394 
3395   // C++ [dcl.stc]p1:
3396   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3397   //   init-declarator-list of the declaration shall not be empty.
3398   // C++ [dcl.fct.spec]p1:
3399   //   If a cv-qualifier appears in a decl-specifier-seq, the
3400   //   init-declarator-list of the declaration shall not be empty.
3401   //
3402   // Spurious qualifiers here appear to be valid in C.
3403   unsigned DiagID = diag::warn_standalone_specifier;
3404   if (getLangOpts().CPlusPlus)
3405     DiagID = diag::ext_standalone_specifier;
3406 
3407   // Note that a linkage-specification sets a storage class, but
3408   // 'extern "C" struct foo;' is actually valid and not theoretically
3409   // useless.
3410   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3411     if (SCS == DeclSpec::SCS_mutable)
3412       // Since mutable is not a viable storage class specifier in C, there is
3413       // no reason to treat it as an extension. Instead, diagnose as an error.
3414       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3415     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3416       Diag(DS.getStorageClassSpecLoc(), DiagID)
3417         << DeclSpec::getSpecifierName(SCS);
3418   }
3419 
3420   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3421     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3422       << DeclSpec::getSpecifierName(TSCS);
3423   if (DS.getTypeQualifiers()) {
3424     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3425       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3426     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3427       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3428     // Restrict is covered above.
3429     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3430       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3431   }
3432 
3433   // Warn about ignored type attributes, for example:
3434   // __attribute__((aligned)) struct A;
3435   // Attributes should be placed after tag to apply to type declaration.
3436   if (!DS.getAttributes().empty()) {
3437     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3438     if (TypeSpecType == DeclSpec::TST_class ||
3439         TypeSpecType == DeclSpec::TST_struct ||
3440         TypeSpecType == DeclSpec::TST_interface ||
3441         TypeSpecType == DeclSpec::TST_union ||
3442         TypeSpecType == DeclSpec::TST_enum) {
3443       AttributeList* attrs = DS.getAttributes().getList();
3444       while (attrs) {
3445         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3446         << attrs->getName()
3447         << (TypeSpecType == DeclSpec::TST_class ? 0 :
3448             TypeSpecType == DeclSpec::TST_struct ? 1 :
3449             TypeSpecType == DeclSpec::TST_union ? 2 :
3450             TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
3451         attrs = attrs->getNext();
3452       }
3453     }
3454   }
3455 
3456   return TagD;
3457 }
3458 
3459 /// We are trying to inject an anonymous member into the given scope;
3460 /// check if there's an existing declaration that can't be overloaded.
3461 ///
3462 /// \return true if this is a forbidden redeclaration
3463 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3464                                          Scope *S,
3465                                          DeclContext *Owner,
3466                                          DeclarationName Name,
3467                                          SourceLocation NameLoc,
3468                                          unsigned diagnostic) {
3469   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3470                  Sema::ForRedeclaration);
3471   if (!SemaRef.LookupName(R, S)) return false;
3472 
3473   if (R.getAsSingle<TagDecl>())
3474     return false;
3475 
3476   // Pick a representative declaration.
3477   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3478   assert(PrevDecl && "Expected a non-null Decl");
3479 
3480   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3481     return false;
3482 
3483   SemaRef.Diag(NameLoc, diagnostic) << Name;
3484   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3485 
3486   return true;
3487 }
3488 
3489 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3490 /// anonymous struct or union AnonRecord into the owning context Owner
3491 /// and scope S. This routine will be invoked just after we realize
3492 /// that an unnamed union or struct is actually an anonymous union or
3493 /// struct, e.g.,
3494 ///
3495 /// @code
3496 /// union {
3497 ///   int i;
3498 ///   float f;
3499 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3500 ///    // f into the surrounding scope.x
3501 /// @endcode
3502 ///
3503 /// This routine is recursive, injecting the names of nested anonymous
3504 /// structs/unions into the owning context and scope as well.
3505 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3506                                          DeclContext *Owner,
3507                                          RecordDecl *AnonRecord,
3508                                          AccessSpecifier AS,
3509                                          SmallVectorImpl<NamedDecl *> &Chaining,
3510                                          bool MSAnonStruct) {
3511   unsigned diagKind
3512     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3513                             : diag::err_anonymous_struct_member_redecl;
3514 
3515   bool Invalid = false;
3516 
3517   // Look every FieldDecl and IndirectFieldDecl with a name.
3518   for (auto *D : AnonRecord->decls()) {
3519     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3520         cast<NamedDecl>(D)->getDeclName()) {
3521       ValueDecl *VD = cast<ValueDecl>(D);
3522       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3523                                        VD->getLocation(), diagKind)) {
3524         // C++ [class.union]p2:
3525         //   The names of the members of an anonymous union shall be
3526         //   distinct from the names of any other entity in the
3527         //   scope in which the anonymous union is declared.
3528         Invalid = true;
3529       } else {
3530         // C++ [class.union]p2:
3531         //   For the purpose of name lookup, after the anonymous union
3532         //   definition, the members of the anonymous union are
3533         //   considered to have been defined in the scope in which the
3534         //   anonymous union is declared.
3535         unsigned OldChainingSize = Chaining.size();
3536         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3537           for (auto *PI : IF->chain())
3538             Chaining.push_back(PI);
3539         else
3540           Chaining.push_back(VD);
3541 
3542         assert(Chaining.size() >= 2);
3543         NamedDecl **NamedChain =
3544           new (SemaRef.Context)NamedDecl*[Chaining.size()];
3545         for (unsigned i = 0; i < Chaining.size(); i++)
3546           NamedChain[i] = Chaining[i];
3547 
3548         IndirectFieldDecl* IndirectField =
3549           IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3550                                     VD->getIdentifier(), VD->getType(),
3551                                     NamedChain, Chaining.size());
3552 
3553         IndirectField->setAccess(AS);
3554         IndirectField->setImplicit();
3555         SemaRef.PushOnScopeChains(IndirectField, S);
3556 
3557         // That includes picking up the appropriate access specifier.
3558         if (AS != AS_none) IndirectField->setAccess(AS);
3559 
3560         Chaining.resize(OldChainingSize);
3561       }
3562     }
3563   }
3564 
3565   return Invalid;
3566 }
3567 
3568 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3569 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
3570 /// illegal input values are mapped to SC_None.
3571 static StorageClass
3572 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3573   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3574   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3575          "Parser allowed 'typedef' as storage class VarDecl.");
3576   switch (StorageClassSpec) {
3577   case DeclSpec::SCS_unspecified:    return SC_None;
3578   case DeclSpec::SCS_extern:
3579     if (DS.isExternInLinkageSpec())
3580       return SC_None;
3581     return SC_Extern;
3582   case DeclSpec::SCS_static:         return SC_Static;
3583   case DeclSpec::SCS_auto:           return SC_Auto;
3584   case DeclSpec::SCS_register:       return SC_Register;
3585   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3586     // Illegal SCSs map to None: error reporting is up to the caller.
3587   case DeclSpec::SCS_mutable:        // Fall through.
3588   case DeclSpec::SCS_typedef:        return SC_None;
3589   }
3590   llvm_unreachable("unknown storage class specifier");
3591 }
3592 
3593 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3594   assert(Record->hasInClassInitializer());
3595 
3596   for (const auto *I : Record->decls()) {
3597     const auto *FD = dyn_cast<FieldDecl>(I);
3598     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
3599       FD = IFD->getAnonField();
3600     if (FD && FD->hasInClassInitializer())
3601       return FD->getLocation();
3602   }
3603 
3604   llvm_unreachable("couldn't find in-class initializer");
3605 }
3606 
3607 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3608                                       SourceLocation DefaultInitLoc) {
3609   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3610     return;
3611 
3612   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3613   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3614 }
3615 
3616 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3617                                       CXXRecordDecl *AnonUnion) {
3618   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3619     return;
3620 
3621   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3622 }
3623 
3624 /// BuildAnonymousStructOrUnion - Handle the declaration of an
3625 /// anonymous structure or union. Anonymous unions are a C++ feature
3626 /// (C++ [class.union]) and a C11 feature; anonymous structures
3627 /// are a C11 feature and GNU C++ extension.
3628 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3629                                         AccessSpecifier AS,
3630                                         RecordDecl *Record,
3631                                         const PrintingPolicy &Policy) {
3632   DeclContext *Owner = Record->getDeclContext();
3633 
3634   // Diagnose whether this anonymous struct/union is an extension.
3635   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
3636     Diag(Record->getLocation(), diag::ext_anonymous_union);
3637   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
3638     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3639   else if (!Record->isUnion() && !getLangOpts().C11)
3640     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3641 
3642   // C and C++ require different kinds of checks for anonymous
3643   // structs/unions.
3644   bool Invalid = false;
3645   if (getLangOpts().CPlusPlus) {
3646     const char *PrevSpec = nullptr;
3647     unsigned DiagID;
3648     if (Record->isUnion()) {
3649       // C++ [class.union]p6:
3650       //   Anonymous unions declared in a named namespace or in the
3651       //   global namespace shall be declared static.
3652       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3653           (isa<TranslationUnitDecl>(Owner) ||
3654            (isa<NamespaceDecl>(Owner) &&
3655             cast<NamespaceDecl>(Owner)->getDeclName()))) {
3656         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3657           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3658 
3659         // Recover by adding 'static'.
3660         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3661                                PrevSpec, DiagID, Policy);
3662       }
3663       // C++ [class.union]p6:
3664       //   A storage class is not allowed in a declaration of an
3665       //   anonymous union in a class scope.
3666       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3667                isa<RecordDecl>(Owner)) {
3668         Diag(DS.getStorageClassSpecLoc(),
3669              diag::err_anonymous_union_with_storage_spec)
3670           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3671 
3672         // Recover by removing the storage specifier.
3673         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3674                                SourceLocation(),
3675                                PrevSpec, DiagID, Context.getPrintingPolicy());
3676       }
3677     }
3678 
3679     // Ignore const/volatile/restrict qualifiers.
3680     if (DS.getTypeQualifiers()) {
3681       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3682         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3683           << Record->isUnion() << "const"
3684           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3685       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3686         Diag(DS.getVolatileSpecLoc(),
3687              diag::ext_anonymous_struct_union_qualified)
3688           << Record->isUnion() << "volatile"
3689           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3690       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3691         Diag(DS.getRestrictSpecLoc(),
3692              diag::ext_anonymous_struct_union_qualified)
3693           << Record->isUnion() << "restrict"
3694           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3695       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3696         Diag(DS.getAtomicSpecLoc(),
3697              diag::ext_anonymous_struct_union_qualified)
3698           << Record->isUnion() << "_Atomic"
3699           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
3700 
3701       DS.ClearTypeQualifiers();
3702     }
3703 
3704     // C++ [class.union]p2:
3705     //   The member-specification of an anonymous union shall only
3706     //   define non-static data members. [Note: nested types and
3707     //   functions cannot be declared within an anonymous union. ]
3708     for (auto *Mem : Record->decls()) {
3709       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
3710         // C++ [class.union]p3:
3711         //   An anonymous union shall not have private or protected
3712         //   members (clause 11).
3713         assert(FD->getAccess() != AS_none);
3714         if (FD->getAccess() != AS_public) {
3715           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3716             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3717           Invalid = true;
3718         }
3719 
3720         // C++ [class.union]p1
3721         //   An object of a class with a non-trivial constructor, a non-trivial
3722         //   copy constructor, a non-trivial destructor, or a non-trivial copy
3723         //   assignment operator cannot be a member of a union, nor can an
3724         //   array of such objects.
3725         if (CheckNontrivialField(FD))
3726           Invalid = true;
3727       } else if (Mem->isImplicit()) {
3728         // Any implicit members are fine.
3729       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
3730         // This is a type that showed up in an
3731         // elaborated-type-specifier inside the anonymous struct or
3732         // union, but which actually declares a type outside of the
3733         // anonymous struct or union. It's okay.
3734       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
3735         if (!MemRecord->isAnonymousStructOrUnion() &&
3736             MemRecord->getDeclName()) {
3737           // Visual C++ allows type definition in anonymous struct or union.
3738           if (getLangOpts().MicrosoftExt)
3739             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3740               << (int)Record->isUnion();
3741           else {
3742             // This is a nested type declaration.
3743             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3744               << (int)Record->isUnion();
3745             Invalid = true;
3746           }
3747         } else {
3748           // This is an anonymous type definition within another anonymous type.
3749           // This is a popular extension, provided by Plan9, MSVC and GCC, but
3750           // not part of standard C++.
3751           Diag(MemRecord->getLocation(),
3752                diag::ext_anonymous_record_with_anonymous_type)
3753             << (int)Record->isUnion();
3754         }
3755       } else if (isa<AccessSpecDecl>(Mem)) {
3756         // Any access specifier is fine.
3757       } else {
3758         // We have something that isn't a non-static data
3759         // member. Complain about it.
3760         unsigned DK = diag::err_anonymous_record_bad_member;
3761         if (isa<TypeDecl>(Mem))
3762           DK = diag::err_anonymous_record_with_type;
3763         else if (isa<FunctionDecl>(Mem))
3764           DK = diag::err_anonymous_record_with_function;
3765         else if (isa<VarDecl>(Mem))
3766           DK = diag::err_anonymous_record_with_static;
3767 
3768         // Visual C++ allows type definition in anonymous struct or union.
3769         if (getLangOpts().MicrosoftExt &&
3770             DK == diag::err_anonymous_record_with_type)
3771           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
3772             << (int)Record->isUnion();
3773         else {
3774           Diag(Mem->getLocation(), DK)
3775               << (int)Record->isUnion();
3776           Invalid = true;
3777         }
3778       }
3779     }
3780 
3781     // C++11 [class.union]p8 (DR1460):
3782     //   At most one variant member of a union may have a
3783     //   brace-or-equal-initializer.
3784     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3785         Owner->isRecord())
3786       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3787                                 cast<CXXRecordDecl>(Record));
3788   }
3789 
3790   if (!Record->isUnion() && !Owner->isRecord()) {
3791     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3792       << (int)getLangOpts().CPlusPlus;
3793     Invalid = true;
3794   }
3795 
3796   // Mock up a declarator.
3797   Declarator Dc(DS, Declarator::MemberContext);
3798   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3799   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3800 
3801   // Create a declaration for this anonymous struct/union.
3802   NamedDecl *Anon = nullptr;
3803   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3804     Anon = FieldDecl::Create(Context, OwningClass,
3805                              DS.getLocStart(),
3806                              Record->getLocation(),
3807                              /*IdentifierInfo=*/nullptr,
3808                              Context.getTypeDeclType(Record),
3809                              TInfo,
3810                              /*BitWidth=*/nullptr, /*Mutable=*/false,
3811                              /*InitStyle=*/ICIS_NoInit);
3812     Anon->setAccess(AS);
3813     if (getLangOpts().CPlusPlus)
3814       FieldCollector->Add(cast<FieldDecl>(Anon));
3815   } else {
3816     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3817     VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
3818     if (SCSpec == DeclSpec::SCS_mutable) {
3819       // mutable can only appear on non-static class members, so it's always
3820       // an error here
3821       Diag(Record->getLocation(), diag::err_mutable_nonmember);
3822       Invalid = true;
3823       SC = SC_None;
3824     }
3825 
3826     Anon = VarDecl::Create(Context, Owner,
3827                            DS.getLocStart(),
3828                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
3829                            Context.getTypeDeclType(Record),
3830                            TInfo, SC);
3831 
3832     // Default-initialize the implicit variable. This initialization will be
3833     // trivial in almost all cases, except if a union member has an in-class
3834     // initializer:
3835     //   union { int n = 0; };
3836     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
3837   }
3838   Anon->setImplicit();
3839 
3840   // Mark this as an anonymous struct/union type.
3841   Record->setAnonymousStructOrUnion(true);
3842 
3843   // Add the anonymous struct/union object to the current
3844   // context. We'll be referencing this object when we refer to one of
3845   // its members.
3846   Owner->addDecl(Anon);
3847 
3848   // Inject the members of the anonymous struct/union into the owning
3849   // context and into the identifier resolver chain for name lookup
3850   // purposes.
3851   SmallVector<NamedDecl*, 2> Chain;
3852   Chain.push_back(Anon);
3853 
3854   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3855                                           Chain, false))
3856     Invalid = true;
3857 
3858   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
3859     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
3860       Decl *ManglingContextDecl;
3861       if (MangleNumberingContext *MCtx =
3862               getCurrentMangleNumberContext(NewVD->getDeclContext(),
3863                                             ManglingContextDecl)) {
3864         Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
3865         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
3866       }
3867     }
3868   }
3869 
3870   if (Invalid)
3871     Anon->setInvalidDecl();
3872 
3873   return Anon;
3874 }
3875 
3876 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3877 /// Microsoft C anonymous structure.
3878 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3879 /// Example:
3880 ///
3881 /// struct A { int a; };
3882 /// struct B { struct A; int b; };
3883 ///
3884 /// void foo() {
3885 ///   B var;
3886 ///   var.a = 3;
3887 /// }
3888 ///
3889 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3890                                            RecordDecl *Record) {
3891 
3892   // If there is no Record, get the record via the typedef.
3893   if (!Record)
3894     Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3895 
3896   // Mock up a declarator.
3897   Declarator Dc(DS, Declarator::TypeNameContext);
3898   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3899   assert(TInfo && "couldn't build declarator info for anonymous struct");
3900 
3901   // Create a declaration for this anonymous struct.
3902   NamedDecl *Anon = FieldDecl::Create(Context,
3903                              cast<RecordDecl>(CurContext),
3904                              DS.getLocStart(),
3905                              DS.getLocStart(),
3906                              /*IdentifierInfo=*/nullptr,
3907                              Context.getTypeDeclType(Record),
3908                              TInfo,
3909                              /*BitWidth=*/nullptr, /*Mutable=*/false,
3910                              /*InitStyle=*/ICIS_NoInit);
3911   Anon->setImplicit();
3912 
3913   // Add the anonymous struct object to the current context.
3914   CurContext->addDecl(Anon);
3915 
3916   // Inject the members of the anonymous struct into the current
3917   // context and into the identifier resolver chain for name lookup
3918   // purposes.
3919   SmallVector<NamedDecl*, 2> Chain;
3920   Chain.push_back(Anon);
3921 
3922   RecordDecl *RecordDef = Record->getDefinition();
3923   if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3924                                                         RecordDef, AS_none,
3925                                                         Chain, true))
3926     Anon->setInvalidDecl();
3927 
3928   return Anon;
3929 }
3930 
3931 /// GetNameForDeclarator - Determine the full declaration name for the
3932 /// given Declarator.
3933 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
3934   return GetNameFromUnqualifiedId(D.getName());
3935 }
3936 
3937 /// \brief Retrieves the declaration name from a parsed unqualified-id.
3938 DeclarationNameInfo
3939 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3940   DeclarationNameInfo NameInfo;
3941   NameInfo.setLoc(Name.StartLocation);
3942 
3943   switch (Name.getKind()) {
3944 
3945   case UnqualifiedId::IK_ImplicitSelfParam:
3946   case UnqualifiedId::IK_Identifier:
3947     NameInfo.setName(Name.Identifier);
3948     NameInfo.setLoc(Name.StartLocation);
3949     return NameInfo;
3950 
3951   case UnqualifiedId::IK_OperatorFunctionId:
3952     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3953                                            Name.OperatorFunctionId.Operator));
3954     NameInfo.setLoc(Name.StartLocation);
3955     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3956       = Name.OperatorFunctionId.SymbolLocations[0];
3957     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3958       = Name.EndLocation.getRawEncoding();
3959     return NameInfo;
3960 
3961   case UnqualifiedId::IK_LiteralOperatorId:
3962     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3963                                                            Name.Identifier));
3964     NameInfo.setLoc(Name.StartLocation);
3965     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3966     return NameInfo;
3967 
3968   case UnqualifiedId::IK_ConversionFunctionId: {
3969     TypeSourceInfo *TInfo;
3970     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3971     if (Ty.isNull())
3972       return DeclarationNameInfo();
3973     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3974                                                Context.getCanonicalType(Ty)));
3975     NameInfo.setLoc(Name.StartLocation);
3976     NameInfo.setNamedTypeInfo(TInfo);
3977     return NameInfo;
3978   }
3979 
3980   case UnqualifiedId::IK_ConstructorName: {
3981     TypeSourceInfo *TInfo;
3982     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3983     if (Ty.isNull())
3984       return DeclarationNameInfo();
3985     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3986                                               Context.getCanonicalType(Ty)));
3987     NameInfo.setLoc(Name.StartLocation);
3988     NameInfo.setNamedTypeInfo(TInfo);
3989     return NameInfo;
3990   }
3991 
3992   case UnqualifiedId::IK_ConstructorTemplateId: {
3993     // In well-formed code, we can only have a constructor
3994     // template-id that refers to the current context, so go there
3995     // to find the actual type being constructed.
3996     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3997     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3998       return DeclarationNameInfo();
3999 
4000     // Determine the type of the class being constructed.
4001     QualType CurClassType = Context.getTypeDeclType(CurClass);
4002 
4003     // FIXME: Check two things: that the template-id names the same type as
4004     // CurClassType, and that the template-id does not occur when the name
4005     // was qualified.
4006 
4007     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4008                                     Context.getCanonicalType(CurClassType)));
4009     NameInfo.setLoc(Name.StartLocation);
4010     // FIXME: should we retrieve TypeSourceInfo?
4011     NameInfo.setNamedTypeInfo(nullptr);
4012     return NameInfo;
4013   }
4014 
4015   case UnqualifiedId::IK_DestructorName: {
4016     TypeSourceInfo *TInfo;
4017     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4018     if (Ty.isNull())
4019       return DeclarationNameInfo();
4020     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4021                                               Context.getCanonicalType(Ty)));
4022     NameInfo.setLoc(Name.StartLocation);
4023     NameInfo.setNamedTypeInfo(TInfo);
4024     return NameInfo;
4025   }
4026 
4027   case UnqualifiedId::IK_TemplateId: {
4028     TemplateName TName = Name.TemplateId->Template.get();
4029     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4030     return Context.getNameForTemplate(TName, TNameLoc);
4031   }
4032 
4033   } // switch (Name.getKind())
4034 
4035   llvm_unreachable("Unknown name kind");
4036 }
4037 
4038 static QualType getCoreType(QualType Ty) {
4039   do {
4040     if (Ty->isPointerType() || Ty->isReferenceType())
4041       Ty = Ty->getPointeeType();
4042     else if (Ty->isArrayType())
4043       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4044     else
4045       return Ty.withoutLocalFastQualifiers();
4046   } while (true);
4047 }
4048 
4049 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4050 /// and Definition have "nearly" matching parameters. This heuristic is
4051 /// used to improve diagnostics in the case where an out-of-line function
4052 /// definition doesn't match any declaration within the class or namespace.
4053 /// Also sets Params to the list of indices to the parameters that differ
4054 /// between the declaration and the definition. If hasSimilarParameters
4055 /// returns true and Params is empty, then all of the parameters match.
4056 static bool hasSimilarParameters(ASTContext &Context,
4057                                      FunctionDecl *Declaration,
4058                                      FunctionDecl *Definition,
4059                                      SmallVectorImpl<unsigned> &Params) {
4060   Params.clear();
4061   if (Declaration->param_size() != Definition->param_size())
4062     return false;
4063   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4064     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4065     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4066 
4067     // The parameter types are identical
4068     if (Context.hasSameType(DefParamTy, DeclParamTy))
4069       continue;
4070 
4071     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4072     QualType DefParamBaseTy = getCoreType(DefParamTy);
4073     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4074     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4075 
4076     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4077         (DeclTyName && DeclTyName == DefTyName))
4078       Params.push_back(Idx);
4079     else  // The two parameters aren't even close
4080       return false;
4081   }
4082 
4083   return true;
4084 }
4085 
4086 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4087 /// declarator needs to be rebuilt in the current instantiation.
4088 /// Any bits of declarator which appear before the name are valid for
4089 /// consideration here.  That's specifically the type in the decl spec
4090 /// and the base type in any member-pointer chunks.
4091 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4092                                                     DeclarationName Name) {
4093   // The types we specifically need to rebuild are:
4094   //   - typenames, typeofs, and decltypes
4095   //   - types which will become injected class names
4096   // Of course, we also need to rebuild any type referencing such a
4097   // type.  It's safest to just say "dependent", but we call out a
4098   // few cases here.
4099 
4100   DeclSpec &DS = D.getMutableDeclSpec();
4101   switch (DS.getTypeSpecType()) {
4102   case DeclSpec::TST_typename:
4103   case DeclSpec::TST_typeofType:
4104   case DeclSpec::TST_underlyingType:
4105   case DeclSpec::TST_atomic: {
4106     // Grab the type from the parser.
4107     TypeSourceInfo *TSI = nullptr;
4108     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4109     if (T.isNull() || !T->isDependentType()) break;
4110 
4111     // Make sure there's a type source info.  This isn't really much
4112     // of a waste; most dependent types should have type source info
4113     // attached already.
4114     if (!TSI)
4115       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4116 
4117     // Rebuild the type in the current instantiation.
4118     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4119     if (!TSI) return true;
4120 
4121     // Store the new type back in the decl spec.
4122     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4123     DS.UpdateTypeRep(LocType);
4124     break;
4125   }
4126 
4127   case DeclSpec::TST_decltype:
4128   case DeclSpec::TST_typeofExpr: {
4129     Expr *E = DS.getRepAsExpr();
4130     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4131     if (Result.isInvalid()) return true;
4132     DS.UpdateExprRep(Result.get());
4133     break;
4134   }
4135 
4136   default:
4137     // Nothing to do for these decl specs.
4138     break;
4139   }
4140 
4141   // It doesn't matter what order we do this in.
4142   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4143     DeclaratorChunk &Chunk = D.getTypeObject(I);
4144 
4145     // The only type information in the declarator which can come
4146     // before the declaration name is the base type of a member
4147     // pointer.
4148     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4149       continue;
4150 
4151     // Rebuild the scope specifier in-place.
4152     CXXScopeSpec &SS = Chunk.Mem.Scope();
4153     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4154       return true;
4155   }
4156 
4157   return false;
4158 }
4159 
4160 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4161   D.setFunctionDefinitionKind(FDK_Declaration);
4162   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4163 
4164   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4165       Dcl && Dcl->getDeclContext()->isFileContext())
4166     Dcl->setTopLevelDeclInObjCContainer();
4167 
4168   return Dcl;
4169 }
4170 
4171 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4172 ///   If T is the name of a class, then each of the following shall have a
4173 ///   name different from T:
4174 ///     - every static data member of class T;
4175 ///     - every member function of class T
4176 ///     - every member of class T that is itself a type;
4177 /// \returns true if the declaration name violates these rules.
4178 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4179                                    DeclarationNameInfo NameInfo) {
4180   DeclarationName Name = NameInfo.getName();
4181 
4182   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4183     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4184       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4185       return true;
4186     }
4187 
4188   return false;
4189 }
4190 
4191 /// \brief Diagnose a declaration whose declarator-id has the given
4192 /// nested-name-specifier.
4193 ///
4194 /// \param SS The nested-name-specifier of the declarator-id.
4195 ///
4196 /// \param DC The declaration context to which the nested-name-specifier
4197 /// resolves.
4198 ///
4199 /// \param Name The name of the entity being declared.
4200 ///
4201 /// \param Loc The location of the name of the entity being declared.
4202 ///
4203 /// \returns true if we cannot safely recover from this error, false otherwise.
4204 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4205                                         DeclarationName Name,
4206                                         SourceLocation Loc) {
4207   DeclContext *Cur = CurContext;
4208   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4209     Cur = Cur->getParent();
4210 
4211   // If the user provided a superfluous scope specifier that refers back to the
4212   // class in which the entity is already declared, diagnose and ignore it.
4213   //
4214   // class X {
4215   //   void X::f();
4216   // };
4217   //
4218   // Note, it was once ill-formed to give redundant qualification in all
4219   // contexts, but that rule was removed by DR482.
4220   if (Cur->Equals(DC)) {
4221     if (Cur->isRecord()) {
4222       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4223                                       : diag::err_member_extra_qualification)
4224         << Name << FixItHint::CreateRemoval(SS.getRange());
4225       SS.clear();
4226     } else {
4227       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4228     }
4229     return false;
4230   }
4231 
4232   // Check whether the qualifying scope encloses the scope of the original
4233   // declaration.
4234   if (!Cur->Encloses(DC)) {
4235     if (Cur->isRecord())
4236       Diag(Loc, diag::err_member_qualification)
4237         << Name << SS.getRange();
4238     else if (isa<TranslationUnitDecl>(DC))
4239       Diag(Loc, diag::err_invalid_declarator_global_scope)
4240         << Name << SS.getRange();
4241     else if (isa<FunctionDecl>(Cur))
4242       Diag(Loc, diag::err_invalid_declarator_in_function)
4243         << Name << SS.getRange();
4244     else if (isa<BlockDecl>(Cur))
4245       Diag(Loc, diag::err_invalid_declarator_in_block)
4246         << Name << SS.getRange();
4247     else
4248       Diag(Loc, diag::err_invalid_declarator_scope)
4249       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4250 
4251     return true;
4252   }
4253 
4254   if (Cur->isRecord()) {
4255     // Cannot qualify members within a class.
4256     Diag(Loc, diag::err_member_qualification)
4257       << Name << SS.getRange();
4258     SS.clear();
4259 
4260     // C++ constructors and destructors with incorrect scopes can break
4261     // our AST invariants by having the wrong underlying types. If
4262     // that's the case, then drop this declaration entirely.
4263     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4264          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4265         !Context.hasSameType(Name.getCXXNameType(),
4266                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4267       return true;
4268 
4269     return false;
4270   }
4271 
4272   // C++11 [dcl.meaning]p1:
4273   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4274   //   not begin with a decltype-specifer"
4275   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4276   while (SpecLoc.getPrefix())
4277     SpecLoc = SpecLoc.getPrefix();
4278   if (dyn_cast_or_null<DecltypeType>(
4279         SpecLoc.getNestedNameSpecifier()->getAsType()))
4280     Diag(Loc, diag::err_decltype_in_declarator)
4281       << SpecLoc.getTypeLoc().getSourceRange();
4282 
4283   return false;
4284 }
4285 
4286 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4287                                   MultiTemplateParamsArg TemplateParamLists) {
4288   // TODO: consider using NameInfo for diagnostic.
4289   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4290   DeclarationName Name = NameInfo.getName();
4291 
4292   // All of these full declarators require an identifier.  If it doesn't have
4293   // one, the ParsedFreeStandingDeclSpec action should be used.
4294   if (!Name) {
4295     if (!D.isInvalidType())  // Reject this if we think it is valid.
4296       Diag(D.getDeclSpec().getLocStart(),
4297            diag::err_declarator_need_ident)
4298         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4299     return nullptr;
4300   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4301     return nullptr;
4302 
4303   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4304   // we find one that is.
4305   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4306          (S->getFlags() & Scope::TemplateParamScope) != 0)
4307     S = S->getParent();
4308 
4309   DeclContext *DC = CurContext;
4310   if (D.getCXXScopeSpec().isInvalid())
4311     D.setInvalidType();
4312   else if (D.getCXXScopeSpec().isSet()) {
4313     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4314                                         UPPC_DeclarationQualifier))
4315       return nullptr;
4316 
4317     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4318     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4319     if (!DC || isa<EnumDecl>(DC)) {
4320       // If we could not compute the declaration context, it's because the
4321       // declaration context is dependent but does not refer to a class,
4322       // class template, or class template partial specialization. Complain
4323       // and return early, to avoid the coming semantic disaster.
4324       Diag(D.getIdentifierLoc(),
4325            diag::err_template_qualified_declarator_no_match)
4326         << D.getCXXScopeSpec().getScopeRep()
4327         << D.getCXXScopeSpec().getRange();
4328       return nullptr;
4329     }
4330     bool IsDependentContext = DC->isDependentContext();
4331 
4332     if (!IsDependentContext &&
4333         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4334       return nullptr;
4335 
4336     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4337       Diag(D.getIdentifierLoc(),
4338            diag::err_member_def_undefined_record)
4339         << Name << DC << D.getCXXScopeSpec().getRange();
4340       D.setInvalidType();
4341     } else if (!D.getDeclSpec().isFriendSpecified()) {
4342       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4343                                       Name, D.getIdentifierLoc())) {
4344         if (DC->isRecord())
4345           return nullptr;
4346 
4347         D.setInvalidType();
4348       }
4349     }
4350 
4351     // Check whether we need to rebuild the type of the given
4352     // declaration in the current instantiation.
4353     if (EnteringContext && IsDependentContext &&
4354         TemplateParamLists.size() != 0) {
4355       ContextRAII SavedContext(*this, DC);
4356       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4357         D.setInvalidType();
4358     }
4359   }
4360 
4361   if (DiagnoseClassNameShadow(DC, NameInfo))
4362     // If this is a typedef, we'll end up spewing multiple diagnostics.
4363     // Just return early; it's safer.
4364     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4365       return nullptr;
4366 
4367   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4368   QualType R = TInfo->getType();
4369 
4370   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4371                                       UPPC_DeclarationType))
4372     D.setInvalidType();
4373 
4374   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4375                         ForRedeclaration);
4376 
4377   // See if this is a redefinition of a variable in the same scope.
4378   if (!D.getCXXScopeSpec().isSet()) {
4379     bool IsLinkageLookup = false;
4380     bool CreateBuiltins = false;
4381 
4382     // If the declaration we're planning to build will be a function
4383     // or object with linkage, then look for another declaration with
4384     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4385     //
4386     // If the declaration we're planning to build will be declared with
4387     // external linkage in the translation unit, create any builtin with
4388     // the same name.
4389     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4390       /* Do nothing*/;
4391     else if (CurContext->isFunctionOrMethod() &&
4392              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4393               R->isFunctionType())) {
4394       IsLinkageLookup = true;
4395       CreateBuiltins =
4396           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4397     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4398                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4399       CreateBuiltins = true;
4400 
4401     if (IsLinkageLookup)
4402       Previous.clear(LookupRedeclarationWithLinkage);
4403 
4404     LookupName(Previous, S, CreateBuiltins);
4405   } else { // Something like "int foo::x;"
4406     LookupQualifiedName(Previous, DC);
4407 
4408     // C++ [dcl.meaning]p1:
4409     //   When the declarator-id is qualified, the declaration shall refer to a
4410     //  previously declared member of the class or namespace to which the
4411     //  qualifier refers (or, in the case of a namespace, of an element of the
4412     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4413     //  thereof; [...]
4414     //
4415     // Note that we already checked the context above, and that we do not have
4416     // enough information to make sure that Previous contains the declaration
4417     // we want to match. For example, given:
4418     //
4419     //   class X {
4420     //     void f();
4421     //     void f(float);
4422     //   };
4423     //
4424     //   void X::f(int) { } // ill-formed
4425     //
4426     // In this case, Previous will point to the overload set
4427     // containing the two f's declared in X, but neither of them
4428     // matches.
4429 
4430     // C++ [dcl.meaning]p1:
4431     //   [...] the member shall not merely have been introduced by a
4432     //   using-declaration in the scope of the class or namespace nominated by
4433     //   the nested-name-specifier of the declarator-id.
4434     RemoveUsingDecls(Previous);
4435   }
4436 
4437   if (Previous.isSingleResult() &&
4438       Previous.getFoundDecl()->isTemplateParameter()) {
4439     // Maybe we will complain about the shadowed template parameter.
4440     if (!D.isInvalidType())
4441       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4442                                       Previous.getFoundDecl());
4443 
4444     // Just pretend that we didn't see the previous declaration.
4445     Previous.clear();
4446   }
4447 
4448   // In C++, the previous declaration we find might be a tag type
4449   // (class or enum). In this case, the new declaration will hide the
4450   // tag type. Note that this does does not apply if we're declaring a
4451   // typedef (C++ [dcl.typedef]p4).
4452   if (Previous.isSingleTagDecl() &&
4453       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4454     Previous.clear();
4455 
4456   // Check that there are no default arguments other than in the parameters
4457   // of a function declaration (C++ only).
4458   if (getLangOpts().CPlusPlus)
4459     CheckExtraCXXDefaultArguments(D);
4460 
4461   NamedDecl *New;
4462 
4463   bool AddToScope = true;
4464   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4465     if (TemplateParamLists.size()) {
4466       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4467       return nullptr;
4468     }
4469 
4470     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4471   } else if (R->isFunctionType()) {
4472     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4473                                   TemplateParamLists,
4474                                   AddToScope);
4475   } else {
4476     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4477                                   AddToScope);
4478   }
4479 
4480   if (!New)
4481     return nullptr;
4482 
4483   // If this has an identifier and is not an invalid redeclaration or
4484   // function template specialization, add it to the scope stack.
4485   if (New->getDeclName() && AddToScope &&
4486        !(D.isRedeclaration() && New->isInvalidDecl())) {
4487     // Only make a locally-scoped extern declaration visible if it is the first
4488     // declaration of this entity. Qualified lookup for such an entity should
4489     // only find this declaration if there is no visible declaration of it.
4490     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4491     PushOnScopeChains(New, S, AddToContext);
4492     if (!AddToContext)
4493       CurContext->addHiddenDecl(New);
4494   }
4495 
4496   return New;
4497 }
4498 
4499 /// Helper method to turn variable array types into constant array
4500 /// types in certain situations which would otherwise be errors (for
4501 /// GCC compatibility).
4502 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4503                                                     ASTContext &Context,
4504                                                     bool &SizeIsNegative,
4505                                                     llvm::APSInt &Oversized) {
4506   // This method tries to turn a variable array into a constant
4507   // array even when the size isn't an ICE.  This is necessary
4508   // for compatibility with code that depends on gcc's buggy
4509   // constant expression folding, like struct {char x[(int)(char*)2];}
4510   SizeIsNegative = false;
4511   Oversized = 0;
4512 
4513   if (T->isDependentType())
4514     return QualType();
4515 
4516   QualifierCollector Qs;
4517   const Type *Ty = Qs.strip(T);
4518 
4519   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4520     QualType Pointee = PTy->getPointeeType();
4521     QualType FixedType =
4522         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4523                                             Oversized);
4524     if (FixedType.isNull()) return FixedType;
4525     FixedType = Context.getPointerType(FixedType);
4526     return Qs.apply(Context, FixedType);
4527   }
4528   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4529     QualType Inner = PTy->getInnerType();
4530     QualType FixedType =
4531         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4532                                             Oversized);
4533     if (FixedType.isNull()) return FixedType;
4534     FixedType = Context.getParenType(FixedType);
4535     return Qs.apply(Context, FixedType);
4536   }
4537 
4538   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4539   if (!VLATy)
4540     return QualType();
4541   // FIXME: We should probably handle this case
4542   if (VLATy->getElementType()->isVariablyModifiedType())
4543     return QualType();
4544 
4545   llvm::APSInt Res;
4546   if (!VLATy->getSizeExpr() ||
4547       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4548     return QualType();
4549 
4550   // Check whether the array size is negative.
4551   if (Res.isSigned() && Res.isNegative()) {
4552     SizeIsNegative = true;
4553     return QualType();
4554   }
4555 
4556   // Check whether the array is too large to be addressed.
4557   unsigned ActiveSizeBits
4558     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4559                                               Res);
4560   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4561     Oversized = Res;
4562     return QualType();
4563   }
4564 
4565   return Context.getConstantArrayType(VLATy->getElementType(),
4566                                       Res, ArrayType::Normal, 0);
4567 }
4568 
4569 static void
4570 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
4571   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4572     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4573     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4574                                       DstPTL.getPointeeLoc());
4575     DstPTL.setStarLoc(SrcPTL.getStarLoc());
4576     return;
4577   }
4578   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4579     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4580     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4581                                       DstPTL.getInnerLoc());
4582     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4583     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
4584     return;
4585   }
4586   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4587   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4588   TypeLoc SrcElemTL = SrcATL.getElementLoc();
4589   TypeLoc DstElemTL = DstATL.getElementLoc();
4590   DstElemTL.initializeFullCopy(SrcElemTL);
4591   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4592   DstATL.setSizeExpr(SrcATL.getSizeExpr());
4593   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
4594 }
4595 
4596 /// Helper method to turn variable array types into constant array
4597 /// types in certain situations which would otherwise be errors (for
4598 /// GCC compatibility).
4599 static TypeSourceInfo*
4600 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4601                                               ASTContext &Context,
4602                                               bool &SizeIsNegative,
4603                                               llvm::APSInt &Oversized) {
4604   QualType FixedTy
4605     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4606                                           SizeIsNegative, Oversized);
4607   if (FixedTy.isNull())
4608     return nullptr;
4609   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4610   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4611                                     FixedTInfo->getTypeLoc());
4612   return FixedTInfo;
4613 }
4614 
4615 /// \brief Register the given locally-scoped extern "C" declaration so
4616 /// that it can be found later for redeclarations. We include any extern "C"
4617 /// declaration that is not visible in the translation unit here, not just
4618 /// function-scope declarations.
4619 void
4620 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
4621   if (!getLangOpts().CPlusPlus &&
4622       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4623     // Don't need to track declarations in the TU in C.
4624     return;
4625 
4626   // Note that we have a locally-scoped external with this name.
4627   // FIXME: There can be multiple such declarations if they are functions marked
4628   // __attribute__((overloadable)) declared in function scope in C.
4629   LocallyScopedExternCDecls[ND->getDeclName()] = ND;
4630 }
4631 
4632 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4633   if (ExternalSource) {
4634     // Load locally-scoped external decls from the external source.
4635     // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
4636     SmallVector<NamedDecl *, 4> Decls;
4637     ExternalSource->ReadLocallyScopedExternCDecls(Decls);
4638     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4639       llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4640         = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4641       if (Pos == LocallyScopedExternCDecls.end())
4642         LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
4643     }
4644   }
4645 
4646   NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
4647   return D ? D->getMostRecentDecl() : nullptr;
4648 }
4649 
4650 /// \brief Diagnose function specifiers on a declaration of an identifier that
4651 /// does not identify a function.
4652 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
4653   // FIXME: We should probably indicate the identifier in question to avoid
4654   // confusion for constructs like "inline int a(), b;"
4655   if (DS.isInlineSpecified())
4656     Diag(DS.getInlineSpecLoc(),
4657          diag::err_inline_non_function);
4658 
4659   if (DS.isVirtualSpecified())
4660     Diag(DS.getVirtualSpecLoc(),
4661          diag::err_virtual_non_function);
4662 
4663   if (DS.isExplicitSpecified())
4664     Diag(DS.getExplicitSpecLoc(),
4665          diag::err_explicit_non_function);
4666 
4667   if (DS.isNoreturnSpecified())
4668     Diag(DS.getNoreturnSpecLoc(),
4669          diag::err_noreturn_non_function);
4670 }
4671 
4672 NamedDecl*
4673 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4674                              TypeSourceInfo *TInfo, LookupResult &Previous) {
4675   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4676   if (D.getCXXScopeSpec().isSet()) {
4677     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4678       << D.getCXXScopeSpec().getRange();
4679     D.setInvalidType();
4680     // Pretend we didn't see the scope specifier.
4681     DC = CurContext;
4682     Previous.clear();
4683   }
4684 
4685   DiagnoseFunctionSpecifiers(D.getDeclSpec());
4686 
4687   if (D.getDeclSpec().isConstexprSpecified())
4688     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4689       << 1;
4690 
4691   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4692     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4693       << D.getName().getSourceRange();
4694     return nullptr;
4695   }
4696 
4697   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4698   if (!NewTD) return nullptr;
4699 
4700   // Handle attributes prior to checking for duplicates in MergeVarDecl
4701   ProcessDeclAttributes(S, NewTD, D);
4702 
4703   CheckTypedefForVariablyModifiedType(S, NewTD);
4704 
4705   bool Redeclaration = D.isRedeclaration();
4706   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4707   D.setRedeclaration(Redeclaration);
4708   return ND;
4709 }
4710 
4711 void
4712 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4713   // C99 6.7.7p2: If a typedef name specifies a variably modified type
4714   // then it shall have block scope.
4715   // Note that variably modified types must be fixed before merging the decl so
4716   // that redeclarations will match.
4717   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4718   QualType T = TInfo->getType();
4719   if (T->isVariablyModifiedType()) {
4720     getCurFunction()->setHasBranchProtectedScope();
4721 
4722     if (S->getFnParent() == nullptr) {
4723       bool SizeIsNegative;
4724       llvm::APSInt Oversized;
4725       TypeSourceInfo *FixedTInfo =
4726         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4727                                                       SizeIsNegative,
4728                                                       Oversized);
4729       if (FixedTInfo) {
4730         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4731         NewTD->setTypeSourceInfo(FixedTInfo);
4732       } else {
4733         if (SizeIsNegative)
4734           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4735         else if (T->isVariableArrayType())
4736           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4737         else if (Oversized.getBoolValue())
4738           Diag(NewTD->getLocation(), diag::err_array_too_large)
4739             << Oversized.toString(10);
4740         else
4741           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4742         NewTD->setInvalidDecl();
4743       }
4744     }
4745   }
4746 }
4747 
4748 
4749 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4750 /// declares a typedef-name, either using the 'typedef' type specifier or via
4751 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4752 NamedDecl*
4753 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4754                            LookupResult &Previous, bool &Redeclaration) {
4755   // Merge the decl with the existing one if appropriate. If the decl is
4756   // in an outer scope, it isn't the same thing.
4757   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4758                        /*AllowInlineNamespace*/false);
4759   filterNonConflictingPreviousDecls(Context, NewTD, Previous);
4760   if (!Previous.empty()) {
4761     Redeclaration = true;
4762     MergeTypedefNameDecl(NewTD, Previous);
4763   }
4764 
4765   // If this is the C FILE type, notify the AST context.
4766   if (IdentifierInfo *II = NewTD->getIdentifier())
4767     if (!NewTD->isInvalidDecl() &&
4768         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4769       if (II->isStr("FILE"))
4770         Context.setFILEDecl(NewTD);
4771       else if (II->isStr("jmp_buf"))
4772         Context.setjmp_bufDecl(NewTD);
4773       else if (II->isStr("sigjmp_buf"))
4774         Context.setsigjmp_bufDecl(NewTD);
4775       else if (II->isStr("ucontext_t"))
4776         Context.setucontext_tDecl(NewTD);
4777     }
4778 
4779   return NewTD;
4780 }
4781 
4782 /// \brief Determines whether the given declaration is an out-of-scope
4783 /// previous declaration.
4784 ///
4785 /// This routine should be invoked when name lookup has found a
4786 /// previous declaration (PrevDecl) that is not in the scope where a
4787 /// new declaration by the same name is being introduced. If the new
4788 /// declaration occurs in a local scope, previous declarations with
4789 /// linkage may still be considered previous declarations (C99
4790 /// 6.2.2p4-5, C++ [basic.link]p6).
4791 ///
4792 /// \param PrevDecl the previous declaration found by name
4793 /// lookup
4794 ///
4795 /// \param DC the context in which the new declaration is being
4796 /// declared.
4797 ///
4798 /// \returns true if PrevDecl is an out-of-scope previous declaration
4799 /// for a new delcaration with the same name.
4800 static bool
4801 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4802                                 ASTContext &Context) {
4803   if (!PrevDecl)
4804     return false;
4805 
4806   if (!PrevDecl->hasLinkage())
4807     return false;
4808 
4809   if (Context.getLangOpts().CPlusPlus) {
4810     // C++ [basic.link]p6:
4811     //   If there is a visible declaration of an entity with linkage
4812     //   having the same name and type, ignoring entities declared
4813     //   outside the innermost enclosing namespace scope, the block
4814     //   scope declaration declares that same entity and receives the
4815     //   linkage of the previous declaration.
4816     DeclContext *OuterContext = DC->getRedeclContext();
4817     if (!OuterContext->isFunctionOrMethod())
4818       // This rule only applies to block-scope declarations.
4819       return false;
4820 
4821     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4822     if (PrevOuterContext->isRecord())
4823       // We found a member function: ignore it.
4824       return false;
4825 
4826     // Find the innermost enclosing namespace for the new and
4827     // previous declarations.
4828     OuterContext = OuterContext->getEnclosingNamespaceContext();
4829     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
4830 
4831     // The previous declaration is in a different namespace, so it
4832     // isn't the same function.
4833     if (!OuterContext->Equals(PrevOuterContext))
4834       return false;
4835   }
4836 
4837   return true;
4838 }
4839 
4840 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4841   CXXScopeSpec &SS = D.getCXXScopeSpec();
4842   if (!SS.isSet()) return;
4843   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
4844 }
4845 
4846 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4847   QualType type = decl->getType();
4848   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4849   if (lifetime == Qualifiers::OCL_Autoreleasing) {
4850     // Various kinds of declaration aren't allowed to be __autoreleasing.
4851     unsigned kind = -1U;
4852     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4853       if (var->hasAttr<BlocksAttr>())
4854         kind = 0; // __block
4855       else if (!var->hasLocalStorage())
4856         kind = 1; // global
4857     } else if (isa<ObjCIvarDecl>(decl)) {
4858       kind = 3; // ivar
4859     } else if (isa<FieldDecl>(decl)) {
4860       kind = 2; // field
4861     }
4862 
4863     if (kind != -1U) {
4864       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4865         << kind;
4866     }
4867   } else if (lifetime == Qualifiers::OCL_None) {
4868     // Try to infer lifetime.
4869     if (!type->isObjCLifetimeType())
4870       return false;
4871 
4872     lifetime = type->getObjCARCImplicitLifetime();
4873     type = Context.getLifetimeQualifiedType(type, lifetime);
4874     decl->setType(type);
4875   }
4876 
4877   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4878     // Thread-local variables cannot have lifetime.
4879     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
4880         var->getTLSKind()) {
4881       Diag(var->getLocation(), diag::err_arc_thread_ownership)
4882         << var->getType();
4883       return true;
4884     }
4885   }
4886 
4887   return false;
4888 }
4889 
4890 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4891   // Ensure that an auto decl is deduced otherwise the checks below might cache
4892   // the wrong linkage.
4893   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
4894 
4895   // 'weak' only applies to declarations with external linkage.
4896   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
4897     if (!ND.isExternallyVisible()) {
4898       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4899       ND.dropAttr<WeakAttr>();
4900     }
4901   }
4902   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
4903     if (ND.isExternallyVisible()) {
4904       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4905       ND.dropAttr<WeakRefAttr>();
4906     }
4907   }
4908 
4909   // 'selectany' only applies to externally visible varable declarations.
4910   // It does not apply to functions.
4911   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4912     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4913       S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4914       ND.dropAttr<SelectAnyAttr>();
4915     }
4916   }
4917 
4918   // dll attributes require external linkage.
4919   if (const DLLImportAttr *Attr = ND.getAttr<DLLImportAttr>()) {
4920     if (!ND.isExternallyVisible()) {
4921       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
4922         << &ND << Attr;
4923       ND.setInvalidDecl();
4924     }
4925   }
4926   if (const DLLExportAttr *Attr = ND.getAttr<DLLExportAttr>()) {
4927     if (!ND.isExternallyVisible()) {
4928       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
4929         << &ND << Attr;
4930       ND.setInvalidDecl();
4931     }
4932   }
4933 }
4934 
4935 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
4936                                            NamedDecl *NewDecl,
4937                                            bool IsSpecialization) {
4938   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
4939     OldDecl = OldTD->getTemplatedDecl();
4940   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
4941     NewDecl = NewTD->getTemplatedDecl();
4942 
4943   if (!OldDecl || !NewDecl)
4944       return;
4945 
4946   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
4947   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
4948   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
4949   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
4950 
4951   // dllimport and dllexport are inheritable attributes so we have to exclude
4952   // inherited attribute instances.
4953   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
4954                     (NewExportAttr && !NewExportAttr->isInherited());
4955 
4956   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
4957   // the only exception being explicit specializations.
4958   // Implicitly generated declarations are also excluded for now because there
4959   // is no other way to switch these to use dllimport or dllexport.
4960   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
4961   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
4962     S.Diag(NewDecl->getLocation(), diag::err_attribute_dll_redeclaration)
4963       << NewDecl
4964       << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
4965     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
4966     NewDecl->setInvalidDecl();
4967     return;
4968   }
4969 
4970   // A redeclaration is not allowed to drop a dllimport attribute, the only
4971   // exception being inline function definitions.
4972   // NB: MSVC converts such a declaration to dllexport.
4973   bool IsInline = false, IsStaticDataMember = false;
4974   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
4975     // Ignore static data because out-of-line definitions are diagnosed
4976     // separately.
4977     IsStaticDataMember = VD->isStaticDataMember();
4978   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl))
4979     IsInline = FD->isInlined();
4980 
4981   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember) {
4982     S.Diag(NewDecl->getLocation(),
4983            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4984       << NewDecl << OldImportAttr;
4985     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
4986     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
4987     OldDecl->dropAttr<DLLImportAttr>();
4988     NewDecl->dropAttr<DLLImportAttr>();
4989   }
4990 }
4991 
4992 /// Given that we are within the definition of the given function,
4993 /// will that definition behave like C99's 'inline', where the
4994 /// definition is discarded except for optimization purposes?
4995 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4996   // Try to avoid calling GetGVALinkageForFunction.
4997 
4998   // All cases of this require the 'inline' keyword.
4999   if (!FD->isInlined()) return false;
5000 
5001   // This is only possible in C++ with the gnu_inline attribute.
5002   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5003     return false;
5004 
5005   // Okay, go ahead and call the relatively-more-expensive function.
5006 
5007 #ifndef NDEBUG
5008   // AST quite reasonably asserts that it's working on a function
5009   // definition.  We don't really have a way to tell it that we're
5010   // currently defining the function, so just lie to it in +Asserts
5011   // builds.  This is an awful hack.
5012   FD->setLazyBody(1);
5013 #endif
5014 
5015   bool isC99Inline =
5016       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5017 
5018 #ifndef NDEBUG
5019   FD->setLazyBody(0);
5020 #endif
5021 
5022   return isC99Inline;
5023 }
5024 
5025 /// Determine whether a variable is extern "C" prior to attaching
5026 /// an initializer. We can't just call isExternC() here, because that
5027 /// will also compute and cache whether the declaration is externally
5028 /// visible, which might change when we attach the initializer.
5029 ///
5030 /// This can only be used if the declaration is known to not be a
5031 /// redeclaration of an internal linkage declaration.
5032 ///
5033 /// For instance:
5034 ///
5035 ///   auto x = []{};
5036 ///
5037 /// Attaching the initializer here makes this declaration not externally
5038 /// visible, because its type has internal linkage.
5039 ///
5040 /// FIXME: This is a hack.
5041 template<typename T>
5042 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5043   if (S.getLangOpts().CPlusPlus) {
5044     // In C++, the overloadable attribute negates the effects of extern "C".
5045     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5046       return false;
5047   }
5048   return D->isExternC();
5049 }
5050 
5051 static bool shouldConsiderLinkage(const VarDecl *VD) {
5052   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5053   if (DC->isFunctionOrMethod())
5054     return VD->hasExternalStorage();
5055   if (DC->isFileContext())
5056     return true;
5057   if (DC->isRecord())
5058     return false;
5059   llvm_unreachable("Unexpected context");
5060 }
5061 
5062 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5063   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5064   if (DC->isFileContext() || DC->isFunctionOrMethod())
5065     return true;
5066   if (DC->isRecord())
5067     return false;
5068   llvm_unreachable("Unexpected context");
5069 }
5070 
5071 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5072                           AttributeList::Kind Kind) {
5073   for (const AttributeList *L = AttrList; L; L = L->getNext())
5074     if (L->getKind() == Kind)
5075       return true;
5076   return false;
5077 }
5078 
5079 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5080                           AttributeList::Kind Kind) {
5081   // Check decl attributes on the DeclSpec.
5082   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5083     return true;
5084 
5085   // Walk the declarator structure, checking decl attributes that were in a type
5086   // position to the decl itself.
5087   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5088     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5089       return true;
5090   }
5091 
5092   // Finally, check attributes on the decl itself.
5093   return hasParsedAttr(S, PD.getAttributes(), Kind);
5094 }
5095 
5096 /// Adjust the \c DeclContext for a function or variable that might be a
5097 /// function-local external declaration.
5098 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5099   if (!DC->isFunctionOrMethod())
5100     return false;
5101 
5102   // If this is a local extern function or variable declared within a function
5103   // template, don't add it into the enclosing namespace scope until it is
5104   // instantiated; it might have a dependent type right now.
5105   if (DC->isDependentContext())
5106     return true;
5107 
5108   // C++11 [basic.link]p7:
5109   //   When a block scope declaration of an entity with linkage is not found to
5110   //   refer to some other declaration, then that entity is a member of the
5111   //   innermost enclosing namespace.
5112   //
5113   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5114   // semantically-enclosing namespace, not a lexically-enclosing one.
5115   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5116     DC = DC->getParent();
5117   return true;
5118 }
5119 
5120 NamedDecl *
5121 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5122                               TypeSourceInfo *TInfo, LookupResult &Previous,
5123                               MultiTemplateParamsArg TemplateParamLists,
5124                               bool &AddToScope) {
5125   QualType R = TInfo->getType();
5126   DeclarationName Name = GetNameForDeclarator(D).getName();
5127 
5128   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5129   VarDecl::StorageClass SC =
5130     StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5131 
5132   // dllimport globals without explicit storage class are treated as extern. We
5133   // have to change the storage class this early to get the right DeclContext.
5134   if (SC == SC_None && !DC->isRecord() &&
5135       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5136       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5137     SC = SC_Extern;
5138 
5139   DeclContext *OriginalDC = DC;
5140   bool IsLocalExternDecl = SC == SC_Extern &&
5141                            adjustContextForLocalExternDecl(DC);
5142 
5143   if (getLangOpts().OpenCL) {
5144     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5145     QualType NR = R;
5146     while (NR->isPointerType()) {
5147       if (NR->isFunctionPointerType()) {
5148         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5149         D.setInvalidType();
5150         break;
5151       }
5152       NR = NR->getPointeeType();
5153     }
5154 
5155     if (!getOpenCLOptions().cl_khr_fp16) {
5156       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5157       // half array type (unless the cl_khr_fp16 extension is enabled).
5158       if (Context.getBaseElementType(R)->isHalfType()) {
5159         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5160         D.setInvalidType();
5161       }
5162     }
5163   }
5164 
5165   if (SCSpec == DeclSpec::SCS_mutable) {
5166     // mutable can only appear on non-static class members, so it's always
5167     // an error here
5168     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5169     D.setInvalidType();
5170     SC = SC_None;
5171   }
5172 
5173   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5174       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5175                               D.getDeclSpec().getStorageClassSpecLoc())) {
5176     // In C++11, the 'register' storage class specifier is deprecated.
5177     // Suppress the warning in system macros, it's used in macros in some
5178     // popular C system headers, such as in glibc's htonl() macro.
5179     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5180          diag::warn_deprecated_register)
5181       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5182   }
5183 
5184   IdentifierInfo *II = Name.getAsIdentifierInfo();
5185   if (!II) {
5186     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5187       << Name;
5188     return nullptr;
5189   }
5190 
5191   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5192 
5193   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5194     // C99 6.9p2: The storage-class specifiers auto and register shall not
5195     // appear in the declaration specifiers in an external declaration.
5196     // Global Register+Asm is a GNU extension we support.
5197     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5198       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5199       D.setInvalidType();
5200     }
5201   }
5202 
5203   if (getLangOpts().OpenCL) {
5204     // Set up the special work-group-local storage class for variables in the
5205     // OpenCL __local address space.
5206     if (R.getAddressSpace() == LangAS::opencl_local) {
5207       SC = SC_OpenCLWorkGroupLocal;
5208     }
5209 
5210     // OpenCL v1.2 s6.9.b p4:
5211     // The sampler type cannot be used with the __local and __global address
5212     // space qualifiers.
5213     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5214       R.getAddressSpace() == LangAS::opencl_global)) {
5215       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5216     }
5217 
5218     // OpenCL 1.2 spec, p6.9 r:
5219     // The event type cannot be used to declare a program scope variable.
5220     // The event type cannot be used with the __local, __constant and __global
5221     // address space qualifiers.
5222     if (R->isEventT()) {
5223       if (S->getParent() == nullptr) {
5224         Diag(D.getLocStart(), diag::err_event_t_global_var);
5225         D.setInvalidType();
5226       }
5227 
5228       if (R.getAddressSpace()) {
5229         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5230         D.setInvalidType();
5231       }
5232     }
5233   }
5234 
5235   bool IsExplicitSpecialization = false;
5236   bool IsVariableTemplateSpecialization = false;
5237   bool IsPartialSpecialization = false;
5238   bool IsVariableTemplate = false;
5239   VarDecl *NewVD = nullptr;
5240   VarTemplateDecl *NewTemplate = nullptr;
5241   TemplateParameterList *TemplateParams = nullptr;
5242   if (!getLangOpts().CPlusPlus) {
5243     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5244                             D.getIdentifierLoc(), II,
5245                             R, TInfo, SC);
5246 
5247     if (D.isInvalidType())
5248       NewVD->setInvalidDecl();
5249   } else {
5250     bool Invalid = false;
5251 
5252     if (DC->isRecord() && !CurContext->isRecord()) {
5253       // This is an out-of-line definition of a static data member.
5254       switch (SC) {
5255       case SC_None:
5256         break;
5257       case SC_Static:
5258         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5259              diag::err_static_out_of_line)
5260           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5261         break;
5262       case SC_Auto:
5263       case SC_Register:
5264       case SC_Extern:
5265         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5266         // to names of variables declared in a block or to function parameters.
5267         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5268         // of class members
5269 
5270         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5271              diag::err_storage_class_for_static_member)
5272           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5273         break;
5274       case SC_PrivateExtern:
5275         llvm_unreachable("C storage class in c++!");
5276       case SC_OpenCLWorkGroupLocal:
5277         llvm_unreachable("OpenCL storage class in c++!");
5278       }
5279     }
5280 
5281     if (SC == SC_Static && CurContext->isRecord()) {
5282       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5283         if (RD->isLocalClass())
5284           Diag(D.getIdentifierLoc(),
5285                diag::err_static_data_member_not_allowed_in_local_class)
5286             << Name << RD->getDeclName();
5287 
5288         // C++98 [class.union]p1: If a union contains a static data member,
5289         // the program is ill-formed. C++11 drops this restriction.
5290         if (RD->isUnion())
5291           Diag(D.getIdentifierLoc(),
5292                getLangOpts().CPlusPlus11
5293                  ? diag::warn_cxx98_compat_static_data_member_in_union
5294                  : diag::ext_static_data_member_in_union) << Name;
5295         // We conservatively disallow static data members in anonymous structs.
5296         else if (!RD->getDeclName())
5297           Diag(D.getIdentifierLoc(),
5298                diag::err_static_data_member_not_allowed_in_anon_struct)
5299             << Name << RD->isUnion();
5300       }
5301     }
5302 
5303     // Match up the template parameter lists with the scope specifier, then
5304     // determine whether we have a template or a template specialization.
5305     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5306         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5307         D.getCXXScopeSpec(),
5308         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5309             ? D.getName().TemplateId
5310             : nullptr,
5311         TemplateParamLists,
5312         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5313 
5314     if (TemplateParams) {
5315       if (!TemplateParams->size() &&
5316           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5317         // There is an extraneous 'template<>' for this variable. Complain
5318         // about it, but allow the declaration of the variable.
5319         Diag(TemplateParams->getTemplateLoc(),
5320              diag::err_template_variable_noparams)
5321           << II
5322           << SourceRange(TemplateParams->getTemplateLoc(),
5323                          TemplateParams->getRAngleLoc());
5324         TemplateParams = nullptr;
5325       } else {
5326         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5327           // This is an explicit specialization or a partial specialization.
5328           // FIXME: Check that we can declare a specialization here.
5329           IsVariableTemplateSpecialization = true;
5330           IsPartialSpecialization = TemplateParams->size() > 0;
5331         } else { // if (TemplateParams->size() > 0)
5332           // This is a template declaration.
5333           IsVariableTemplate = true;
5334 
5335           // Check that we can declare a template here.
5336           if (CheckTemplateDeclScope(S, TemplateParams))
5337             return nullptr;
5338 
5339           // Only C++1y supports variable templates (N3651).
5340           Diag(D.getIdentifierLoc(),
5341                getLangOpts().CPlusPlus1y
5342                    ? diag::warn_cxx11_compat_variable_template
5343                    : diag::ext_variable_template);
5344         }
5345       }
5346     } else {
5347       assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId &&
5348              "should have a 'template<>' for this decl");
5349     }
5350 
5351     if (IsVariableTemplateSpecialization) {
5352       SourceLocation TemplateKWLoc =
5353           TemplateParamLists.size() > 0
5354               ? TemplateParamLists[0]->getTemplateLoc()
5355               : SourceLocation();
5356       DeclResult Res = ActOnVarTemplateSpecialization(
5357           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5358           IsPartialSpecialization);
5359       if (Res.isInvalid())
5360         return nullptr;
5361       NewVD = cast<VarDecl>(Res.get());
5362       AddToScope = false;
5363     } else
5364       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5365                               D.getIdentifierLoc(), II, R, TInfo, SC);
5366 
5367     // If this is supposed to be a variable template, create it as such.
5368     if (IsVariableTemplate) {
5369       NewTemplate =
5370           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5371                                   TemplateParams, NewVD);
5372       NewVD->setDescribedVarTemplate(NewTemplate);
5373     }
5374 
5375     // If this decl has an auto type in need of deduction, make a note of the
5376     // Decl so we can diagnose uses of it in its own initializer.
5377     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5378       ParsingInitForAutoVars.insert(NewVD);
5379 
5380     if (D.isInvalidType() || Invalid) {
5381       NewVD->setInvalidDecl();
5382       if (NewTemplate)
5383         NewTemplate->setInvalidDecl();
5384     }
5385 
5386     SetNestedNameSpecifier(NewVD, D);
5387 
5388     // If we have any template parameter lists that don't directly belong to
5389     // the variable (matching the scope specifier), store them.
5390     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5391     if (TemplateParamLists.size() > VDTemplateParamLists)
5392       NewVD->setTemplateParameterListsInfo(
5393           Context, TemplateParamLists.size() - VDTemplateParamLists,
5394           TemplateParamLists.data());
5395 
5396     if (D.getDeclSpec().isConstexprSpecified())
5397       NewVD->setConstexpr(true);
5398   }
5399 
5400   // Set the lexical context. If the declarator has a C++ scope specifier, the
5401   // lexical context will be different from the semantic context.
5402   NewVD->setLexicalDeclContext(CurContext);
5403   if (NewTemplate)
5404     NewTemplate->setLexicalDeclContext(CurContext);
5405 
5406   if (IsLocalExternDecl)
5407     NewVD->setLocalExternDecl();
5408 
5409   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5410     if (NewVD->hasLocalStorage()) {
5411       // C++11 [dcl.stc]p4:
5412       //   When thread_local is applied to a variable of block scope the
5413       //   storage-class-specifier static is implied if it does not appear
5414       //   explicitly.
5415       // Core issue: 'static' is not implied if the variable is declared
5416       //   'extern'.
5417       if (SCSpec == DeclSpec::SCS_unspecified &&
5418           TSCS == DeclSpec::TSCS_thread_local &&
5419           DC->isFunctionOrMethod())
5420         NewVD->setTSCSpec(TSCS);
5421       else
5422         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5423              diag::err_thread_non_global)
5424           << DeclSpec::getSpecifierName(TSCS);
5425     } else if (!Context.getTargetInfo().isTLSSupported())
5426       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5427            diag::err_thread_unsupported);
5428     else
5429       NewVD->setTSCSpec(TSCS);
5430   }
5431 
5432   // C99 6.7.4p3
5433   //   An inline definition of a function with external linkage shall
5434   //   not contain a definition of a modifiable object with static or
5435   //   thread storage duration...
5436   // We only apply this when the function is required to be defined
5437   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5438   // that a local variable with thread storage duration still has to
5439   // be marked 'static'.  Also note that it's possible to get these
5440   // semantics in C++ using __attribute__((gnu_inline)).
5441   if (SC == SC_Static && S->getFnParent() != nullptr &&
5442       !NewVD->getType().isConstQualified()) {
5443     FunctionDecl *CurFD = getCurFunctionDecl();
5444     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5445       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5446            diag::warn_static_local_in_extern_inline);
5447       MaybeSuggestAddingStaticToDecl(CurFD);
5448     }
5449   }
5450 
5451   if (D.getDeclSpec().isModulePrivateSpecified()) {
5452     if (IsVariableTemplateSpecialization)
5453       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5454           << (IsPartialSpecialization ? 1 : 0)
5455           << FixItHint::CreateRemoval(
5456                  D.getDeclSpec().getModulePrivateSpecLoc());
5457     else if (IsExplicitSpecialization)
5458       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5459         << 2
5460         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5461     else if (NewVD->hasLocalStorage())
5462       Diag(NewVD->getLocation(), diag::err_module_private_local)
5463         << 0 << NewVD->getDeclName()
5464         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5465         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5466     else {
5467       NewVD->setModulePrivate();
5468       if (NewTemplate)
5469         NewTemplate->setModulePrivate();
5470     }
5471   }
5472 
5473   // Handle attributes prior to checking for duplicates in MergeVarDecl
5474   ProcessDeclAttributes(S, NewVD, D);
5475 
5476   if (getLangOpts().CUDA) {
5477     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5478     // storage [duration]."
5479     if (SC == SC_None && S->getFnParent() != nullptr &&
5480         (NewVD->hasAttr<CUDASharedAttr>() ||
5481          NewVD->hasAttr<CUDAConstantAttr>())) {
5482       NewVD->setStorageClass(SC_Static);
5483     }
5484   }
5485 
5486   // Ensure that dllimport globals without explicit storage class are treated as
5487   // extern. The storage class is set above using parsed attributes. Now we can
5488   // check the VarDecl itself.
5489   assert(!NewVD->hasAttr<DLLImportAttr>() ||
5490          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5491          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5492 
5493   // In auto-retain/release, infer strong retension for variables of
5494   // retainable type.
5495   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5496     NewVD->setInvalidDecl();
5497 
5498   // Handle GNU asm-label extension (encoded as an attribute).
5499   if (Expr *E = (Expr*)D.getAsmLabel()) {
5500     // The parser guarantees this is a string.
5501     StringLiteral *SE = cast<StringLiteral>(E);
5502     StringRef Label = SE->getString();
5503     if (S->getFnParent() != nullptr) {
5504       switch (SC) {
5505       case SC_None:
5506       case SC_Auto:
5507         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5508         break;
5509       case SC_Register:
5510         // Local Named register
5511         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5512           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5513         break;
5514       case SC_Static:
5515       case SC_Extern:
5516       case SC_PrivateExtern:
5517       case SC_OpenCLWorkGroupLocal:
5518         break;
5519       }
5520     } else if (SC == SC_Register) {
5521       // Global Named register
5522       if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5523         Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5524       if (!R->isIntegralType(Context) && !R->isPointerType()) {
5525         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
5526         NewVD->setInvalidDecl(true);
5527       }
5528     }
5529 
5530     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
5531                                                 Context, Label, 0));
5532   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5533     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5534       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5535     if (I != ExtnameUndeclaredIdentifiers.end()) {
5536       NewVD->addAttr(I->second);
5537       ExtnameUndeclaredIdentifiers.erase(I);
5538     }
5539   }
5540 
5541   // Diagnose shadowed variables before filtering for scope.
5542   if (D.getCXXScopeSpec().isEmpty())
5543     CheckShadow(S, NewVD, Previous);
5544 
5545   // Don't consider existing declarations that are in a different
5546   // scope and are out-of-semantic-context declarations (if the new
5547   // declaration has linkage).
5548   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5549                        D.getCXXScopeSpec().isNotEmpty() ||
5550                        IsExplicitSpecialization ||
5551                        IsVariableTemplateSpecialization);
5552 
5553   // Check whether the previous declaration is in the same block scope. This
5554   // affects whether we merge types with it, per C++11 [dcl.array]p3.
5555   if (getLangOpts().CPlusPlus &&
5556       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5557     NewVD->setPreviousDeclInSameBlockScope(
5558         Previous.isSingleResult() && !Previous.isShadowed() &&
5559         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
5560 
5561   if (!getLangOpts().CPlusPlus) {
5562     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5563   } else {
5564     // If this is an explicit specialization of a static data member, check it.
5565     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5566         CheckMemberSpecialization(NewVD, Previous))
5567       NewVD->setInvalidDecl();
5568 
5569     // Merge the decl with the existing one if appropriate.
5570     if (!Previous.empty()) {
5571       if (Previous.isSingleResult() &&
5572           isa<FieldDecl>(Previous.getFoundDecl()) &&
5573           D.getCXXScopeSpec().isSet()) {
5574         // The user tried to define a non-static data member
5575         // out-of-line (C++ [dcl.meaning]p1).
5576         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5577           << D.getCXXScopeSpec().getRange();
5578         Previous.clear();
5579         NewVD->setInvalidDecl();
5580       }
5581     } else if (D.getCXXScopeSpec().isSet()) {
5582       // No previous declaration in the qualifying scope.
5583       Diag(D.getIdentifierLoc(), diag::err_no_member)
5584         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
5585         << D.getCXXScopeSpec().getRange();
5586       NewVD->setInvalidDecl();
5587     }
5588 
5589     if (!IsVariableTemplateSpecialization)
5590       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5591 
5592     if (NewTemplate) {
5593       VarTemplateDecl *PrevVarTemplate =
5594           NewVD->getPreviousDecl()
5595               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5596               : nullptr;
5597 
5598       // Check the template parameter list of this declaration, possibly
5599       // merging in the template parameter list from the previous variable
5600       // template declaration.
5601       if (CheckTemplateParameterList(
5602               TemplateParams,
5603               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5604                               : nullptr,
5605               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5606                DC->isDependentContext())
5607                   ? TPC_ClassTemplateMember
5608                   : TPC_VarTemplate))
5609         NewVD->setInvalidDecl();
5610 
5611       // If we are providing an explicit specialization of a static variable
5612       // template, make a note of that.
5613       if (PrevVarTemplate &&
5614           PrevVarTemplate->getInstantiatedFromMemberTemplate())
5615         PrevVarTemplate->setMemberSpecialization();
5616     }
5617   }
5618 
5619   ProcessPragmaWeak(S, NewVD);
5620 
5621   // If this is the first declaration of an extern C variable, update
5622   // the map of such variables.
5623   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
5624       isIncompleteDeclExternC(*this, NewVD))
5625     RegisterLocallyScopedExternCDecl(NewVD, S);
5626 
5627   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5628     Decl *ManglingContextDecl;
5629     if (MangleNumberingContext *MCtx =
5630             getCurrentMangleNumberContext(NewVD->getDeclContext(),
5631                                           ManglingContextDecl)) {
5632       Context.setManglingNumber(
5633           NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
5634       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5635     }
5636   }
5637 
5638   if (D.isRedeclaration() && !Previous.empty()) {
5639     checkDLLAttributeRedeclaration(
5640         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
5641         IsExplicitSpecialization);
5642   }
5643 
5644   if (NewTemplate) {
5645     if (NewVD->isInvalidDecl())
5646       NewTemplate->setInvalidDecl();
5647     ActOnDocumentableDecl(NewTemplate);
5648     return NewTemplate;
5649   }
5650 
5651   return NewVD;
5652 }
5653 
5654 /// \brief Diagnose variable or built-in function shadowing.  Implements
5655 /// -Wshadow.
5656 ///
5657 /// This method is called whenever a VarDecl is added to a "useful"
5658 /// scope.
5659 ///
5660 /// \param S the scope in which the shadowing name is being declared
5661 /// \param R the lookup of the name
5662 ///
5663 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
5664   // Return if warning is ignored.
5665   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
5666     return;
5667 
5668   // Don't diagnose declarations at file scope.
5669   if (D->hasGlobalStorage())
5670     return;
5671 
5672   DeclContext *NewDC = D->getDeclContext();
5673 
5674   // Only diagnose if we're shadowing an unambiguous field or variable.
5675   if (R.getResultKind() != LookupResult::Found)
5676     return;
5677 
5678   NamedDecl* ShadowedDecl = R.getFoundDecl();
5679   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5680     return;
5681 
5682   // Fields are not shadowed by variables in C++ static methods.
5683   if (isa<FieldDecl>(ShadowedDecl))
5684     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5685       if (MD->isStatic())
5686         return;
5687 
5688   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5689     if (shadowedVar->isExternC()) {
5690       // For shadowing external vars, make sure that we point to the global
5691       // declaration, not a locally scoped extern declaration.
5692       for (auto I : shadowedVar->redecls())
5693         if (I->isFileVarDecl()) {
5694           ShadowedDecl = I;
5695           break;
5696         }
5697     }
5698 
5699   DeclContext *OldDC = ShadowedDecl->getDeclContext();
5700 
5701   // Only warn about certain kinds of shadowing for class members.
5702   if (NewDC && NewDC->isRecord()) {
5703     // In particular, don't warn about shadowing non-class members.
5704     if (!OldDC->isRecord())
5705       return;
5706 
5707     // TODO: should we warn about static data members shadowing
5708     // static data members from base classes?
5709 
5710     // TODO: don't diagnose for inaccessible shadowed members.
5711     // This is hard to do perfectly because we might friend the
5712     // shadowing context, but that's just a false negative.
5713   }
5714 
5715   // Determine what kind of declaration we're shadowing.
5716   unsigned Kind;
5717   if (isa<RecordDecl>(OldDC)) {
5718     if (isa<FieldDecl>(ShadowedDecl))
5719       Kind = 3; // field
5720     else
5721       Kind = 2; // static data member
5722   } else if (OldDC->isFileContext())
5723     Kind = 1; // global
5724   else
5725     Kind = 0; // local
5726 
5727   DeclarationName Name = R.getLookupName();
5728 
5729   // Emit warning and note.
5730   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5731     return;
5732   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
5733   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5734 }
5735 
5736 /// \brief Check -Wshadow without the advantage of a previous lookup.
5737 void Sema::CheckShadow(Scope *S, VarDecl *D) {
5738   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
5739     return;
5740 
5741   LookupResult R(*this, D->getDeclName(), D->getLocation(),
5742                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5743   LookupName(R, S);
5744   CheckShadow(S, D, R);
5745 }
5746 
5747 /// Check for conflict between this global or extern "C" declaration and
5748 /// previous global or extern "C" declarations. This is only used in C++.
5749 template<typename T>
5750 static bool checkGlobalOrExternCConflict(
5751     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5752   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5753   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
5754 
5755   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5756     // The common case: this global doesn't conflict with any extern "C"
5757     // declaration.
5758     return false;
5759   }
5760 
5761   if (Prev) {
5762     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5763       // Both the old and new declarations have C language linkage. This is a
5764       // redeclaration.
5765       Previous.clear();
5766       Previous.addDecl(Prev);
5767       return true;
5768     }
5769 
5770     // This is a global, non-extern "C" declaration, and there is a previous
5771     // non-global extern "C" declaration. Diagnose if this is a variable
5772     // declaration.
5773     if (!isa<VarDecl>(ND))
5774       return false;
5775   } else {
5776     // The declaration is extern "C". Check for any declaration in the
5777     // translation unit which might conflict.
5778     if (IsGlobal) {
5779       // We have already performed the lookup into the translation unit.
5780       IsGlobal = false;
5781       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5782            I != E; ++I) {
5783         if (isa<VarDecl>(*I)) {
5784           Prev = *I;
5785           break;
5786         }
5787       }
5788     } else {
5789       DeclContext::lookup_result R =
5790           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5791       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5792            I != E; ++I) {
5793         if (isa<VarDecl>(*I)) {
5794           Prev = *I;
5795           break;
5796         }
5797         // FIXME: If we have any other entity with this name in global scope,
5798         // the declaration is ill-formed, but that is a defect: it breaks the
5799         // 'stat' hack, for instance. Only variables can have mangled name
5800         // clashes with extern "C" declarations, so only they deserve a
5801         // diagnostic.
5802       }
5803     }
5804 
5805     if (!Prev)
5806       return false;
5807   }
5808 
5809   // Use the first declaration's location to ensure we point at something which
5810   // is lexically inside an extern "C" linkage-spec.
5811   assert(Prev && "should have found a previous declaration to diagnose");
5812   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
5813     Prev = FD->getFirstDecl();
5814   else
5815     Prev = cast<VarDecl>(Prev)->getFirstDecl();
5816 
5817   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5818     << IsGlobal << ND;
5819   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5820     << IsGlobal;
5821   return false;
5822 }
5823 
5824 /// Apply special rules for handling extern "C" declarations. Returns \c true
5825 /// if we have found that this is a redeclaration of some prior entity.
5826 ///
5827 /// Per C++ [dcl.link]p6:
5828 ///   Two declarations [for a function or variable] with C language linkage
5829 ///   with the same name that appear in different scopes refer to the same
5830 ///   [entity]. An entity with C language linkage shall not be declared with
5831 ///   the same name as an entity in global scope.
5832 template<typename T>
5833 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5834                                                   LookupResult &Previous) {
5835   if (!S.getLangOpts().CPlusPlus) {
5836     // In C, when declaring a global variable, look for a corresponding 'extern'
5837     // variable declared in function scope. We don't need this in C++, because
5838     // we find local extern decls in the surrounding file-scope DeclContext.
5839     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5840       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5841         Previous.clear();
5842         Previous.addDecl(Prev);
5843         return true;
5844       }
5845     }
5846     return false;
5847   }
5848 
5849   // A declaration in the translation unit can conflict with an extern "C"
5850   // declaration.
5851   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5852     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5853 
5854   // An extern "C" declaration can conflict with a declaration in the
5855   // translation unit or can be a redeclaration of an extern "C" declaration
5856   // in another scope.
5857   if (isIncompleteDeclExternC(S,ND))
5858     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5859 
5860   // Neither global nor extern "C": nothing to do.
5861   return false;
5862 }
5863 
5864 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
5865   // If the decl is already known invalid, don't check it.
5866   if (NewVD->isInvalidDecl())
5867     return;
5868 
5869   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5870   QualType T = TInfo->getType();
5871 
5872   // Defer checking an 'auto' type until its initializer is attached.
5873   if (T->isUndeducedType())
5874     return;
5875 
5876   if (NewVD->hasAttrs())
5877     CheckAlignasUnderalignment(NewVD);
5878 
5879   if (T->isObjCObjectType()) {
5880     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5881       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
5882     T = Context.getObjCObjectPointerType(T);
5883     NewVD->setType(T);
5884   }
5885 
5886   // Emit an error if an address space was applied to decl with local storage.
5887   // This includes arrays of objects with address space qualifiers, but not
5888   // automatic variables that point to other address spaces.
5889   // ISO/IEC TR 18037 S5.1.2
5890   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
5891     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
5892     NewVD->setInvalidDecl();
5893     return;
5894   }
5895 
5896   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5897   // __constant address space.
5898   if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5899       && T.getAddressSpace() != LangAS::opencl_constant
5900       && !T->isSamplerT()){
5901     Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5902     NewVD->setInvalidDecl();
5903     return;
5904   }
5905 
5906   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5907   // scope.
5908   if ((getLangOpts().OpenCLVersion >= 120)
5909       && NewVD->isStaticLocal()) {
5910     Diag(NewVD->getLocation(), diag::err_static_function_scope);
5911     NewVD->setInvalidDecl();
5912     return;
5913   }
5914 
5915   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
5916       && !NewVD->hasAttr<BlocksAttr>()) {
5917     if (getLangOpts().getGC() != LangOptions::NonGC)
5918       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
5919     else {
5920       assert(!getLangOpts().ObjCAutoRefCount);
5921       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
5922     }
5923   }
5924 
5925   bool isVM = T->isVariablyModifiedType();
5926   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
5927       NewVD->hasAttr<BlocksAttr>())
5928     getCurFunction()->setHasBranchProtectedScope();
5929 
5930   if ((isVM && NewVD->hasLinkage()) ||
5931       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
5932     bool SizeIsNegative;
5933     llvm::APSInt Oversized;
5934     TypeSourceInfo *FixedTInfo =
5935       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5936                                                     SizeIsNegative, Oversized);
5937     if (!FixedTInfo && T->isVariableArrayType()) {
5938       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
5939       // FIXME: This won't give the correct result for
5940       // int a[10][n];
5941       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
5942 
5943       if (NewVD->isFileVarDecl())
5944         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
5945         << SizeRange;
5946       else if (NewVD->isStaticLocal())
5947         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
5948         << SizeRange;
5949       else
5950         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
5951         << SizeRange;
5952       NewVD->setInvalidDecl();
5953       return;
5954     }
5955 
5956     if (!FixedTInfo) {
5957       if (NewVD->isFileVarDecl())
5958         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5959       else
5960         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
5961       NewVD->setInvalidDecl();
5962       return;
5963     }
5964 
5965     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
5966     NewVD->setType(FixedTInfo->getType());
5967     NewVD->setTypeSourceInfo(FixedTInfo);
5968   }
5969 
5970   if (T->isVoidType()) {
5971     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5972     //                    of objects and functions.
5973     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5974       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5975         << T;
5976       NewVD->setInvalidDecl();
5977       return;
5978     }
5979   }
5980 
5981   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5982     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5983     NewVD->setInvalidDecl();
5984     return;
5985   }
5986 
5987   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5988     Diag(NewVD->getLocation(), diag::err_block_on_vm);
5989     NewVD->setInvalidDecl();
5990     return;
5991   }
5992 
5993   if (NewVD->isConstexpr() && !T->isDependentType() &&
5994       RequireLiteralType(NewVD->getLocation(), T,
5995                          diag::err_constexpr_var_non_literal)) {
5996     NewVD->setInvalidDecl();
5997     return;
5998   }
5999 }
6000 
6001 /// \brief Perform semantic checking on a newly-created variable
6002 /// declaration.
6003 ///
6004 /// This routine performs all of the type-checking required for a
6005 /// variable declaration once it has been built. It is used both to
6006 /// check variables after they have been parsed and their declarators
6007 /// have been translated into a declaration, and to check variables
6008 /// that have been instantiated from a template.
6009 ///
6010 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6011 ///
6012 /// Returns true if the variable declaration is a redeclaration.
6013 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6014   CheckVariableDeclarationType(NewVD);
6015 
6016   // If the decl is already known invalid, don't check it.
6017   if (NewVD->isInvalidDecl())
6018     return false;
6019 
6020   // If we did not find anything by this name, look for a non-visible
6021   // extern "C" declaration with the same name.
6022   if (Previous.empty() &&
6023       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6024     Previous.setShadowed();
6025 
6026   // Filter out any non-conflicting previous declarations.
6027   filterNonConflictingPreviousDecls(Context, NewVD, Previous);
6028 
6029   if (!Previous.empty()) {
6030     MergeVarDecl(NewVD, Previous);
6031     return true;
6032   }
6033   return false;
6034 }
6035 
6036 /// \brief Data used with FindOverriddenMethod
6037 struct FindOverriddenMethodData {
6038   Sema *S;
6039   CXXMethodDecl *Method;
6040 };
6041 
6042 /// \brief Member lookup function that determines whether a given C++
6043 /// method overrides a method in a base class, to be used with
6044 /// CXXRecordDecl::lookupInBases().
6045 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
6046                                  CXXBasePath &Path,
6047                                  void *UserData) {
6048   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6049 
6050   FindOverriddenMethodData *Data
6051     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
6052 
6053   DeclarationName Name = Data->Method->getDeclName();
6054 
6055   // FIXME: Do we care about other names here too?
6056   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6057     // We really want to find the base class destructor here.
6058     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
6059     CanQualType CT = Data->S->Context.getCanonicalType(T);
6060 
6061     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
6062   }
6063 
6064   for (Path.Decls = BaseRecord->lookup(Name);
6065        !Path.Decls.empty();
6066        Path.Decls = Path.Decls.slice(1)) {
6067     NamedDecl *D = Path.Decls.front();
6068     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6069       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
6070         return true;
6071     }
6072   }
6073 
6074   return false;
6075 }
6076 
6077 namespace {
6078   enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6079 }
6080 /// \brief Report an error regarding overriding, along with any relevant
6081 /// overriden methods.
6082 ///
6083 /// \param DiagID the primary error to report.
6084 /// \param MD the overriding method.
6085 /// \param OEK which overrides to include as notes.
6086 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6087                             OverrideErrorKind OEK = OEK_All) {
6088   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6089   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6090                                       E = MD->end_overridden_methods();
6091        I != E; ++I) {
6092     // This check (& the OEK parameter) could be replaced by a predicate, but
6093     // without lambdas that would be overkill. This is still nicer than writing
6094     // out the diag loop 3 times.
6095     if ((OEK == OEK_All) ||
6096         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6097         (OEK == OEK_Deleted && (*I)->isDeleted()))
6098       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6099   }
6100 }
6101 
6102 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6103 /// and if so, check that it's a valid override and remember it.
6104 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6105   // Look for virtual methods in base classes that this method might override.
6106   CXXBasePaths Paths;
6107   FindOverriddenMethodData Data;
6108   Data.Method = MD;
6109   Data.S = this;
6110   bool hasDeletedOverridenMethods = false;
6111   bool hasNonDeletedOverridenMethods = false;
6112   bool AddedAny = false;
6113   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
6114     for (auto *I : Paths.found_decls()) {
6115       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6116         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6117         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6118             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6119             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6120             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6121           hasDeletedOverridenMethods |= OldMD->isDeleted();
6122           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6123           AddedAny = true;
6124         }
6125       }
6126     }
6127   }
6128 
6129   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6130     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6131   }
6132   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6133     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6134   }
6135 
6136   return AddedAny;
6137 }
6138 
6139 namespace {
6140   // Struct for holding all of the extra arguments needed by
6141   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6142   struct ActOnFDArgs {
6143     Scope *S;
6144     Declarator &D;
6145     MultiTemplateParamsArg TemplateParamLists;
6146     bool AddToScope;
6147   };
6148 }
6149 
6150 namespace {
6151 
6152 // Callback to only accept typo corrections that have a non-zero edit distance.
6153 // Also only accept corrections that have the same parent decl.
6154 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6155  public:
6156   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6157                             CXXRecordDecl *Parent)
6158       : Context(Context), OriginalFD(TypoFD),
6159         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6160 
6161   bool ValidateCandidate(const TypoCorrection &candidate) override {
6162     if (candidate.getEditDistance() == 0)
6163       return false;
6164 
6165     SmallVector<unsigned, 1> MismatchedParams;
6166     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6167                                           CDeclEnd = candidate.end();
6168          CDecl != CDeclEnd; ++CDecl) {
6169       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6170 
6171       if (FD && !FD->hasBody() &&
6172           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6173         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6174           CXXRecordDecl *Parent = MD->getParent();
6175           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6176             return true;
6177         } else if (!ExpectedParent) {
6178           return true;
6179         }
6180       }
6181     }
6182 
6183     return false;
6184   }
6185 
6186  private:
6187   ASTContext &Context;
6188   FunctionDecl *OriginalFD;
6189   CXXRecordDecl *ExpectedParent;
6190 };
6191 
6192 }
6193 
6194 /// \brief Generate diagnostics for an invalid function redeclaration.
6195 ///
6196 /// This routine handles generating the diagnostic messages for an invalid
6197 /// function redeclaration, including finding possible similar declarations
6198 /// or performing typo correction if there are no previous declarations with
6199 /// the same name.
6200 ///
6201 /// Returns a NamedDecl iff typo correction was performed and substituting in
6202 /// the new declaration name does not cause new errors.
6203 static NamedDecl *DiagnoseInvalidRedeclaration(
6204     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6205     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6206   DeclarationName Name = NewFD->getDeclName();
6207   DeclContext *NewDC = NewFD->getDeclContext();
6208   SmallVector<unsigned, 1> MismatchedParams;
6209   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6210   TypoCorrection Correction;
6211   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6212   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6213                                    : diag::err_member_decl_does_not_match;
6214   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6215                     IsLocalFriend ? Sema::LookupLocalFriendName
6216                                   : Sema::LookupOrdinaryName,
6217                     Sema::ForRedeclaration);
6218 
6219   NewFD->setInvalidDecl();
6220   if (IsLocalFriend)
6221     SemaRef.LookupName(Prev, S);
6222   else
6223     SemaRef.LookupQualifiedName(Prev, NewDC);
6224   assert(!Prev.isAmbiguous() &&
6225          "Cannot have an ambiguity in previous-declaration lookup");
6226   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6227   DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6228                                       MD ? MD->getParent() : nullptr);
6229   if (!Prev.empty()) {
6230     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6231          Func != FuncEnd; ++Func) {
6232       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6233       if (FD &&
6234           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6235         // Add 1 to the index so that 0 can mean the mismatch didn't
6236         // involve a parameter
6237         unsigned ParamNum =
6238             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6239         NearMatches.push_back(std::make_pair(FD, ParamNum));
6240       }
6241     }
6242   // If the qualified name lookup yielded nothing, try typo correction
6243   } else if ((Correction = SemaRef.CorrectTypo(
6244                  Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6245                  &ExtraArgs.D.getCXXScopeSpec(), Validator,
6246                  Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6247     // Set up everything for the call to ActOnFunctionDeclarator
6248     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6249                               ExtraArgs.D.getIdentifierLoc());
6250     Previous.clear();
6251     Previous.setLookupName(Correction.getCorrection());
6252     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6253                                     CDeclEnd = Correction.end();
6254          CDecl != CDeclEnd; ++CDecl) {
6255       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6256       if (FD && !FD->hasBody() &&
6257           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6258         Previous.addDecl(FD);
6259       }
6260     }
6261     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6262 
6263     NamedDecl *Result;
6264     // Retry building the function declaration with the new previous
6265     // declarations, and with errors suppressed.
6266     {
6267       // Trap errors.
6268       Sema::SFINAETrap Trap(SemaRef);
6269 
6270       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6271       // pieces need to verify the typo-corrected C++ declaration and hopefully
6272       // eliminate the need for the parameter pack ExtraArgs.
6273       Result = SemaRef.ActOnFunctionDeclarator(
6274           ExtraArgs.S, ExtraArgs.D,
6275           Correction.getCorrectionDecl()->getDeclContext(),
6276           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6277           ExtraArgs.AddToScope);
6278 
6279       if (Trap.hasErrorOccurred())
6280         Result = nullptr;
6281     }
6282 
6283     if (Result) {
6284       // Determine which correction we picked.
6285       Decl *Canonical = Result->getCanonicalDecl();
6286       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6287            I != E; ++I)
6288         if ((*I)->getCanonicalDecl() == Canonical)
6289           Correction.setCorrectionDecl(*I);
6290 
6291       SemaRef.diagnoseTypo(
6292           Correction,
6293           SemaRef.PDiag(IsLocalFriend
6294                           ? diag::err_no_matching_local_friend_suggest
6295                           : diag::err_member_decl_does_not_match_suggest)
6296             << Name << NewDC << IsDefinition);
6297       return Result;
6298     }
6299 
6300     // Pretend the typo correction never occurred
6301     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6302                               ExtraArgs.D.getIdentifierLoc());
6303     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6304     Previous.clear();
6305     Previous.setLookupName(Name);
6306   }
6307 
6308   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6309       << Name << NewDC << IsDefinition << NewFD->getLocation();
6310 
6311   bool NewFDisConst = false;
6312   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6313     NewFDisConst = NewMD->isConst();
6314 
6315   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6316        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6317        NearMatch != NearMatchEnd; ++NearMatch) {
6318     FunctionDecl *FD = NearMatch->first;
6319     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6320     bool FDisConst = MD && MD->isConst();
6321     bool IsMember = MD || !IsLocalFriend;
6322 
6323     // FIXME: These notes are poorly worded for the local friend case.
6324     if (unsigned Idx = NearMatch->second) {
6325       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6326       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6327       if (Loc.isInvalid()) Loc = FD->getLocation();
6328       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6329                                  : diag::note_local_decl_close_param_match)
6330         << Idx << FDParam->getType()
6331         << NewFD->getParamDecl(Idx - 1)->getType();
6332     } else if (FDisConst != NewFDisConst) {
6333       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6334           << NewFDisConst << FD->getSourceRange().getEnd();
6335     } else
6336       SemaRef.Diag(FD->getLocation(),
6337                    IsMember ? diag::note_member_def_close_match
6338                             : diag::note_local_decl_close_match);
6339   }
6340   return nullptr;
6341 }
6342 
6343 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6344                                                           Declarator &D) {
6345   switch (D.getDeclSpec().getStorageClassSpec()) {
6346   default: llvm_unreachable("Unknown storage class!");
6347   case DeclSpec::SCS_auto:
6348   case DeclSpec::SCS_register:
6349   case DeclSpec::SCS_mutable:
6350     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6351                  diag::err_typecheck_sclass_func);
6352     D.setInvalidType();
6353     break;
6354   case DeclSpec::SCS_unspecified: break;
6355   case DeclSpec::SCS_extern:
6356     if (D.getDeclSpec().isExternInLinkageSpec())
6357       return SC_None;
6358     return SC_Extern;
6359   case DeclSpec::SCS_static: {
6360     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6361       // C99 6.7.1p5:
6362       //   The declaration of an identifier for a function that has
6363       //   block scope shall have no explicit storage-class specifier
6364       //   other than extern
6365       // See also (C++ [dcl.stc]p4).
6366       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6367                    diag::err_static_block_func);
6368       break;
6369     } else
6370       return SC_Static;
6371   }
6372   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6373   }
6374 
6375   // No explicit storage class has already been returned
6376   return SC_None;
6377 }
6378 
6379 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6380                                            DeclContext *DC, QualType &R,
6381                                            TypeSourceInfo *TInfo,
6382                                            FunctionDecl::StorageClass SC,
6383                                            bool &IsVirtualOkay) {
6384   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6385   DeclarationName Name = NameInfo.getName();
6386 
6387   FunctionDecl *NewFD = nullptr;
6388   bool isInline = D.getDeclSpec().isInlineSpecified();
6389 
6390   if (!SemaRef.getLangOpts().CPlusPlus) {
6391     // Determine whether the function was written with a
6392     // prototype. This true when:
6393     //   - there is a prototype in the declarator, or
6394     //   - the type R of the function is some kind of typedef or other reference
6395     //     to a type name (which eventually refers to a function type).
6396     bool HasPrototype =
6397       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6398       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6399 
6400     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6401                                  D.getLocStart(), NameInfo, R,
6402                                  TInfo, SC, isInline,
6403                                  HasPrototype, false);
6404     if (D.isInvalidType())
6405       NewFD->setInvalidDecl();
6406 
6407     // Set the lexical context.
6408     NewFD->setLexicalDeclContext(SemaRef.CurContext);
6409 
6410     return NewFD;
6411   }
6412 
6413   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6414   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6415 
6416   // Check that the return type is not an abstract class type.
6417   // For record types, this is done by the AbstractClassUsageDiagnoser once
6418   // the class has been completely parsed.
6419   if (!DC->isRecord() &&
6420       SemaRef.RequireNonAbstractType(
6421           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6422           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
6423     D.setInvalidType();
6424 
6425   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6426     // This is a C++ constructor declaration.
6427     assert(DC->isRecord() &&
6428            "Constructors can only be declared in a member context");
6429 
6430     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6431     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6432                                       D.getLocStart(), NameInfo,
6433                                       R, TInfo, isExplicit, isInline,
6434                                       /*isImplicitlyDeclared=*/false,
6435                                       isConstexpr);
6436 
6437   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6438     // This is a C++ destructor declaration.
6439     if (DC->isRecord()) {
6440       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6441       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6442       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6443                                         SemaRef.Context, Record,
6444                                         D.getLocStart(),
6445                                         NameInfo, R, TInfo, isInline,
6446                                         /*isImplicitlyDeclared=*/false);
6447 
6448       // If the class is complete, then we now create the implicit exception
6449       // specification. If the class is incomplete or dependent, we can't do
6450       // it yet.
6451       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6452           Record->getDefinition() && !Record->isBeingDefined() &&
6453           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6454         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6455       }
6456 
6457       IsVirtualOkay = true;
6458       return NewDD;
6459 
6460     } else {
6461       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6462       D.setInvalidType();
6463 
6464       // Create a FunctionDecl to satisfy the function definition parsing
6465       // code path.
6466       return FunctionDecl::Create(SemaRef.Context, DC,
6467                                   D.getLocStart(),
6468                                   D.getIdentifierLoc(), Name, R, TInfo,
6469                                   SC, isInline,
6470                                   /*hasPrototype=*/true, isConstexpr);
6471     }
6472 
6473   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6474     if (!DC->isRecord()) {
6475       SemaRef.Diag(D.getIdentifierLoc(),
6476            diag::err_conv_function_not_member);
6477       return nullptr;
6478     }
6479 
6480     SemaRef.CheckConversionDeclarator(D, R, SC);
6481     IsVirtualOkay = true;
6482     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6483                                      D.getLocStart(), NameInfo,
6484                                      R, TInfo, isInline, isExplicit,
6485                                      isConstexpr, SourceLocation());
6486 
6487   } else if (DC->isRecord()) {
6488     // If the name of the function is the same as the name of the record,
6489     // then this must be an invalid constructor that has a return type.
6490     // (The parser checks for a return type and makes the declarator a
6491     // constructor if it has no return type).
6492     if (Name.getAsIdentifierInfo() &&
6493         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6494       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6495         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6496         << SourceRange(D.getIdentifierLoc());
6497       return nullptr;
6498     }
6499 
6500     // This is a C++ method declaration.
6501     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6502                                                cast<CXXRecordDecl>(DC),
6503                                                D.getLocStart(), NameInfo, R,
6504                                                TInfo, SC, isInline,
6505                                                isConstexpr, SourceLocation());
6506     IsVirtualOkay = !Ret->isStatic();
6507     return Ret;
6508   } else {
6509     // Determine whether the function was written with a
6510     // prototype. This true when:
6511     //   - we're in C++ (where every function has a prototype),
6512     return FunctionDecl::Create(SemaRef.Context, DC,
6513                                 D.getLocStart(),
6514                                 NameInfo, R, TInfo, SC, isInline,
6515                                 true/*HasPrototype*/, isConstexpr);
6516   }
6517 }
6518 
6519 enum OpenCLParamType {
6520   ValidKernelParam,
6521   PtrPtrKernelParam,
6522   PtrKernelParam,
6523   PrivatePtrKernelParam,
6524   InvalidKernelParam,
6525   RecordKernelParam
6526 };
6527 
6528 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6529   if (PT->isPointerType()) {
6530     QualType PointeeType = PT->getPointeeType();
6531     if (PointeeType->isPointerType())
6532       return PtrPtrKernelParam;
6533     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
6534                                               : PtrKernelParam;
6535   }
6536 
6537   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6538   // be used as builtin types.
6539 
6540   if (PT->isImageType())
6541     return PtrKernelParam;
6542 
6543   if (PT->isBooleanType())
6544     return InvalidKernelParam;
6545 
6546   if (PT->isEventT())
6547     return InvalidKernelParam;
6548 
6549   if (PT->isHalfType())
6550     return InvalidKernelParam;
6551 
6552   if (PT->isRecordType())
6553     return RecordKernelParam;
6554 
6555   return ValidKernelParam;
6556 }
6557 
6558 static void checkIsValidOpenCLKernelParameter(
6559   Sema &S,
6560   Declarator &D,
6561   ParmVarDecl *Param,
6562   llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6563   QualType PT = Param->getType();
6564 
6565   // Cache the valid types we encounter to avoid rechecking structs that are
6566   // used again
6567   if (ValidTypes.count(PT.getTypePtr()))
6568     return;
6569 
6570   switch (getOpenCLKernelParameterType(PT)) {
6571   case PtrPtrKernelParam:
6572     // OpenCL v1.2 s6.9.a:
6573     // A kernel function argument cannot be declared as a
6574     // pointer to a pointer type.
6575     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6576     D.setInvalidType();
6577     return;
6578 
6579   case PrivatePtrKernelParam:
6580     // OpenCL v1.2 s6.9.a:
6581     // A kernel function argument cannot be declared as a
6582     // pointer to the private address space.
6583     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
6584     D.setInvalidType();
6585     return;
6586 
6587     // OpenCL v1.2 s6.9.k:
6588     // Arguments to kernel functions in a program cannot be declared with the
6589     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6590     // uintptr_t or a struct and/or union that contain fields declared to be
6591     // one of these built-in scalar types.
6592 
6593   case InvalidKernelParam:
6594     // OpenCL v1.2 s6.8 n:
6595     // A kernel function argument cannot be declared
6596     // of event_t type.
6597     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6598     D.setInvalidType();
6599     return;
6600 
6601   case PtrKernelParam:
6602   case ValidKernelParam:
6603     ValidTypes.insert(PT.getTypePtr());
6604     return;
6605 
6606   case RecordKernelParam:
6607     break;
6608   }
6609 
6610   // Track nested structs we will inspect
6611   SmallVector<const Decl *, 4> VisitStack;
6612 
6613   // Track where we are in the nested structs. Items will migrate from
6614   // VisitStack to HistoryStack as we do the DFS for bad field.
6615   SmallVector<const FieldDecl *, 4> HistoryStack;
6616   HistoryStack.push_back(nullptr);
6617 
6618   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6619   VisitStack.push_back(PD);
6620 
6621   assert(VisitStack.back() && "First decl null?");
6622 
6623   do {
6624     const Decl *Next = VisitStack.pop_back_val();
6625     if (!Next) {
6626       assert(!HistoryStack.empty());
6627       // Found a marker, we have gone up a level
6628       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6629         ValidTypes.insert(Hist->getType().getTypePtr());
6630 
6631       continue;
6632     }
6633 
6634     // Adds everything except the original parameter declaration (which is not a
6635     // field itself) to the history stack.
6636     const RecordDecl *RD;
6637     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6638       HistoryStack.push_back(Field);
6639       RD = Field->getType()->castAs<RecordType>()->getDecl();
6640     } else {
6641       RD = cast<RecordDecl>(Next);
6642     }
6643 
6644     // Add a null marker so we know when we've gone back up a level
6645     VisitStack.push_back(nullptr);
6646 
6647     for (const auto *FD : RD->fields()) {
6648       QualType QT = FD->getType();
6649 
6650       if (ValidTypes.count(QT.getTypePtr()))
6651         continue;
6652 
6653       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6654       if (ParamType == ValidKernelParam)
6655         continue;
6656 
6657       if (ParamType == RecordKernelParam) {
6658         VisitStack.push_back(FD);
6659         continue;
6660       }
6661 
6662       // OpenCL v1.2 s6.9.p:
6663       // Arguments to kernel functions that are declared to be a struct or union
6664       // do not allow OpenCL objects to be passed as elements of the struct or
6665       // union.
6666       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
6667           ParamType == PrivatePtrKernelParam) {
6668         S.Diag(Param->getLocation(),
6669                diag::err_record_with_pointers_kernel_param)
6670           << PT->isUnionType()
6671           << PT;
6672       } else {
6673         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6674       }
6675 
6676       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6677         << PD->getDeclName();
6678 
6679       // We have an error, now let's go back up through history and show where
6680       // the offending field came from
6681       for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6682              E = HistoryStack.end(); I != E; ++I) {
6683         const FieldDecl *OuterField = *I;
6684         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6685           << OuterField->getType();
6686       }
6687 
6688       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6689         << QT->isPointerType()
6690         << QT;
6691       D.setInvalidType();
6692       return;
6693     }
6694   } while (!VisitStack.empty());
6695 }
6696 
6697 NamedDecl*
6698 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
6699                               TypeSourceInfo *TInfo, LookupResult &Previous,
6700                               MultiTemplateParamsArg TemplateParamLists,
6701                               bool &AddToScope) {
6702   QualType R = TInfo->getType();
6703 
6704   assert(R.getTypePtr()->isFunctionType());
6705 
6706   // TODO: consider using NameInfo for diagnostic.
6707   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6708   DeclarationName Name = NameInfo.getName();
6709   FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
6710 
6711   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6712     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6713          diag::err_invalid_thread)
6714       << DeclSpec::getSpecifierName(TSCS);
6715 
6716   if (D.isFirstDeclarationOfMember())
6717     adjustMemberFunctionCC(R, D.isStaticMember());
6718 
6719   bool isFriend = false;
6720   FunctionTemplateDecl *FunctionTemplate = nullptr;
6721   bool isExplicitSpecialization = false;
6722   bool isFunctionTemplateSpecialization = false;
6723 
6724   bool isDependentClassScopeExplicitSpecialization = false;
6725   bool HasExplicitTemplateArgs = false;
6726   TemplateArgumentListInfo TemplateArgs;
6727 
6728   bool isVirtualOkay = false;
6729 
6730   DeclContext *OriginalDC = DC;
6731   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6732 
6733   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6734                                               isVirtualOkay);
6735   if (!NewFD) return nullptr;
6736 
6737   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6738     NewFD->setTopLevelDeclInObjCContainer();
6739 
6740   // Set the lexical context. If this is a function-scope declaration, or has a
6741   // C++ scope specifier, or is the object of a friend declaration, the lexical
6742   // context will be different from the semantic context.
6743   NewFD->setLexicalDeclContext(CurContext);
6744 
6745   if (IsLocalExternDecl)
6746     NewFD->setLocalExternDecl();
6747 
6748   if (getLangOpts().CPlusPlus) {
6749     bool isInline = D.getDeclSpec().isInlineSpecified();
6750     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6751     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6752     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6753     isFriend = D.getDeclSpec().isFriendSpecified();
6754     if (isFriend && !isInline && D.isFunctionDefinition()) {
6755       // C++ [class.friend]p5
6756       //   A function can be defined in a friend declaration of a
6757       //   class . . . . Such a function is implicitly inline.
6758       NewFD->setImplicitlyInline();
6759     }
6760 
6761     // If this is a method defined in an __interface, and is not a constructor
6762     // or an overloaded operator, then set the pure flag (isVirtual will already
6763     // return true).
6764     if (const CXXRecordDecl *Parent =
6765           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6766       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
6767         NewFD->setPure(true);
6768     }
6769 
6770     SetNestedNameSpecifier(NewFD, D);
6771     isExplicitSpecialization = false;
6772     isFunctionTemplateSpecialization = false;
6773     if (D.isInvalidType())
6774       NewFD->setInvalidDecl();
6775 
6776     // Match up the template parameter lists with the scope specifier, then
6777     // determine whether we have a template or a template specialization.
6778     bool Invalid = false;
6779     if (TemplateParameterList *TemplateParams =
6780             MatchTemplateParametersToScopeSpecifier(
6781                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6782                 D.getCXXScopeSpec(),
6783                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
6784                     ? D.getName().TemplateId
6785                     : nullptr,
6786                 TemplateParamLists, isFriend, isExplicitSpecialization,
6787                 Invalid)) {
6788       if (TemplateParams->size() > 0) {
6789         // This is a function template
6790 
6791         // Check that we can declare a template here.
6792         if (CheckTemplateDeclScope(S, TemplateParams))
6793           return nullptr;
6794 
6795         // A destructor cannot be a template.
6796         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6797           Diag(NewFD->getLocation(), diag::err_destructor_template);
6798           return nullptr;
6799         }
6800 
6801         // If we're adding a template to a dependent context, we may need to
6802         // rebuilding some of the types used within the template parameter list,
6803         // now that we know what the current instantiation is.
6804         if (DC->isDependentContext()) {
6805           ContextRAII SavedContext(*this, DC);
6806           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6807             Invalid = true;
6808         }
6809 
6810 
6811         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6812                                                         NewFD->getLocation(),
6813                                                         Name, TemplateParams,
6814                                                         NewFD);
6815         FunctionTemplate->setLexicalDeclContext(CurContext);
6816         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6817 
6818         // For source fidelity, store the other template param lists.
6819         if (TemplateParamLists.size() > 1) {
6820           NewFD->setTemplateParameterListsInfo(Context,
6821                                                TemplateParamLists.size() - 1,
6822                                                TemplateParamLists.data());
6823         }
6824       } else {
6825         // This is a function template specialization.
6826         isFunctionTemplateSpecialization = true;
6827         // For source fidelity, store all the template param lists.
6828         if (TemplateParamLists.size() > 0)
6829           NewFD->setTemplateParameterListsInfo(Context,
6830                                                TemplateParamLists.size(),
6831                                                TemplateParamLists.data());
6832 
6833         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6834         if (isFriend) {
6835           // We want to remove the "template<>", found here.
6836           SourceRange RemoveRange = TemplateParams->getSourceRange();
6837 
6838           // If we remove the template<> and the name is not a
6839           // template-id, we're actually silently creating a problem:
6840           // the friend declaration will refer to an untemplated decl,
6841           // and clearly the user wants a template specialization.  So
6842           // we need to insert '<>' after the name.
6843           SourceLocation InsertLoc;
6844           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6845             InsertLoc = D.getName().getSourceRange().getEnd();
6846             InsertLoc = getLocForEndOfToken(InsertLoc);
6847           }
6848 
6849           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6850             << Name << RemoveRange
6851             << FixItHint::CreateRemoval(RemoveRange)
6852             << FixItHint::CreateInsertion(InsertLoc, "<>");
6853         }
6854       }
6855     }
6856     else {
6857       // All template param lists were matched against the scope specifier:
6858       // this is NOT (an explicit specialization of) a template.
6859       if (TemplateParamLists.size() > 0)
6860         // For source fidelity, store all the template param lists.
6861         NewFD->setTemplateParameterListsInfo(Context,
6862                                              TemplateParamLists.size(),
6863                                              TemplateParamLists.data());
6864     }
6865 
6866     if (Invalid) {
6867       NewFD->setInvalidDecl();
6868       if (FunctionTemplate)
6869         FunctionTemplate->setInvalidDecl();
6870     }
6871 
6872     // C++ [dcl.fct.spec]p5:
6873     //   The virtual specifier shall only be used in declarations of
6874     //   nonstatic class member functions that appear within a
6875     //   member-specification of a class declaration; see 10.3.
6876     //
6877     if (isVirtual && !NewFD->isInvalidDecl()) {
6878       if (!isVirtualOkay) {
6879         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6880              diag::err_virtual_non_function);
6881       } else if (!CurContext->isRecord()) {
6882         // 'virtual' was specified outside of the class.
6883         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6884              diag::err_virtual_out_of_class)
6885           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6886       } else if (NewFD->getDescribedFunctionTemplate()) {
6887         // C++ [temp.mem]p3:
6888         //  A member function template shall not be virtual.
6889         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6890              diag::err_virtual_member_function_template)
6891           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6892       } else {
6893         // Okay: Add virtual to the method.
6894         NewFD->setVirtualAsWritten(true);
6895       }
6896 
6897       if (getLangOpts().CPlusPlus1y &&
6898           NewFD->getReturnType()->isUndeducedType())
6899         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
6900     }
6901 
6902     if (getLangOpts().CPlusPlus1y &&
6903         (NewFD->isDependentContext() ||
6904          (isFriend && CurContext->isDependentContext())) &&
6905         NewFD->getReturnType()->isUndeducedType()) {
6906       // If the function template is referenced directly (for instance, as a
6907       // member of the current instantiation), pretend it has a dependent type.
6908       // This is not really justified by the standard, but is the only sane
6909       // thing to do.
6910       // FIXME: For a friend function, we have not marked the function as being
6911       // a friend yet, so 'isDependentContext' on the FD doesn't work.
6912       const FunctionProtoType *FPT =
6913           NewFD->getType()->castAs<FunctionProtoType>();
6914       QualType Result =
6915           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
6916       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
6917                                              FPT->getExtProtoInfo()));
6918     }
6919 
6920     // C++ [dcl.fct.spec]p3:
6921     //  The inline specifier shall not appear on a block scope function
6922     //  declaration.
6923     if (isInline && !NewFD->isInvalidDecl()) {
6924       if (CurContext->isFunctionOrMethod()) {
6925         // 'inline' is not allowed on block scope function declaration.
6926         Diag(D.getDeclSpec().getInlineSpecLoc(),
6927              diag::err_inline_declaration_block_scope) << Name
6928           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6929       }
6930     }
6931 
6932     // C++ [dcl.fct.spec]p6:
6933     //  The explicit specifier shall be used only in the declaration of a
6934     //  constructor or conversion function within its class definition;
6935     //  see 12.3.1 and 12.3.2.
6936     if (isExplicit && !NewFD->isInvalidDecl()) {
6937       if (!CurContext->isRecord()) {
6938         // 'explicit' was specified outside of the class.
6939         Diag(D.getDeclSpec().getExplicitSpecLoc(),
6940              diag::err_explicit_out_of_class)
6941           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6942       } else if (!isa<CXXConstructorDecl>(NewFD) &&
6943                  !isa<CXXConversionDecl>(NewFD)) {
6944         // 'explicit' was specified on a function that wasn't a constructor
6945         // or conversion function.
6946         Diag(D.getDeclSpec().getExplicitSpecLoc(),
6947              diag::err_explicit_non_ctor_or_conv_function)
6948           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6949       }
6950     }
6951 
6952     if (isConstexpr) {
6953       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
6954       // are implicitly inline.
6955       NewFD->setImplicitlyInline();
6956 
6957       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
6958       // be either constructors or to return a literal type. Therefore,
6959       // destructors cannot be declared constexpr.
6960       if (isa<CXXDestructorDecl>(NewFD))
6961         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
6962     }
6963 
6964     // If __module_private__ was specified, mark the function accordingly.
6965     if (D.getDeclSpec().isModulePrivateSpecified()) {
6966       if (isFunctionTemplateSpecialization) {
6967         SourceLocation ModulePrivateLoc
6968           = D.getDeclSpec().getModulePrivateSpecLoc();
6969         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6970           << 0
6971           << FixItHint::CreateRemoval(ModulePrivateLoc);
6972       } else {
6973         NewFD->setModulePrivate();
6974         if (FunctionTemplate)
6975           FunctionTemplate->setModulePrivate();
6976       }
6977     }
6978 
6979     if (isFriend) {
6980       if (FunctionTemplate) {
6981         FunctionTemplate->setObjectOfFriendDecl();
6982         FunctionTemplate->setAccess(AS_public);
6983       }
6984       NewFD->setObjectOfFriendDecl();
6985       NewFD->setAccess(AS_public);
6986     }
6987 
6988     // If a function is defined as defaulted or deleted, mark it as such now.
6989     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
6990     // definition kind to FDK_Definition.
6991     switch (D.getFunctionDefinitionKind()) {
6992       case FDK_Declaration:
6993       case FDK_Definition:
6994         break;
6995 
6996       case FDK_Defaulted:
6997         NewFD->setDefaulted();
6998         break;
6999 
7000       case FDK_Deleted:
7001         NewFD->setDeletedAsWritten();
7002         break;
7003     }
7004 
7005     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7006         D.isFunctionDefinition()) {
7007       // C++ [class.mfct]p2:
7008       //   A member function may be defined (8.4) in its class definition, in
7009       //   which case it is an inline member function (7.1.2)
7010       NewFD->setImplicitlyInline();
7011     }
7012 
7013     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7014         !CurContext->isRecord()) {
7015       // C++ [class.static]p1:
7016       //   A data or function member of a class may be declared static
7017       //   in a class definition, in which case it is a static member of
7018       //   the class.
7019 
7020       // Complain about the 'static' specifier if it's on an out-of-line
7021       // member function definition.
7022       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7023            diag::err_static_out_of_line)
7024         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7025     }
7026 
7027     // C++11 [except.spec]p15:
7028     //   A deallocation function with no exception-specification is treated
7029     //   as if it were specified with noexcept(true).
7030     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7031     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7032          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7033         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
7034       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7035       EPI.ExceptionSpecType = EST_BasicNoexcept;
7036       NewFD->setType(Context.getFunctionType(FPT->getReturnType(),
7037                                              FPT->getParamTypes(), EPI));
7038     }
7039   }
7040 
7041   // Filter out previous declarations that don't match the scope.
7042   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7043                        D.getCXXScopeSpec().isNotEmpty() ||
7044                        isExplicitSpecialization ||
7045                        isFunctionTemplateSpecialization);
7046 
7047   // Handle GNU asm-label extension (encoded as an attribute).
7048   if (Expr *E = (Expr*) D.getAsmLabel()) {
7049     // The parser guarantees this is a string.
7050     StringLiteral *SE = cast<StringLiteral>(E);
7051     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7052                                                 SE->getString(), 0));
7053   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7054     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7055       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7056     if (I != ExtnameUndeclaredIdentifiers.end()) {
7057       NewFD->addAttr(I->second);
7058       ExtnameUndeclaredIdentifiers.erase(I);
7059     }
7060   }
7061 
7062   // Copy the parameter declarations from the declarator D to the function
7063   // declaration NewFD, if they are available.  First scavenge them into Params.
7064   SmallVector<ParmVarDecl*, 16> Params;
7065   if (D.isFunctionDeclarator()) {
7066     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7067 
7068     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7069     // function that takes no arguments, not a function that takes a
7070     // single void argument.
7071     // We let through "const void" here because Sema::GetTypeForDeclarator
7072     // already checks for that case.
7073     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7074       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7075         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7076         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7077         Param->setDeclContext(NewFD);
7078         Params.push_back(Param);
7079 
7080         if (Param->isInvalidDecl())
7081           NewFD->setInvalidDecl();
7082       }
7083     }
7084 
7085   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7086     // When we're declaring a function with a typedef, typeof, etc as in the
7087     // following example, we'll need to synthesize (unnamed)
7088     // parameters for use in the declaration.
7089     //
7090     // @code
7091     // typedef void fn(int);
7092     // fn f;
7093     // @endcode
7094 
7095     // Synthesize a parameter for each argument type.
7096     for (const auto &AI : FT->param_types()) {
7097       ParmVarDecl *Param =
7098           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7099       Param->setScopeInfo(0, Params.size());
7100       Params.push_back(Param);
7101     }
7102   } else {
7103     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7104            "Should not need args for typedef of non-prototype fn");
7105   }
7106 
7107   // Finally, we know we have the right number of parameters, install them.
7108   NewFD->setParams(Params);
7109 
7110   // Find all anonymous symbols defined during the declaration of this function
7111   // and add to NewFD. This lets us track decls such 'enum Y' in:
7112   //
7113   //   void f(enum Y {AA} x) {}
7114   //
7115   // which would otherwise incorrectly end up in the translation unit scope.
7116   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7117   DeclsInPrototypeScope.clear();
7118 
7119   if (D.getDeclSpec().isNoreturnSpecified())
7120     NewFD->addAttr(
7121         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7122                                        Context, 0));
7123 
7124   // Functions returning a variably modified type violate C99 6.7.5.2p2
7125   // because all functions have linkage.
7126   if (!NewFD->isInvalidDecl() &&
7127       NewFD->getReturnType()->isVariablyModifiedType()) {
7128     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7129     NewFD->setInvalidDecl();
7130   }
7131 
7132   if (D.isFunctionDefinition() && CodeSegStack.CurrentValue &&
7133       !NewFD->hasAttr<SectionAttr>()) {
7134     NewFD->addAttr(
7135         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7136                                     CodeSegStack.CurrentValue->getString(),
7137                                     CodeSegStack.CurrentPragmaLocation));
7138     if (UnifySection(CodeSegStack.CurrentValue->getString(),
7139                      PSF_Implicit | PSF_Execute | PSF_Read, NewFD))
7140       NewFD->dropAttr<SectionAttr>();
7141   }
7142 
7143   // Handle attributes.
7144   ProcessDeclAttributes(S, NewFD, D);
7145 
7146   QualType RetType = NewFD->getReturnType();
7147   const CXXRecordDecl *Ret = RetType->isRecordType() ?
7148       RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
7149   if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
7150       Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
7151     const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7152     // Attach WarnUnusedResult to functions returning types with that attribute.
7153     // Don't apply the attribute to that type's own non-static member functions
7154     // (to avoid warning on things like assignment operators)
7155     if (!MD || MD->getParent() != Ret)
7156       NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
7157   }
7158 
7159   if (getLangOpts().OpenCL) {
7160     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7161     // type declaration will generate a compilation error.
7162     unsigned AddressSpace = RetType.getAddressSpace();
7163     if (AddressSpace == LangAS::opencl_local ||
7164         AddressSpace == LangAS::opencl_global ||
7165         AddressSpace == LangAS::opencl_constant) {
7166       Diag(NewFD->getLocation(),
7167            diag::err_opencl_return_value_with_address_space);
7168       NewFD->setInvalidDecl();
7169     }
7170   }
7171 
7172   if (!getLangOpts().CPlusPlus) {
7173     // Perform semantic checking on the function declaration.
7174     bool isExplicitSpecialization=false;
7175     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7176       CheckMain(NewFD, D.getDeclSpec());
7177 
7178     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7179       CheckMSVCRTEntryPoint(NewFD);
7180 
7181     if (!NewFD->isInvalidDecl())
7182       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7183                                                   isExplicitSpecialization));
7184     else if (!Previous.empty())
7185       // Make graceful recovery from an invalid redeclaration.
7186       D.setRedeclaration(true);
7187     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7188             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7189            "previous declaration set still overloaded");
7190   } else {
7191     // C++11 [replacement.functions]p3:
7192     //  The program's definitions shall not be specified as inline.
7193     //
7194     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7195     //
7196     // Suppress the diagnostic if the function is __attribute__((used)), since
7197     // that forces an external definition to be emitted.
7198     if (D.getDeclSpec().isInlineSpecified() &&
7199         NewFD->isReplaceableGlobalAllocationFunction() &&
7200         !NewFD->hasAttr<UsedAttr>())
7201       Diag(D.getDeclSpec().getInlineSpecLoc(),
7202            diag::ext_operator_new_delete_declared_inline)
7203         << NewFD->getDeclName();
7204 
7205     // If the declarator is a template-id, translate the parser's template
7206     // argument list into our AST format.
7207     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7208       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7209       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7210       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7211       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7212                                          TemplateId->NumArgs);
7213       translateTemplateArguments(TemplateArgsPtr,
7214                                  TemplateArgs);
7215 
7216       HasExplicitTemplateArgs = true;
7217 
7218       if (NewFD->isInvalidDecl()) {
7219         HasExplicitTemplateArgs = false;
7220       } else if (FunctionTemplate) {
7221         // Function template with explicit template arguments.
7222         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7223           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7224 
7225         HasExplicitTemplateArgs = false;
7226       } else {
7227         assert((isFunctionTemplateSpecialization ||
7228                 D.getDeclSpec().isFriendSpecified()) &&
7229                "should have a 'template<>' for this decl");
7230         // "friend void foo<>(int);" is an implicit specialization decl.
7231         isFunctionTemplateSpecialization = true;
7232       }
7233     } else if (isFriend && isFunctionTemplateSpecialization) {
7234       // This combination is only possible in a recovery case;  the user
7235       // wrote something like:
7236       //   template <> friend void foo(int);
7237       // which we're recovering from as if the user had written:
7238       //   friend void foo<>(int);
7239       // Go ahead and fake up a template id.
7240       HasExplicitTemplateArgs = true;
7241       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7242       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7243     }
7244 
7245     // If it's a friend (and only if it's a friend), it's possible
7246     // that either the specialized function type or the specialized
7247     // template is dependent, and therefore matching will fail.  In
7248     // this case, don't check the specialization yet.
7249     bool InstantiationDependent = false;
7250     if (isFunctionTemplateSpecialization && isFriend &&
7251         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7252          TemplateSpecializationType::anyDependentTemplateArguments(
7253             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7254             InstantiationDependent))) {
7255       assert(HasExplicitTemplateArgs &&
7256              "friend function specialization without template args");
7257       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7258                                                        Previous))
7259         NewFD->setInvalidDecl();
7260     } else if (isFunctionTemplateSpecialization) {
7261       if (CurContext->isDependentContext() && CurContext->isRecord()
7262           && !isFriend) {
7263         isDependentClassScopeExplicitSpecialization = true;
7264         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7265           diag::ext_function_specialization_in_class :
7266           diag::err_function_specialization_in_class)
7267           << NewFD->getDeclName();
7268       } else if (CheckFunctionTemplateSpecialization(NewFD,
7269                                   (HasExplicitTemplateArgs ? &TemplateArgs
7270                                                            : nullptr),
7271                                                      Previous))
7272         NewFD->setInvalidDecl();
7273 
7274       // C++ [dcl.stc]p1:
7275       //   A storage-class-specifier shall not be specified in an explicit
7276       //   specialization (14.7.3)
7277       FunctionTemplateSpecializationInfo *Info =
7278           NewFD->getTemplateSpecializationInfo();
7279       if (Info && SC != SC_None) {
7280         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7281           Diag(NewFD->getLocation(),
7282                diag::err_explicit_specialization_inconsistent_storage_class)
7283             << SC
7284             << FixItHint::CreateRemoval(
7285                                       D.getDeclSpec().getStorageClassSpecLoc());
7286 
7287         else
7288           Diag(NewFD->getLocation(),
7289                diag::ext_explicit_specialization_storage_class)
7290             << FixItHint::CreateRemoval(
7291                                       D.getDeclSpec().getStorageClassSpecLoc());
7292       }
7293 
7294     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7295       if (CheckMemberSpecialization(NewFD, Previous))
7296           NewFD->setInvalidDecl();
7297     }
7298 
7299     // Perform semantic checking on the function declaration.
7300     if (!isDependentClassScopeExplicitSpecialization) {
7301       if (!NewFD->isInvalidDecl() && NewFD->isMain())
7302         CheckMain(NewFD, D.getDeclSpec());
7303 
7304       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7305         CheckMSVCRTEntryPoint(NewFD);
7306 
7307       if (!NewFD->isInvalidDecl())
7308         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7309                                                     isExplicitSpecialization));
7310     }
7311 
7312     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7313             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7314            "previous declaration set still overloaded");
7315 
7316     NamedDecl *PrincipalDecl = (FunctionTemplate
7317                                 ? cast<NamedDecl>(FunctionTemplate)
7318                                 : NewFD);
7319 
7320     if (isFriend && D.isRedeclaration()) {
7321       AccessSpecifier Access = AS_public;
7322       if (!NewFD->isInvalidDecl())
7323         Access = NewFD->getPreviousDecl()->getAccess();
7324 
7325       NewFD->setAccess(Access);
7326       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7327     }
7328 
7329     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7330         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7331       PrincipalDecl->setNonMemberOperator();
7332 
7333     // If we have a function template, check the template parameter
7334     // list. This will check and merge default template arguments.
7335     if (FunctionTemplate) {
7336       FunctionTemplateDecl *PrevTemplate =
7337                                      FunctionTemplate->getPreviousDecl();
7338       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7339                        PrevTemplate ? PrevTemplate->getTemplateParameters()
7340                                     : nullptr,
7341                             D.getDeclSpec().isFriendSpecified()
7342                               ? (D.isFunctionDefinition()
7343                                    ? TPC_FriendFunctionTemplateDefinition
7344                                    : TPC_FriendFunctionTemplate)
7345                               : (D.getCXXScopeSpec().isSet() &&
7346                                  DC && DC->isRecord() &&
7347                                  DC->isDependentContext())
7348                                   ? TPC_ClassTemplateMember
7349                                   : TPC_FunctionTemplate);
7350     }
7351 
7352     if (NewFD->isInvalidDecl()) {
7353       // Ignore all the rest of this.
7354     } else if (!D.isRedeclaration()) {
7355       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7356                                        AddToScope };
7357       // Fake up an access specifier if it's supposed to be a class member.
7358       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7359         NewFD->setAccess(AS_public);
7360 
7361       // Qualified decls generally require a previous declaration.
7362       if (D.getCXXScopeSpec().isSet()) {
7363         // ...with the major exception of templated-scope or
7364         // dependent-scope friend declarations.
7365 
7366         // TODO: we currently also suppress this check in dependent
7367         // contexts because (1) the parameter depth will be off when
7368         // matching friend templates and (2) we might actually be
7369         // selecting a friend based on a dependent factor.  But there
7370         // are situations where these conditions don't apply and we
7371         // can actually do this check immediately.
7372         if (isFriend &&
7373             (TemplateParamLists.size() ||
7374              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7375              CurContext->isDependentContext())) {
7376           // ignore these
7377         } else {
7378           // The user tried to provide an out-of-line definition for a
7379           // function that is a member of a class or namespace, but there
7380           // was no such member function declared (C++ [class.mfct]p2,
7381           // C++ [namespace.memdef]p2). For example:
7382           //
7383           // class X {
7384           //   void f() const;
7385           // };
7386           //
7387           // void X::f() { } // ill-formed
7388           //
7389           // Complain about this problem, and attempt to suggest close
7390           // matches (e.g., those that differ only in cv-qualifiers and
7391           // whether the parameter types are references).
7392 
7393           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7394                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
7395             AddToScope = ExtraArgs.AddToScope;
7396             return Result;
7397           }
7398         }
7399 
7400         // Unqualified local friend declarations are required to resolve
7401         // to something.
7402       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7403         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7404                 *this, Previous, NewFD, ExtraArgs, true, S)) {
7405           AddToScope = ExtraArgs.AddToScope;
7406           return Result;
7407         }
7408       }
7409 
7410     } else if (!D.isFunctionDefinition() &&
7411                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
7412                !isFriend && !isFunctionTemplateSpecialization &&
7413                !isExplicitSpecialization) {
7414       // An out-of-line member function declaration must also be a
7415       // definition (C++ [class.mfct]p2).
7416       // Note that this is not the case for explicit specializations of
7417       // function templates or member functions of class templates, per
7418       // C++ [temp.expl.spec]p2. We also allow these declarations as an
7419       // extension for compatibility with old SWIG code which likes to
7420       // generate them.
7421       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7422         << D.getCXXScopeSpec().getRange();
7423     }
7424   }
7425 
7426   ProcessPragmaWeak(S, NewFD);
7427   checkAttributesAfterMerging(*this, *NewFD);
7428 
7429   AddKnownFunctionAttributes(NewFD);
7430 
7431   if (NewFD->hasAttr<OverloadableAttr>() &&
7432       !NewFD->getType()->getAs<FunctionProtoType>()) {
7433     Diag(NewFD->getLocation(),
7434          diag::err_attribute_overloadable_no_prototype)
7435       << NewFD;
7436 
7437     // Turn this into a variadic function with no parameters.
7438     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7439     FunctionProtoType::ExtProtoInfo EPI(
7440         Context.getDefaultCallingConvention(true, false));
7441     EPI.Variadic = true;
7442     EPI.ExtInfo = FT->getExtInfo();
7443 
7444     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
7445     NewFD->setType(R);
7446   }
7447 
7448   // If there's a #pragma GCC visibility in scope, and this isn't a class
7449   // member, set the visibility of this function.
7450   if (!DC->isRecord() && NewFD->isExternallyVisible())
7451     AddPushedVisibilityAttribute(NewFD);
7452 
7453   // If there's a #pragma clang arc_cf_code_audited in scope, consider
7454   // marking the function.
7455   AddCFAuditedAttribute(NewFD);
7456 
7457   // If this is a function definition, check if we have to apply optnone due to
7458   // a pragma.
7459   if(D.isFunctionDefinition())
7460     AddRangeBasedOptnone(NewFD);
7461 
7462   // If this is the first declaration of an extern C variable, update
7463   // the map of such variables.
7464   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7465       isIncompleteDeclExternC(*this, NewFD))
7466     RegisterLocallyScopedExternCDecl(NewFD, S);
7467 
7468   // Set this FunctionDecl's range up to the right paren.
7469   NewFD->setRangeEnd(D.getSourceRange().getEnd());
7470 
7471   if (D.isRedeclaration() && !Previous.empty()) {
7472     checkDLLAttributeRedeclaration(
7473         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
7474         isExplicitSpecialization || isFunctionTemplateSpecialization);
7475   }
7476 
7477   if (getLangOpts().CPlusPlus) {
7478     if (FunctionTemplate) {
7479       if (NewFD->isInvalidDecl())
7480         FunctionTemplate->setInvalidDecl();
7481       return FunctionTemplate;
7482     }
7483   }
7484 
7485   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7486     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7487     if ((getLangOpts().OpenCLVersion >= 120)
7488         && (SC == SC_Static)) {
7489       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7490       D.setInvalidType();
7491     }
7492 
7493     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7494     if (!NewFD->getReturnType()->isVoidType()) {
7495       Diag(D.getIdentifierLoc(),
7496            diag::err_expected_kernel_void_return_type);
7497       D.setInvalidType();
7498     }
7499 
7500     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
7501     for (auto Param : NewFD->params())
7502       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
7503   }
7504 
7505   MarkUnusedFileScopedDecl(NewFD);
7506 
7507   if (getLangOpts().CUDA)
7508     if (IdentifierInfo *II = NewFD->getIdentifier())
7509       if (!NewFD->isInvalidDecl() &&
7510           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7511         if (II->isStr("cudaConfigureCall")) {
7512           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
7513             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7514 
7515           Context.setcudaConfigureCallDecl(NewFD);
7516         }
7517       }
7518 
7519   // Here we have an function template explicit specialization at class scope.
7520   // The actually specialization will be postponed to template instatiation
7521   // time via the ClassScopeFunctionSpecializationDecl node.
7522   if (isDependentClassScopeExplicitSpecialization) {
7523     ClassScopeFunctionSpecializationDecl *NewSpec =
7524                          ClassScopeFunctionSpecializationDecl::Create(
7525                                 Context, CurContext, SourceLocation(),
7526                                 cast<CXXMethodDecl>(NewFD),
7527                                 HasExplicitTemplateArgs, TemplateArgs);
7528     CurContext->addDecl(NewSpec);
7529     AddToScope = false;
7530   }
7531 
7532   return NewFD;
7533 }
7534 
7535 /// \brief Perform semantic checking of a new function declaration.
7536 ///
7537 /// Performs semantic analysis of the new function declaration
7538 /// NewFD. This routine performs all semantic checking that does not
7539 /// require the actual declarator involved in the declaration, and is
7540 /// used both for the declaration of functions as they are parsed
7541 /// (called via ActOnDeclarator) and for the declaration of functions
7542 /// that have been instantiated via C++ template instantiation (called
7543 /// via InstantiateDecl).
7544 ///
7545 /// \param IsExplicitSpecialization whether this new function declaration is
7546 /// an explicit specialization of the previous declaration.
7547 ///
7548 /// This sets NewFD->isInvalidDecl() to true if there was an error.
7549 ///
7550 /// \returns true if the function declaration is a redeclaration.
7551 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
7552                                     LookupResult &Previous,
7553                                     bool IsExplicitSpecialization) {
7554   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7555          "Variably modified return types are not handled here");
7556 
7557   // Determine whether the type of this function should be merged with
7558   // a previous visible declaration. This never happens for functions in C++,
7559   // and always happens in C if the previous declaration was visible.
7560   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7561                                !Previous.isShadowed();
7562 
7563   // Filter out any non-conflicting previous declarations.
7564   filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7565 
7566   bool Redeclaration = false;
7567   NamedDecl *OldDecl = nullptr;
7568 
7569   // Merge or overload the declaration with an existing declaration of
7570   // the same name, if appropriate.
7571   if (!Previous.empty()) {
7572     // Determine whether NewFD is an overload of PrevDecl or
7573     // a declaration that requires merging. If it's an overload,
7574     // there's no more work to do here; we'll just add the new
7575     // function to the scope.
7576     if (!AllowOverloadingOfFunction(Previous, Context)) {
7577       NamedDecl *Candidate = Previous.getFoundDecl();
7578       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7579         Redeclaration = true;
7580         OldDecl = Candidate;
7581       }
7582     } else {
7583       switch (CheckOverload(S, NewFD, Previous, OldDecl,
7584                             /*NewIsUsingDecl*/ false)) {
7585       case Ovl_Match:
7586         Redeclaration = true;
7587         break;
7588 
7589       case Ovl_NonFunction:
7590         Redeclaration = true;
7591         break;
7592 
7593       case Ovl_Overload:
7594         Redeclaration = false;
7595         break;
7596       }
7597 
7598       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7599         // If a function name is overloadable in C, then every function
7600         // with that name must be marked "overloadable".
7601         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7602           << Redeclaration << NewFD;
7603         NamedDecl *OverloadedDecl = nullptr;
7604         if (Redeclaration)
7605           OverloadedDecl = OldDecl;
7606         else if (!Previous.empty())
7607           OverloadedDecl = Previous.getRepresentativeDecl();
7608         if (OverloadedDecl)
7609           Diag(OverloadedDecl->getLocation(),
7610                diag::note_attribute_overloadable_prev_overload);
7611         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7612       }
7613     }
7614   }
7615 
7616   // Check for a previous extern "C" declaration with this name.
7617   if (!Redeclaration &&
7618       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7619     filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7620     if (!Previous.empty()) {
7621       // This is an extern "C" declaration with the same name as a previous
7622       // declaration, and thus redeclares that entity...
7623       Redeclaration = true;
7624       OldDecl = Previous.getFoundDecl();
7625       MergeTypeWithPrevious = false;
7626 
7627       // ... except in the presence of __attribute__((overloadable)).
7628       if (OldDecl->hasAttr<OverloadableAttr>()) {
7629         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7630           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7631             << Redeclaration << NewFD;
7632           Diag(Previous.getFoundDecl()->getLocation(),
7633                diag::note_attribute_overloadable_prev_overload);
7634           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7635         }
7636         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7637           Redeclaration = false;
7638           OldDecl = nullptr;
7639         }
7640       }
7641     }
7642   }
7643 
7644   // C++11 [dcl.constexpr]p8:
7645   //   A constexpr specifier for a non-static member function that is not
7646   //   a constructor declares that member function to be const.
7647   //
7648   // This needs to be delayed until we know whether this is an out-of-line
7649   // definition of a static member function.
7650   //
7651   // This rule is not present in C++1y, so we produce a backwards
7652   // compatibility warning whenever it happens in C++11.
7653   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7654   if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7655       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
7656       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7657     CXXMethodDecl *OldMD = nullptr;
7658     if (OldDecl)
7659       OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
7660     if (!OldMD || !OldMD->isStatic()) {
7661       const FunctionProtoType *FPT =
7662         MD->getType()->castAs<FunctionProtoType>();
7663       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7664       EPI.TypeQuals |= Qualifiers::Const;
7665       MD->setType(Context.getFunctionType(FPT->getReturnType(),
7666                                           FPT->getParamTypes(), EPI));
7667 
7668       // Warn that we did this, if we're not performing template instantiation.
7669       // In that case, we'll have warned already when the template was defined.
7670       if (ActiveTemplateInstantiations.empty()) {
7671         SourceLocation AddConstLoc;
7672         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7673                 .IgnoreParens().getAs<FunctionTypeLoc>())
7674           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
7675 
7676         Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7677           << FixItHint::CreateInsertion(AddConstLoc, " const");
7678       }
7679     }
7680   }
7681 
7682   if (Redeclaration) {
7683     // NewFD and OldDecl represent declarations that need to be
7684     // merged.
7685     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
7686       NewFD->setInvalidDecl();
7687       return Redeclaration;
7688     }
7689 
7690     Previous.clear();
7691     Previous.addDecl(OldDecl);
7692 
7693     if (FunctionTemplateDecl *OldTemplateDecl
7694                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7695       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7696       FunctionTemplateDecl *NewTemplateDecl
7697         = NewFD->getDescribedFunctionTemplate();
7698       assert(NewTemplateDecl && "Template/non-template mismatch");
7699       if (CXXMethodDecl *Method
7700             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7701         Method->setAccess(OldTemplateDecl->getAccess());
7702         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
7703       }
7704 
7705       // If this is an explicit specialization of a member that is a function
7706       // template, mark it as a member specialization.
7707       if (IsExplicitSpecialization &&
7708           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7709         NewTemplateDecl->setMemberSpecialization();
7710         assert(OldTemplateDecl->isMemberSpecialization());
7711       }
7712 
7713     } else {
7714       // This needs to happen first so that 'inline' propagates.
7715       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
7716 
7717       if (isa<CXXMethodDecl>(NewFD)) {
7718         // A valid redeclaration of a C++ method must be out-of-line,
7719         // but (unfortunately) it's not necessarily a definition
7720         // because of templates, which means that the previous
7721         // declaration is not necessarily from the class definition.
7722 
7723         // For just setting the access, that doesn't matter.
7724         CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7725         NewFD->setAccess(oldMethod->getAccess());
7726 
7727         // Update the key-function state if necessary for this ABI.
7728         if (NewFD->isInlined() &&
7729             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7730           // setNonKeyFunction needs to work with the original
7731           // declaration from the class definition, and isVirtual() is
7732           // just faster in that case, so map back to that now.
7733           oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
7734           if (oldMethod->isVirtual()) {
7735             Context.setNonKeyFunction(oldMethod);
7736           }
7737         }
7738       }
7739     }
7740   }
7741 
7742   // Semantic checking for this function declaration (in isolation).
7743   if (getLangOpts().CPlusPlus) {
7744     // C++-specific checks.
7745     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7746       CheckConstructor(Constructor);
7747     } else if (CXXDestructorDecl *Destructor =
7748                 dyn_cast<CXXDestructorDecl>(NewFD)) {
7749       CXXRecordDecl *Record = Destructor->getParent();
7750       QualType ClassType = Context.getTypeDeclType(Record);
7751 
7752       // FIXME: Shouldn't we be able to perform this check even when the class
7753       // type is dependent? Both gcc and edg can handle that.
7754       if (!ClassType->isDependentType()) {
7755         DeclarationName Name
7756           = Context.DeclarationNames.getCXXDestructorName(
7757                                         Context.getCanonicalType(ClassType));
7758         if (NewFD->getDeclName() != Name) {
7759           Diag(NewFD->getLocation(), diag::err_destructor_name);
7760           NewFD->setInvalidDecl();
7761           return Redeclaration;
7762         }
7763       }
7764     } else if (CXXConversionDecl *Conversion
7765                = dyn_cast<CXXConversionDecl>(NewFD)) {
7766       ActOnConversionDeclarator(Conversion);
7767     }
7768 
7769     // Find any virtual functions that this function overrides.
7770     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7771       if (!Method->isFunctionTemplateSpecialization() &&
7772           !Method->getDescribedFunctionTemplate() &&
7773           Method->isCanonicalDecl()) {
7774         if (AddOverriddenMethods(Method->getParent(), Method)) {
7775           // If the function was marked as "static", we have a problem.
7776           if (NewFD->getStorageClass() == SC_Static) {
7777             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
7778           }
7779         }
7780       }
7781 
7782       if (Method->isStatic())
7783         checkThisInStaticMemberFunctionType(Method);
7784     }
7785 
7786     // Extra checking for C++ overloaded operators (C++ [over.oper]).
7787     if (NewFD->isOverloadedOperator() &&
7788         CheckOverloadedOperatorDeclaration(NewFD)) {
7789       NewFD->setInvalidDecl();
7790       return Redeclaration;
7791     }
7792 
7793     // Extra checking for C++0x literal operators (C++0x [over.literal]).
7794     if (NewFD->getLiteralIdentifier() &&
7795         CheckLiteralOperatorDeclaration(NewFD)) {
7796       NewFD->setInvalidDecl();
7797       return Redeclaration;
7798     }
7799 
7800     // In C++, check default arguments now that we have merged decls. Unless
7801     // the lexical context is the class, because in this case this is done
7802     // during delayed parsing anyway.
7803     if (!CurContext->isRecord())
7804       CheckCXXDefaultArguments(NewFD);
7805 
7806     // If this function declares a builtin function, check the type of this
7807     // declaration against the expected type for the builtin.
7808     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7809       ASTContext::GetBuiltinTypeError Error;
7810       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
7811       QualType T = Context.GetBuiltinType(BuiltinID, Error);
7812       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7813         // The type of this function differs from the type of the builtin,
7814         // so forget about the builtin entirely.
7815         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7816       }
7817     }
7818 
7819     // If this function is declared as being extern "C", then check to see if
7820     // the function returns a UDT (class, struct, or union type) that is not C
7821     // compatible, and if it does, warn the user.
7822     // But, issue any diagnostic on the first declaration only.
7823     if (NewFD->isExternC() && Previous.empty()) {
7824       QualType R = NewFD->getReturnType();
7825       if (R->isIncompleteType() && !R->isVoidType())
7826         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7827             << NewFD << R;
7828       else if (!R.isPODType(Context) && !R->isVoidType() &&
7829                !R->isObjCObjectPointerType())
7830         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
7831     }
7832   }
7833   return Redeclaration;
7834 }
7835 
7836 static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7837   const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7838   if (!TSI)
7839     return SourceRange();
7840 
7841   TypeLoc TL = TSI->getTypeLoc();
7842   FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
7843   if (!FunctionTL)
7844     return SourceRange();
7845 
7846   TypeLoc ResultTL = FunctionTL.getReturnLoc();
7847   if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
7848     return ResultTL.getSourceRange();
7849 
7850   return SourceRange();
7851 }
7852 
7853 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
7854   // C++11 [basic.start.main]p3:
7855   //   A program that [...] declares main to be inline, static or
7856   //   constexpr is ill-formed.
7857   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
7858   //   appear in a declaration of main.
7859   // static main is not an error under C99, but we should warn about it.
7860   // We accept _Noreturn main as an extension.
7861   if (FD->getStorageClass() == SC_Static)
7862     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
7863          ? diag::err_static_main : diag::warn_static_main)
7864       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7865   if (FD->isInlineSpecified())
7866     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7867       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
7868   if (DS.isNoreturnSpecified()) {
7869     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7870     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
7871     Diag(NoreturnLoc, diag::ext_noreturn_main);
7872     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7873       << FixItHint::CreateRemoval(NoreturnRange);
7874   }
7875   if (FD->isConstexpr()) {
7876     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7877       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7878     FD->setConstexpr(false);
7879   }
7880 
7881   if (getLangOpts().OpenCL) {
7882     Diag(FD->getLocation(), diag::err_opencl_no_main)
7883         << FD->hasAttr<OpenCLKernelAttr>();
7884     FD->setInvalidDecl();
7885     return;
7886   }
7887 
7888   QualType T = FD->getType();
7889   assert(T->isFunctionType() && "function decl is not of function type");
7890   const FunctionType* FT = T->castAs<FunctionType>();
7891 
7892   // All the standards say that main() should should return 'int'.
7893   if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) {
7894     // In C and C++, main magically returns 0 if you fall off the end;
7895     // set the flag which tells us that.
7896     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7897     FD->setHasImplicitReturnZero(true);
7898 
7899   // In C with GNU extensions we allow main() to have non-integer return
7900   // type, but we should warn about the extension, and we disable the
7901   // implicit-return-zero rule.
7902   } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
7903     Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7904 
7905     SourceRange ResultRange = getResultSourceRange(FD);
7906     if (ResultRange.isValid())
7907       Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7908           << FixItHint::CreateReplacement(ResultRange, "int");
7909 
7910   // Otherwise, this is just a flat-out error.
7911   } else {
7912     SourceRange ResultRange = getResultSourceRange(FD);
7913     if (ResultRange.isValid())
7914       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7915           << FixItHint::CreateReplacement(ResultRange, "int");
7916     else
7917       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7918 
7919     FD->setInvalidDecl(true);
7920   }
7921 
7922   // Treat protoless main() as nullary.
7923   if (isa<FunctionNoProtoType>(FT)) return;
7924 
7925   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7926   unsigned nparams = FTP->getNumParams();
7927   assert(FD->getNumParams() == nparams);
7928 
7929   bool HasExtraParameters = (nparams > 3);
7930 
7931   // Darwin passes an undocumented fourth argument of type char**.  If
7932   // other platforms start sprouting these, the logic below will start
7933   // getting shifty.
7934   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
7935     HasExtraParameters = false;
7936 
7937   if (HasExtraParameters) {
7938     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7939     FD->setInvalidDecl(true);
7940     nparams = 3;
7941   }
7942 
7943   // FIXME: a lot of the following diagnostics would be improved
7944   // if we had some location information about types.
7945 
7946   QualType CharPP =
7947     Context.getPointerType(Context.getPointerType(Context.CharTy));
7948   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
7949 
7950   for (unsigned i = 0; i < nparams; ++i) {
7951     QualType AT = FTP->getParamType(i);
7952 
7953     bool mismatch = true;
7954 
7955     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7956       mismatch = false;
7957     else if (Expected[i] == CharPP) {
7958       // As an extension, the following forms are okay:
7959       //   char const **
7960       //   char const * const *
7961       //   char * const *
7962 
7963       QualifierCollector qs;
7964       const PointerType* PT;
7965       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7966           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
7967           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7968                               Context.CharTy)) {
7969         qs.removeConst();
7970         mismatch = !qs.empty();
7971       }
7972     }
7973 
7974     if (mismatch) {
7975       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7976       // TODO: suggest replacing given type with expected type
7977       FD->setInvalidDecl(true);
7978     }
7979   }
7980 
7981   if (nparams == 1 && !FD->isInvalidDecl()) {
7982     Diag(FD->getLocation(), diag::warn_main_one_arg);
7983   }
7984 
7985   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7986     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
7987     FD->setInvalidDecl();
7988   }
7989 }
7990 
7991 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7992   QualType T = FD->getType();
7993   assert(T->isFunctionType() && "function decl is not of function type");
7994   const FunctionType *FT = T->castAs<FunctionType>();
7995 
7996   // Set an implicit return of 'zero' if the function can return some integral,
7997   // enumeration, pointer or nullptr type.
7998   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
7999       FT->getReturnType()->isAnyPointerType() ||
8000       FT->getReturnType()->isNullPtrType())
8001     // DllMain is exempt because a return value of zero means it failed.
8002     if (FD->getName() != "DllMain")
8003       FD->setHasImplicitReturnZero(true);
8004 
8005   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8006     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8007     FD->setInvalidDecl();
8008   }
8009 }
8010 
8011 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8012   // FIXME: Need strict checking.  In C89, we need to check for
8013   // any assignment, increment, decrement, function-calls, or
8014   // commas outside of a sizeof.  In C99, it's the same list,
8015   // except that the aforementioned are allowed in unevaluated
8016   // expressions.  Everything else falls under the
8017   // "may accept other forms of constant expressions" exception.
8018   // (We never end up here for C++, so the constant expression
8019   // rules there don't matter.)
8020   const Expr *Culprit;
8021   if (Init->isConstantInitializer(Context, false, &Culprit))
8022     return false;
8023   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8024     << Culprit->getSourceRange();
8025   return true;
8026 }
8027 
8028 namespace {
8029   // Visits an initialization expression to see if OrigDecl is evaluated in
8030   // its own initialization and throws a warning if it does.
8031   class SelfReferenceChecker
8032       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8033     Sema &S;
8034     Decl *OrigDecl;
8035     bool isRecordType;
8036     bool isPODType;
8037     bool isReferenceType;
8038 
8039   public:
8040     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8041 
8042     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8043                                                     S(S), OrigDecl(OrigDecl) {
8044       isPODType = false;
8045       isRecordType = false;
8046       isReferenceType = false;
8047       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8048         isPODType = VD->getType().isPODType(S.Context);
8049         isRecordType = VD->getType()->isRecordType();
8050         isReferenceType = VD->getType()->isReferenceType();
8051       }
8052     }
8053 
8054     // For most expressions, the cast is directly above the DeclRefExpr.
8055     // For conditional operators, the cast can be outside the conditional
8056     // operator if both expressions are DeclRefExpr's.
8057     void HandleValue(Expr *E) {
8058       if (isReferenceType)
8059         return;
8060       E = E->IgnoreParenImpCasts();
8061       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8062         HandleDeclRefExpr(DRE);
8063         return;
8064       }
8065 
8066       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8067         HandleValue(CO->getTrueExpr());
8068         HandleValue(CO->getFalseExpr());
8069         return;
8070       }
8071 
8072       if (isa<MemberExpr>(E)) {
8073         Expr *Base = E->IgnoreParenImpCasts();
8074         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8075           // Check for static member variables and don't warn on them.
8076           if (!isa<FieldDecl>(ME->getMemberDecl()))
8077             return;
8078           Base = ME->getBase()->IgnoreParenImpCasts();
8079         }
8080         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8081           HandleDeclRefExpr(DRE);
8082         return;
8083       }
8084     }
8085 
8086     // Reference types are handled here since all uses of references are
8087     // bad, not just r-value uses.
8088     void VisitDeclRefExpr(DeclRefExpr *E) {
8089       if (isReferenceType)
8090         HandleDeclRefExpr(E);
8091     }
8092 
8093     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8094       if (E->getCastKind() == CK_LValueToRValue ||
8095           (isRecordType && E->getCastKind() == CK_NoOp))
8096         HandleValue(E->getSubExpr());
8097 
8098       Inherited::VisitImplicitCastExpr(E);
8099     }
8100 
8101     void VisitMemberExpr(MemberExpr *E) {
8102       // Don't warn on arrays since they can be treated as pointers.
8103       if (E->getType()->canDecayToPointerType()) return;
8104 
8105       // Warn when a non-static method call is followed by non-static member
8106       // field accesses, which is followed by a DeclRefExpr.
8107       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8108       bool Warn = (MD && !MD->isStatic());
8109       Expr *Base = E->getBase()->IgnoreParenImpCasts();
8110       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8111         if (!isa<FieldDecl>(ME->getMemberDecl()))
8112           Warn = false;
8113         Base = ME->getBase()->IgnoreParenImpCasts();
8114       }
8115 
8116       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8117         if (Warn)
8118           HandleDeclRefExpr(DRE);
8119         return;
8120       }
8121 
8122       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8123       // Visit that expression.
8124       Visit(Base);
8125     }
8126 
8127     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8128       if (E->getNumArgs() > 0)
8129         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
8130           HandleDeclRefExpr(DRE);
8131 
8132       Inherited::VisitCXXOperatorCallExpr(E);
8133     }
8134 
8135     void VisitUnaryOperator(UnaryOperator *E) {
8136       // For POD record types, addresses of its own members are well-defined.
8137       if (E->getOpcode() == UO_AddrOf && isRecordType &&
8138           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8139         if (!isPODType)
8140           HandleValue(E->getSubExpr());
8141         return;
8142       }
8143       Inherited::VisitUnaryOperator(E);
8144     }
8145 
8146     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8147 
8148     void HandleDeclRefExpr(DeclRefExpr *DRE) {
8149       Decl* ReferenceDecl = DRE->getDecl();
8150       if (OrigDecl != ReferenceDecl) return;
8151       unsigned diag;
8152       if (isReferenceType) {
8153         diag = diag::warn_uninit_self_reference_in_reference_init;
8154       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8155         diag = diag::warn_static_self_reference_in_init;
8156       } else {
8157         diag = diag::warn_uninit_self_reference_in_init;
8158       }
8159 
8160       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
8161                             S.PDiag(diag)
8162                               << DRE->getNameInfo().getName()
8163                               << OrigDecl->getLocation()
8164                               << DRE->getSourceRange());
8165     }
8166   };
8167 
8168   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8169   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8170                                  bool DirectInit) {
8171     // Parameters arguments are occassionially constructed with itself,
8172     // for instance, in recursive functions.  Skip them.
8173     if (isa<ParmVarDecl>(OrigDecl))
8174       return;
8175 
8176     E = E->IgnoreParens();
8177 
8178     // Skip checking T a = a where T is not a record or reference type.
8179     // Doing so is a way to silence uninitialized warnings.
8180     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8181       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8182         if (ICE->getCastKind() == CK_LValueToRValue)
8183           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8184             if (DRE->getDecl() == OrigDecl)
8185               return;
8186 
8187     SelfReferenceChecker(S, OrigDecl).Visit(E);
8188   }
8189 }
8190 
8191 /// AddInitializerToDecl - Adds the initializer Init to the
8192 /// declaration dcl. If DirectInit is true, this is C++ direct
8193 /// initialization rather than copy initialization.
8194 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8195                                 bool DirectInit, bool TypeMayContainAuto) {
8196   // If there is no declaration, there was an error parsing it.  Just ignore
8197   // the initializer.
8198   if (!RealDecl || RealDecl->isInvalidDecl())
8199     return;
8200 
8201   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8202     // With declarators parsed the way they are, the parser cannot
8203     // distinguish between a normal initializer and a pure-specifier.
8204     // Thus this grotesque test.
8205     IntegerLiteral *IL;
8206     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
8207         Context.getCanonicalType(IL->getType()) == Context.IntTy)
8208       CheckPureMethod(Method, Init->getSourceRange());
8209     else {
8210       Diag(Method->getLocation(), diag::err_member_function_initialization)
8211         << Method->getDeclName() << Init->getSourceRange();
8212       Method->setInvalidDecl();
8213     }
8214     return;
8215   }
8216 
8217   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8218   if (!VDecl) {
8219     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8220     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8221     RealDecl->setInvalidDecl();
8222     return;
8223   }
8224   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8225 
8226   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8227   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8228     Expr *DeduceInit = Init;
8229     // Initializer could be a C++ direct-initializer. Deduction only works if it
8230     // contains exactly one expression.
8231     if (CXXDirectInit) {
8232       if (CXXDirectInit->getNumExprs() == 0) {
8233         // It isn't possible to write this directly, but it is possible to
8234         // end up in this situation with "auto x(some_pack...);"
8235         Diag(CXXDirectInit->getLocStart(),
8236              VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8237                                     : diag::err_auto_var_init_no_expression)
8238           << VDecl->getDeclName() << VDecl->getType()
8239           << VDecl->getSourceRange();
8240         RealDecl->setInvalidDecl();
8241         return;
8242       } else if (CXXDirectInit->getNumExprs() > 1) {
8243         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8244              VDecl->isInitCapture()
8245                  ? diag::err_init_capture_multiple_expressions
8246                  : diag::err_auto_var_init_multiple_expressions)
8247           << VDecl->getDeclName() << VDecl->getType()
8248           << VDecl->getSourceRange();
8249         RealDecl->setInvalidDecl();
8250         return;
8251       } else {
8252         DeduceInit = CXXDirectInit->getExpr(0);
8253         if (isa<InitListExpr>(DeduceInit))
8254           Diag(CXXDirectInit->getLocStart(),
8255                diag::err_auto_var_init_paren_braces)
8256             << VDecl->getDeclName() << VDecl->getType()
8257             << VDecl->getSourceRange();
8258       }
8259     }
8260 
8261     // Expressions default to 'id' when we're in a debugger.
8262     bool DefaultedToAuto = false;
8263     if (getLangOpts().DebuggerCastResultToId &&
8264         Init->getType() == Context.UnknownAnyTy) {
8265       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8266       if (Result.isInvalid()) {
8267         VDecl->setInvalidDecl();
8268         return;
8269       }
8270       Init = Result.get();
8271       DefaultedToAuto = true;
8272     }
8273 
8274     QualType DeducedType;
8275     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8276             DAR_Failed)
8277       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8278     if (DeducedType.isNull()) {
8279       RealDecl->setInvalidDecl();
8280       return;
8281     }
8282     VDecl->setType(DeducedType);
8283     assert(VDecl->isLinkageValid());
8284 
8285     // In ARC, infer lifetime.
8286     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8287       VDecl->setInvalidDecl();
8288 
8289     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8290     // 'id' instead of a specific object type prevents most of our usual checks.
8291     // We only want to warn outside of template instantiations, though:
8292     // inside a template, the 'id' could have come from a parameter.
8293     if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8294         DeducedType->isObjCIdType()) {
8295       SourceLocation Loc =
8296           VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8297       Diag(Loc, diag::warn_auto_var_is_id)
8298         << VDecl->getDeclName() << DeduceInit->getSourceRange();
8299     }
8300 
8301     // If this is a redeclaration, check that the type we just deduced matches
8302     // the previously declared type.
8303     if (VarDecl *Old = VDecl->getPreviousDecl()) {
8304       // We never need to merge the type, because we cannot form an incomplete
8305       // array of auto, nor deduce such a type.
8306       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8307     }
8308 
8309     // Check the deduced type is valid for a variable declaration.
8310     CheckVariableDeclarationType(VDecl);
8311     if (VDecl->isInvalidDecl())
8312       return;
8313   }
8314 
8315   // dllimport cannot be used on variable definitions.
8316   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8317     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8318     VDecl->setInvalidDecl();
8319     return;
8320   }
8321 
8322   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8323     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8324     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8325     VDecl->setInvalidDecl();
8326     return;
8327   }
8328 
8329   if (!VDecl->getType()->isDependentType()) {
8330     // A definition must end up with a complete type, which means it must be
8331     // complete with the restriction that an array type might be completed by
8332     // the initializer; note that later code assumes this restriction.
8333     QualType BaseDeclType = VDecl->getType();
8334     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8335       BaseDeclType = Array->getElementType();
8336     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8337                             diag::err_typecheck_decl_incomplete_type)) {
8338       RealDecl->setInvalidDecl();
8339       return;
8340     }
8341 
8342     // The variable can not have an abstract class type.
8343     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8344                                diag::err_abstract_type_in_decl,
8345                                AbstractVariableType))
8346       VDecl->setInvalidDecl();
8347   }
8348 
8349   const VarDecl *Def;
8350   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8351     Diag(VDecl->getLocation(), diag::err_redefinition)
8352       << VDecl->getDeclName();
8353     Diag(Def->getLocation(), diag::note_previous_definition);
8354     VDecl->setInvalidDecl();
8355     return;
8356   }
8357 
8358   const VarDecl *PrevInit = nullptr;
8359   if (getLangOpts().CPlusPlus) {
8360     // C++ [class.static.data]p4
8361     //   If a static data member is of const integral or const
8362     //   enumeration type, its declaration in the class definition can
8363     //   specify a constant-initializer which shall be an integral
8364     //   constant expression (5.19). In that case, the member can appear
8365     //   in integral constant expressions. The member shall still be
8366     //   defined in a namespace scope if it is used in the program and the
8367     //   namespace scope definition shall not contain an initializer.
8368     //
8369     // We already performed a redefinition check above, but for static
8370     // data members we also need to check whether there was an in-class
8371     // declaration with an initializer.
8372     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8373       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8374           << VDecl->getDeclName();
8375       Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
8376       return;
8377     }
8378 
8379     if (VDecl->hasLocalStorage())
8380       getCurFunction()->setHasBranchProtectedScope();
8381 
8382     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8383       VDecl->setInvalidDecl();
8384       return;
8385     }
8386   }
8387 
8388   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8389   // a kernel function cannot be initialized."
8390   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8391     Diag(VDecl->getLocation(), diag::err_local_cant_init);
8392     VDecl->setInvalidDecl();
8393     return;
8394   }
8395 
8396   // Get the decls type and save a reference for later, since
8397   // CheckInitializerTypes may change it.
8398   QualType DclT = VDecl->getType(), SavT = DclT;
8399 
8400   // Expressions default to 'id' when we're in a debugger
8401   // and we are assigning it to a variable of Objective-C pointer type.
8402   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8403       Init->getType() == Context.UnknownAnyTy) {
8404     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8405     if (Result.isInvalid()) {
8406       VDecl->setInvalidDecl();
8407       return;
8408     }
8409     Init = Result.get();
8410   }
8411 
8412   // Perform the initialization.
8413   if (!VDecl->isInvalidDecl()) {
8414     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8415     InitializationKind Kind
8416       = DirectInit ?
8417           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8418                                                            Init->getLocStart(),
8419                                                            Init->getLocEnd())
8420                         : InitializationKind::CreateDirectList(
8421                                                           VDecl->getLocation())
8422                    : InitializationKind::CreateCopy(VDecl->getLocation(),
8423                                                     Init->getLocStart());
8424 
8425     MultiExprArg Args = Init;
8426     if (CXXDirectInit)
8427       Args = MultiExprArg(CXXDirectInit->getExprs(),
8428                           CXXDirectInit->getNumExprs());
8429 
8430     InitializationSequence InitSeq(*this, Entity, Kind, Args);
8431     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8432     if (Result.isInvalid()) {
8433       VDecl->setInvalidDecl();
8434       return;
8435     }
8436 
8437     Init = Result.getAs<Expr>();
8438   }
8439 
8440   // Check for self-references within variable initializers.
8441   // Variables declared within a function/method body (except for references)
8442   // are handled by a dataflow analysis.
8443   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8444       VDecl->getType()->isReferenceType()) {
8445     CheckSelfReference(*this, RealDecl, Init, DirectInit);
8446   }
8447 
8448   // If the type changed, it means we had an incomplete type that was
8449   // completed by the initializer. For example:
8450   //   int ary[] = { 1, 3, 5 };
8451   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
8452   if (!VDecl->isInvalidDecl() && (DclT != SavT))
8453     VDecl->setType(DclT);
8454 
8455   if (!VDecl->isInvalidDecl()) {
8456     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8457 
8458     if (VDecl->hasAttr<BlocksAttr>())
8459       checkRetainCycles(VDecl, Init);
8460 
8461     // It is safe to assign a weak reference into a strong variable.
8462     // Although this code can still have problems:
8463     //   id x = self.weakProp;
8464     //   id y = self.weakProp;
8465     // we do not warn to warn spuriously when 'x' and 'y' are on separate
8466     // paths through the function. This should be revisited if
8467     // -Wrepeated-use-of-weak is made flow-sensitive.
8468     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
8469         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8470                          Init->getLocStart()))
8471         getCurFunction()->markSafeWeakUse(Init);
8472   }
8473 
8474   // The initialization is usually a full-expression.
8475   //
8476   // FIXME: If this is a braced initialization of an aggregate, it is not
8477   // an expression, and each individual field initializer is a separate
8478   // full-expression. For instance, in:
8479   //
8480   //   struct Temp { ~Temp(); };
8481   //   struct S { S(Temp); };
8482   //   struct T { S a, b; } t = { Temp(), Temp() }
8483   //
8484   // we should destroy the first Temp before constructing the second.
8485   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8486                                           false,
8487                                           VDecl->isConstexpr());
8488   if (Result.isInvalid()) {
8489     VDecl->setInvalidDecl();
8490     return;
8491   }
8492   Init = Result.get();
8493 
8494   // Attach the initializer to the decl.
8495   VDecl->setInit(Init);
8496 
8497   if (VDecl->isLocalVarDecl()) {
8498     // C99 6.7.8p4: All the expressions in an initializer for an object that has
8499     // static storage duration shall be constant expressions or string literals.
8500     // C++ does not have this restriction.
8501     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8502       const Expr *Culprit;
8503       if (VDecl->getStorageClass() == SC_Static)
8504         CheckForConstantInitializer(Init, DclT);
8505       // C89 is stricter than C99 for non-static aggregate types.
8506       // C89 6.5.7p3: All the expressions [...] in an initializer list
8507       // for an object that has aggregate or union type shall be
8508       // constant expressions.
8509       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
8510                isa<InitListExpr>(Init) &&
8511                !Init->isConstantInitializer(Context, false, &Culprit))
8512         Diag(Culprit->getExprLoc(),
8513              diag::ext_aggregate_init_not_constant)
8514           << Culprit->getSourceRange();
8515     }
8516   } else if (VDecl->isStaticDataMember() &&
8517              VDecl->getLexicalDeclContext()->isRecord()) {
8518     // This is an in-class initialization for a static data member, e.g.,
8519     //
8520     // struct S {
8521     //   static const int value = 17;
8522     // };
8523 
8524     // C++ [class.mem]p4:
8525     //   A member-declarator can contain a constant-initializer only
8526     //   if it declares a static member (9.4) of const integral or
8527     //   const enumeration type, see 9.4.2.
8528     //
8529     // C++11 [class.static.data]p3:
8530     //   If a non-volatile const static data member is of integral or
8531     //   enumeration type, its declaration in the class definition can
8532     //   specify a brace-or-equal-initializer in which every initalizer-clause
8533     //   that is an assignment-expression is a constant expression. A static
8534     //   data member of literal type can be declared in the class definition
8535     //   with the constexpr specifier; if so, its declaration shall specify a
8536     //   brace-or-equal-initializer in which every initializer-clause that is
8537     //   an assignment-expression is a constant expression.
8538 
8539     // Do nothing on dependent types.
8540     if (DclT->isDependentType()) {
8541 
8542     // Allow any 'static constexpr' members, whether or not they are of literal
8543     // type. We separately check that every constexpr variable is of literal
8544     // type.
8545     } else if (VDecl->isConstexpr()) {
8546 
8547     // Require constness.
8548     } else if (!DclT.isConstQualified()) {
8549       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8550         << Init->getSourceRange();
8551       VDecl->setInvalidDecl();
8552 
8553     // We allow integer constant expressions in all cases.
8554     } else if (DclT->isIntegralOrEnumerationType()) {
8555       // Check whether the expression is a constant expression.
8556       SourceLocation Loc;
8557       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
8558         // In C++11, a non-constexpr const static data member with an
8559         // in-class initializer cannot be volatile.
8560         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8561       else if (Init->isValueDependent())
8562         ; // Nothing to check.
8563       else if (Init->isIntegerConstantExpr(Context, &Loc))
8564         ; // Ok, it's an ICE!
8565       else if (Init->isEvaluatable(Context)) {
8566         // If we can constant fold the initializer through heroics, accept it,
8567         // but report this as a use of an extension for -pedantic.
8568         Diag(Loc, diag::ext_in_class_initializer_non_constant)
8569           << Init->getSourceRange();
8570       } else {
8571         // Otherwise, this is some crazy unknown case.  Report the issue at the
8572         // location provided by the isIntegerConstantExpr failed check.
8573         Diag(Loc, diag::err_in_class_initializer_non_constant)
8574           << Init->getSourceRange();
8575         VDecl->setInvalidDecl();
8576       }
8577 
8578     // We allow foldable floating-point constants as an extension.
8579     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
8580       // In C++98, this is a GNU extension. In C++11, it is not, but we support
8581       // it anyway and provide a fixit to add the 'constexpr'.
8582       if (getLangOpts().CPlusPlus11) {
8583         Diag(VDecl->getLocation(),
8584              diag::ext_in_class_initializer_float_type_cxx11)
8585             << DclT << Init->getSourceRange();
8586         Diag(VDecl->getLocStart(),
8587              diag::note_in_class_initializer_float_type_cxx11)
8588             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8589       } else {
8590         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8591           << DclT << Init->getSourceRange();
8592 
8593         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8594           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8595             << Init->getSourceRange();
8596           VDecl->setInvalidDecl();
8597         }
8598       }
8599 
8600     // Suggest adding 'constexpr' in C++11 for literal types.
8601     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
8602       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
8603         << DclT << Init->getSourceRange()
8604         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8605       VDecl->setConstexpr(true);
8606 
8607     } else {
8608       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
8609         << DclT << Init->getSourceRange();
8610       VDecl->setInvalidDecl();
8611     }
8612   } else if (VDecl->isFileVarDecl()) {
8613     if (VDecl->getStorageClass() == SC_Extern &&
8614         (!getLangOpts().CPlusPlus ||
8615          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
8616            VDecl->isExternC())) &&
8617         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
8618       Diag(VDecl->getLocation(), diag::warn_extern_init);
8619 
8620     // C99 6.7.8p4. All file scoped initializers need to be constant.
8621     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
8622       CheckForConstantInitializer(Init, DclT);
8623   }
8624 
8625   // We will represent direct-initialization similarly to copy-initialization:
8626   //    int x(1);  -as-> int x = 1;
8627   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8628   //
8629   // Clients that want to distinguish between the two forms, can check for
8630   // direct initializer using VarDecl::getInitStyle().
8631   // A major benefit is that clients that don't particularly care about which
8632   // exactly form was it (like the CodeGen) can handle both cases without
8633   // special case code.
8634 
8635   // C++ 8.5p11:
8636   // The form of initialization (using parentheses or '=') is generally
8637   // insignificant, but does matter when the entity being initialized has a
8638   // class type.
8639   if (CXXDirectInit) {
8640     assert(DirectInit && "Call-style initializer must be direct init.");
8641     VDecl->setInitStyle(VarDecl::CallInit);
8642   } else if (DirectInit) {
8643     // This must be list-initialization. No other way is direct-initialization.
8644     VDecl->setInitStyle(VarDecl::ListInit);
8645   }
8646 
8647   CheckCompleteVariableDeclaration(VDecl);
8648 }
8649 
8650 /// ActOnInitializerError - Given that there was an error parsing an
8651 /// initializer for the given declaration, try to return to some form
8652 /// of sanity.
8653 void Sema::ActOnInitializerError(Decl *D) {
8654   // Our main concern here is re-establishing invariants like "a
8655   // variable's type is either dependent or complete".
8656   if (!D || D->isInvalidDecl()) return;
8657 
8658   VarDecl *VD = dyn_cast<VarDecl>(D);
8659   if (!VD) return;
8660 
8661   // Auto types are meaningless if we can't make sense of the initializer.
8662   if (ParsingInitForAutoVars.count(D)) {
8663     D->setInvalidDecl();
8664     return;
8665   }
8666 
8667   QualType Ty = VD->getType();
8668   if (Ty->isDependentType()) return;
8669 
8670   // Require a complete type.
8671   if (RequireCompleteType(VD->getLocation(),
8672                           Context.getBaseElementType(Ty),
8673                           diag::err_typecheck_decl_incomplete_type)) {
8674     VD->setInvalidDecl();
8675     return;
8676   }
8677 
8678   // Require a non-abstract type.
8679   if (RequireNonAbstractType(VD->getLocation(), Ty,
8680                              diag::err_abstract_type_in_decl,
8681                              AbstractVariableType)) {
8682     VD->setInvalidDecl();
8683     return;
8684   }
8685 
8686   // Don't bother complaining about constructors or destructors,
8687   // though.
8688 }
8689 
8690 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
8691                                   bool TypeMayContainAuto) {
8692   // If there is no declaration, there was an error parsing it. Just ignore it.
8693   if (!RealDecl)
8694     return;
8695 
8696   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8697     QualType Type = Var->getType();
8698 
8699     // C++11 [dcl.spec.auto]p3
8700     if (TypeMayContainAuto && Type->getContainedAutoType()) {
8701       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8702         << Var->getDeclName() << Type;
8703       Var->setInvalidDecl();
8704       return;
8705     }
8706 
8707     // C++11 [class.static.data]p3: A static data member can be declared with
8708     // the constexpr specifier; if so, its declaration shall specify
8709     // a brace-or-equal-initializer.
8710     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8711     // the definition of a variable [...] or the declaration of a static data
8712     // member.
8713     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8714       if (Var->isStaticDataMember())
8715         Diag(Var->getLocation(),
8716              diag::err_constexpr_static_mem_var_requires_init)
8717           << Var->getDeclName();
8718       else
8719         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
8720       Var->setInvalidDecl();
8721       return;
8722     }
8723 
8724     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
8725     // be initialized.
8726     if (!Var->isInvalidDecl() &&
8727         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
8728         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
8729       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
8730       Var->setInvalidDecl();
8731       return;
8732     }
8733 
8734     switch (Var->isThisDeclarationADefinition()) {
8735     case VarDecl::Definition:
8736       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8737         break;
8738 
8739       // We have an out-of-line definition of a static data member
8740       // that has an in-class initializer, so we type-check this like
8741       // a declaration.
8742       //
8743       // Fall through
8744 
8745     case VarDecl::DeclarationOnly:
8746       // It's only a declaration.
8747 
8748       // Block scope. C99 6.7p7: If an identifier for an object is
8749       // declared with no linkage (C99 6.2.2p6), the type for the
8750       // object shall be complete.
8751       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
8752           !Var->hasLinkage() && !Var->isInvalidDecl() &&
8753           RequireCompleteType(Var->getLocation(), Type,
8754                               diag::err_typecheck_decl_incomplete_type))
8755         Var->setInvalidDecl();
8756 
8757       // Make sure that the type is not abstract.
8758       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8759           RequireNonAbstractType(Var->getLocation(), Type,
8760                                  diag::err_abstract_type_in_decl,
8761                                  AbstractVariableType))
8762         Var->setInvalidDecl();
8763       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8764           Var->getStorageClass() == SC_PrivateExtern) {
8765         Diag(Var->getLocation(), diag::warn_private_extern);
8766         Diag(Var->getLocation(), diag::note_private_extern);
8767       }
8768 
8769       return;
8770 
8771     case VarDecl::TentativeDefinition:
8772       // File scope. C99 6.9.2p2: A declaration of an identifier for an
8773       // object that has file scope without an initializer, and without a
8774       // storage-class specifier or with the storage-class specifier "static",
8775       // constitutes a tentative definition. Note: A tentative definition with
8776       // external linkage is valid (C99 6.2.2p5).
8777       if (!Var->isInvalidDecl()) {
8778         if (const IncompleteArrayType *ArrayT
8779                                     = Context.getAsIncompleteArrayType(Type)) {
8780           if (RequireCompleteType(Var->getLocation(),
8781                                   ArrayT->getElementType(),
8782                                   diag::err_illegal_decl_array_incomplete_type))
8783             Var->setInvalidDecl();
8784         } else if (Var->getStorageClass() == SC_Static) {
8785           // C99 6.9.2p3: If the declaration of an identifier for an object is
8786           // a tentative definition and has internal linkage (C99 6.2.2p3), the
8787           // declared type shall not be an incomplete type.
8788           // NOTE: code such as the following
8789           //     static struct s;
8790           //     struct s { int a; };
8791           // is accepted by gcc. Hence here we issue a warning instead of
8792           // an error and we do not invalidate the static declaration.
8793           // NOTE: to avoid multiple warnings, only check the first declaration.
8794           if (Var->isFirstDecl())
8795             RequireCompleteType(Var->getLocation(), Type,
8796                                 diag::ext_typecheck_decl_incomplete_type);
8797         }
8798       }
8799 
8800       // Record the tentative definition; we're done.
8801       if (!Var->isInvalidDecl())
8802         TentativeDefinitions.push_back(Var);
8803       return;
8804     }
8805 
8806     // Provide a specific diagnostic for uninitialized variable
8807     // definitions with incomplete array type.
8808     if (Type->isIncompleteArrayType()) {
8809       Diag(Var->getLocation(),
8810            diag::err_typecheck_incomplete_array_needs_initializer);
8811       Var->setInvalidDecl();
8812       return;
8813     }
8814 
8815     // Provide a specific diagnostic for uninitialized variable
8816     // definitions with reference type.
8817     if (Type->isReferenceType()) {
8818       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8819         << Var->getDeclName()
8820         << SourceRange(Var->getLocation(), Var->getLocation());
8821       Var->setInvalidDecl();
8822       return;
8823     }
8824 
8825     // Do not attempt to type-check the default initializer for a
8826     // variable with dependent type.
8827     if (Type->isDependentType())
8828       return;
8829 
8830     if (Var->isInvalidDecl())
8831       return;
8832 
8833     if (RequireCompleteType(Var->getLocation(),
8834                             Context.getBaseElementType(Type),
8835                             diag::err_typecheck_decl_incomplete_type)) {
8836       Var->setInvalidDecl();
8837       return;
8838     }
8839 
8840     // The variable can not have an abstract class type.
8841     if (RequireNonAbstractType(Var->getLocation(), Type,
8842                                diag::err_abstract_type_in_decl,
8843                                AbstractVariableType)) {
8844       Var->setInvalidDecl();
8845       return;
8846     }
8847 
8848     // Check for jumps past the implicit initializer.  C++0x
8849     // clarifies that this applies to a "variable with automatic
8850     // storage duration", not a "local variable".
8851     // C++11 [stmt.dcl]p3
8852     //   A program that jumps from a point where a variable with automatic
8853     //   storage duration is not in scope to a point where it is in scope is
8854     //   ill-formed unless the variable has scalar type, class type with a
8855     //   trivial default constructor and a trivial destructor, a cv-qualified
8856     //   version of one of these types, or an array of one of the preceding
8857     //   types and is declared without an initializer.
8858     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
8859       if (const RecordType *Record
8860             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
8861         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
8862         // Mark the function for further checking even if the looser rules of
8863         // C++11 do not require such checks, so that we can diagnose
8864         // incompatibilities with C++98.
8865         if (!CXXRecord->isPOD())
8866           getCurFunction()->setHasBranchProtectedScope();
8867       }
8868     }
8869 
8870     // C++03 [dcl.init]p9:
8871     //   If no initializer is specified for an object, and the
8872     //   object is of (possibly cv-qualified) non-POD class type (or
8873     //   array thereof), the object shall be default-initialized; if
8874     //   the object is of const-qualified type, the underlying class
8875     //   type shall have a user-declared default
8876     //   constructor. Otherwise, if no initializer is specified for
8877     //   a non- static object, the object and its subobjects, if
8878     //   any, have an indeterminate initial value); if the object
8879     //   or any of its subobjects are of const-qualified type, the
8880     //   program is ill-formed.
8881     // C++0x [dcl.init]p11:
8882     //   If no initializer is specified for an object, the object is
8883     //   default-initialized; [...].
8884     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8885     InitializationKind Kind
8886       = InitializationKind::CreateDefault(Var->getLocation());
8887 
8888     InitializationSequence InitSeq(*this, Entity, Kind, None);
8889     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
8890     if (Init.isInvalid())
8891       Var->setInvalidDecl();
8892     else if (Init.get()) {
8893       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
8894       // This is important for template substitution.
8895       Var->setInitStyle(VarDecl::CallInit);
8896     }
8897 
8898     CheckCompleteVariableDeclaration(Var);
8899   }
8900 }
8901 
8902 void Sema::ActOnCXXForRangeDecl(Decl *D) {
8903   VarDecl *VD = dyn_cast<VarDecl>(D);
8904   if (!VD) {
8905     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8906     D->setInvalidDecl();
8907     return;
8908   }
8909 
8910   VD->setCXXForRangeDecl(true);
8911 
8912   // for-range-declaration cannot be given a storage class specifier.
8913   int Error = -1;
8914   switch (VD->getStorageClass()) {
8915   case SC_None:
8916     break;
8917   case SC_Extern:
8918     Error = 0;
8919     break;
8920   case SC_Static:
8921     Error = 1;
8922     break;
8923   case SC_PrivateExtern:
8924     Error = 2;
8925     break;
8926   case SC_Auto:
8927     Error = 3;
8928     break;
8929   case SC_Register:
8930     Error = 4;
8931     break;
8932   case SC_OpenCLWorkGroupLocal:
8933     llvm_unreachable("Unexpected storage class");
8934   }
8935   if (VD->isConstexpr())
8936     Error = 5;
8937   if (Error != -1) {
8938     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8939       << VD->getDeclName() << Error;
8940     D->setInvalidDecl();
8941   }
8942 }
8943 
8944 StmtResult
8945 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
8946                                  IdentifierInfo *Ident,
8947                                  ParsedAttributes &Attrs,
8948                                  SourceLocation AttrEnd) {
8949   // C++1y [stmt.iter]p1:
8950   //   A range-based for statement of the form
8951   //      for ( for-range-identifier : for-range-initializer ) statement
8952   //   is equivalent to
8953   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
8954   DeclSpec DS(Attrs.getPool().getFactory());
8955 
8956   const char *PrevSpec;
8957   unsigned DiagID;
8958   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
8959                      getPrintingPolicy());
8960 
8961   Declarator D(DS, Declarator::ForContext);
8962   D.SetIdentifier(Ident, IdentLoc);
8963   D.takeAttributes(Attrs, AttrEnd);
8964 
8965   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
8966   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
8967                 EmptyAttrs, IdentLoc);
8968   Decl *Var = ActOnDeclarator(S, D);
8969   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
8970   FinalizeDeclaration(Var);
8971   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
8972                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
8973 }
8974 
8975 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8976   if (var->isInvalidDecl()) return;
8977 
8978   // In ARC, don't allow jumps past the implicit initialization of a
8979   // local retaining variable.
8980   if (getLangOpts().ObjCAutoRefCount &&
8981       var->hasLocalStorage()) {
8982     switch (var->getType().getObjCLifetime()) {
8983     case Qualifiers::OCL_None:
8984     case Qualifiers::OCL_ExplicitNone:
8985     case Qualifiers::OCL_Autoreleasing:
8986       break;
8987 
8988     case Qualifiers::OCL_Weak:
8989     case Qualifiers::OCL_Strong:
8990       getCurFunction()->setHasBranchProtectedScope();
8991       break;
8992     }
8993   }
8994 
8995   // Warn about externally-visible variables being defined without a
8996   // prior declaration.  We only want to do this for global
8997   // declarations, but we also specifically need to avoid doing it for
8998   // class members because the linkage of an anonymous class can
8999   // change if it's later given a typedef name.
9000   if (var->isThisDeclarationADefinition() &&
9001       var->getDeclContext()->getRedeclContext()->isFileContext() &&
9002       var->isExternallyVisible() && var->hasLinkage() &&
9003       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9004                                   var->getLocation())) {
9005     // Find a previous declaration that's not a definition.
9006     VarDecl *prev = var->getPreviousDecl();
9007     while (prev && prev->isThisDeclarationADefinition())
9008       prev = prev->getPreviousDecl();
9009 
9010     if (!prev)
9011       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9012   }
9013 
9014   if (var->getTLSKind() == VarDecl::TLS_Static) {
9015     const Expr *Culprit;
9016     if (var->getType().isDestructedType()) {
9017       // GNU C++98 edits for __thread, [basic.start.term]p3:
9018       //   The type of an object with thread storage duration shall not
9019       //   have a non-trivial destructor.
9020       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9021       if (getLangOpts().CPlusPlus11)
9022         Diag(var->getLocation(), diag::note_use_thread_local);
9023     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9024                !var->getInit()->isConstantInitializer(
9025                    Context, var->getType()->isReferenceType(), &Culprit)) {
9026       // GNU C++98 edits for __thread, [basic.start.init]p4:
9027       //   An object of thread storage duration shall not require dynamic
9028       //   initialization.
9029       // FIXME: Need strict checking here.
9030       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9031         << Culprit->getSourceRange();
9032       if (getLangOpts().CPlusPlus11)
9033         Diag(var->getLocation(), diag::note_use_thread_local);
9034     }
9035 
9036   }
9037 
9038   if (var->isThisDeclarationADefinition() &&
9039       ActiveTemplateInstantiations.empty()) {
9040     PragmaStack<StringLiteral *> *Stack = nullptr;
9041     int SectionFlags = PSF_Implicit | PSF_Read;
9042     if (var->getType().isConstQualified())
9043       Stack = &ConstSegStack;
9044     else if (!var->getInit()) {
9045       Stack = &BSSSegStack;
9046       SectionFlags |= PSF_Write;
9047     } else {
9048       Stack = &DataSegStack;
9049       SectionFlags |= PSF_Write;
9050     }
9051     if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue)
9052       var->addAttr(
9053           SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
9054                                       Stack->CurrentValue->getString(),
9055                                       Stack->CurrentPragmaLocation));
9056     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
9057       if (UnifySection(SA->getName(), SectionFlags, var))
9058         var->dropAttr<SectionAttr>();
9059   }
9060 
9061   // All the following checks are C++ only.
9062   if (!getLangOpts().CPlusPlus) return;
9063 
9064   QualType type = var->getType();
9065   if (type->isDependentType()) return;
9066 
9067   // __block variables might require us to capture a copy-initializer.
9068   if (var->hasAttr<BlocksAttr>()) {
9069     // It's currently invalid to ever have a __block variable with an
9070     // array type; should we diagnose that here?
9071 
9072     // Regardless, we don't want to ignore array nesting when
9073     // constructing this copy.
9074     if (type->isStructureOrClassType()) {
9075       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
9076       SourceLocation poi = var->getLocation();
9077       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
9078       ExprResult result
9079         = PerformMoveOrCopyInitialization(
9080             InitializedEntity::InitializeBlock(poi, type, false),
9081             var, var->getType(), varRef, /*AllowNRVO=*/true);
9082       if (!result.isInvalid()) {
9083         result = MaybeCreateExprWithCleanups(result);
9084         Expr *init = result.getAs<Expr>();
9085         Context.setBlockVarCopyInits(var, init);
9086       }
9087     }
9088   }
9089 
9090   Expr *Init = var->getInit();
9091   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
9092   QualType baseType = Context.getBaseElementType(type);
9093 
9094   if (!var->getDeclContext()->isDependentContext() &&
9095       Init && !Init->isValueDependent()) {
9096     if (IsGlobal && !var->isConstexpr() &&
9097         !getDiagnostics().isIgnored(diag::warn_global_constructor,
9098                                     var->getLocation())) {
9099       // Warn about globals which don't have a constant initializer.  Don't
9100       // warn about globals with a non-trivial destructor because we already
9101       // warned about them.
9102       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
9103       if (!(RD && !RD->hasTrivialDestructor()) &&
9104           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
9105         Diag(var->getLocation(), diag::warn_global_constructor)
9106           << Init->getSourceRange();
9107     }
9108 
9109     if (var->isConstexpr()) {
9110       SmallVector<PartialDiagnosticAt, 8> Notes;
9111       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
9112         SourceLocation DiagLoc = var->getLocation();
9113         // If the note doesn't add any useful information other than a source
9114         // location, fold it into the primary diagnostic.
9115         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9116               diag::note_invalid_subexpr_in_const_expr) {
9117           DiagLoc = Notes[0].first;
9118           Notes.clear();
9119         }
9120         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
9121           << var << Init->getSourceRange();
9122         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9123           Diag(Notes[I].first, Notes[I].second);
9124       }
9125     } else if (var->isUsableInConstantExpressions(Context)) {
9126       // Check whether the initializer of a const variable of integral or
9127       // enumeration type is an ICE now, since we can't tell whether it was
9128       // initialized by a constant expression if we check later.
9129       var->checkInitIsICE();
9130     }
9131   }
9132 
9133   // Require the destructor.
9134   if (const RecordType *recordType = baseType->getAs<RecordType>())
9135     FinalizeVarWithDestructor(var, recordType);
9136 }
9137 
9138 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9139 /// any semantic actions necessary after any initializer has been attached.
9140 void
9141 Sema::FinalizeDeclaration(Decl *ThisDecl) {
9142   // Note that we are no longer parsing the initializer for this declaration.
9143   ParsingInitForAutoVars.erase(ThisDecl);
9144 
9145   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
9146   if (!VD)
9147     return;
9148 
9149   checkAttributesAfterMerging(*this, *VD);
9150 
9151   // Static locals inherit dll attributes from their function.
9152   if (VD->isStaticLocal()) {
9153     if (FunctionDecl *FD =
9154             dyn_cast<FunctionDecl>(VD->getParentFunctionOrMethod())) {
9155       if (Attr *A = getDLLAttr(FD)) {
9156         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
9157         NewAttr->setInherited(true);
9158         VD->addAttr(NewAttr);
9159       }
9160     }
9161   }
9162 
9163   // Imported static data members cannot be defined out-of-line.
9164   if (const DLLImportAttr *IA = VD->getAttr<DLLImportAttr>()) {
9165     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
9166         VD->isThisDeclarationADefinition()) {
9167       // We allow definitions of dllimport class template static data members
9168       // with a warning.
9169       CXXRecordDecl *Context =
9170         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
9171       bool IsClassTemplateMember =
9172           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
9173           Context->getDescribedClassTemplate();
9174 
9175       Diag(VD->getLocation(),
9176            IsClassTemplateMember
9177                ? diag::warn_attribute_dllimport_static_field_definition
9178                : diag::err_attribute_dllimport_static_field_definition);
9179       Diag(IA->getLocation(), diag::note_attribute);
9180       if (!IsClassTemplateMember)
9181         VD->setInvalidDecl();
9182     }
9183   }
9184 
9185   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9186     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
9187       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
9188       VD->dropAttr<UsedAttr>();
9189     }
9190   }
9191 
9192   if (!VD->isInvalidDecl() &&
9193       VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
9194     if (const VarDecl *Def = VD->getDefinition()) {
9195       if (Def->hasAttr<AliasAttr>()) {
9196         Diag(VD->getLocation(), diag::err_tentative_after_alias)
9197             << VD->getDeclName();
9198         Diag(Def->getLocation(), diag::note_previous_definition);
9199         VD->setInvalidDecl();
9200       }
9201     }
9202   }
9203 
9204   const DeclContext *DC = VD->getDeclContext();
9205   // If there's a #pragma GCC visibility in scope, and this isn't a class
9206   // member, set the visibility of this variable.
9207   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
9208     AddPushedVisibilityAttribute(VD);
9209 
9210   // FIXME: Warn on unused templates.
9211   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
9212       !isa<VarTemplatePartialSpecializationDecl>(VD))
9213     MarkUnusedFileScopedDecl(VD);
9214 
9215   // Now we have parsed the initializer and can update the table of magic
9216   // tag values.
9217   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
9218       !VD->getType()->isIntegralOrEnumerationType())
9219     return;
9220 
9221   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
9222     const Expr *MagicValueExpr = VD->getInit();
9223     if (!MagicValueExpr) {
9224       continue;
9225     }
9226     llvm::APSInt MagicValueInt;
9227     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9228       Diag(I->getRange().getBegin(),
9229            diag::err_type_tag_for_datatype_not_ice)
9230         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9231       continue;
9232     }
9233     if (MagicValueInt.getActiveBits() > 64) {
9234       Diag(I->getRange().getBegin(),
9235            diag::err_type_tag_for_datatype_too_large)
9236         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9237       continue;
9238     }
9239     uint64_t MagicValue = MagicValueInt.getZExtValue();
9240     RegisterTypeTagForDatatype(I->getArgumentKind(),
9241                                MagicValue,
9242                                I->getMatchingCType(),
9243                                I->getLayoutCompatible(),
9244                                I->getMustBeNull());
9245   }
9246 }
9247 
9248 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
9249                                                    ArrayRef<Decl *> Group) {
9250   SmallVector<Decl*, 8> Decls;
9251 
9252   if (DS.isTypeSpecOwned())
9253     Decls.push_back(DS.getRepAsDecl());
9254 
9255   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
9256   for (unsigned i = 0, e = Group.size(); i != e; ++i)
9257     if (Decl *D = Group[i]) {
9258       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9259         if (!FirstDeclaratorInGroup)
9260           FirstDeclaratorInGroup = DD;
9261       Decls.push_back(D);
9262     }
9263 
9264   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
9265     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
9266       HandleTagNumbering(*this, Tag, S);
9267       if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9268         Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9269     }
9270   }
9271 
9272   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
9273 }
9274 
9275 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
9276 /// group, performing any necessary semantic checking.
9277 Sema::DeclGroupPtrTy
9278 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
9279                            bool TypeMayContainAuto) {
9280   // C++0x [dcl.spec.auto]p7:
9281   //   If the type deduced for the template parameter U is not the same in each
9282   //   deduction, the program is ill-formed.
9283   // FIXME: When initializer-list support is added, a distinction is needed
9284   // between the deduced type U and the deduced type which 'auto' stands for.
9285   //   auto a = 0, b = { 1, 2, 3 };
9286   // is legal because the deduced type U is 'int' in both cases.
9287   if (TypeMayContainAuto && Group.size() > 1) {
9288     QualType Deduced;
9289     CanQualType DeducedCanon;
9290     VarDecl *DeducedDecl = nullptr;
9291     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
9292       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9293         AutoType *AT = D->getType()->getContainedAutoType();
9294         // Don't reissue diagnostics when instantiating a template.
9295         if (AT && D->isInvalidDecl())
9296           break;
9297         QualType U = AT ? AT->getDeducedType() : QualType();
9298         if (!U.isNull()) {
9299           CanQualType UCanon = Context.getCanonicalType(U);
9300           if (Deduced.isNull()) {
9301             Deduced = U;
9302             DeducedCanon = UCanon;
9303             DeducedDecl = D;
9304           } else if (DeducedCanon != UCanon) {
9305             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9306                  diag::err_auto_different_deductions)
9307               << (AT->isDecltypeAuto() ? 1 : 0)
9308               << Deduced << DeducedDecl->getDeclName()
9309               << U << D->getDeclName()
9310               << DeducedDecl->getInit()->getSourceRange()
9311               << D->getInit()->getSourceRange();
9312             D->setInvalidDecl();
9313             break;
9314           }
9315         }
9316       }
9317     }
9318   }
9319 
9320   ActOnDocumentableDecls(Group);
9321 
9322   return DeclGroupPtrTy::make(
9323       DeclGroupRef::Create(Context, Group.data(), Group.size()));
9324 }
9325 
9326 void Sema::ActOnDocumentableDecl(Decl *D) {
9327   ActOnDocumentableDecls(D);
9328 }
9329 
9330 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
9331   // Don't parse the comment if Doxygen diagnostics are ignored.
9332   if (Group.empty() || !Group[0])
9333    return;
9334 
9335   if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation()))
9336     return;
9337 
9338   if (Group.size() >= 2) {
9339     // This is a decl group.  Normally it will contain only declarations
9340     // produced from declarator list.  But in case we have any definitions or
9341     // additional declaration references:
9342     //   'typedef struct S {} S;'
9343     //   'typedef struct S *S;'
9344     //   'struct S *pS;'
9345     // FinalizeDeclaratorGroup adds these as separate declarations.
9346     Decl *MaybeTagDecl = Group[0];
9347     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
9348       Group = Group.slice(1);
9349     }
9350   }
9351 
9352   // See if there are any new comments that are not attached to a decl.
9353   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9354   if (!Comments.empty() &&
9355       !Comments.back()->isAttached()) {
9356     // There is at least one comment that not attached to a decl.
9357     // Maybe it should be attached to one of these decls?
9358     //
9359     // Note that this way we pick up not only comments that precede the
9360     // declaration, but also comments that *follow* the declaration -- thanks to
9361     // the lookahead in the lexer: we've consumed the semicolon and looked
9362     // ahead through comments.
9363     for (unsigned i = 0, e = Group.size(); i != e; ++i)
9364       Context.getCommentForDecl(Group[i], &PP);
9365   }
9366 }
9367 
9368 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9369 /// to introduce parameters into function prototype scope.
9370 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
9371   const DeclSpec &DS = D.getDeclSpec();
9372 
9373   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
9374 
9375   // C++03 [dcl.stc]p2 also permits 'auto'.
9376   VarDecl::StorageClass StorageClass = SC_None;
9377   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
9378     StorageClass = SC_Register;
9379   } else if (getLangOpts().CPlusPlus &&
9380              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9381     StorageClass = SC_Auto;
9382   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
9383     Diag(DS.getStorageClassSpecLoc(),
9384          diag::err_invalid_storage_class_in_func_decl);
9385     D.getMutableDeclSpec().ClearStorageClassSpecs();
9386   }
9387 
9388   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9389     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9390       << DeclSpec::getSpecifierName(TSCS);
9391   if (DS.isConstexprSpecified())
9392     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
9393       << 0;
9394 
9395   DiagnoseFunctionSpecifiers(DS);
9396 
9397   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9398   QualType parmDeclType = TInfo->getType();
9399 
9400   if (getLangOpts().CPlusPlus) {
9401     // Check that there are no default arguments inside the type of this
9402     // parameter.
9403     CheckExtraCXXDefaultArguments(D);
9404 
9405     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9406     if (D.getCXXScopeSpec().isSet()) {
9407       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9408         << D.getCXXScopeSpec().getRange();
9409       D.getCXXScopeSpec().clear();
9410     }
9411   }
9412 
9413   // Ensure we have a valid name
9414   IdentifierInfo *II = nullptr;
9415   if (D.hasName()) {
9416     II = D.getIdentifier();
9417     if (!II) {
9418       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9419         << GetNameForDeclarator(D).getName();
9420       D.setInvalidType(true);
9421     }
9422   }
9423 
9424   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
9425   if (II) {
9426     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9427                    ForRedeclaration);
9428     LookupName(R, S);
9429     if (R.isSingleResult()) {
9430       NamedDecl *PrevDecl = R.getFoundDecl();
9431       if (PrevDecl->isTemplateParameter()) {
9432         // Maybe we will complain about the shadowed template parameter.
9433         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9434         // Just pretend that we didn't see the previous declaration.
9435         PrevDecl = nullptr;
9436       } else if (S->isDeclScope(PrevDecl)) {
9437         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
9438         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9439 
9440         // Recover by removing the name
9441         II = nullptr;
9442         D.SetIdentifier(nullptr, D.getIdentifierLoc());
9443         D.setInvalidType(true);
9444       }
9445     }
9446   }
9447 
9448   // Temporarily put parameter variables in the translation unit, not
9449   // the enclosing context.  This prevents them from accidentally
9450   // looking like class members in C++.
9451   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
9452                                     D.getLocStart(),
9453                                     D.getIdentifierLoc(), II,
9454                                     parmDeclType, TInfo,
9455                                     StorageClass);
9456 
9457   if (D.isInvalidType())
9458     New->setInvalidDecl();
9459 
9460   assert(S->isFunctionPrototypeScope());
9461   assert(S->getFunctionPrototypeDepth() >= 1);
9462   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9463                     S->getNextFunctionPrototypeIndex());
9464 
9465   // Add the parameter declaration into this scope.
9466   S->AddDecl(New);
9467   if (II)
9468     IdResolver.AddDecl(New);
9469 
9470   ProcessDeclAttributes(S, New, D);
9471 
9472   if (D.getDeclSpec().isModulePrivateSpecified())
9473     Diag(New->getLocation(), diag::err_module_private_local)
9474       << 1 << New->getDeclName()
9475       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9476       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9477 
9478   if (New->hasAttr<BlocksAttr>()) {
9479     Diag(New->getLocation(), diag::err_block_on_nonlocal);
9480   }
9481   return New;
9482 }
9483 
9484 /// \brief Synthesizes a variable for a parameter arising from a
9485 /// typedef.
9486 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9487                                               SourceLocation Loc,
9488                                               QualType T) {
9489   /* FIXME: setting StartLoc == Loc.
9490      Would it be worth to modify callers so as to provide proper source
9491      location for the unnamed parameters, embedding the parameter's type? */
9492   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
9493                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
9494                                            SC_None, nullptr);
9495   Param->setImplicit();
9496   return Param;
9497 }
9498 
9499 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9500                                     ParmVarDecl * const *ParamEnd) {
9501   // Don't diagnose unused-parameter errors in template instantiations; we
9502   // will already have done so in the template itself.
9503   if (!ActiveTemplateInstantiations.empty())
9504     return;
9505 
9506   for (; Param != ParamEnd; ++Param) {
9507     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
9508         !(*Param)->hasAttr<UnusedAttr>()) {
9509       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9510         << (*Param)->getDeclName();
9511     }
9512   }
9513 }
9514 
9515 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9516                                                   ParmVarDecl * const *ParamEnd,
9517                                                   QualType ReturnTy,
9518                                                   NamedDecl *D) {
9519   if (LangOpts.NumLargeByValueCopy == 0) // No check.
9520     return;
9521 
9522   // Warn if the return value is pass-by-value and larger than the specified
9523   // threshold.
9524   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
9525     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
9526     if (Size > LangOpts.NumLargeByValueCopy)
9527       Diag(D->getLocation(), diag::warn_return_value_size)
9528           << D->getDeclName() << Size;
9529   }
9530 
9531   // Warn if any parameter is pass-by-value and larger than the specified
9532   // threshold.
9533   for (; Param != ParamEnd; ++Param) {
9534     QualType T = (*Param)->getType();
9535     if (T->isDependentType() || !T.isPODType(Context))
9536       continue;
9537     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
9538     if (Size > LangOpts.NumLargeByValueCopy)
9539       Diag((*Param)->getLocation(), diag::warn_parameter_size)
9540           << (*Param)->getDeclName() << Size;
9541   }
9542 }
9543 
9544 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9545                                   SourceLocation NameLoc, IdentifierInfo *Name,
9546                                   QualType T, TypeSourceInfo *TSInfo,
9547                                   VarDecl::StorageClass StorageClass) {
9548   // In ARC, infer a lifetime qualifier for appropriate parameter types.
9549   if (getLangOpts().ObjCAutoRefCount &&
9550       T.getObjCLifetime() == Qualifiers::OCL_None &&
9551       T->isObjCLifetimeType()) {
9552 
9553     Qualifiers::ObjCLifetime lifetime;
9554 
9555     // Special cases for arrays:
9556     //   - if it's const, use __unsafe_unretained
9557     //   - otherwise, it's an error
9558     if (T->isArrayType()) {
9559       if (!T.isConstQualified()) {
9560         DelayedDiagnostics.add(
9561             sema::DelayedDiagnostic::makeForbiddenType(
9562             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
9563       }
9564       lifetime = Qualifiers::OCL_ExplicitNone;
9565     } else {
9566       lifetime = T->getObjCARCImplicitLifetime();
9567     }
9568     T = Context.getLifetimeQualifiedType(T, lifetime);
9569   }
9570 
9571   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
9572                                          Context.getAdjustedParameterType(T),
9573                                          TSInfo,
9574                                          StorageClass, nullptr);
9575 
9576   // Parameters can not be abstract class types.
9577   // For record types, this is done by the AbstractClassUsageDiagnoser once
9578   // the class has been completely parsed.
9579   if (!CurContext->isRecord() &&
9580       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9581                              AbstractParamType))
9582     New->setInvalidDecl();
9583 
9584   // Parameter declarators cannot be interface types. All ObjC objects are
9585   // passed by reference.
9586   if (T->isObjCObjectType()) {
9587     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
9588     Diag(NameLoc,
9589          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
9590       << FixItHint::CreateInsertion(TypeEndLoc, "*");
9591     T = Context.getObjCObjectPointerType(T);
9592     New->setType(T);
9593   }
9594 
9595   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9596   // duration shall not be qualified by an address-space qualifier."
9597   // Since all parameters have automatic store duration, they can not have
9598   // an address space.
9599   if (T.getAddressSpace() != 0) {
9600     // OpenCL allows function arguments declared to be an array of a type
9601     // to be qualified with an address space.
9602     if (!(getLangOpts().OpenCL && T->isArrayType())) {
9603       Diag(NameLoc, diag::err_arg_with_address_space);
9604       New->setInvalidDecl();
9605     }
9606   }
9607 
9608   return New;
9609 }
9610 
9611 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9612                                            SourceLocation LocAfterDecls) {
9613   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
9614 
9615   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9616   // for a K&R function.
9617   if (!FTI.hasPrototype) {
9618     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
9619       --i;
9620       if (FTI.Params[i].Param == nullptr) {
9621         SmallString<256> Code;
9622         llvm::raw_svector_ostream(Code)
9623             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
9624         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
9625             << FTI.Params[i].Ident
9626             << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
9627 
9628         // Implicitly declare the argument as type 'int' for lack of a better
9629         // type.
9630         AttributeFactory attrs;
9631         DeclSpec DS(attrs);
9632         const char* PrevSpec; // unused
9633         unsigned DiagID; // unused
9634         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
9635                            DiagID, Context.getPrintingPolicy());
9636         // Use the identifier location for the type source range.
9637         DS.SetRangeStart(FTI.Params[i].IdentLoc);
9638         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
9639         Declarator ParamD(DS, Declarator::KNRTypeListContext);
9640         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
9641         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
9642       }
9643     }
9644   }
9645 }
9646 
9647 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
9648   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
9649   assert(D.isFunctionDeclarator() && "Not a function declarator!");
9650   Scope *ParentScope = FnBodyScope->getParent();
9651 
9652   D.setFunctionDefinitionKind(FDK_Definition);
9653   Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
9654   return ActOnStartOfFunctionDef(FnBodyScope, DP);
9655 }
9656 
9657 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
9658   Consumer.HandleInlineMethodDefinition(D);
9659 }
9660 
9661 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9662                              const FunctionDecl*& PossibleZeroParamPrototype) {
9663   // Don't warn about invalid declarations.
9664   if (FD->isInvalidDecl())
9665     return false;
9666 
9667   // Or declarations that aren't global.
9668   if (!FD->isGlobal())
9669     return false;
9670 
9671   // Don't warn about C++ member functions.
9672   if (isa<CXXMethodDecl>(FD))
9673     return false;
9674 
9675   // Don't warn about 'main'.
9676   if (FD->isMain())
9677     return false;
9678 
9679   // Don't warn about inline functions.
9680   if (FD->isInlined())
9681     return false;
9682 
9683   // Don't warn about function templates.
9684   if (FD->getDescribedFunctionTemplate())
9685     return false;
9686 
9687   // Don't warn about function template specializations.
9688   if (FD->isFunctionTemplateSpecialization())
9689     return false;
9690 
9691   // Don't warn for OpenCL kernels.
9692   if (FD->hasAttr<OpenCLKernelAttr>())
9693     return false;
9694 
9695   bool MissingPrototype = true;
9696   for (const FunctionDecl *Prev = FD->getPreviousDecl();
9697        Prev; Prev = Prev->getPreviousDecl()) {
9698     // Ignore any declarations that occur in function or method
9699     // scope, because they aren't visible from the header.
9700     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
9701       continue;
9702 
9703     MissingPrototype = !Prev->getType()->isFunctionProtoType();
9704     if (FD->getNumParams() == 0)
9705       PossibleZeroParamPrototype = Prev;
9706     break;
9707   }
9708 
9709   return MissingPrototype;
9710 }
9711 
9712 void
9713 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9714                                    const FunctionDecl *EffectiveDefinition) {
9715   // Don't complain if we're in GNU89 mode and the previous definition
9716   // was an extern inline function.
9717   const FunctionDecl *Definition = EffectiveDefinition;
9718   if (!Definition)
9719     if (!FD->isDefined(Definition))
9720       return;
9721 
9722   if (canRedefineFunction(Definition, getLangOpts()))
9723     return;
9724 
9725   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9726       Definition->getStorageClass() == SC_Extern)
9727     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
9728         << FD->getDeclName() << getLangOpts().CPlusPlus;
9729   else
9730     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9731 
9732   Diag(Definition->getLocation(), diag::note_previous_definition);
9733   FD->setInvalidDecl();
9734 }
9735 
9736 
9737 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9738                                    Sema &S) {
9739   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
9740 
9741   LambdaScopeInfo *LSI = S.PushLambdaScope();
9742   LSI->CallOperator = CallOperator;
9743   LSI->Lambda = LambdaClass;
9744   LSI->ReturnType = CallOperator->getReturnType();
9745   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9746 
9747   if (LCD == LCD_None)
9748     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9749   else if (LCD == LCD_ByCopy)
9750     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9751   else if (LCD == LCD_ByRef)
9752     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9753   DeclarationNameInfo DNI = CallOperator->getNameInfo();
9754 
9755   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9756   LSI->Mutable = !CallOperator->isConst();
9757 
9758   // Add the captures to the LSI so they can be noted as already
9759   // captured within tryCaptureVar.
9760   for (const auto &C : LambdaClass->captures()) {
9761     if (C.capturesVariable()) {
9762       VarDecl *VD = C.getCapturedVar();
9763       if (VD->isInitCapture())
9764         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9765       QualType CaptureType = VD->getType();
9766       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
9767       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9768           /*RefersToEnclosingLocal*/true, C.getLocation(),
9769           /*EllipsisLoc*/C.isPackExpansion()
9770                          ? C.getEllipsisLoc() : SourceLocation(),
9771           CaptureType, /*Expr*/ nullptr);
9772 
9773     } else if (C.capturesThis()) {
9774       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
9775                               S.getCurrentThisType(), /*Expr*/ nullptr);
9776     }
9777   }
9778 }
9779 
9780 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
9781   // Clear the last template instantiation error context.
9782   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9783 
9784   if (!D)
9785     return D;
9786   FunctionDecl *FD = nullptr;
9787 
9788   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
9789     FD = FunTmpl->getTemplatedDecl();
9790   else
9791     FD = cast<FunctionDecl>(D);
9792   // If we are instantiating a generic lambda call operator, push
9793   // a LambdaScopeInfo onto the function stack.  But use the information
9794   // that's already been calculated (ActOnLambdaExpr) to prime the current
9795   // LambdaScopeInfo.
9796   // When the template operator is being specialized, the LambdaScopeInfo,
9797   // has to be properly restored so that tryCaptureVariable doesn't try
9798   // and capture any new variables. In addition when calculating potential
9799   // captures during transformation of nested lambdas, it is necessary to
9800   // have the LSI properly restored.
9801   if (isGenericLambdaCallOperatorSpecialization(FD)) {
9802     assert(ActiveTemplateInstantiations.size() &&
9803       "There should be an active template instantiation on the stack "
9804       "when instantiating a generic lambda!");
9805     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
9806   }
9807   else
9808     // Enter a new function scope
9809     PushFunctionScope();
9810 
9811   // See if this is a redefinition.
9812   if (!FD->isLateTemplateParsed())
9813     CheckForFunctionRedefinition(FD);
9814 
9815   // Builtin functions cannot be defined.
9816   if (unsigned BuiltinID = FD->getBuiltinID()) {
9817     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9818         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
9819       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
9820       FD->setInvalidDecl();
9821     }
9822   }
9823 
9824   // The return type of a function definition must be complete
9825   // (C99 6.9.1p3, C++ [dcl.fct]p6).
9826   QualType ResultType = FD->getReturnType();
9827   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
9828       !FD->isInvalidDecl() &&
9829       RequireCompleteType(FD->getLocation(), ResultType,
9830                           diag::err_func_def_incomplete_result))
9831     FD->setInvalidDecl();
9832 
9833   // GNU warning -Wmissing-prototypes:
9834   //   Warn if a global function is defined without a previous
9835   //   prototype declaration. This warning is issued even if the
9836   //   definition itself provides a prototype. The aim is to detect
9837   //   global functions that fail to be declared in header files.
9838   const FunctionDecl *PossibleZeroParamPrototype = nullptr;
9839   if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
9840     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
9841 
9842     if (PossibleZeroParamPrototype) {
9843       // We found a declaration that is not a prototype,
9844       // but that could be a zero-parameter prototype
9845       if (TypeSourceInfo *TI =
9846               PossibleZeroParamPrototype->getTypeSourceInfo()) {
9847         TypeLoc TL = TI->getTypeLoc();
9848         if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9849           Diag(PossibleZeroParamPrototype->getLocation(),
9850                diag::note_declaration_not_a_prototype)
9851             << PossibleZeroParamPrototype
9852             << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9853       }
9854     }
9855   }
9856 
9857   if (FnBodyScope)
9858     PushDeclContext(FnBodyScope, FD);
9859 
9860   // Check the validity of our function parameters
9861   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9862                            /*CheckParameterNames=*/true);
9863 
9864   // Introduce our parameters into the function scope
9865   for (auto Param : FD->params()) {
9866     Param->setOwningFunction(FD);
9867 
9868     // If this has an identifier, add it to the scope stack.
9869     if (Param->getIdentifier() && FnBodyScope) {
9870       CheckShadow(FnBodyScope, Param);
9871 
9872       PushOnScopeChains(Param, FnBodyScope);
9873     }
9874   }
9875 
9876   // If we had any tags defined in the function prototype,
9877   // introduce them into the function scope.
9878   if (FnBodyScope) {
9879     for (ArrayRef<NamedDecl *>::iterator
9880              I = FD->getDeclsInPrototypeScope().begin(),
9881              E = FD->getDeclsInPrototypeScope().end();
9882          I != E; ++I) {
9883       NamedDecl *D = *I;
9884 
9885       // Some of these decls (like enums) may have been pinned to the translation unit
9886       // for lack of a real context earlier. If so, remove from the translation unit
9887       // and reattach to the current context.
9888       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9889         // Is the decl actually in the context?
9890         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
9891           if (DI == D) {
9892             Context.getTranslationUnitDecl()->removeDecl(D);
9893             break;
9894           }
9895         }
9896         // Either way, reassign the lexical decl context to our FunctionDecl.
9897         D->setLexicalDeclContext(CurContext);
9898       }
9899 
9900       // If the decl has a non-null name, make accessible in the current scope.
9901       if (!D->getName().empty())
9902         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9903 
9904       // Similarly, dive into enums and fish their constants out, making them
9905       // accessible in this scope.
9906       if (auto *ED = dyn_cast<EnumDecl>(D)) {
9907         for (auto *EI : ED->enumerators())
9908           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
9909       }
9910     }
9911   }
9912 
9913   // Ensure that the function's exception specification is instantiated.
9914   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9915     ResolveExceptionSpec(D->getLocation(), FPT);
9916 
9917   // dllimport cannot be applied to non-inline function definitions.
9918   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
9919       !FD->isTemplateInstantiation()) {
9920     assert(!FD->hasAttr<DLLExportAttr>());
9921     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
9922     FD->setInvalidDecl();
9923     return D;
9924   }
9925   // We want to attach documentation to original Decl (which might be
9926   // a function template).
9927   ActOnDocumentableDecl(D);
9928   if (getCurLexicalContext()->isObjCContainer() &&
9929       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
9930       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
9931     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
9932 
9933   return D;
9934 }
9935 
9936 /// \brief Given the set of return statements within a function body,
9937 /// compute the variables that are subject to the named return value
9938 /// optimization.
9939 ///
9940 /// Each of the variables that is subject to the named return value
9941 /// optimization will be marked as NRVO variables in the AST, and any
9942 /// return statement that has a marked NRVO variable as its NRVO candidate can
9943 /// use the named return value optimization.
9944 ///
9945 /// This function applies a very simplistic algorithm for NRVO: if every return
9946 /// statement in the scope of a variable has the same NRVO candidate, that
9947 /// candidate is an NRVO variable.
9948 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
9949   ReturnStmt **Returns = Scope->Returns.data();
9950 
9951   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
9952     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
9953       if (!NRVOCandidate->isNRVOVariable())
9954         Returns[I]->setNRVOCandidate(nullptr);
9955     }
9956   }
9957 }
9958 
9959 bool Sema::canDelayFunctionBody(const Declarator &D) {
9960   // We can't delay parsing the body of a constexpr function template (yet).
9961   if (D.getDeclSpec().isConstexprSpecified())
9962     return false;
9963 
9964   // We can't delay parsing the body of a function template with a deduced
9965   // return type (yet).
9966   if (D.getDeclSpec().containsPlaceholderType()) {
9967     // If the placeholder introduces a non-deduced trailing return type,
9968     // we can still delay parsing it.
9969     if (D.getNumTypeObjects()) {
9970       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
9971       if (Outer.Kind == DeclaratorChunk::Function &&
9972           Outer.Fun.hasTrailingReturnType()) {
9973         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
9974         return Ty.isNull() || !Ty->isUndeducedType();
9975       }
9976     }
9977     return false;
9978   }
9979 
9980   return true;
9981 }
9982 
9983 bool Sema::canSkipFunctionBody(Decl *D) {
9984   // We cannot skip the body of a function (or function template) which is
9985   // constexpr, since we may need to evaluate its body in order to parse the
9986   // rest of the file.
9987   // We cannot skip the body of a function with an undeduced return type,
9988   // because any callers of that function need to know the type.
9989   if (const FunctionDecl *FD = D->getAsFunction())
9990     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
9991       return false;
9992   return Consumer.shouldSkipFunctionBody(D);
9993 }
9994 
9995 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
9996   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
9997     FD->setHasSkippedBody();
9998   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
9999     MD->setHasSkippedBody();
10000   return ActOnFinishFunctionBody(Decl, nullptr);
10001 }
10002 
10003 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
10004   return ActOnFinishFunctionBody(D, BodyArg, false);
10005 }
10006 
10007 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
10008                                     bool IsInstantiation) {
10009   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
10010 
10011   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10012   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
10013 
10014   if (FD) {
10015     FD->setBody(Body);
10016 
10017     if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
10018         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
10019       // If the function has a deduced result type but contains no 'return'
10020       // statements, the result type as written must be exactly 'auto', and
10021       // the deduced result type is 'void'.
10022       if (!FD->getReturnType()->getAs<AutoType>()) {
10023         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
10024             << FD->getReturnType();
10025         FD->setInvalidDecl();
10026       } else {
10027         // Substitute 'void' for the 'auto' in the type.
10028         TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
10029             IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
10030         Context.adjustDeducedFunctionResultType(
10031             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
10032       }
10033     }
10034 
10035     // The only way to be included in UndefinedButUsed is if there is an
10036     // ODR use before the definition. Avoid the expensive map lookup if this
10037     // is the first declaration.
10038     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
10039       if (!FD->isExternallyVisible())
10040         UndefinedButUsed.erase(FD);
10041       else if (FD->isInlined() &&
10042                (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10043                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
10044         UndefinedButUsed.erase(FD);
10045     }
10046 
10047     // If the function implicitly returns zero (like 'main') or is naked,
10048     // don't complain about missing return statements.
10049     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
10050       WP.disableCheckFallThrough();
10051 
10052     // MSVC permits the use of pure specifier (=0) on function definition,
10053     // defined at class scope, warn about this non-standard construct.
10054     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
10055       Diag(FD->getLocation(), diag::warn_pure_function_definition);
10056 
10057     if (!FD->isInvalidDecl()) {
10058       // Don't diagnose unused parameters of defaulted or deleted functions.
10059       if (Body)
10060         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
10061       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
10062                                              FD->getReturnType(), FD);
10063 
10064       // If this is a constructor, we need a vtable.
10065       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
10066         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
10067 
10068       // Try to apply the named return value optimization. We have to check
10069       // if we can do this here because lambdas keep return statements around
10070       // to deduce an implicit return type.
10071       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
10072           !FD->isDependentContext())
10073         computeNRVO(Body, getCurFunction());
10074     }
10075 
10076     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
10077            "Function parsing confused");
10078   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
10079     assert(MD == getCurMethodDecl() && "Method parsing confused");
10080     MD->setBody(Body);
10081     if (!MD->isInvalidDecl()) {
10082       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
10083       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
10084                                              MD->getReturnType(), MD);
10085 
10086       if (Body)
10087         computeNRVO(Body, getCurFunction());
10088     }
10089     if (getCurFunction()->ObjCShouldCallSuper) {
10090       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
10091         << MD->getSelector().getAsString();
10092       getCurFunction()->ObjCShouldCallSuper = false;
10093     }
10094     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
10095       const ObjCMethodDecl *InitMethod = nullptr;
10096       bool isDesignated =
10097           MD->isDesignatedInitializerForTheInterface(&InitMethod);
10098       assert(isDesignated && InitMethod);
10099       (void)isDesignated;
10100 
10101       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
10102         auto IFace = MD->getClassInterface();
10103         if (!IFace)
10104           return false;
10105         auto SuperD = IFace->getSuperClass();
10106         if (!SuperD)
10107           return false;
10108         return SuperD->getIdentifier() ==
10109             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
10110       };
10111       // Don't issue this warning for unavailable inits or direct subclasses
10112       // of NSObject.
10113       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
10114         Diag(MD->getLocation(),
10115              diag::warn_objc_designated_init_missing_super_call);
10116         Diag(InitMethod->getLocation(),
10117              diag::note_objc_designated_init_marked_here);
10118       }
10119       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
10120     }
10121     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
10122       // Don't issue this warning for unavaialable inits.
10123       if (!MD->isUnavailable())
10124         Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
10125       getCurFunction()->ObjCWarnForNoInitDelegation = false;
10126     }
10127   } else {
10128     return nullptr;
10129   }
10130 
10131   assert(!getCurFunction()->ObjCShouldCallSuper &&
10132          "This should only be set for ObjC methods, which should have been "
10133          "handled in the block above.");
10134 
10135   // Verify and clean out per-function state.
10136   if (Body) {
10137     // C++ constructors that have function-try-blocks can't have return
10138     // statements in the handlers of that block. (C++ [except.handle]p14)
10139     // Verify this.
10140     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
10141       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
10142 
10143     // Verify that gotos and switch cases don't jump into scopes illegally.
10144     if (getCurFunction()->NeedsScopeChecking() &&
10145         !PP.isCodeCompletionEnabled())
10146       DiagnoseInvalidJumps(Body);
10147 
10148     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
10149       if (!Destructor->getParent()->isDependentType())
10150         CheckDestructor(Destructor);
10151 
10152       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10153                                              Destructor->getParent());
10154     }
10155 
10156     // If any errors have occurred, clear out any temporaries that may have
10157     // been leftover. This ensures that these temporaries won't be picked up for
10158     // deletion in some later function.
10159     if (getDiagnostics().hasErrorOccurred() ||
10160         getDiagnostics().getSuppressAllDiagnostics()) {
10161       DiscardCleanupsInEvaluationContext();
10162     }
10163     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
10164         !isa<FunctionTemplateDecl>(dcl)) {
10165       // Since the body is valid, issue any analysis-based warnings that are
10166       // enabled.
10167       ActivePolicy = &WP;
10168     }
10169 
10170     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10171         (!CheckConstexprFunctionDecl(FD) ||
10172          !CheckConstexprFunctionBody(FD, Body)))
10173       FD->setInvalidDecl();
10174 
10175     assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
10176     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
10177     assert(MaybeODRUseExprs.empty() &&
10178            "Leftover expressions for odr-use checking");
10179   }
10180 
10181   if (!IsInstantiation)
10182     PopDeclContext();
10183 
10184   PopFunctionScopeInfo(ActivePolicy, dcl);
10185   // If any errors have occurred, clear out any temporaries that may have
10186   // been leftover. This ensures that these temporaries won't be picked up for
10187   // deletion in some later function.
10188   if (getDiagnostics().hasErrorOccurred()) {
10189     DiscardCleanupsInEvaluationContext();
10190   }
10191 
10192   return dcl;
10193 }
10194 
10195 
10196 /// When we finish delayed parsing of an attribute, we must attach it to the
10197 /// relevant Decl.
10198 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
10199                                        ParsedAttributes &Attrs) {
10200   // Always attach attributes to the underlying decl.
10201   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
10202     D = TD->getTemplatedDecl();
10203   ProcessDeclAttributeList(S, D, Attrs.getList());
10204 
10205   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
10206     if (Method->isStatic())
10207       checkThisInStaticMemberFunctionAttributes(Method);
10208 }
10209 
10210 
10211 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
10212 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
10213 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
10214                                           IdentifierInfo &II, Scope *S) {
10215   // Before we produce a declaration for an implicitly defined
10216   // function, see whether there was a locally-scoped declaration of
10217   // this name as a function or variable. If so, use that
10218   // (non-visible) declaration, and complain about it.
10219   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
10220     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
10221     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
10222     return ExternCPrev;
10223   }
10224 
10225   // Extension in C99.  Legal in C90, but warn about it.
10226   unsigned diag_id;
10227   if (II.getName().startswith("__builtin_"))
10228     diag_id = diag::warn_builtin_unknown;
10229   else if (getLangOpts().C99)
10230     diag_id = diag::ext_implicit_function_decl;
10231   else
10232     diag_id = diag::warn_implicit_function_decl;
10233   Diag(Loc, diag_id) << &II;
10234 
10235   // Because typo correction is expensive, only do it if the implicit
10236   // function declaration is going to be treated as an error.
10237   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
10238     TypoCorrection Corrected;
10239     DeclFilterCCC<FunctionDecl> Validator;
10240     if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
10241                                       LookupOrdinaryName, S, nullptr, Validator,
10242                                       CTK_NonError)))
10243       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
10244                    /*ErrorRecovery*/false);
10245   }
10246 
10247   // Set a Declarator for the implicit definition: int foo();
10248   const char *Dummy;
10249   AttributeFactory attrFactory;
10250   DeclSpec DS(attrFactory);
10251   unsigned DiagID;
10252   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
10253                                   Context.getPrintingPolicy());
10254   (void)Error; // Silence warning.
10255   assert(!Error && "Error setting up implicit decl!");
10256   SourceLocation NoLoc;
10257   Declarator D(DS, Declarator::BlockContext);
10258   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
10259                                              /*IsAmbiguous=*/false,
10260                                              /*LParenLoc=*/NoLoc,
10261                                              /*Params=*/nullptr,
10262                                              /*NumParams=*/0,
10263                                              /*EllipsisLoc=*/NoLoc,
10264                                              /*RParenLoc=*/NoLoc,
10265                                              /*TypeQuals=*/0,
10266                                              /*RefQualifierIsLvalueRef=*/true,
10267                                              /*RefQualifierLoc=*/NoLoc,
10268                                              /*ConstQualifierLoc=*/NoLoc,
10269                                              /*VolatileQualifierLoc=*/NoLoc,
10270                                              /*MutableLoc=*/NoLoc,
10271                                              EST_None,
10272                                              /*ESpecLoc=*/NoLoc,
10273                                              /*Exceptions=*/nullptr,
10274                                              /*ExceptionRanges=*/nullptr,
10275                                              /*NumExceptions=*/0,
10276                                              /*NoexceptExpr=*/nullptr,
10277                                              Loc, Loc, D),
10278                 DS.getAttributes(),
10279                 SourceLocation());
10280   D.SetIdentifier(&II, Loc);
10281 
10282   // Insert this function into translation-unit scope.
10283 
10284   DeclContext *PrevDC = CurContext;
10285   CurContext = Context.getTranslationUnitDecl();
10286 
10287   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
10288   FD->setImplicit();
10289 
10290   CurContext = PrevDC;
10291 
10292   AddKnownFunctionAttributes(FD);
10293 
10294   return FD;
10295 }
10296 
10297 /// \brief Adds any function attributes that we know a priori based on
10298 /// the declaration of this function.
10299 ///
10300 /// These attributes can apply both to implicitly-declared builtins
10301 /// (like __builtin___printf_chk) or to library-declared functions
10302 /// like NSLog or printf.
10303 ///
10304 /// We need to check for duplicate attributes both here and where user-written
10305 /// attributes are applied to declarations.
10306 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10307   if (FD->isInvalidDecl())
10308     return;
10309 
10310   // If this is a built-in function, map its builtin attributes to
10311   // actual attributes.
10312   if (unsigned BuiltinID = FD->getBuiltinID()) {
10313     // Handle printf-formatting attributes.
10314     unsigned FormatIdx;
10315     bool HasVAListArg;
10316     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
10317       if (!FD->hasAttr<FormatAttr>()) {
10318         const char *fmt = "printf";
10319         unsigned int NumParams = FD->getNumParams();
10320         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10321             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10322           fmt = "NSString";
10323         FD->addAttr(FormatAttr::CreateImplicit(Context,
10324                                                &Context.Idents.get(fmt),
10325                                                FormatIdx+1,
10326                                                HasVAListArg ? 0 : FormatIdx+2,
10327                                                FD->getLocation()));
10328       }
10329     }
10330     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10331                                              HasVAListArg)) {
10332      if (!FD->hasAttr<FormatAttr>())
10333        FD->addAttr(FormatAttr::CreateImplicit(Context,
10334                                               &Context.Idents.get("scanf"),
10335                                               FormatIdx+1,
10336                                               HasVAListArg ? 0 : FormatIdx+2,
10337                                               FD->getLocation()));
10338     }
10339 
10340     // Mark const if we don't care about errno and that is the only
10341     // thing preventing the function from being const. This allows
10342     // IRgen to use LLVM intrinsics for such functions.
10343     if (!getLangOpts().MathErrno &&
10344         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
10345       if (!FD->hasAttr<ConstAttr>())
10346         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10347     }
10348 
10349     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10350         !FD->hasAttr<ReturnsTwiceAttr>())
10351       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10352                                          FD->getLocation()));
10353     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
10354       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
10355     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
10356       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10357   }
10358 
10359   IdentifierInfo *Name = FD->getIdentifier();
10360   if (!Name)
10361     return;
10362   if ((!getLangOpts().CPlusPlus &&
10363        FD->getDeclContext()->isTranslationUnit()) ||
10364       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
10365        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
10366        LinkageSpecDecl::lang_c)) {
10367     // Okay: this could be a libc/libm/Objective-C function we know
10368     // about.
10369   } else
10370     return;
10371 
10372   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
10373     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
10374     // target-specific builtins, perhaps?
10375     if (!FD->hasAttr<FormatAttr>())
10376       FD->addAttr(FormatAttr::CreateImplicit(Context,
10377                                              &Context.Idents.get("printf"), 2,
10378                                              Name->isStr("vasprintf") ? 0 : 3,
10379                                              FD->getLocation()));
10380   }
10381 
10382   if (Name->isStr("__CFStringMakeConstantString")) {
10383     // We already have a __builtin___CFStringMakeConstantString,
10384     // but builds that use -fno-constant-cfstrings don't go through that.
10385     if (!FD->hasAttr<FormatArgAttr>())
10386       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10387                                                 FD->getLocation()));
10388   }
10389 }
10390 
10391 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
10392                                     TypeSourceInfo *TInfo) {
10393   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
10394   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
10395 
10396   if (!TInfo) {
10397     assert(D.isInvalidType() && "no declarator info for valid type");
10398     TInfo = Context.getTrivialTypeSourceInfo(T);
10399   }
10400 
10401   // Scope manipulation handled by caller.
10402   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
10403                                            D.getLocStart(),
10404                                            D.getIdentifierLoc(),
10405                                            D.getIdentifier(),
10406                                            TInfo);
10407 
10408   // Bail out immediately if we have an invalid declaration.
10409   if (D.isInvalidType()) {
10410     NewTD->setInvalidDecl();
10411     return NewTD;
10412   }
10413 
10414   if (D.getDeclSpec().isModulePrivateSpecified()) {
10415     if (CurContext->isFunctionOrMethod())
10416       Diag(NewTD->getLocation(), diag::err_module_private_local)
10417         << 2 << NewTD->getDeclName()
10418         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10419         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10420     else
10421       NewTD->setModulePrivate();
10422   }
10423 
10424   // C++ [dcl.typedef]p8:
10425   //   If the typedef declaration defines an unnamed class (or
10426   //   enum), the first typedef-name declared by the declaration
10427   //   to be that class type (or enum type) is used to denote the
10428   //   class type (or enum type) for linkage purposes only.
10429   // We need to check whether the type was declared in the declaration.
10430   switch (D.getDeclSpec().getTypeSpecType()) {
10431   case TST_enum:
10432   case TST_struct:
10433   case TST_interface:
10434   case TST_union:
10435   case TST_class: {
10436     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10437 
10438     // Do nothing if the tag is not anonymous or already has an
10439     // associated typedef (from an earlier typedef in this decl group).
10440     if (tagFromDeclSpec->getIdentifier()) break;
10441     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
10442 
10443     // A well-formed anonymous tag must always be a TUK_Definition.
10444     assert(tagFromDeclSpec->isThisDeclarationADefinition());
10445 
10446     // The type must match the tag exactly;  no qualifiers allowed.
10447     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10448       break;
10449 
10450     // If we've already computed linkage for the anonymous tag, then
10451     // adding a typedef name for the anonymous decl can change that
10452     // linkage, which might be a serious problem.  Diagnose this as
10453     // unsupported and ignore the typedef name.  TODO: we should
10454     // pursue this as a language defect and establish a formal rule
10455     // for how to handle it.
10456     if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10457       Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10458 
10459       SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
10460       tagLoc = getLocForEndOfToken(tagLoc);
10461 
10462       llvm::SmallString<40> textToInsert;
10463       textToInsert += ' ';
10464       textToInsert += D.getIdentifier()->getName();
10465       Diag(tagLoc, diag::note_typedef_changes_linkage)
10466         << FixItHint::CreateInsertion(tagLoc, textToInsert);
10467       break;
10468     }
10469 
10470     // Otherwise, set this is the anon-decl typedef for the tag.
10471     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
10472     break;
10473   }
10474 
10475   default:
10476     break;
10477   }
10478 
10479   return NewTD;
10480 }
10481 
10482 
10483 /// \brief Check that this is a valid underlying type for an enum declaration.
10484 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10485   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10486   QualType T = TI->getType();
10487 
10488   if (T->isDependentType())
10489     return false;
10490 
10491   if (const BuiltinType *BT = T->getAs<BuiltinType>())
10492     if (BT->isInteger())
10493       return false;
10494 
10495   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10496   return true;
10497 }
10498 
10499 /// Check whether this is a valid redeclaration of a previous enumeration.
10500 /// \return true if the redeclaration was invalid.
10501 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10502                                   QualType EnumUnderlyingTy,
10503                                   const EnumDecl *Prev) {
10504   bool IsFixed = !EnumUnderlyingTy.isNull();
10505 
10506   if (IsScoped != Prev->isScoped()) {
10507     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10508       << Prev->isScoped();
10509     Diag(Prev->getLocation(), diag::note_previous_declaration);
10510     return true;
10511   }
10512 
10513   if (IsFixed && Prev->isFixed()) {
10514     if (!EnumUnderlyingTy->isDependentType() &&
10515         !Prev->getIntegerType()->isDependentType() &&
10516         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
10517                                         Prev->getIntegerType())) {
10518       // TODO: Highlight the underlying type of the redeclaration.
10519       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10520         << EnumUnderlyingTy << Prev->getIntegerType();
10521       Diag(Prev->getLocation(), diag::note_previous_declaration)
10522           << Prev->getIntegerTypeRange();
10523       return true;
10524     }
10525   } else if (IsFixed != Prev->isFixed()) {
10526     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10527       << Prev->isFixed();
10528     Diag(Prev->getLocation(), diag::note_previous_declaration);
10529     return true;
10530   }
10531 
10532   return false;
10533 }
10534 
10535 /// \brief Get diagnostic %select index for tag kind for
10536 /// redeclaration diagnostic message.
10537 /// WARNING: Indexes apply to particular diagnostics only!
10538 ///
10539 /// \returns diagnostic %select index.
10540 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
10541   switch (Tag) {
10542   case TTK_Struct: return 0;
10543   case TTK_Interface: return 1;
10544   case TTK_Class:  return 2;
10545   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
10546   }
10547 }
10548 
10549 /// \brief Determine if tag kind is a class-key compatible with
10550 /// class for redeclaration (class, struct, or __interface).
10551 ///
10552 /// \returns true iff the tag kind is compatible.
10553 static bool isClassCompatTagKind(TagTypeKind Tag)
10554 {
10555   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10556 }
10557 
10558 /// \brief Determine whether a tag with a given kind is acceptable
10559 /// as a redeclaration of the given tag declaration.
10560 ///
10561 /// \returns true if the new tag kind is acceptable, false otherwise.
10562 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
10563                                         TagTypeKind NewTag, bool isDefinition,
10564                                         SourceLocation NewTagLoc,
10565                                         const IdentifierInfo &Name) {
10566   // C++ [dcl.type.elab]p3:
10567   //   The class-key or enum keyword present in the
10568   //   elaborated-type-specifier shall agree in kind with the
10569   //   declaration to which the name in the elaborated-type-specifier
10570   //   refers. This rule also applies to the form of
10571   //   elaborated-type-specifier that declares a class-name or
10572   //   friend class since it can be construed as referring to the
10573   //   definition of the class. Thus, in any
10574   //   elaborated-type-specifier, the enum keyword shall be used to
10575   //   refer to an enumeration (7.2), the union class-key shall be
10576   //   used to refer to a union (clause 9), and either the class or
10577   //   struct class-key shall be used to refer to a class (clause 9)
10578   //   declared using the class or struct class-key.
10579   TagTypeKind OldTag = Previous->getTagKind();
10580   if (!isDefinition || !isClassCompatTagKind(NewTag))
10581     if (OldTag == NewTag)
10582       return true;
10583 
10584   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
10585     // Warn about the struct/class tag mismatch.
10586     bool isTemplate = false;
10587     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10588       isTemplate = Record->getDescribedClassTemplate();
10589 
10590     if (!ActiveTemplateInstantiations.empty()) {
10591       // In a template instantiation, do not offer fix-its for tag mismatches
10592       // since they usually mess up the template instead of fixing the problem.
10593       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10594         << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10595         << getRedeclDiagFromTagKind(OldTag);
10596       return true;
10597     }
10598 
10599     if (isDefinition) {
10600       // On definitions, check previous tags and issue a fix-it for each
10601       // one that doesn't match the current tag.
10602       if (Previous->getDefinition()) {
10603         // Don't suggest fix-its for redefinitions.
10604         return true;
10605       }
10606 
10607       bool previousMismatch = false;
10608       for (auto I : Previous->redecls()) {
10609         if (I->getTagKind() != NewTag) {
10610           if (!previousMismatch) {
10611             previousMismatch = true;
10612             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
10613               << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10614               << getRedeclDiagFromTagKind(I->getTagKind());
10615           }
10616           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
10617             << getRedeclDiagFromTagKind(NewTag)
10618             << FixItHint::CreateReplacement(I->getInnerLocStart(),
10619                  TypeWithKeyword::getTagTypeKindName(NewTag));
10620         }
10621       }
10622       return true;
10623     }
10624 
10625     // Check for a previous definition.  If current tag and definition
10626     // are same type, do nothing.  If no definition, but disagree with
10627     // with previous tag type, give a warning, but no fix-it.
10628     const TagDecl *Redecl = Previous->getDefinition() ?
10629                             Previous->getDefinition() : Previous;
10630     if (Redecl->getTagKind() == NewTag) {
10631       return true;
10632     }
10633 
10634     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10635       << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10636       << getRedeclDiagFromTagKind(OldTag);
10637     Diag(Redecl->getLocation(), diag::note_previous_use);
10638 
10639     // If there is a previous definition, suggest a fix-it.
10640     if (Previous->getDefinition()) {
10641         Diag(NewTagLoc, diag::note_struct_class_suggestion)
10642           << getRedeclDiagFromTagKind(Redecl->getTagKind())
10643           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
10644                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
10645     }
10646 
10647     return true;
10648   }
10649   return false;
10650 }
10651 
10652 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
10653 /// former case, Name will be non-null.  In the later case, Name will be null.
10654 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
10655 /// reference/declaration/definition of a tag.
10656 ///
10657 /// IsTypeSpecifier is true if this is a type-specifier (or
10658 /// trailing-type-specifier) other than one in an alias-declaration.
10659 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10660                      SourceLocation KWLoc, CXXScopeSpec &SS,
10661                      IdentifierInfo *Name, SourceLocation NameLoc,
10662                      AttributeList *Attr, AccessSpecifier AS,
10663                      SourceLocation ModulePrivateLoc,
10664                      MultiTemplateParamsArg TemplateParameterLists,
10665                      bool &OwnedDecl, bool &IsDependent,
10666                      SourceLocation ScopedEnumKWLoc,
10667                      bool ScopedEnumUsesClassTag,
10668                      TypeResult UnderlyingType,
10669                      bool IsTypeSpecifier) {
10670   // If this is not a definition, it must have a name.
10671   IdentifierInfo *OrigName = Name;
10672   assert((Name != nullptr || TUK == TUK_Definition) &&
10673          "Nameless record must be a definition!");
10674   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
10675 
10676   OwnedDecl = false;
10677   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10678   bool ScopedEnum = ScopedEnumKWLoc.isValid();
10679 
10680   // FIXME: Check explicit specializations more carefully.
10681   bool isExplicitSpecialization = false;
10682   bool Invalid = false;
10683 
10684   // We only need to do this matching if we have template parameters
10685   // or a scope specifier, which also conveniently avoids this work
10686   // for non-C++ cases.
10687   if (TemplateParameterLists.size() > 0 ||
10688       (SS.isNotEmpty() && TUK != TUK_Reference)) {
10689     if (TemplateParameterList *TemplateParams =
10690             MatchTemplateParametersToScopeSpecifier(
10691                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
10692                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
10693       if (Kind == TTK_Enum) {
10694         Diag(KWLoc, diag::err_enum_template);
10695         return nullptr;
10696       }
10697 
10698       if (TemplateParams->size() > 0) {
10699         // This is a declaration or definition of a class template (which may
10700         // be a member of another template).
10701 
10702         if (Invalid)
10703           return nullptr;
10704 
10705         OwnedDecl = false;
10706         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
10707                                                SS, Name, NameLoc, Attr,
10708                                                TemplateParams, AS,
10709                                                ModulePrivateLoc,
10710                                                TemplateParameterLists.size()-1,
10711                                                TemplateParameterLists.data());
10712         return Result.get();
10713       } else {
10714         // The "template<>" header is extraneous.
10715         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10716           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10717         isExplicitSpecialization = true;
10718       }
10719     }
10720   }
10721 
10722   // Figure out the underlying type if this a enum declaration. We need to do
10723   // this early, because it's needed to detect if this is an incompatible
10724   // redeclaration.
10725   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10726 
10727   if (Kind == TTK_Enum) {
10728     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10729       // No underlying type explicitly specified, or we failed to parse the
10730       // type, default to int.
10731       EnumUnderlying = Context.IntTy.getTypePtr();
10732     else if (UnderlyingType.get()) {
10733       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10734       // integral type; any cv-qualification is ignored.
10735       TypeSourceInfo *TI = nullptr;
10736       GetTypeFromParser(UnderlyingType.get(), &TI);
10737       EnumUnderlying = TI;
10738 
10739       if (CheckEnumUnderlyingType(TI))
10740         // Recover by falling back to int.
10741         EnumUnderlying = Context.IntTy.getTypePtr();
10742 
10743       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
10744                                           UPPC_FixedUnderlyingType))
10745         EnumUnderlying = Context.IntTy.getTypePtr();
10746 
10747     } else if (getLangOpts().MSVCCompat)
10748       // Microsoft enums are always of int type.
10749       EnumUnderlying = Context.IntTy.getTypePtr();
10750   }
10751 
10752   DeclContext *SearchDC = CurContext;
10753   DeclContext *DC = CurContext;
10754   bool isStdBadAlloc = false;
10755 
10756   RedeclarationKind Redecl = ForRedeclaration;
10757   if (TUK == TUK_Friend || TUK == TUK_Reference)
10758     Redecl = NotForRedeclaration;
10759 
10760   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
10761   bool FriendSawTagOutsideEnclosingNamespace = false;
10762   if (Name && SS.isNotEmpty()) {
10763     // We have a nested-name tag ('struct foo::bar').
10764 
10765     // Check for invalid 'foo::'.
10766     if (SS.isInvalid()) {
10767       Name = nullptr;
10768       goto CreateNewDecl;
10769     }
10770 
10771     // If this is a friend or a reference to a class in a dependent
10772     // context, don't try to make a decl for it.
10773     if (TUK == TUK_Friend || TUK == TUK_Reference) {
10774       DC = computeDeclContext(SS, false);
10775       if (!DC) {
10776         IsDependent = true;
10777         return nullptr;
10778       }
10779     } else {
10780       DC = computeDeclContext(SS, true);
10781       if (!DC) {
10782         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10783           << SS.getRange();
10784         return nullptr;
10785       }
10786     }
10787 
10788     if (RequireCompleteDeclContext(SS, DC))
10789       return nullptr;
10790 
10791     SearchDC = DC;
10792     // Look-up name inside 'foo::'.
10793     LookupQualifiedName(Previous, DC);
10794 
10795     if (Previous.isAmbiguous())
10796       return nullptr;
10797 
10798     if (Previous.empty()) {
10799       // Name lookup did not find anything. However, if the
10800       // nested-name-specifier refers to the current instantiation,
10801       // and that current instantiation has any dependent base
10802       // classes, we might find something at instantiation time: treat
10803       // this as a dependent elaborated-type-specifier.
10804       // But this only makes any sense for reference-like lookups.
10805       if (Previous.wasNotFoundInCurrentInstantiation() &&
10806           (TUK == TUK_Reference || TUK == TUK_Friend)) {
10807         IsDependent = true;
10808         return nullptr;
10809       }
10810 
10811       // A tag 'foo::bar' must already exist.
10812       Diag(NameLoc, diag::err_not_tag_in_scope)
10813         << Kind << Name << DC << SS.getRange();
10814       Name = nullptr;
10815       Invalid = true;
10816       goto CreateNewDecl;
10817     }
10818   } else if (Name) {
10819     // If this is a named struct, check to see if there was a previous forward
10820     // declaration or definition.
10821     // FIXME: We're looking into outer scopes here, even when we
10822     // shouldn't be. Doing so can result in ambiguities that we
10823     // shouldn't be diagnosing.
10824     LookupName(Previous, S);
10825 
10826     // When declaring or defining a tag, ignore ambiguities introduced
10827     // by types using'ed into this scope.
10828     if (Previous.isAmbiguous() &&
10829         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
10830       LookupResult::Filter F = Previous.makeFilter();
10831       while (F.hasNext()) {
10832         NamedDecl *ND = F.next();
10833         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10834           F.erase();
10835       }
10836       F.done();
10837     }
10838 
10839     // C++11 [namespace.memdef]p3:
10840     //   If the name in a friend declaration is neither qualified nor
10841     //   a template-id and the declaration is a function or an
10842     //   elaborated-type-specifier, the lookup to determine whether
10843     //   the entity has been previously declared shall not consider
10844     //   any scopes outside the innermost enclosing namespace.
10845     //
10846     // Does it matter that this should be by scope instead of by
10847     // semantic context?
10848     if (!Previous.empty() && TUK == TUK_Friend) {
10849       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10850       LookupResult::Filter F = Previous.makeFilter();
10851       while (F.hasNext()) {
10852         NamedDecl *ND = F.next();
10853         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
10854         if (DC->isFileContext() &&
10855             !EnclosingNS->Encloses(ND->getDeclContext())) {
10856           F.erase();
10857           FriendSawTagOutsideEnclosingNamespace = true;
10858         }
10859       }
10860       F.done();
10861     }
10862 
10863     // Note:  there used to be some attempt at recovery here.
10864     if (Previous.isAmbiguous())
10865       return nullptr;
10866 
10867     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
10868       // FIXME: This makes sure that we ignore the contexts associated
10869       // with C structs, unions, and enums when looking for a matching
10870       // tag declaration or definition. See the similar lookup tweak
10871       // in Sema::LookupName; is there a better way to deal with this?
10872       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10873         SearchDC = SearchDC->getParent();
10874     }
10875   } else if (S->isFunctionPrototypeScope()) {
10876     // If this is an enum declaration in function prototype scope, set its
10877     // initial context to the translation unit.
10878     // FIXME: [citation needed]
10879     SearchDC = Context.getTranslationUnitDecl();
10880   }
10881 
10882   if (Previous.isSingleResult() &&
10883       Previous.getFoundDecl()->isTemplateParameter()) {
10884     // Maybe we will complain about the shadowed template parameter.
10885     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
10886     // Just pretend that we didn't see the previous declaration.
10887     Previous.clear();
10888   }
10889 
10890   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
10891       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
10892     // This is a declaration of or a reference to "std::bad_alloc".
10893     isStdBadAlloc = true;
10894 
10895     if (Previous.empty() && StdBadAlloc) {
10896       // std::bad_alloc has been implicitly declared (but made invisible to
10897       // name lookup). Fill in this implicit declaration as the previous
10898       // declaration, so that the declarations get chained appropriately.
10899       Previous.addDecl(getStdBadAlloc());
10900     }
10901   }
10902 
10903   // If we didn't find a previous declaration, and this is a reference
10904   // (or friend reference), move to the correct scope.  In C++, we
10905   // also need to do a redeclaration lookup there, just in case
10906   // there's a shadow friend decl.
10907   if (Name && Previous.empty() &&
10908       (TUK == TUK_Reference || TUK == TUK_Friend)) {
10909     if (Invalid) goto CreateNewDecl;
10910     assert(SS.isEmpty());
10911 
10912     if (TUK == TUK_Reference) {
10913       // C++ [basic.scope.pdecl]p5:
10914       //   -- for an elaborated-type-specifier of the form
10915       //
10916       //          class-key identifier
10917       //
10918       //      if the elaborated-type-specifier is used in the
10919       //      decl-specifier-seq or parameter-declaration-clause of a
10920       //      function defined in namespace scope, the identifier is
10921       //      declared as a class-name in the namespace that contains
10922       //      the declaration; otherwise, except as a friend
10923       //      declaration, the identifier is declared in the smallest
10924       //      non-class, non-function-prototype scope that contains the
10925       //      declaration.
10926       //
10927       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10928       // C structs and unions.
10929       //
10930       // It is an error in C++ to declare (rather than define) an enum
10931       // type, including via an elaborated type specifier.  We'll
10932       // diagnose that later; for now, declare the enum in the same
10933       // scope as we would have picked for any other tag type.
10934       //
10935       // GNU C also supports this behavior as part of its incomplete
10936       // enum types extension, while GNU C++ does not.
10937       //
10938       // Find the context where we'll be declaring the tag.
10939       // FIXME: We would like to maintain the current DeclContext as the
10940       // lexical context,
10941       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
10942         SearchDC = SearchDC->getParent();
10943 
10944       // Find the scope where we'll be declaring the tag.
10945       while (S->isClassScope() ||
10946              (getLangOpts().CPlusPlus &&
10947               S->isFunctionPrototypeScope()) ||
10948              ((S->getFlags() & Scope::DeclScope) == 0) ||
10949              (S->getEntity() && S->getEntity()->isTransparentContext()))
10950         S = S->getParent();
10951     } else {
10952       assert(TUK == TUK_Friend);
10953       // C++ [namespace.memdef]p3:
10954       //   If a friend declaration in a non-local class first declares a
10955       //   class or function, the friend class or function is a member of
10956       //   the innermost enclosing namespace.
10957       SearchDC = SearchDC->getEnclosingNamespaceContext();
10958     }
10959 
10960     // In C++, we need to do a redeclaration lookup to properly
10961     // diagnose some problems.
10962     if (getLangOpts().CPlusPlus) {
10963       Previous.setRedeclarationKind(ForRedeclaration);
10964       LookupQualifiedName(Previous, SearchDC);
10965     }
10966   }
10967 
10968   if (!Previous.empty()) {
10969     NamedDecl *PrevDecl = Previous.getFoundDecl();
10970     NamedDecl *DirectPrevDecl =
10971         getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
10972 
10973     // It's okay to have a tag decl in the same scope as a typedef
10974     // which hides a tag decl in the same scope.  Finding this
10975     // insanity with a redeclaration lookup can only actually happen
10976     // in C++.
10977     //
10978     // This is also okay for elaborated-type-specifiers, which is
10979     // technically forbidden by the current standard but which is
10980     // okay according to the likely resolution of an open issue;
10981     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
10982     if (getLangOpts().CPlusPlus) {
10983       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10984         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10985           TagDecl *Tag = TT->getDecl();
10986           if (Tag->getDeclName() == Name &&
10987               Tag->getDeclContext()->getRedeclContext()
10988                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
10989             PrevDecl = Tag;
10990             Previous.clear();
10991             Previous.addDecl(Tag);
10992             Previous.resolveKind();
10993           }
10994         }
10995       }
10996     }
10997 
10998     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
10999       // If this is a use of a previous tag, or if the tag is already declared
11000       // in the same scope (so that the definition/declaration completes or
11001       // rementions the tag), reuse the decl.
11002       if (TUK == TUK_Reference || TUK == TUK_Friend ||
11003           isDeclInScope(DirectPrevDecl, SearchDC, S,
11004                         SS.isNotEmpty() || isExplicitSpecialization)) {
11005         // Make sure that this wasn't declared as an enum and now used as a
11006         // struct or something similar.
11007         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
11008                                           TUK == TUK_Definition, KWLoc,
11009                                           *Name)) {
11010           bool SafeToContinue
11011             = (PrevTagDecl->getTagKind() != TTK_Enum &&
11012                Kind != TTK_Enum);
11013           if (SafeToContinue)
11014             Diag(KWLoc, diag::err_use_with_wrong_tag)
11015               << Name
11016               << FixItHint::CreateReplacement(SourceRange(KWLoc),
11017                                               PrevTagDecl->getKindName());
11018           else
11019             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
11020           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
11021 
11022           if (SafeToContinue)
11023             Kind = PrevTagDecl->getTagKind();
11024           else {
11025             // Recover by making this an anonymous redefinition.
11026             Name = nullptr;
11027             Previous.clear();
11028             Invalid = true;
11029           }
11030         }
11031 
11032         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
11033           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
11034 
11035           // If this is an elaborated-type-specifier for a scoped enumeration,
11036           // the 'class' keyword is not necessary and not permitted.
11037           if (TUK == TUK_Reference || TUK == TUK_Friend) {
11038             if (ScopedEnum)
11039               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
11040                 << PrevEnum->isScoped()
11041                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
11042             return PrevTagDecl;
11043           }
11044 
11045           QualType EnumUnderlyingTy;
11046           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11047             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
11048           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
11049             EnumUnderlyingTy = QualType(T, 0);
11050 
11051           // All conflicts with previous declarations are recovered by
11052           // returning the previous declaration, unless this is a definition,
11053           // in which case we want the caller to bail out.
11054           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
11055                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
11056             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
11057         }
11058 
11059         // C++11 [class.mem]p1:
11060         //   A member shall not be declared twice in the member-specification,
11061         //   except that a nested class or member class template can be declared
11062         //   and then later defined.
11063         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
11064             S->isDeclScope(PrevDecl)) {
11065           Diag(NameLoc, diag::ext_member_redeclared);
11066           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
11067         }
11068 
11069         if (!Invalid) {
11070           // If this is a use, just return the declaration we found, unless
11071           // we have attributes.
11072 
11073           // FIXME: In the future, return a variant or some other clue
11074           // for the consumer of this Decl to know it doesn't own it.
11075           // For our current ASTs this shouldn't be a problem, but will
11076           // need to be changed with DeclGroups.
11077           if (!Attr &&
11078               ((TUK == TUK_Reference &&
11079                 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
11080                || TUK == TUK_Friend))
11081             return PrevTagDecl;
11082 
11083           // Diagnose attempts to redefine a tag.
11084           if (TUK == TUK_Definition) {
11085             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
11086               // If we're defining a specialization and the previous definition
11087               // is from an implicit instantiation, don't emit an error
11088               // here; we'll catch this in the general case below.
11089               bool IsExplicitSpecializationAfterInstantiation = false;
11090               if (isExplicitSpecialization) {
11091                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
11092                   IsExplicitSpecializationAfterInstantiation =
11093                     RD->getTemplateSpecializationKind() !=
11094                     TSK_ExplicitSpecialization;
11095                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
11096                   IsExplicitSpecializationAfterInstantiation =
11097                     ED->getTemplateSpecializationKind() !=
11098                     TSK_ExplicitSpecialization;
11099               }
11100 
11101               if (!IsExplicitSpecializationAfterInstantiation) {
11102                 // A redeclaration in function prototype scope in C isn't
11103                 // visible elsewhere, so merely issue a warning.
11104                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
11105                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
11106                 else
11107                   Diag(NameLoc, diag::err_redefinition) << Name;
11108                 Diag(Def->getLocation(), diag::note_previous_definition);
11109                 // If this is a redefinition, recover by making this
11110                 // struct be anonymous, which will make any later
11111                 // references get the previous definition.
11112                 Name = nullptr;
11113                 Previous.clear();
11114                 Invalid = true;
11115               }
11116             } else {
11117               // If the type is currently being defined, complain
11118               // about a nested redefinition.
11119               const TagType *Tag
11120                 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
11121               if (Tag->isBeingDefined()) {
11122                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
11123                 Diag(PrevTagDecl->getLocation(),
11124                      diag::note_previous_definition);
11125                 Name = nullptr;
11126                 Previous.clear();
11127                 Invalid = true;
11128               }
11129             }
11130 
11131             // Okay, this is definition of a previously declared or referenced
11132             // tag. We're going to create a new Decl for it.
11133           }
11134 
11135           // Okay, we're going to make a redeclaration.  If this is some kind
11136           // of reference, make sure we build the redeclaration in the same DC
11137           // as the original, and ignore the current access specifier.
11138           if (TUK == TUK_Friend || TUK == TUK_Reference) {
11139             SearchDC = PrevTagDecl->getDeclContext();
11140             AS = AS_none;
11141           }
11142         }
11143         // If we get here we have (another) forward declaration or we
11144         // have a definition.  Just create a new decl.
11145 
11146       } else {
11147         // If we get here, this is a definition of a new tag type in a nested
11148         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
11149         // new decl/type.  We set PrevDecl to NULL so that the entities
11150         // have distinct types.
11151         Previous.clear();
11152       }
11153       // If we get here, we're going to create a new Decl. If PrevDecl
11154       // is non-NULL, it's a definition of the tag declared by
11155       // PrevDecl. If it's NULL, we have a new definition.
11156 
11157 
11158     // Otherwise, PrevDecl is not a tag, but was found with tag
11159     // lookup.  This is only actually possible in C++, where a few
11160     // things like templates still live in the tag namespace.
11161     } else {
11162       // Use a better diagnostic if an elaborated-type-specifier
11163       // found the wrong kind of type on the first
11164       // (non-redeclaration) lookup.
11165       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
11166           !Previous.isForRedeclaration()) {
11167         unsigned Kind = 0;
11168         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11169         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11170         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11171         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
11172         Diag(PrevDecl->getLocation(), diag::note_declared_at);
11173         Invalid = true;
11174 
11175       // Otherwise, only diagnose if the declaration is in scope.
11176       } else if (!isDeclInScope(PrevDecl, SearchDC, S,
11177                                 SS.isNotEmpty() || isExplicitSpecialization)) {
11178         // do nothing
11179 
11180       // Diagnose implicit declarations introduced by elaborated types.
11181       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
11182         unsigned Kind = 0;
11183         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11184         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11185         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11186         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
11187         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11188         Invalid = true;
11189 
11190       // Otherwise it's a declaration.  Call out a particularly common
11191       // case here.
11192       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11193         unsigned Kind = 0;
11194         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
11195         Diag(NameLoc, diag::err_tag_definition_of_typedef)
11196           << Name << Kind << TND->getUnderlyingType();
11197         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11198         Invalid = true;
11199 
11200       // Otherwise, diagnose.
11201       } else {
11202         // The tag name clashes with something else in the target scope,
11203         // issue an error and recover by making this tag be anonymous.
11204         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
11205         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11206         Name = nullptr;
11207         Invalid = true;
11208       }
11209 
11210       // The existing declaration isn't relevant to us; we're in a
11211       // new scope, so clear out the previous declaration.
11212       Previous.clear();
11213     }
11214   }
11215 
11216 CreateNewDecl:
11217 
11218   TagDecl *PrevDecl = nullptr;
11219   if (Previous.isSingleResult())
11220     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
11221 
11222   // If there is an identifier, use the location of the identifier as the
11223   // location of the decl, otherwise use the location of the struct/union
11224   // keyword.
11225   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
11226 
11227   // Otherwise, create a new declaration. If there is a previous
11228   // declaration of the same entity, the two will be linked via
11229   // PrevDecl.
11230   TagDecl *New;
11231 
11232   bool IsForwardReference = false;
11233   if (Kind == TTK_Enum) {
11234     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11235     // enum X { A, B, C } D;    D should chain to X.
11236     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
11237                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
11238                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
11239     // If this is an undefined enum, warn.
11240     if (TUK != TUK_Definition && !Invalid) {
11241       TagDecl *Def;
11242       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
11243           cast<EnumDecl>(New)->isFixed()) {
11244         // C++0x: 7.2p2: opaque-enum-declaration.
11245         // Conflicts are diagnosed above. Do nothing.
11246       }
11247       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
11248         Diag(Loc, diag::ext_forward_ref_enum_def)
11249           << New;
11250         Diag(Def->getLocation(), diag::note_previous_definition);
11251       } else {
11252         unsigned DiagID = diag::ext_forward_ref_enum;
11253         if (getLangOpts().MSVCCompat)
11254           DiagID = diag::ext_ms_forward_ref_enum;
11255         else if (getLangOpts().CPlusPlus)
11256           DiagID = diag::err_forward_ref_enum;
11257         Diag(Loc, DiagID);
11258 
11259         // If this is a forward-declared reference to an enumeration, make a
11260         // note of it; we won't actually be introducing the declaration into
11261         // the declaration context.
11262         if (TUK == TUK_Reference)
11263           IsForwardReference = true;
11264       }
11265     }
11266 
11267     if (EnumUnderlying) {
11268       EnumDecl *ED = cast<EnumDecl>(New);
11269       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11270         ED->setIntegerTypeSourceInfo(TI);
11271       else
11272         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
11273       ED->setPromotionType(ED->getIntegerType());
11274     }
11275 
11276   } else {
11277     // struct/union/class
11278 
11279     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11280     // struct X { int A; } D;    D should chain to X.
11281     if (getLangOpts().CPlusPlus) {
11282       // FIXME: Look for a way to use RecordDecl for simple structs.
11283       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11284                                   cast_or_null<CXXRecordDecl>(PrevDecl));
11285 
11286       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
11287         StdBadAlloc = cast<CXXRecordDecl>(New);
11288     } else
11289       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11290                                cast_or_null<RecordDecl>(PrevDecl));
11291   }
11292 
11293   // C++11 [dcl.type]p3:
11294   //   A type-specifier-seq shall not define a class or enumeration [...].
11295   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11296     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11297       << Context.getTagDeclType(New);
11298     Invalid = true;
11299   }
11300 
11301   // Maybe add qualifier info.
11302   if (SS.isNotEmpty()) {
11303     if (SS.isSet()) {
11304       // If this is either a declaration or a definition, check the
11305       // nested-name-specifier against the current context. We don't do this
11306       // for explicit specializations, because they have similar checking
11307       // (with more specific diagnostics) in the call to
11308       // CheckMemberSpecialization, below.
11309       if (!isExplicitSpecialization &&
11310           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11311           diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11312         Invalid = true;
11313 
11314       New->setQualifierInfo(SS.getWithLocInContext(Context));
11315       if (TemplateParameterLists.size() > 0) {
11316         New->setTemplateParameterListsInfo(Context,
11317                                            TemplateParameterLists.size(),
11318                                            TemplateParameterLists.data());
11319       }
11320     }
11321     else
11322       Invalid = true;
11323   }
11324 
11325   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11326     // Add alignment attributes if necessary; these attributes are checked when
11327     // the ASTContext lays out the structure.
11328     //
11329     // It is important for implementing the correct semantics that this
11330     // happen here (in act on tag decl). The #pragma pack stack is
11331     // maintained as a result of parser callbacks which can occur at
11332     // many points during the parsing of a struct declaration (because
11333     // the #pragma tokens are effectively skipped over during the
11334     // parsing of the struct).
11335     if (TUK == TUK_Definition) {
11336       AddAlignmentAttributesForRecord(RD);
11337       AddMsStructLayoutForRecord(RD);
11338     }
11339   }
11340 
11341   if (ModulePrivateLoc.isValid()) {
11342     if (isExplicitSpecialization)
11343       Diag(New->getLocation(), diag::err_module_private_specialization)
11344         << 2
11345         << FixItHint::CreateRemoval(ModulePrivateLoc);
11346     // __module_private__ does not apply to local classes. However, we only
11347     // diagnose this as an error when the declaration specifiers are
11348     // freestanding. Here, we just ignore the __module_private__.
11349     else if (!SearchDC->isFunctionOrMethod())
11350       New->setModulePrivate();
11351   }
11352 
11353   // If this is a specialization of a member class (of a class template),
11354   // check the specialization.
11355   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
11356     Invalid = true;
11357 
11358   if (Invalid)
11359     New->setInvalidDecl();
11360 
11361   if (Attr)
11362     ProcessDeclAttributeList(S, New, Attr);
11363 
11364   // If we're declaring or defining a tag in function prototype scope in C,
11365   // note that this type can only be used within the function and add it to
11366   // the list of decls to inject into the function definition scope.
11367   if (!getLangOpts().CPlusPlus && (Name || Kind == TTK_Enum) &&
11368       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
11369     Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11370     DeclsInPrototypeScope.push_back(New);
11371   }
11372 
11373   // Set the lexical context. If the tag has a C++ scope specifier, the
11374   // lexical context will be different from the semantic context.
11375   New->setLexicalDeclContext(CurContext);
11376 
11377   // Mark this as a friend decl if applicable.
11378   // In Microsoft mode, a friend declaration also acts as a forward
11379   // declaration so we always pass true to setObjectOfFriendDecl to make
11380   // the tag name visible.
11381   if (TUK == TUK_Friend)
11382     New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11383                                getLangOpts().MicrosoftExt);
11384 
11385   // Set the access specifier.
11386   if (!Invalid && SearchDC->isRecord())
11387     SetMemberAccessSpecifier(New, PrevDecl, AS);
11388 
11389   if (TUK == TUK_Definition)
11390     New->startDefinition();
11391 
11392   // If this has an identifier, add it to the scope stack.
11393   if (TUK == TUK_Friend) {
11394     // We might be replacing an existing declaration in the lookup tables;
11395     // if so, borrow its access specifier.
11396     if (PrevDecl)
11397       New->setAccess(PrevDecl->getAccess());
11398 
11399     DeclContext *DC = New->getDeclContext()->getRedeclContext();
11400     DC->makeDeclVisibleInContext(New);
11401     if (Name) // can be null along some error paths
11402       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11403         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
11404   } else if (Name) {
11405     S = getNonFieldDeclScope(S);
11406     PushOnScopeChains(New, S, !IsForwardReference);
11407     if (IsForwardReference)
11408       SearchDC->makeDeclVisibleInContext(New);
11409 
11410   } else {
11411     CurContext->addDecl(New);
11412   }
11413 
11414   // If this is the C FILE type, notify the AST context.
11415   if (IdentifierInfo *II = New->getIdentifier())
11416     if (!New->isInvalidDecl() &&
11417         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
11418         II->isStr("FILE"))
11419       Context.setFILEDecl(New);
11420 
11421   if (PrevDecl)
11422     mergeDeclAttributes(New, PrevDecl);
11423 
11424   // If there's a #pragma GCC visibility in scope, set the visibility of this
11425   // record.
11426   AddPushedVisibilityAttribute(New);
11427 
11428   OwnedDecl = true;
11429   // In C++, don't return an invalid declaration. We can't recover well from
11430   // the cases where we make the type anonymous.
11431   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
11432 }
11433 
11434 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
11435   AdjustDeclIfTemplate(TagD);
11436   TagDecl *Tag = cast<TagDecl>(TagD);
11437 
11438   // Enter the tag context.
11439   PushDeclContext(S, Tag);
11440 
11441   ActOnDocumentableDecl(TagD);
11442 
11443   // If there's a #pragma GCC visibility in scope, set the visibility of this
11444   // record.
11445   AddPushedVisibilityAttribute(Tag);
11446 }
11447 
11448 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
11449   assert(isa<ObjCContainerDecl>(IDecl) &&
11450          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11451   DeclContext *OCD = cast<DeclContext>(IDecl);
11452   assert(getContainingDC(OCD) == CurContext &&
11453       "The next DeclContext should be lexically contained in the current one.");
11454   CurContext = OCD;
11455   return IDecl;
11456 }
11457 
11458 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
11459                                            SourceLocation FinalLoc,
11460                                            bool IsFinalSpelledSealed,
11461                                            SourceLocation LBraceLoc) {
11462   AdjustDeclIfTemplate(TagD);
11463   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
11464 
11465   FieldCollector->StartClass();
11466 
11467   if (!Record->getIdentifier())
11468     return;
11469 
11470   if (FinalLoc.isValid())
11471     Record->addAttr(new (Context)
11472                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11473 
11474   // C++ [class]p2:
11475   //   [...] The class-name is also inserted into the scope of the
11476   //   class itself; this is known as the injected-class-name. For
11477   //   purposes of access checking, the injected-class-name is treated
11478   //   as if it were a public member name.
11479   CXXRecordDecl *InjectedClassName
11480     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11481                             Record->getLocStart(), Record->getLocation(),
11482                             Record->getIdentifier(),
11483                             /*PrevDecl=*/nullptr,
11484                             /*DelayTypeCreation=*/true);
11485   Context.getTypeDeclType(InjectedClassName, Record);
11486   InjectedClassName->setImplicit();
11487   InjectedClassName->setAccess(AS_public);
11488   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11489       InjectedClassName->setDescribedClassTemplate(Template);
11490   PushOnScopeChains(InjectedClassName, S);
11491   assert(InjectedClassName->isInjectedClassName() &&
11492          "Broken injected-class-name");
11493 }
11494 
11495 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
11496                                     SourceLocation RBraceLoc) {
11497   AdjustDeclIfTemplate(TagD);
11498   TagDecl *Tag = cast<TagDecl>(TagD);
11499   Tag->setRBraceLoc(RBraceLoc);
11500 
11501   // Make sure we "complete" the definition even it is invalid.
11502   if (Tag->isBeingDefined()) {
11503     assert(Tag->isInvalidDecl() && "We should already have completed it");
11504     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11505       RD->completeDefinition();
11506   }
11507 
11508   if (isa<CXXRecordDecl>(Tag))
11509     FieldCollector->FinishClass();
11510 
11511   // Exit this scope of this tag's definition.
11512   PopDeclContext();
11513 
11514   if (getCurLexicalContext()->isObjCContainer() &&
11515       Tag->getDeclContext()->isFileContext())
11516     Tag->setTopLevelDeclInObjCContainer();
11517 
11518   // Notify the consumer that we've defined a tag.
11519   if (!Tag->isInvalidDecl())
11520     Consumer.HandleTagDeclDefinition(Tag);
11521 }
11522 
11523 void Sema::ActOnObjCContainerFinishDefinition() {
11524   // Exit this scope of this interface definition.
11525   PopDeclContext();
11526 }
11527 
11528 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
11529   assert(DC == CurContext && "Mismatch of container contexts");
11530   OriginalLexicalContext = DC;
11531   ActOnObjCContainerFinishDefinition();
11532 }
11533 
11534 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11535   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
11536   OriginalLexicalContext = nullptr;
11537 }
11538 
11539 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
11540   AdjustDeclIfTemplate(TagD);
11541   TagDecl *Tag = cast<TagDecl>(TagD);
11542   Tag->setInvalidDecl();
11543 
11544   // Make sure we "complete" the definition even it is invalid.
11545   if (Tag->isBeingDefined()) {
11546     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11547       RD->completeDefinition();
11548   }
11549 
11550   // We're undoing ActOnTagStartDefinition here, not
11551   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11552   // the FieldCollector.
11553 
11554   PopDeclContext();
11555 }
11556 
11557 // Note that FieldName may be null for anonymous bitfields.
11558 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11559                                 IdentifierInfo *FieldName,
11560                                 QualType FieldTy, bool IsMsStruct,
11561                                 Expr *BitWidth, bool *ZeroWidth) {
11562   // Default to true; that shouldn't confuse checks for emptiness
11563   if (ZeroWidth)
11564     *ZeroWidth = true;
11565 
11566   // C99 6.7.2.1p4 - verify the field type.
11567   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
11568   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
11569     // Handle incomplete types with specific error.
11570     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
11571       return ExprError();
11572     if (FieldName)
11573       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11574         << FieldName << FieldTy << BitWidth->getSourceRange();
11575     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11576       << FieldTy << BitWidth->getSourceRange();
11577   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11578                                              UPPC_BitFieldWidth))
11579     return ExprError();
11580 
11581   // If the bit-width is type- or value-dependent, don't try to check
11582   // it now.
11583   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
11584     return BitWidth;
11585 
11586   llvm::APSInt Value;
11587   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11588   if (ICE.isInvalid())
11589     return ICE;
11590   BitWidth = ICE.get();
11591 
11592   if (Value != 0 && ZeroWidth)
11593     *ZeroWidth = false;
11594 
11595   // Zero-width bitfield is ok for anonymous field.
11596   if (Value == 0 && FieldName)
11597     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
11598 
11599   if (Value.isSigned() && Value.isNegative()) {
11600     if (FieldName)
11601       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
11602                << FieldName << Value.toString(10);
11603     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11604       << Value.toString(10);
11605   }
11606 
11607   if (!FieldTy->isDependentType()) {
11608     uint64_t TypeSize = Context.getTypeSize(FieldTy);
11609     if (Value.getZExtValue() > TypeSize) {
11610       if (!getLangOpts().CPlusPlus || IsMsStruct ||
11611           Context.getTargetInfo().getCXXABI().isMicrosoft()) {
11612         if (FieldName)
11613           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11614             << FieldName << (unsigned)Value.getZExtValue()
11615             << (unsigned)TypeSize;
11616 
11617         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11618           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11619       }
11620 
11621       if (FieldName)
11622         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11623           << FieldName << (unsigned)Value.getZExtValue()
11624           << (unsigned)TypeSize;
11625       else
11626         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11627           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11628     }
11629   }
11630 
11631   return BitWidth;
11632 }
11633 
11634 /// ActOnField - Each field of a C struct/union is passed into this in order
11635 /// to create a FieldDecl object for it.
11636 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
11637                        Declarator &D, Expr *BitfieldWidth) {
11638   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
11639                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
11640                                /*InitStyle=*/ICIS_NoInit, AS_public);
11641   return Res;
11642 }
11643 
11644 /// HandleField - Analyze a field of a C struct or a C++ data member.
11645 ///
11646 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11647                              SourceLocation DeclStart,
11648                              Declarator &D, Expr *BitWidth,
11649                              InClassInitStyle InitStyle,
11650                              AccessSpecifier AS) {
11651   IdentifierInfo *II = D.getIdentifier();
11652   SourceLocation Loc = DeclStart;
11653   if (II) Loc = D.getIdentifierLoc();
11654 
11655   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11656   QualType T = TInfo->getType();
11657   if (getLangOpts().CPlusPlus) {
11658     CheckExtraCXXDefaultArguments(D);
11659 
11660     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11661                                         UPPC_DataMemberType)) {
11662       D.setInvalidType();
11663       T = Context.IntTy;
11664       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11665     }
11666   }
11667 
11668   // TR 18037 does not allow fields to be declared with address spaces.
11669   if (T.getQualifiers().hasAddressSpace()) {
11670     Diag(Loc, diag::err_field_with_address_space);
11671     D.setInvalidType();
11672   }
11673 
11674   // OpenCL 1.2 spec, s6.9 r:
11675   // The event type cannot be used to declare a structure or union field.
11676   if (LangOpts.OpenCL && T->isEventT()) {
11677     Diag(Loc, diag::err_event_t_struct_field);
11678     D.setInvalidType();
11679   }
11680 
11681   DiagnoseFunctionSpecifiers(D.getDeclSpec());
11682 
11683   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11684     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11685          diag::err_invalid_thread)
11686       << DeclSpec::getSpecifierName(TSCS);
11687 
11688   // Check to see if this name was declared as a member previously
11689   NamedDecl *PrevDecl = nullptr;
11690   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11691   LookupName(Previous, S);
11692   switch (Previous.getResultKind()) {
11693     case LookupResult::Found:
11694     case LookupResult::FoundUnresolvedValue:
11695       PrevDecl = Previous.getAsSingle<NamedDecl>();
11696       break;
11697 
11698     case LookupResult::FoundOverloaded:
11699       PrevDecl = Previous.getRepresentativeDecl();
11700       break;
11701 
11702     case LookupResult::NotFound:
11703     case LookupResult::NotFoundInCurrentInstantiation:
11704     case LookupResult::Ambiguous:
11705       break;
11706   }
11707   Previous.suppressDiagnostics();
11708 
11709   if (PrevDecl && PrevDecl->isTemplateParameter()) {
11710     // Maybe we will complain about the shadowed template parameter.
11711     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11712     // Just pretend that we didn't see the previous declaration.
11713     PrevDecl = nullptr;
11714   }
11715 
11716   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11717     PrevDecl = nullptr;
11718 
11719   bool Mutable
11720     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
11721   SourceLocation TSSL = D.getLocStart();
11722   FieldDecl *NewFD
11723     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
11724                      TSSL, AS, PrevDecl, &D);
11725 
11726   if (NewFD->isInvalidDecl())
11727     Record->setInvalidDecl();
11728 
11729   if (D.getDeclSpec().isModulePrivateSpecified())
11730     NewFD->setModulePrivate();
11731 
11732   if (NewFD->isInvalidDecl() && PrevDecl) {
11733     // Don't introduce NewFD into scope; there's already something
11734     // with the same name in the same scope.
11735   } else if (II) {
11736     PushOnScopeChains(NewFD, S);
11737   } else
11738     Record->addDecl(NewFD);
11739 
11740   return NewFD;
11741 }
11742 
11743 /// \brief Build a new FieldDecl and check its well-formedness.
11744 ///
11745 /// This routine builds a new FieldDecl given the fields name, type,
11746 /// record, etc. \p PrevDecl should refer to any previous declaration
11747 /// with the same name and in the same scope as the field to be
11748 /// created.
11749 ///
11750 /// \returns a new FieldDecl.
11751 ///
11752 /// \todo The Declarator argument is a hack. It will be removed once
11753 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
11754                                 TypeSourceInfo *TInfo,
11755                                 RecordDecl *Record, SourceLocation Loc,
11756                                 bool Mutable, Expr *BitWidth,
11757                                 InClassInitStyle InitStyle,
11758                                 SourceLocation TSSL,
11759                                 AccessSpecifier AS, NamedDecl *PrevDecl,
11760                                 Declarator *D) {
11761   IdentifierInfo *II = Name.getAsIdentifierInfo();
11762   bool InvalidDecl = false;
11763   if (D) InvalidDecl = D->isInvalidType();
11764 
11765   // If we receive a broken type, recover by assuming 'int' and
11766   // marking this declaration as invalid.
11767   if (T.isNull()) {
11768     InvalidDecl = true;
11769     T = Context.IntTy;
11770   }
11771 
11772   QualType EltTy = Context.getBaseElementType(T);
11773   if (!EltTy->isDependentType()) {
11774     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11775       // Fields of incomplete type force their record to be invalid.
11776       Record->setInvalidDecl();
11777       InvalidDecl = true;
11778     } else {
11779       NamedDecl *Def;
11780       EltTy->isIncompleteType(&Def);
11781       if (Def && Def->isInvalidDecl()) {
11782         Record->setInvalidDecl();
11783         InvalidDecl = true;
11784       }
11785     }
11786   }
11787 
11788   // OpenCL v1.2 s6.9.c: bitfields are not supported.
11789   if (BitWidth && getLangOpts().OpenCL) {
11790     Diag(Loc, diag::err_opencl_bitfields);
11791     InvalidDecl = true;
11792   }
11793 
11794   // C99 6.7.2.1p8: A member of a structure or union may have any type other
11795   // than a variably modified type.
11796   if (!InvalidDecl && T->isVariablyModifiedType()) {
11797     bool SizeIsNegative;
11798     llvm::APSInt Oversized;
11799 
11800     TypeSourceInfo *FixedTInfo =
11801       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11802                                                     SizeIsNegative,
11803                                                     Oversized);
11804     if (FixedTInfo) {
11805       Diag(Loc, diag::warn_illegal_constant_array_size);
11806       TInfo = FixedTInfo;
11807       T = FixedTInfo->getType();
11808     } else {
11809       if (SizeIsNegative)
11810         Diag(Loc, diag::err_typecheck_negative_array_size);
11811       else if (Oversized.getBoolValue())
11812         Diag(Loc, diag::err_array_too_large)
11813           << Oversized.toString(10);
11814       else
11815         Diag(Loc, diag::err_typecheck_field_variable_size);
11816       InvalidDecl = true;
11817     }
11818   }
11819 
11820   // Fields can not have abstract class types
11821   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11822                                              diag::err_abstract_type_in_decl,
11823                                              AbstractFieldType))
11824     InvalidDecl = true;
11825 
11826   bool ZeroWidth = false;
11827   // If this is declared as a bit-field, check the bit-field.
11828   if (!InvalidDecl && BitWidth) {
11829     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11830                               &ZeroWidth).get();
11831     if (!BitWidth) {
11832       InvalidDecl = true;
11833       BitWidth = nullptr;
11834       ZeroWidth = false;
11835     }
11836   }
11837 
11838   // Check that 'mutable' is consistent with the type of the declaration.
11839   if (!InvalidDecl && Mutable) {
11840     unsigned DiagID = 0;
11841     if (T->isReferenceType())
11842       DiagID = diag::err_mutable_reference;
11843     else if (T.isConstQualified())
11844       DiagID = diag::err_mutable_const;
11845 
11846     if (DiagID) {
11847       SourceLocation ErrLoc = Loc;
11848       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11849         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11850       Diag(ErrLoc, DiagID);
11851       Mutable = false;
11852       InvalidDecl = true;
11853     }
11854   }
11855 
11856   // C++11 [class.union]p8 (DR1460):
11857   //   At most one variant member of a union may have a
11858   //   brace-or-equal-initializer.
11859   if (InitStyle != ICIS_NoInit)
11860     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
11861 
11862   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
11863                                        BitWidth, Mutable, InitStyle);
11864   if (InvalidDecl)
11865     NewFD->setInvalidDecl();
11866 
11867   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11868     Diag(Loc, diag::err_duplicate_member) << II;
11869     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11870     NewFD->setInvalidDecl();
11871   }
11872 
11873   if (!InvalidDecl && getLangOpts().CPlusPlus) {
11874     if (Record->isUnion()) {
11875       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11876         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11877         if (RDecl->getDefinition()) {
11878           // C++ [class.union]p1: An object of a class with a non-trivial
11879           // constructor, a non-trivial copy constructor, a non-trivial
11880           // destructor, or a non-trivial copy assignment operator
11881           // cannot be a member of a union, nor can an array of such
11882           // objects.
11883           if (CheckNontrivialField(NewFD))
11884             NewFD->setInvalidDecl();
11885         }
11886       }
11887 
11888       // C++ [class.union]p1: If a union contains a member of reference type,
11889       // the program is ill-formed, except when compiling with MSVC extensions
11890       // enabled.
11891       if (EltTy->isReferenceType()) {
11892         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11893                                     diag::ext_union_member_of_reference_type :
11894                                     diag::err_union_member_of_reference_type)
11895           << NewFD->getDeclName() << EltTy;
11896         if (!getLangOpts().MicrosoftExt)
11897           NewFD->setInvalidDecl();
11898       }
11899     }
11900   }
11901 
11902   // FIXME: We need to pass in the attributes given an AST
11903   // representation, not a parser representation.
11904   if (D) {
11905     // FIXME: The current scope is almost... but not entirely... correct here.
11906     ProcessDeclAttributes(getCurScope(), NewFD, *D);
11907 
11908     if (NewFD->hasAttrs())
11909       CheckAlignasUnderalignment(NewFD);
11910   }
11911 
11912   // In auto-retain/release, infer strong retension for fields of
11913   // retainable type.
11914   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
11915     NewFD->setInvalidDecl();
11916 
11917   if (T.isObjCGCWeak())
11918     Diag(Loc, diag::warn_attribute_weak_on_field);
11919 
11920   NewFD->setAccess(AS);
11921   return NewFD;
11922 }
11923 
11924 bool Sema::CheckNontrivialField(FieldDecl *FD) {
11925   assert(FD);
11926   assert(getLangOpts().CPlusPlus && "valid check only for C++");
11927 
11928   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11929     return false;
11930 
11931   QualType EltTy = Context.getBaseElementType(FD->getType());
11932   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11933     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
11934     if (RDecl->getDefinition()) {
11935       // We check for copy constructors before constructors
11936       // because otherwise we'll never get complaints about
11937       // copy constructors.
11938 
11939       CXXSpecialMember member = CXXInvalid;
11940       // We're required to check for any non-trivial constructors. Since the
11941       // implicit default constructor is suppressed if there are any
11942       // user-declared constructors, we just need to check that there is a
11943       // trivial default constructor and a trivial copy constructor. (We don't
11944       // worry about move constructors here, since this is a C++98 check.)
11945       if (RDecl->hasNonTrivialCopyConstructor())
11946         member = CXXCopyConstructor;
11947       else if (!RDecl->hasTrivialDefaultConstructor())
11948         member = CXXDefaultConstructor;
11949       else if (RDecl->hasNonTrivialCopyAssignment())
11950         member = CXXCopyAssignment;
11951       else if (RDecl->hasNonTrivialDestructor())
11952         member = CXXDestructor;
11953 
11954       if (member != CXXInvalid) {
11955         if (!getLangOpts().CPlusPlus11 &&
11956             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
11957           // Objective-C++ ARC: it is an error to have a non-trivial field of
11958           // a union. However, system headers in Objective-C programs
11959           // occasionally have Objective-C lifetime objects within unions,
11960           // and rather than cause the program to fail, we make those
11961           // members unavailable.
11962           SourceLocation Loc = FD->getLocation();
11963           if (getSourceManager().isInSystemHeader(Loc)) {
11964             if (!FD->hasAttr<UnavailableAttr>())
11965               FD->addAttr(UnavailableAttr::CreateImplicit(Context,
11966                                   "this system field has retaining ownership",
11967                                   Loc));
11968             return false;
11969           }
11970         }
11971 
11972         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
11973                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11974                diag::err_illegal_union_or_anon_struct_member)
11975           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
11976         DiagnoseNontrivial(RDecl, member);
11977         return !getLangOpts().CPlusPlus11;
11978       }
11979     }
11980   }
11981 
11982   return false;
11983 }
11984 
11985 /// TranslateIvarVisibility - Translate visibility from a token ID to an
11986 ///  AST enum value.
11987 static ObjCIvarDecl::AccessControl
11988 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
11989   switch (ivarVisibility) {
11990   default: llvm_unreachable("Unknown visitibility kind");
11991   case tok::objc_private: return ObjCIvarDecl::Private;
11992   case tok::objc_public: return ObjCIvarDecl::Public;
11993   case tok::objc_protected: return ObjCIvarDecl::Protected;
11994   case tok::objc_package: return ObjCIvarDecl::Package;
11995   }
11996 }
11997 
11998 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
11999 /// in order to create an IvarDecl object for it.
12000 Decl *Sema::ActOnIvar(Scope *S,
12001                                 SourceLocation DeclStart,
12002                                 Declarator &D, Expr *BitfieldWidth,
12003                                 tok::ObjCKeywordKind Visibility) {
12004 
12005   IdentifierInfo *II = D.getIdentifier();
12006   Expr *BitWidth = (Expr*)BitfieldWidth;
12007   SourceLocation Loc = DeclStart;
12008   if (II) Loc = D.getIdentifierLoc();
12009 
12010   // FIXME: Unnamed fields can be handled in various different ways, for
12011   // example, unnamed unions inject all members into the struct namespace!
12012 
12013   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12014   QualType T = TInfo->getType();
12015 
12016   if (BitWidth) {
12017     // 6.7.2.1p3, 6.7.2.1p4
12018     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
12019     if (!BitWidth)
12020       D.setInvalidType();
12021   } else {
12022     // Not a bitfield.
12023 
12024     // validate II.
12025 
12026   }
12027   if (T->isReferenceType()) {
12028     Diag(Loc, diag::err_ivar_reference_type);
12029     D.setInvalidType();
12030   }
12031   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12032   // than a variably modified type.
12033   else if (T->isVariablyModifiedType()) {
12034     Diag(Loc, diag::err_typecheck_ivar_variable_size);
12035     D.setInvalidType();
12036   }
12037 
12038   // Get the visibility (access control) for this ivar.
12039   ObjCIvarDecl::AccessControl ac =
12040     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
12041                                         : ObjCIvarDecl::None;
12042   // Must set ivar's DeclContext to its enclosing interface.
12043   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
12044   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
12045     return nullptr;
12046   ObjCContainerDecl *EnclosingContext;
12047   if (ObjCImplementationDecl *IMPDecl =
12048       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12049     if (LangOpts.ObjCRuntime.isFragile()) {
12050     // Case of ivar declared in an implementation. Context is that of its class.
12051       EnclosingContext = IMPDecl->getClassInterface();
12052       assert(EnclosingContext && "Implementation has no class interface!");
12053     }
12054     else
12055       EnclosingContext = EnclosingDecl;
12056   } else {
12057     if (ObjCCategoryDecl *CDecl =
12058         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12059       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
12060         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
12061         return nullptr;
12062       }
12063     }
12064     EnclosingContext = EnclosingDecl;
12065   }
12066 
12067   // Construct the decl.
12068   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
12069                                              DeclStart, Loc, II, T,
12070                                              TInfo, ac, (Expr *)BitfieldWidth);
12071 
12072   if (II) {
12073     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
12074                                            ForRedeclaration);
12075     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
12076         && !isa<TagDecl>(PrevDecl)) {
12077       Diag(Loc, diag::err_duplicate_member) << II;
12078       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12079       NewID->setInvalidDecl();
12080     }
12081   }
12082 
12083   // Process attributes attached to the ivar.
12084   ProcessDeclAttributes(S, NewID, D);
12085 
12086   if (D.isInvalidType())
12087     NewID->setInvalidDecl();
12088 
12089   // In ARC, infer 'retaining' for ivars of retainable type.
12090   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
12091     NewID->setInvalidDecl();
12092 
12093   if (D.getDeclSpec().isModulePrivateSpecified())
12094     NewID->setModulePrivate();
12095 
12096   if (II) {
12097     // FIXME: When interfaces are DeclContexts, we'll need to add
12098     // these to the interface.
12099     S->AddDecl(NewID);
12100     IdResolver.AddDecl(NewID);
12101   }
12102 
12103   if (LangOpts.ObjCRuntime.isNonFragile() &&
12104       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
12105     Diag(Loc, diag::warn_ivars_in_interface);
12106 
12107   return NewID;
12108 }
12109 
12110 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
12111 /// class and class extensions. For every class \@interface and class
12112 /// extension \@interface, if the last ivar is a bitfield of any type,
12113 /// then add an implicit `char :0` ivar to the end of that interface.
12114 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
12115                              SmallVectorImpl<Decl *> &AllIvarDecls) {
12116   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
12117     return;
12118 
12119   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
12120   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
12121 
12122   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
12123     return;
12124   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
12125   if (!ID) {
12126     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
12127       if (!CD->IsClassExtension())
12128         return;
12129     }
12130     // No need to add this to end of @implementation.
12131     else
12132       return;
12133   }
12134   // All conditions are met. Add a new bitfield to the tail end of ivars.
12135   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
12136   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
12137 
12138   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
12139                               DeclLoc, DeclLoc, nullptr,
12140                               Context.CharTy,
12141                               Context.getTrivialTypeSourceInfo(Context.CharTy,
12142                                                                DeclLoc),
12143                               ObjCIvarDecl::Private, BW,
12144                               true);
12145   AllIvarDecls.push_back(Ivar);
12146 }
12147 
12148 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
12149                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
12150                        SourceLocation RBrac, AttributeList *Attr) {
12151   assert(EnclosingDecl && "missing record or interface decl");
12152 
12153   // If this is an Objective-C @implementation or category and we have
12154   // new fields here we should reset the layout of the interface since
12155   // it will now change.
12156   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
12157     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
12158     switch (DC->getKind()) {
12159     default: break;
12160     case Decl::ObjCCategory:
12161       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
12162       break;
12163     case Decl::ObjCImplementation:
12164       Context.
12165         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
12166       break;
12167     }
12168   }
12169 
12170   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
12171 
12172   // Start counting up the number of named members; make sure to include
12173   // members of anonymous structs and unions in the total.
12174   unsigned NumNamedMembers = 0;
12175   if (Record) {
12176     for (const auto *I : Record->decls()) {
12177       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
12178         if (IFD->getDeclName())
12179           ++NumNamedMembers;
12180     }
12181   }
12182 
12183   // Verify that all the fields are okay.
12184   SmallVector<FieldDecl*, 32> RecFields;
12185 
12186   bool ARCErrReported = false;
12187   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
12188        i != end; ++i) {
12189     FieldDecl *FD = cast<FieldDecl>(*i);
12190 
12191     // Get the type for the field.
12192     const Type *FDTy = FD->getType().getTypePtr();
12193 
12194     if (!FD->isAnonymousStructOrUnion()) {
12195       // Remember all fields written by the user.
12196       RecFields.push_back(FD);
12197     }
12198 
12199     // If the field is already invalid for some reason, don't emit more
12200     // diagnostics about it.
12201     if (FD->isInvalidDecl()) {
12202       EnclosingDecl->setInvalidDecl();
12203       continue;
12204     }
12205 
12206     // C99 6.7.2.1p2:
12207     //   A structure or union shall not contain a member with
12208     //   incomplete or function type (hence, a structure shall not
12209     //   contain an instance of itself, but may contain a pointer to
12210     //   an instance of itself), except that the last member of a
12211     //   structure with more than one named member may have incomplete
12212     //   array type; such a structure (and any union containing,
12213     //   possibly recursively, a member that is such a structure)
12214     //   shall not be a member of a structure or an element of an
12215     //   array.
12216     if (FDTy->isFunctionType()) {
12217       // Field declared as a function.
12218       Diag(FD->getLocation(), diag::err_field_declared_as_function)
12219         << FD->getDeclName();
12220       FD->setInvalidDecl();
12221       EnclosingDecl->setInvalidDecl();
12222       continue;
12223     } else if (FDTy->isIncompleteArrayType() && Record &&
12224                ((i + 1 == Fields.end() && !Record->isUnion()) ||
12225                 ((getLangOpts().MicrosoftExt ||
12226                   getLangOpts().CPlusPlus) &&
12227                  (i + 1 == Fields.end() || Record->isUnion())))) {
12228       // Flexible array member.
12229       // Microsoft and g++ is more permissive regarding flexible array.
12230       // It will accept flexible array in union and also
12231       // as the sole element of a struct/class.
12232       unsigned DiagID = 0;
12233       if (Record->isUnion())
12234         DiagID = getLangOpts().MicrosoftExt
12235                      ? diag::ext_flexible_array_union_ms
12236                      : getLangOpts().CPlusPlus
12237                            ? diag::ext_flexible_array_union_gnu
12238                            : diag::err_flexible_array_union;
12239       else if (Fields.size() == 1)
12240         DiagID = getLangOpts().MicrosoftExt
12241                      ? diag::ext_flexible_array_empty_aggregate_ms
12242                      : getLangOpts().CPlusPlus
12243                            ? diag::ext_flexible_array_empty_aggregate_gnu
12244                            : NumNamedMembers < 1
12245                                  ? diag::err_flexible_array_empty_aggregate
12246                                  : 0;
12247 
12248       if (DiagID)
12249         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
12250                                         << Record->getTagKind();
12251       // While the layout of types that contain virtual bases is not specified
12252       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
12253       // virtual bases after the derived members.  This would make a flexible
12254       // array member declared at the end of an object not adjacent to the end
12255       // of the type.
12256       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
12257         if (RD->getNumVBases() != 0)
12258           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
12259             << FD->getDeclName() << Record->getTagKind();
12260       if (!getLangOpts().C99)
12261         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
12262           << FD->getDeclName() << Record->getTagKind();
12263 
12264       // If the element type has a non-trivial destructor, we would not
12265       // implicitly destroy the elements, so disallow it for now.
12266       //
12267       // FIXME: GCC allows this. We should probably either implicitly delete
12268       // the destructor of the containing class, or just allow this.
12269       QualType BaseElem = Context.getBaseElementType(FD->getType());
12270       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
12271         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
12272           << FD->getDeclName() << FD->getType();
12273         FD->setInvalidDecl();
12274         EnclosingDecl->setInvalidDecl();
12275         continue;
12276       }
12277       // Okay, we have a legal flexible array member at the end of the struct.
12278       if (Record)
12279         Record->setHasFlexibleArrayMember(true);
12280     } else if (!FDTy->isDependentType() &&
12281                RequireCompleteType(FD->getLocation(), FD->getType(),
12282                                    diag::err_field_incomplete)) {
12283       // Incomplete type
12284       FD->setInvalidDecl();
12285       EnclosingDecl->setInvalidDecl();
12286       continue;
12287     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
12288       if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
12289         // If this is a member of a union, then entire union becomes "flexible".
12290         if (Record && Record->isUnion()) {
12291           Record->setHasFlexibleArrayMember(true);
12292         } else {
12293           // If this is a struct/class and this is not the last element, reject
12294           // it.  Note that GCC supports variable sized arrays in the middle of
12295           // structures.
12296           if (i + 1 != Fields.end())
12297             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
12298               << FD->getDeclName() << FD->getType();
12299           else {
12300             // We support flexible arrays at the end of structs in
12301             // other structs as an extension.
12302             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12303               << FD->getDeclName();
12304             if (Record)
12305               Record->setHasFlexibleArrayMember(true);
12306           }
12307         }
12308       }
12309       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12310           RequireNonAbstractType(FD->getLocation(), FD->getType(),
12311                                  diag::err_abstract_type_in_decl,
12312                                  AbstractIvarType)) {
12313         // Ivars can not have abstract class types
12314         FD->setInvalidDecl();
12315       }
12316       if (Record && FDTTy->getDecl()->hasObjectMember())
12317         Record->setHasObjectMember(true);
12318       if (Record && FDTTy->getDecl()->hasVolatileMember())
12319         Record->setHasVolatileMember(true);
12320     } else if (FDTy->isObjCObjectType()) {
12321       /// A field cannot be an Objective-c object
12322       Diag(FD->getLocation(), diag::err_statically_allocated_object)
12323         << FixItHint::CreateInsertion(FD->getLocation(), "*");
12324       QualType T = Context.getObjCObjectPointerType(FD->getType());
12325       FD->setType(T);
12326     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12327                (!getLangOpts().CPlusPlus || Record->isUnion())) {
12328       // It's an error in ARC if a field has lifetime.
12329       // We don't want to report this in a system header, though,
12330       // so we just make the field unavailable.
12331       // FIXME: that's really not sufficient; we need to make the type
12332       // itself invalid to, say, initialize or copy.
12333       QualType T = FD->getType();
12334       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12335       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12336         SourceLocation loc = FD->getLocation();
12337         if (getSourceManager().isInSystemHeader(loc)) {
12338           if (!FD->hasAttr<UnavailableAttr>()) {
12339             FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12340                               "this system field has retaining ownership",
12341                               loc));
12342           }
12343         } else {
12344           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
12345             << T->isBlockPointerType() << Record->getTagKind();
12346         }
12347         ARCErrReported = true;
12348       }
12349     } else if (getLangOpts().ObjC1 &&
12350                getLangOpts().getGC() != LangOptions::NonGC &&
12351                Record && !Record->hasObjectMember()) {
12352       if (FD->getType()->isObjCObjectPointerType() ||
12353           FD->getType().isObjCGCStrong())
12354         Record->setHasObjectMember(true);
12355       else if (Context.getAsArrayType(FD->getType())) {
12356         QualType BaseType = Context.getBaseElementType(FD->getType());
12357         if (BaseType->isRecordType() &&
12358             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
12359           Record->setHasObjectMember(true);
12360         else if (BaseType->isObjCObjectPointerType() ||
12361                  BaseType.isObjCGCStrong())
12362                Record->setHasObjectMember(true);
12363       }
12364     }
12365     if (Record && FD->getType().isVolatileQualified())
12366       Record->setHasVolatileMember(true);
12367     // Keep track of the number of named members.
12368     if (FD->getIdentifier())
12369       ++NumNamedMembers;
12370   }
12371 
12372   // Okay, we successfully defined 'Record'.
12373   if (Record) {
12374     bool Completed = false;
12375     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12376       if (!CXXRecord->isInvalidDecl()) {
12377         // Set access bits correctly on the directly-declared conversions.
12378         for (CXXRecordDecl::conversion_iterator
12379                I = CXXRecord->conversion_begin(),
12380                E = CXXRecord->conversion_end(); I != E; ++I)
12381           I.setAccess((*I)->getAccess());
12382 
12383         if (!CXXRecord->isDependentType()) {
12384           if (CXXRecord->hasUserDeclaredDestructor()) {
12385             // Adjust user-defined destructor exception spec.
12386             if (getLangOpts().CPlusPlus11)
12387               AdjustDestructorExceptionSpec(CXXRecord,
12388                                             CXXRecord->getDestructor());
12389           }
12390 
12391           // Add any implicitly-declared members to this class.
12392           AddImplicitlyDeclaredMembersToClass(CXXRecord);
12393 
12394           // If we have virtual base classes, we may end up finding multiple
12395           // final overriders for a given virtual function. Check for this
12396           // problem now.
12397           if (CXXRecord->getNumVBases()) {
12398             CXXFinalOverriderMap FinalOverriders;
12399             CXXRecord->getFinalOverriders(FinalOverriders);
12400 
12401             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12402                                              MEnd = FinalOverriders.end();
12403                  M != MEnd; ++M) {
12404               for (OverridingMethods::iterator SO = M->second.begin(),
12405                                             SOEnd = M->second.end();
12406                    SO != SOEnd; ++SO) {
12407                 assert(SO->second.size() > 0 &&
12408                        "Virtual function without overridding functions?");
12409                 if (SO->second.size() == 1)
12410                   continue;
12411 
12412                 // C++ [class.virtual]p2:
12413                 //   In a derived class, if a virtual member function of a base
12414                 //   class subobject has more than one final overrider the
12415                 //   program is ill-formed.
12416                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
12417                   << (const NamedDecl *)M->first << Record;
12418                 Diag(M->first->getLocation(),
12419                      diag::note_overridden_virtual_function);
12420                 for (OverridingMethods::overriding_iterator
12421                           OM = SO->second.begin(),
12422                        OMEnd = SO->second.end();
12423                      OM != OMEnd; ++OM)
12424                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
12425                     << (const NamedDecl *)M->first << OM->Method->getParent();
12426 
12427                 Record->setInvalidDecl();
12428               }
12429             }
12430             CXXRecord->completeDefinition(&FinalOverriders);
12431             Completed = true;
12432           }
12433         }
12434       }
12435     }
12436 
12437     if (!Completed)
12438       Record->completeDefinition();
12439 
12440     if (Record->hasAttrs()) {
12441       CheckAlignasUnderalignment(Record);
12442 
12443       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
12444         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
12445                                            IA->getRange(), IA->getBestCase(),
12446                                            IA->getSemanticSpelling());
12447     }
12448 
12449     // Check if the structure/union declaration is a type that can have zero
12450     // size in C. For C this is a language extension, for C++ it may cause
12451     // compatibility problems.
12452     bool CheckForZeroSize;
12453     if (!getLangOpts().CPlusPlus) {
12454       CheckForZeroSize = true;
12455     } else {
12456       // For C++ filter out types that cannot be referenced in C code.
12457       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12458       CheckForZeroSize =
12459           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12460           !CXXRecord->isDependentType() &&
12461           CXXRecord->isCLike();
12462     }
12463     if (CheckForZeroSize) {
12464       bool ZeroSize = true;
12465       bool IsEmpty = true;
12466       unsigned NonBitFields = 0;
12467       for (RecordDecl::field_iterator I = Record->field_begin(),
12468                                       E = Record->field_end();
12469            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12470         IsEmpty = false;
12471         if (I->isUnnamedBitfield()) {
12472           if (I->getBitWidthValue(Context) > 0)
12473             ZeroSize = false;
12474         } else {
12475           ++NonBitFields;
12476           QualType FieldType = I->getType();
12477           if (FieldType->isIncompleteType() ||
12478               !Context.getTypeSizeInChars(FieldType).isZero())
12479             ZeroSize = false;
12480         }
12481       }
12482 
12483       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12484       // allowed in C++, but warn if its declaration is inside
12485       // extern "C" block.
12486       if (ZeroSize) {
12487         Diag(RecLoc, getLangOpts().CPlusPlus ?
12488                          diag::warn_zero_size_struct_union_in_extern_c :
12489                          diag::warn_zero_size_struct_union_compat)
12490           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12491       }
12492 
12493       // Structs without named members are extension in C (C99 6.7.2.1p7),
12494       // but are accepted by GCC.
12495       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12496         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12497                                diag::ext_no_named_members_in_struct_union)
12498           << Record->isUnion();
12499       }
12500     }
12501   } else {
12502     ObjCIvarDecl **ClsFields =
12503       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
12504     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
12505       ID->setEndOfDefinitionLoc(RBrac);
12506       // Add ivar's to class's DeclContext.
12507       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12508         ClsFields[i]->setLexicalDeclContext(ID);
12509         ID->addDecl(ClsFields[i]);
12510       }
12511       // Must enforce the rule that ivars in the base classes may not be
12512       // duplicates.
12513       if (ID->getSuperClass())
12514         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
12515     } else if (ObjCImplementationDecl *IMPDecl =
12516                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12517       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
12518       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12519         // Ivar declared in @implementation never belongs to the implementation.
12520         // Only it is in implementation's lexical context.
12521         ClsFields[I]->setLexicalDeclContext(IMPDecl);
12522       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
12523       IMPDecl->setIvarLBraceLoc(LBrac);
12524       IMPDecl->setIvarRBraceLoc(RBrac);
12525     } else if (ObjCCategoryDecl *CDecl =
12526                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12527       // case of ivars in class extension; all other cases have been
12528       // reported as errors elsewhere.
12529       // FIXME. Class extension does not have a LocEnd field.
12530       // CDecl->setLocEnd(RBrac);
12531       // Add ivar's to class extension's DeclContext.
12532       // Diagnose redeclaration of private ivars.
12533       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
12534       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12535         if (IDecl) {
12536           if (const ObjCIvarDecl *ClsIvar =
12537               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12538             Diag(ClsFields[i]->getLocation(),
12539                  diag::err_duplicate_ivar_declaration);
12540             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12541             continue;
12542           }
12543           for (const auto *Ext : IDecl->known_extensions()) {
12544             if (const ObjCIvarDecl *ClsExtIvar
12545                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
12546               Diag(ClsFields[i]->getLocation(),
12547                    diag::err_duplicate_ivar_declaration);
12548               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12549               continue;
12550             }
12551           }
12552         }
12553         ClsFields[i]->setLexicalDeclContext(CDecl);
12554         CDecl->addDecl(ClsFields[i]);
12555       }
12556       CDecl->setIvarLBraceLoc(LBrac);
12557       CDecl->setIvarRBraceLoc(RBrac);
12558     }
12559   }
12560 
12561   if (Attr)
12562     ProcessDeclAttributeList(S, Record, Attr);
12563 }
12564 
12565 /// \brief Determine whether the given integral value is representable within
12566 /// the given type T.
12567 static bool isRepresentableIntegerValue(ASTContext &Context,
12568                                         llvm::APSInt &Value,
12569                                         QualType T) {
12570   assert(T->isIntegralType(Context) && "Integral type required!");
12571   unsigned BitWidth = Context.getIntWidth(T);
12572 
12573   if (Value.isUnsigned() || Value.isNonNegative()) {
12574     if (T->isSignedIntegerOrEnumerationType())
12575       --BitWidth;
12576     return Value.getActiveBits() <= BitWidth;
12577   }
12578   return Value.getMinSignedBits() <= BitWidth;
12579 }
12580 
12581 // \brief Given an integral type, return the next larger integral type
12582 // (or a NULL type of no such type exists).
12583 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12584   // FIXME: Int128/UInt128 support, which also needs to be introduced into
12585   // enum checking below.
12586   assert(T->isIntegralType(Context) && "Integral type required!");
12587   const unsigned NumTypes = 4;
12588   QualType SignedIntegralTypes[NumTypes] = {
12589     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12590   };
12591   QualType UnsignedIntegralTypes[NumTypes] = {
12592     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12593     Context.UnsignedLongLongTy
12594   };
12595 
12596   unsigned BitWidth = Context.getTypeSize(T);
12597   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12598                                                         : UnsignedIntegralTypes;
12599   for (unsigned I = 0; I != NumTypes; ++I)
12600     if (Context.getTypeSize(Types[I]) > BitWidth)
12601       return Types[I];
12602 
12603   return QualType();
12604 }
12605 
12606 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12607                                           EnumConstantDecl *LastEnumConst,
12608                                           SourceLocation IdLoc,
12609                                           IdentifierInfo *Id,
12610                                           Expr *Val) {
12611   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12612   llvm::APSInt EnumVal(IntWidth);
12613   QualType EltTy;
12614 
12615   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12616     Val = nullptr;
12617 
12618   if (Val)
12619     Val = DefaultLvalueConversion(Val).get();
12620 
12621   if (Val) {
12622     if (Enum->isDependentType() || Val->isTypeDependent())
12623       EltTy = Context.DependentTy;
12624     else {
12625       SourceLocation ExpLoc;
12626       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
12627           !getLangOpts().MSVCCompat) {
12628         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12629         // constant-expression in the enumerator-definition shall be a converted
12630         // constant expression of the underlying type.
12631         EltTy = Enum->getIntegerType();
12632         ExprResult Converted =
12633           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12634                                            CCEK_Enumerator);
12635         if (Converted.isInvalid())
12636           Val = nullptr;
12637         else
12638           Val = Converted.get();
12639       } else if (!Val->isValueDependent() &&
12640                  !(Val = VerifyIntegerConstantExpression(Val,
12641                                                          &EnumVal).get())) {
12642         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
12643       } else {
12644         if (Enum->isFixed()) {
12645           EltTy = Enum->getIntegerType();
12646 
12647           // In Obj-C and Microsoft mode, require the enumeration value to be
12648           // representable in the underlying type of the enumeration. In C++11,
12649           // we perform a non-narrowing conversion as part of converted constant
12650           // expression checking.
12651           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12652             if (getLangOpts().MSVCCompat) {
12653               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
12654               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
12655             } else
12656               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
12657           } else
12658             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
12659         } else if (getLangOpts().CPlusPlus) {
12660           // C++11 [dcl.enum]p5:
12661           //   If the underlying type is not fixed, the type of each enumerator
12662           //   is the type of its initializing value:
12663           //     - If an initializer is specified for an enumerator, the
12664           //       initializing value has the same type as the expression.
12665           EltTy = Val->getType();
12666         } else {
12667           // C99 6.7.2.2p2:
12668           //   The expression that defines the value of an enumeration constant
12669           //   shall be an integer constant expression that has a value
12670           //   representable as an int.
12671 
12672           // Complain if the value is not representable in an int.
12673           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12674             Diag(IdLoc, diag::ext_enum_value_not_int)
12675               << EnumVal.toString(10) << Val->getSourceRange()
12676               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12677           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12678             // Force the type of the expression to 'int'.
12679             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
12680           }
12681           EltTy = Val->getType();
12682         }
12683       }
12684     }
12685   }
12686 
12687   if (!Val) {
12688     if (Enum->isDependentType())
12689       EltTy = Context.DependentTy;
12690     else if (!LastEnumConst) {
12691       // C++0x [dcl.enum]p5:
12692       //   If the underlying type is not fixed, the type of each enumerator
12693       //   is the type of its initializing value:
12694       //     - If no initializer is specified for the first enumerator, the
12695       //       initializing value has an unspecified integral type.
12696       //
12697       // GCC uses 'int' for its unspecified integral type, as does
12698       // C99 6.7.2.2p3.
12699       if (Enum->isFixed()) {
12700         EltTy = Enum->getIntegerType();
12701       }
12702       else {
12703         EltTy = Context.IntTy;
12704       }
12705     } else {
12706       // Assign the last value + 1.
12707       EnumVal = LastEnumConst->getInitVal();
12708       ++EnumVal;
12709       EltTy = LastEnumConst->getType();
12710 
12711       // Check for overflow on increment.
12712       if (EnumVal < LastEnumConst->getInitVal()) {
12713         // C++0x [dcl.enum]p5:
12714         //   If the underlying type is not fixed, the type of each enumerator
12715         //   is the type of its initializing value:
12716         //
12717         //     - Otherwise the type of the initializing value is the same as
12718         //       the type of the initializing value of the preceding enumerator
12719         //       unless the incremented value is not representable in that type,
12720         //       in which case the type is an unspecified integral type
12721         //       sufficient to contain the incremented value. If no such type
12722         //       exists, the program is ill-formed.
12723         QualType T = getNextLargerIntegralType(Context, EltTy);
12724         if (T.isNull() || Enum->isFixed()) {
12725           // There is no integral type larger enough to represent this
12726           // value. Complain, then allow the value to wrap around.
12727           EnumVal = LastEnumConst->getInitVal();
12728           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
12729           ++EnumVal;
12730           if (Enum->isFixed())
12731             // When the underlying type is fixed, this is ill-formed.
12732             Diag(IdLoc, diag::err_enumerator_wrapped)
12733               << EnumVal.toString(10)
12734               << EltTy;
12735           else
12736             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
12737               << EnumVal.toString(10);
12738         } else {
12739           EltTy = T;
12740         }
12741 
12742         // Retrieve the last enumerator's value, extent that type to the
12743         // type that is supposed to be large enough to represent the incremented
12744         // value, then increment.
12745         EnumVal = LastEnumConst->getInitVal();
12746         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12747         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
12748         ++EnumVal;
12749 
12750         // If we're not in C++, diagnose the overflow of enumerator values,
12751         // which in C99 means that the enumerator value is not representable in
12752         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12753         // permits enumerator values that are representable in some larger
12754         // integral type.
12755         if (!getLangOpts().CPlusPlus && !T.isNull())
12756           Diag(IdLoc, diag::warn_enum_value_overflow);
12757       } else if (!getLangOpts().CPlusPlus &&
12758                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12759         // Enforce C99 6.7.2.2p2 even when we compute the next value.
12760         Diag(IdLoc, diag::ext_enum_value_not_int)
12761           << EnumVal.toString(10) << 1;
12762       }
12763     }
12764   }
12765 
12766   if (!EltTy->isDependentType()) {
12767     // Make the enumerator value match the signedness and size of the
12768     // enumerator's type.
12769     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
12770     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12771   }
12772 
12773   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
12774                                   Val, EnumVal);
12775 }
12776 
12777 
12778 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12779                               SourceLocation IdLoc, IdentifierInfo *Id,
12780                               AttributeList *Attr,
12781                               SourceLocation EqualLoc, Expr *Val) {
12782   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
12783   EnumConstantDecl *LastEnumConst =
12784     cast_or_null<EnumConstantDecl>(lastEnumConst);
12785 
12786   // The scope passed in may not be a decl scope.  Zip up the scope tree until
12787   // we find one that is.
12788   S = getNonFieldDeclScope(S);
12789 
12790   // Verify that there isn't already something declared with this name in this
12791   // scope.
12792   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
12793                                          ForRedeclaration);
12794   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12795     // Maybe we will complain about the shadowed template parameter.
12796     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12797     // Just pretend that we didn't see the previous declaration.
12798     PrevDecl = nullptr;
12799   }
12800 
12801   if (PrevDecl) {
12802     // When in C++, we may get a TagDecl with the same name; in this case the
12803     // enum constant will 'hide' the tag.
12804     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
12805            "Received TagDecl when not in C++!");
12806     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
12807       if (isa<EnumConstantDecl>(PrevDecl))
12808         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
12809       else
12810         Diag(IdLoc, diag::err_redefinition) << Id;
12811       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12812       return nullptr;
12813     }
12814   }
12815 
12816   // C++ [class.mem]p15:
12817   // If T is the name of a class, then each of the following shall have a name
12818   // different from T:
12819   // - every enumerator of every member of class T that is an unscoped
12820   // enumerated type
12821   if (CXXRecordDecl *Record
12822                       = dyn_cast<CXXRecordDecl>(
12823                              TheEnumDecl->getDeclContext()->getRedeclContext()))
12824     if (!TheEnumDecl->isScoped() &&
12825         Record->getIdentifier() && Record->getIdentifier() == Id)
12826       Diag(IdLoc, diag::err_member_name_of_class) << Id;
12827 
12828   EnumConstantDecl *New =
12829     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
12830 
12831   if (New) {
12832     // Process attributes.
12833     if (Attr) ProcessDeclAttributeList(S, New, Attr);
12834 
12835     // Register this decl in the current scope stack.
12836     New->setAccess(TheEnumDecl->getAccess());
12837     PushOnScopeChains(New, S);
12838   }
12839 
12840   ActOnDocumentableDecl(New);
12841 
12842   return New;
12843 }
12844 
12845 // Returns true when the enum initial expression does not trigger the
12846 // duplicate enum warning.  A few common cases are exempted as follows:
12847 // Element2 = Element1
12848 // Element2 = Element1 + 1
12849 // Element2 = Element1 - 1
12850 // Where Element2 and Element1 are from the same enum.
12851 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12852   Expr *InitExpr = ECD->getInitExpr();
12853   if (!InitExpr)
12854     return true;
12855   InitExpr = InitExpr->IgnoreImpCasts();
12856 
12857   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12858     if (!BO->isAdditiveOp())
12859       return true;
12860     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12861     if (!IL)
12862       return true;
12863     if (IL->getValue() != 1)
12864       return true;
12865 
12866     InitExpr = BO->getLHS();
12867   }
12868 
12869   // This checks if the elements are from the same enum.
12870   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12871   if (!DRE)
12872     return true;
12873 
12874   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12875   if (!EnumConstant)
12876     return true;
12877 
12878   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12879       Enum)
12880     return true;
12881 
12882   return false;
12883 }
12884 
12885 struct DupKey {
12886   int64_t val;
12887   bool isTombstoneOrEmptyKey;
12888   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12889     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12890 };
12891 
12892 static DupKey GetDupKey(const llvm::APSInt& Val) {
12893   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12894                 false);
12895 }
12896 
12897 struct DenseMapInfoDupKey {
12898   static DupKey getEmptyKey() { return DupKey(0, true); }
12899   static DupKey getTombstoneKey() { return DupKey(1, true); }
12900   static unsigned getHashValue(const DupKey Key) {
12901     return (unsigned)(Key.val * 37);
12902   }
12903   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12904     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12905            LHS.val == RHS.val;
12906   }
12907 };
12908 
12909 // Emits a warning when an element is implicitly set a value that
12910 // a previous element has already been set to.
12911 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12912                                         EnumDecl *Enum,
12913                                         QualType EnumType) {
12914   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
12915     return;
12916   // Avoid anonymous enums
12917   if (!Enum->getIdentifier())
12918     return;
12919 
12920   // Only check for small enums.
12921   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12922     return;
12923 
12924   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12925   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
12926 
12927   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12928   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12929           ValueToVectorMap;
12930 
12931   DuplicatesVector DupVector;
12932   ValueToVectorMap EnumMap;
12933 
12934   // Populate the EnumMap with all values represented by enum constants without
12935   // an initialier.
12936   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12937     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12938 
12939     // Null EnumConstantDecl means a previous diagnostic has been emitted for
12940     // this constant.  Skip this enum since it may be ill-formed.
12941     if (!ECD) {
12942       return;
12943     }
12944 
12945     if (ECD->getInitExpr())
12946       continue;
12947 
12948     DupKey Key = GetDupKey(ECD->getInitVal());
12949     DeclOrVector &Entry = EnumMap[Key];
12950 
12951     // First time encountering this value.
12952     if (Entry.isNull())
12953       Entry = ECD;
12954   }
12955 
12956   // Create vectors for any values that has duplicates.
12957   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12958     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12959     if (!ValidDuplicateEnum(ECD, Enum))
12960       continue;
12961 
12962     DupKey Key = GetDupKey(ECD->getInitVal());
12963 
12964     DeclOrVector& Entry = EnumMap[Key];
12965     if (Entry.isNull())
12966       continue;
12967 
12968     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12969       // Ensure constants are different.
12970       if (D == ECD)
12971         continue;
12972 
12973       // Create new vector and push values onto it.
12974       ECDVector *Vec = new ECDVector();
12975       Vec->push_back(D);
12976       Vec->push_back(ECD);
12977 
12978       // Update entry to point to the duplicates vector.
12979       Entry = Vec;
12980 
12981       // Store the vector somewhere we can consult later for quick emission of
12982       // diagnostics.
12983       DupVector.push_back(Vec);
12984       continue;
12985     }
12986 
12987     ECDVector *Vec = Entry.get<ECDVector*>();
12988     // Make sure constants are not added more than once.
12989     if (*Vec->begin() == ECD)
12990       continue;
12991 
12992     Vec->push_back(ECD);
12993   }
12994 
12995   // Emit diagnostics.
12996   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12997                                   DupVectorEnd = DupVector.end();
12998        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12999     ECDVector *Vec = *DupVectorIter;
13000     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
13001 
13002     // Emit warning for one enum constant.
13003     ECDVector::iterator I = Vec->begin();
13004     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
13005       << (*I)->getName() << (*I)->getInitVal().toString(10)
13006       << (*I)->getSourceRange();
13007     ++I;
13008 
13009     // Emit one note for each of the remaining enum constants with
13010     // the same value.
13011     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
13012       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
13013         << (*I)->getName() << (*I)->getInitVal().toString(10)
13014         << (*I)->getSourceRange();
13015     delete Vec;
13016   }
13017 }
13018 
13019 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
13020                          SourceLocation RBraceLoc, Decl *EnumDeclX,
13021                          ArrayRef<Decl *> Elements,
13022                          Scope *S, AttributeList *Attr) {
13023   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
13024   QualType EnumType = Context.getTypeDeclType(Enum);
13025 
13026   if (Attr)
13027     ProcessDeclAttributeList(S, Enum, Attr);
13028 
13029   if (Enum->isDependentType()) {
13030     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13031       EnumConstantDecl *ECD =
13032         cast_or_null<EnumConstantDecl>(Elements[i]);
13033       if (!ECD) continue;
13034 
13035       ECD->setType(EnumType);
13036     }
13037 
13038     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
13039     return;
13040   }
13041 
13042   // TODO: If the result value doesn't fit in an int, it must be a long or long
13043   // long value.  ISO C does not support this, but GCC does as an extension,
13044   // emit a warning.
13045   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13046   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
13047   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
13048 
13049   // Verify that all the values are okay, compute the size of the values, and
13050   // reverse the list.
13051   unsigned NumNegativeBits = 0;
13052   unsigned NumPositiveBits = 0;
13053 
13054   // Keep track of whether all elements have type int.
13055   bool AllElementsInt = true;
13056 
13057   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13058     EnumConstantDecl *ECD =
13059       cast_or_null<EnumConstantDecl>(Elements[i]);
13060     if (!ECD) continue;  // Already issued a diagnostic.
13061 
13062     const llvm::APSInt &InitVal = ECD->getInitVal();
13063 
13064     // Keep track of the size of positive and negative values.
13065     if (InitVal.isUnsigned() || InitVal.isNonNegative())
13066       NumPositiveBits = std::max(NumPositiveBits,
13067                                  (unsigned)InitVal.getActiveBits());
13068     else
13069       NumNegativeBits = std::max(NumNegativeBits,
13070                                  (unsigned)InitVal.getMinSignedBits());
13071 
13072     // Keep track of whether every enum element has type int (very commmon).
13073     if (AllElementsInt)
13074       AllElementsInt = ECD->getType() == Context.IntTy;
13075   }
13076 
13077   // Figure out the type that should be used for this enum.
13078   QualType BestType;
13079   unsigned BestWidth;
13080 
13081   // C++0x N3000 [conv.prom]p3:
13082   //   An rvalue of an unscoped enumeration type whose underlying
13083   //   type is not fixed can be converted to an rvalue of the first
13084   //   of the following types that can represent all the values of
13085   //   the enumeration: int, unsigned int, long int, unsigned long
13086   //   int, long long int, or unsigned long long int.
13087   // C99 6.4.4.3p2:
13088   //   An identifier declared as an enumeration constant has type int.
13089   // The C99 rule is modified by a gcc extension
13090   QualType BestPromotionType;
13091 
13092   bool Packed = Enum->hasAttr<PackedAttr>();
13093   // -fshort-enums is the equivalent to specifying the packed attribute on all
13094   // enum definitions.
13095   if (LangOpts.ShortEnums)
13096     Packed = true;
13097 
13098   if (Enum->isFixed()) {
13099     BestType = Enum->getIntegerType();
13100     if (BestType->isPromotableIntegerType())
13101       BestPromotionType = Context.getPromotedIntegerType(BestType);
13102     else
13103       BestPromotionType = BestType;
13104     // We don't need to set BestWidth, because BestType is going to be the type
13105     // of the enumerators, but we do anyway because otherwise some compilers
13106     // warn that it might be used uninitialized.
13107     BestWidth = CharWidth;
13108   }
13109   else if (NumNegativeBits) {
13110     // If there is a negative value, figure out the smallest integer type (of
13111     // int/long/longlong) that fits.
13112     // If it's packed, check also if it fits a char or a short.
13113     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
13114       BestType = Context.SignedCharTy;
13115       BestWidth = CharWidth;
13116     } else if (Packed && NumNegativeBits <= ShortWidth &&
13117                NumPositiveBits < ShortWidth) {
13118       BestType = Context.ShortTy;
13119       BestWidth = ShortWidth;
13120     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
13121       BestType = Context.IntTy;
13122       BestWidth = IntWidth;
13123     } else {
13124       BestWidth = Context.getTargetInfo().getLongWidth();
13125 
13126       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
13127         BestType = Context.LongTy;
13128       } else {
13129         BestWidth = Context.getTargetInfo().getLongLongWidth();
13130 
13131         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
13132           Diag(Enum->getLocation(), diag::ext_enum_too_large);
13133         BestType = Context.LongLongTy;
13134       }
13135     }
13136     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
13137   } else {
13138     // If there is no negative value, figure out the smallest type that fits
13139     // all of the enumerator values.
13140     // If it's packed, check also if it fits a char or a short.
13141     if (Packed && NumPositiveBits <= CharWidth) {
13142       BestType = Context.UnsignedCharTy;
13143       BestPromotionType = Context.IntTy;
13144       BestWidth = CharWidth;
13145     } else if (Packed && NumPositiveBits <= ShortWidth) {
13146       BestType = Context.UnsignedShortTy;
13147       BestPromotionType = Context.IntTy;
13148       BestWidth = ShortWidth;
13149     } else if (NumPositiveBits <= IntWidth) {
13150       BestType = Context.UnsignedIntTy;
13151       BestWidth = IntWidth;
13152       BestPromotionType
13153         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13154                            ? Context.UnsignedIntTy : Context.IntTy;
13155     } else if (NumPositiveBits <=
13156                (BestWidth = Context.getTargetInfo().getLongWidth())) {
13157       BestType = Context.UnsignedLongTy;
13158       BestPromotionType
13159         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13160                            ? Context.UnsignedLongTy : Context.LongTy;
13161     } else {
13162       BestWidth = Context.getTargetInfo().getLongLongWidth();
13163       assert(NumPositiveBits <= BestWidth &&
13164              "How could an initializer get larger than ULL?");
13165       BestType = Context.UnsignedLongLongTy;
13166       BestPromotionType
13167         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13168                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
13169     }
13170   }
13171 
13172   // Loop over all of the enumerator constants, changing their types to match
13173   // the type of the enum if needed.
13174   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13175     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
13176     if (!ECD) continue;  // Already issued a diagnostic.
13177 
13178     // Standard C says the enumerators have int type, but we allow, as an
13179     // extension, the enumerators to be larger than int size.  If each
13180     // enumerator value fits in an int, type it as an int, otherwise type it the
13181     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
13182     // that X has type 'int', not 'unsigned'.
13183 
13184     // Determine whether the value fits into an int.
13185     llvm::APSInt InitVal = ECD->getInitVal();
13186 
13187     // If it fits into an integer type, force it.  Otherwise force it to match
13188     // the enum decl type.
13189     QualType NewTy;
13190     unsigned NewWidth;
13191     bool NewSign;
13192     if (!getLangOpts().CPlusPlus &&
13193         !Enum->isFixed() &&
13194         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
13195       NewTy = Context.IntTy;
13196       NewWidth = IntWidth;
13197       NewSign = true;
13198     } else if (ECD->getType() == BestType) {
13199       // Already the right type!
13200       if (getLangOpts().CPlusPlus)
13201         // C++ [dcl.enum]p4: Following the closing brace of an
13202         // enum-specifier, each enumerator has the type of its
13203         // enumeration.
13204         ECD->setType(EnumType);
13205       continue;
13206     } else {
13207       NewTy = BestType;
13208       NewWidth = BestWidth;
13209       NewSign = BestType->isSignedIntegerOrEnumerationType();
13210     }
13211 
13212     // Adjust the APSInt value.
13213     InitVal = InitVal.extOrTrunc(NewWidth);
13214     InitVal.setIsSigned(NewSign);
13215     ECD->setInitVal(InitVal);
13216 
13217     // Adjust the Expr initializer and type.
13218     if (ECD->getInitExpr() &&
13219         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
13220       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
13221                                                 CK_IntegralCast,
13222                                                 ECD->getInitExpr(),
13223                                                 /*base paths*/ nullptr,
13224                                                 VK_RValue));
13225     if (getLangOpts().CPlusPlus)
13226       // C++ [dcl.enum]p4: Following the closing brace of an
13227       // enum-specifier, each enumerator has the type of its
13228       // enumeration.
13229       ECD->setType(EnumType);
13230     else
13231       ECD->setType(NewTy);
13232   }
13233 
13234   Enum->completeDefinition(BestType, BestPromotionType,
13235                            NumPositiveBits, NumNegativeBits);
13236 
13237   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
13238 
13239   // Now that the enum type is defined, ensure it's not been underaligned.
13240   if (Enum->hasAttrs())
13241     CheckAlignasUnderalignment(Enum);
13242 }
13243 
13244 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
13245                                   SourceLocation StartLoc,
13246                                   SourceLocation EndLoc) {
13247   StringLiteral *AsmString = cast<StringLiteral>(expr);
13248 
13249   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
13250                                                    AsmString, StartLoc,
13251                                                    EndLoc);
13252   CurContext->addDecl(New);
13253   return New;
13254 }
13255 
13256 static void checkModuleImportContext(Sema &S, Module *M,
13257                                      SourceLocation ImportLoc,
13258                                      DeclContext *DC) {
13259   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
13260     switch (LSD->getLanguage()) {
13261     case LinkageSpecDecl::lang_c:
13262       if (!M->IsExternC) {
13263         S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
13264           << M->getFullModuleName();
13265         S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
13266         return;
13267       }
13268       break;
13269     case LinkageSpecDecl::lang_cxx:
13270       break;
13271     }
13272     DC = LSD->getParent();
13273   }
13274 
13275   while (isa<LinkageSpecDecl>(DC))
13276     DC = DC->getParent();
13277   if (!isa<TranslationUnitDecl>(DC)) {
13278     S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
13279       << M->getFullModuleName() << DC;
13280     S.Diag(cast<Decl>(DC)->getLocStart(),
13281            diag::note_module_import_not_at_top_level)
13282       << DC;
13283   }
13284 }
13285 
13286 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
13287                                    SourceLocation ImportLoc,
13288                                    ModuleIdPath Path) {
13289   Module *Mod =
13290       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
13291                                    /*IsIncludeDirective=*/false);
13292   if (!Mod)
13293     return true;
13294 
13295   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13296 
13297   // FIXME: we should support importing a submodule within a different submodule
13298   // of the same top-level module. Until we do, make it an error rather than
13299   // silently ignoring the import.
13300   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
13301     Diag(ImportLoc, diag::err_module_self_import)
13302         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
13303 
13304   SmallVector<SourceLocation, 2> IdentifierLocs;
13305   Module *ModCheck = Mod;
13306   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13307     // If we've run out of module parents, just drop the remaining identifiers.
13308     // We need the length to be consistent.
13309     if (!ModCheck)
13310       break;
13311     ModCheck = ModCheck->Parent;
13312 
13313     IdentifierLocs.push_back(Path[I].second);
13314   }
13315 
13316   ImportDecl *Import = ImportDecl::Create(Context,
13317                                           Context.getTranslationUnitDecl(),
13318                                           AtLoc.isValid()? AtLoc : ImportLoc,
13319                                           Mod, IdentifierLocs);
13320   Context.getTranslationUnitDecl()->addDecl(Import);
13321   return Import;
13322 }
13323 
13324 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
13325   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13326 
13327   // FIXME: Should we synthesize an ImportDecl here?
13328   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13329                                       /*Complain=*/true);
13330 }
13331 
13332 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
13333                                                       Module *Mod) {
13334   // Bail if we're not allowed to implicitly import a module here.
13335   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
13336     return;
13337 
13338   // Create the implicit import declaration.
13339   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13340   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13341                                                    Loc, Mod, Loc);
13342   TU->addDecl(ImportD);
13343   Consumer.HandleImplicitImportDecl(ImportD);
13344 
13345   // Make the module visible.
13346   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13347                                       /*Complain=*/false);
13348 }
13349 
13350 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13351                                       IdentifierInfo* AliasName,
13352                                       SourceLocation PragmaLoc,
13353                                       SourceLocation NameLoc,
13354                                       SourceLocation AliasNameLoc) {
13355   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13356                                     LookupOrdinaryName);
13357   AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13358                                                     AliasName->getName(), 0);
13359 
13360   if (PrevDecl)
13361     PrevDecl->addAttr(Attr);
13362   else
13363     (void)ExtnameUndeclaredIdentifiers.insert(
13364       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13365 }
13366 
13367 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13368                              SourceLocation PragmaLoc,
13369                              SourceLocation NameLoc) {
13370   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
13371 
13372   if (PrevDecl) {
13373     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
13374   } else {
13375     (void)WeakUndeclaredIdentifiers.insert(
13376       std::pair<IdentifierInfo*,WeakInfo>
13377         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
13378   }
13379 }
13380 
13381 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13382                                 IdentifierInfo* AliasName,
13383                                 SourceLocation PragmaLoc,
13384                                 SourceLocation NameLoc,
13385                                 SourceLocation AliasNameLoc) {
13386   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13387                                     LookupOrdinaryName);
13388   WeakInfo W = WeakInfo(Name, NameLoc);
13389 
13390   if (PrevDecl) {
13391     if (!PrevDecl->hasAttr<AliasAttr>())
13392       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
13393         DeclApplyPragmaWeak(TUScope, ND, W);
13394   } else {
13395     (void)WeakUndeclaredIdentifiers.insert(
13396       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
13397   }
13398 }
13399 
13400 Decl *Sema::getObjCDeclContext() const {
13401   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13402 }
13403 
13404 AvailabilityResult Sema::getCurContextAvailability() const {
13405   const Decl *D = cast<Decl>(getCurObjCLexicalContext());
13406   // If we are within an Objective-C method, we should consult
13407   // both the availability of the method as well as the
13408   // enclosing class.  If the class is (say) deprecated,
13409   // the entire method is considered deprecated from the
13410   // purpose of checking if the current context is deprecated.
13411   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13412     AvailabilityResult R = MD->getAvailability();
13413     if (R != AR_Available)
13414       return R;
13415     D = MD->getClassInterface();
13416   }
13417   // If we are within an Objective-c @implementation, it
13418   // gets the same availability context as the @interface.
13419   else if (const ObjCImplementationDecl *ID =
13420             dyn_cast<ObjCImplementationDecl>(D)) {
13421     D = ID->getClassInterface();
13422   }
13423   return D->getAvailability();
13424 }
13425