1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/RecordLayout.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/NonTrivialTypeVisitor.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
35 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
36 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
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/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/ADT/SmallString.h"
48 #include "llvm/ADT/Triple.h"
49 #include <algorithm>
50 #include <cstring>
51 #include <functional>
52 #include <unordered_map>
53 
54 using namespace clang;
55 using namespace sema;
56 
ConvertDeclToDeclGroup(Decl * Ptr,Decl * OwnedType)57 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
58   if (OwnedType) {
59     Decl *Group[2] = { OwnedType, Ptr };
60     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
61   }
62 
63   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
64 }
65 
66 namespace {
67 
68 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
69  public:
TypeNameValidatorCCC(bool AllowInvalid,bool WantClass=false,bool AllowTemplates=false,bool AllowNonTemplates=true)70    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
71                         bool AllowTemplates = false,
72                         bool AllowNonTemplates = true)
73        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
74          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
75      WantExpressionKeywords = false;
76      WantCXXNamedCasts = false;
77      WantRemainingKeywords = false;
78   }
79 
ValidateCandidate(const TypoCorrection & candidate)80   bool ValidateCandidate(const TypoCorrection &candidate) override {
81     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
82       if (!AllowInvalidDecl && ND->isInvalidDecl())
83         return false;
84 
85       if (getAsTypeTemplateDecl(ND))
86         return AllowTemplates;
87 
88       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
89       if (!IsType)
90         return false;
91 
92       if (AllowNonTemplates)
93         return true;
94 
95       // An injected-class-name of a class template (specialization) is valid
96       // as a template or as a non-template.
97       if (AllowTemplates) {
98         auto *RD = dyn_cast<CXXRecordDecl>(ND);
99         if (!RD || !RD->isInjectedClassName())
100           return false;
101         RD = cast<CXXRecordDecl>(RD->getDeclContext());
102         return RD->getDescribedClassTemplate() ||
103                isa<ClassTemplateSpecializationDecl>(RD);
104       }
105 
106       return false;
107     }
108 
109     return !WantClassName && candidate.isKeyword();
110   }
111 
clone()112   std::unique_ptr<CorrectionCandidateCallback> clone() override {
113     return std::make_unique<TypeNameValidatorCCC>(*this);
114   }
115 
116  private:
117   bool AllowInvalidDecl;
118   bool WantClassName;
119   bool AllowTemplates;
120   bool AllowNonTemplates;
121 };
122 
123 } // end anonymous namespace
124 
125 /// Determine whether the token kind starts a simple-type-specifier.
isSimpleTypeSpecifier(tok::TokenKind Kind) const126 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
127   switch (Kind) {
128   // FIXME: Take into account the current language when deciding whether a
129   // token kind is a valid type specifier
130   case tok::kw_short:
131   case tok::kw_long:
132   case tok::kw___int64:
133   case tok::kw___int128:
134   case tok::kw_signed:
135   case tok::kw_unsigned:
136   case tok::kw_void:
137   case tok::kw_char:
138   case tok::kw_int:
139   case tok::kw_half:
140   case tok::kw_float:
141   case tok::kw_double:
142   case tok::kw___bf16:
143   case tok::kw__Float16:
144   case tok::kw___float128:
145   case tok::kw_wchar_t:
146   case tok::kw_bool:
147   case tok::kw___underlying_type:
148   case tok::kw___auto_type:
149     return true;
150 
151   case tok::annot_typename:
152   case tok::kw_char16_t:
153   case tok::kw_char32_t:
154   case tok::kw_typeof:
155   case tok::annot_decltype:
156   case tok::kw_decltype:
157     return getLangOpts().CPlusPlus;
158 
159   case tok::kw_char8_t:
160     return getLangOpts().Char8;
161 
162   default:
163     break;
164   }
165 
166   return false;
167 }
168 
169 namespace {
170 enum class UnqualifiedTypeNameLookupResult {
171   NotFound,
172   FoundNonType,
173   FoundType
174 };
175 } // end anonymous namespace
176 
177 /// Tries to perform unqualified lookup of the type decls in bases for
178 /// dependent class.
179 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
180 /// type decl, \a FoundType if only type decls are found.
181 static UnqualifiedTypeNameLookupResult
lookupUnqualifiedTypeNameInBase(Sema & S,const IdentifierInfo & II,SourceLocation NameLoc,const CXXRecordDecl * RD)182 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
183                                 SourceLocation NameLoc,
184                                 const CXXRecordDecl *RD) {
185   if (!RD->hasDefinition())
186     return UnqualifiedTypeNameLookupResult::NotFound;
187   // Look for type decls in base classes.
188   UnqualifiedTypeNameLookupResult FoundTypeDecl =
189       UnqualifiedTypeNameLookupResult::NotFound;
190   for (const auto &Base : RD->bases()) {
191     const CXXRecordDecl *BaseRD = nullptr;
192     if (auto *BaseTT = Base.getType()->getAs<TagType>())
193       BaseRD = BaseTT->getAsCXXRecordDecl();
194     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
195       // Look for type decls in dependent base classes that have known primary
196       // templates.
197       if (!TST || !TST->isDependentType())
198         continue;
199       auto *TD = TST->getTemplateName().getAsTemplateDecl();
200       if (!TD)
201         continue;
202       if (auto *BasePrimaryTemplate =
203           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
204         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
205           BaseRD = BasePrimaryTemplate;
206         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
207           if (const ClassTemplatePartialSpecializationDecl *PS =
208                   CTD->findPartialSpecialization(Base.getType()))
209             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
210               BaseRD = PS;
211         }
212       }
213     }
214     if (BaseRD) {
215       for (NamedDecl *ND : BaseRD->lookup(&II)) {
216         if (!isa<TypeDecl>(ND))
217           return UnqualifiedTypeNameLookupResult::FoundNonType;
218         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
219       }
220       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
221         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
222         case UnqualifiedTypeNameLookupResult::FoundNonType:
223           return UnqualifiedTypeNameLookupResult::FoundNonType;
224         case UnqualifiedTypeNameLookupResult::FoundType:
225           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
226           break;
227         case UnqualifiedTypeNameLookupResult::NotFound:
228           break;
229         }
230       }
231     }
232   }
233 
234   return FoundTypeDecl;
235 }
236 
recoverFromTypeInKnownDependentBase(Sema & S,const IdentifierInfo & II,SourceLocation NameLoc)237 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
238                                                       const IdentifierInfo &II,
239                                                       SourceLocation NameLoc) {
240   // Lookup in the parent class template context, if any.
241   const CXXRecordDecl *RD = nullptr;
242   UnqualifiedTypeNameLookupResult FoundTypeDecl =
243       UnqualifiedTypeNameLookupResult::NotFound;
244   for (DeclContext *DC = S.CurContext;
245        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
246        DC = DC->getParent()) {
247     // Look for type decls in dependent base classes that have known primary
248     // templates.
249     RD = dyn_cast<CXXRecordDecl>(DC);
250     if (RD && RD->getDescribedClassTemplate())
251       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
252   }
253   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
254     return nullptr;
255 
256   // We found some types in dependent base classes.  Recover as if the user
257   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
258   // lookup during template instantiation.
259   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
260 
261   ASTContext &Context = S.Context;
262   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
263                                           cast<Type>(Context.getRecordType(RD)));
264   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
265 
266   CXXScopeSpec SS;
267   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
268 
269   TypeLocBuilder Builder;
270   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
271   DepTL.setNameLoc(NameLoc);
272   DepTL.setElaboratedKeywordLoc(SourceLocation());
273   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
274   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
275 }
276 
277 /// If the identifier refers to a type name within this scope,
278 /// return the declaration of that type.
279 ///
280 /// This routine performs ordinary name lookup of the identifier II
281 /// within the given scope, with optional C++ scope specifier SS, to
282 /// determine whether the name refers to a type. If so, returns an
283 /// opaque pointer (actually a QualType) corresponding to that
284 /// type. Otherwise, returns NULL.
getTypeName(const IdentifierInfo & II,SourceLocation NameLoc,Scope * S,CXXScopeSpec * SS,bool isClassName,bool HasTrailingDot,ParsedType ObjectTypePtr,bool IsCtorOrDtorName,bool WantNontrivialTypeSourceInfo,bool IsClassTemplateDeductionContext,IdentifierInfo ** CorrectedII)285 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
286                              Scope *S, CXXScopeSpec *SS,
287                              bool isClassName, bool HasTrailingDot,
288                              ParsedType ObjectTypePtr,
289                              bool IsCtorOrDtorName,
290                              bool WantNontrivialTypeSourceInfo,
291                              bool IsClassTemplateDeductionContext,
292                              IdentifierInfo **CorrectedII) {
293   // FIXME: Consider allowing this outside C++1z mode as an extension.
294   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
295                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
296                               !isClassName && !HasTrailingDot;
297 
298   // Determine where we will perform name lookup.
299   DeclContext *LookupCtx = nullptr;
300   if (ObjectTypePtr) {
301     QualType ObjectType = ObjectTypePtr.get();
302     if (ObjectType->isRecordType())
303       LookupCtx = computeDeclContext(ObjectType);
304   } else if (SS && SS->isNotEmpty()) {
305     LookupCtx = computeDeclContext(*SS, false);
306 
307     if (!LookupCtx) {
308       if (isDependentScopeSpecifier(*SS)) {
309         // C++ [temp.res]p3:
310         //   A qualified-id that refers to a type and in which the
311         //   nested-name-specifier depends on a template-parameter (14.6.2)
312         //   shall be prefixed by the keyword typename to indicate that the
313         //   qualified-id denotes a type, forming an
314         //   elaborated-type-specifier (7.1.5.3).
315         //
316         // We therefore do not perform any name lookup if the result would
317         // refer to a member of an unknown specialization.
318         if (!isClassName && !IsCtorOrDtorName)
319           return nullptr;
320 
321         // We know from the grammar that this name refers to a type,
322         // so build a dependent node to describe the type.
323         if (WantNontrivialTypeSourceInfo)
324           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
325 
326         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
327         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
328                                        II, NameLoc);
329         return ParsedType::make(T);
330       }
331 
332       return nullptr;
333     }
334 
335     if (!LookupCtx->isDependentContext() &&
336         RequireCompleteDeclContext(*SS, LookupCtx))
337       return nullptr;
338   }
339 
340   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
341   // lookup for class-names.
342   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
343                                       LookupOrdinaryName;
344   LookupResult Result(*this, &II, NameLoc, Kind);
345   if (LookupCtx) {
346     // Perform "qualified" name lookup into the declaration context we
347     // computed, which is either the type of the base of a member access
348     // expression or the declaration context associated with a prior
349     // nested-name-specifier.
350     LookupQualifiedName(Result, LookupCtx);
351 
352     if (ObjectTypePtr && Result.empty()) {
353       // C++ [basic.lookup.classref]p3:
354       //   If the unqualified-id is ~type-name, the type-name is looked up
355       //   in the context of the entire postfix-expression. If the type T of
356       //   the object expression is of a class type C, the type-name is also
357       //   looked up in the scope of class C. At least one of the lookups shall
358       //   find a name that refers to (possibly cv-qualified) T.
359       LookupName(Result, S);
360     }
361   } else {
362     // Perform unqualified name lookup.
363     LookupName(Result, S);
364 
365     // For unqualified lookup in a class template in MSVC mode, look into
366     // dependent base classes where the primary class template is known.
367     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
368       if (ParsedType TypeInBase =
369               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
370         return TypeInBase;
371     }
372   }
373 
374   NamedDecl *IIDecl = nullptr;
375   switch (Result.getResultKind()) {
376   case LookupResult::NotFound:
377   case LookupResult::NotFoundInCurrentInstantiation:
378     if (CorrectedII) {
379       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
380                                AllowDeducedTemplate);
381       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
382                                               S, SS, CCC, CTK_ErrorRecovery);
383       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
384       TemplateTy Template;
385       bool MemberOfUnknownSpecialization;
386       UnqualifiedId TemplateName;
387       TemplateName.setIdentifier(NewII, NameLoc);
388       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
389       CXXScopeSpec NewSS, *NewSSPtr = SS;
390       if (SS && NNS) {
391         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
392         NewSSPtr = &NewSS;
393       }
394       if (Correction && (NNS || NewII != &II) &&
395           // Ignore a correction to a template type as the to-be-corrected
396           // identifier is not a template (typo correction for template names
397           // is handled elsewhere).
398           !(getLangOpts().CPlusPlus && NewSSPtr &&
399             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
400                            Template, MemberOfUnknownSpecialization))) {
401         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
402                                     isClassName, HasTrailingDot, ObjectTypePtr,
403                                     IsCtorOrDtorName,
404                                     WantNontrivialTypeSourceInfo,
405                                     IsClassTemplateDeductionContext);
406         if (Ty) {
407           diagnoseTypo(Correction,
408                        PDiag(diag::err_unknown_type_or_class_name_suggest)
409                          << Result.getLookupName() << isClassName);
410           if (SS && NNS)
411             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
412           *CorrectedII = NewII;
413           return Ty;
414         }
415       }
416     }
417     // If typo correction failed or was not performed, fall through
418     LLVM_FALLTHROUGH;
419   case LookupResult::FoundOverloaded:
420   case LookupResult::FoundUnresolvedValue:
421     Result.suppressDiagnostics();
422     return nullptr;
423 
424   case LookupResult::Ambiguous:
425     // Recover from type-hiding ambiguities by hiding the type.  We'll
426     // do the lookup again when looking for an object, and we can
427     // diagnose the error then.  If we don't do this, then the error
428     // about hiding the type will be immediately followed by an error
429     // that only makes sense if the identifier was treated like a type.
430     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
431       Result.suppressDiagnostics();
432       return nullptr;
433     }
434 
435     // Look to see if we have a type anywhere in the list of results.
436     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
437          Res != ResEnd; ++Res) {
438       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
439           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
440         if (!IIDecl ||
441             (*Res)->getLocation().getRawEncoding() <
442               IIDecl->getLocation().getRawEncoding())
443           IIDecl = *Res;
444       }
445     }
446 
447     if (!IIDecl) {
448       // None of the entities we found is a type, so there is no way
449       // to even assume that the result is a type. In this case, don't
450       // complain about the ambiguity. The parser will either try to
451       // perform this lookup again (e.g., as an object name), which
452       // will produce the ambiguity, or will complain that it expected
453       // a type name.
454       Result.suppressDiagnostics();
455       return nullptr;
456     }
457 
458     // We found a type within the ambiguous lookup; diagnose the
459     // ambiguity and then return that type. This might be the right
460     // answer, or it might not be, but it suppresses any attempt to
461     // perform the name lookup again.
462     break;
463 
464   case LookupResult::Found:
465     IIDecl = Result.getFoundDecl();
466     break;
467   }
468 
469   assert(IIDecl && "Didn't find decl");
470 
471   QualType T;
472   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
473     // C++ [class.qual]p2: A lookup that would find the injected-class-name
474     // instead names the constructors of the class, except when naming a class.
475     // This is ill-formed when we're not actually forming a ctor or dtor name.
476     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
477     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
478     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
479         FoundRD->isInjectedClassName() &&
480         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
481       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
482           << &II << /*Type*/1;
483 
484     DiagnoseUseOfDecl(IIDecl, NameLoc);
485 
486     T = Context.getTypeDeclType(TD);
487     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
488   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
489     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
490     if (!HasTrailingDot)
491       T = Context.getObjCInterfaceType(IDecl);
492   } else if (AllowDeducedTemplate) {
493     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
494       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
495                                                        QualType(), false);
496   }
497 
498   if (T.isNull()) {
499     // If it's not plausibly a type, suppress diagnostics.
500     Result.suppressDiagnostics();
501     return nullptr;
502   }
503 
504   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
505   // constructor or destructor name (in such a case, the scope specifier
506   // will be attached to the enclosing Expr or Decl node).
507   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
508       !isa<ObjCInterfaceDecl>(IIDecl)) {
509     if (WantNontrivialTypeSourceInfo) {
510       // Construct a type with type-source information.
511       TypeLocBuilder Builder;
512       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
513 
514       T = getElaboratedType(ETK_None, *SS, T);
515       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
516       ElabTL.setElaboratedKeywordLoc(SourceLocation());
517       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
518       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
519     } else {
520       T = getElaboratedType(ETK_None, *SS, T);
521     }
522   }
523 
524   return ParsedType::make(T);
525 }
526 
527 // Builds a fake NNS for the given decl context.
528 static NestedNameSpecifier *
synthesizeCurrentNestedNameSpecifier(ASTContext & Context,DeclContext * DC)529 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
530   for (;; DC = DC->getLookupParent()) {
531     DC = DC->getPrimaryContext();
532     auto *ND = dyn_cast<NamespaceDecl>(DC);
533     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
534       return NestedNameSpecifier::Create(Context, nullptr, ND);
535     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
536       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
537                                          RD->getTypeForDecl());
538     else if (isa<TranslationUnitDecl>(DC))
539       return NestedNameSpecifier::GlobalSpecifier(Context);
540   }
541   llvm_unreachable("something isn't in TU scope?");
542 }
543 
544 /// Find the parent class with dependent bases of the innermost enclosing method
545 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
546 /// up allowing unqualified dependent type names at class-level, which MSVC
547 /// correctly rejects.
548 static const CXXRecordDecl *
findRecordWithDependentBasesOfEnclosingMethod(const DeclContext * DC)549 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
550   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
551     DC = DC->getPrimaryContext();
552     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
553       if (MD->getParent()->hasAnyDependentBases())
554         return MD->getParent();
555   }
556   return nullptr;
557 }
558 
ActOnMSVCUnknownTypeName(const IdentifierInfo & II,SourceLocation NameLoc,bool IsTemplateTypeArg)559 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
560                                           SourceLocation NameLoc,
561                                           bool IsTemplateTypeArg) {
562   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
563 
564   NestedNameSpecifier *NNS = nullptr;
565   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
566     // If we weren't able to parse a default template argument, delay lookup
567     // until instantiation time by making a non-dependent DependentTypeName. We
568     // pretend we saw a NestedNameSpecifier referring to the current scope, and
569     // lookup is retried.
570     // FIXME: This hurts our diagnostic quality, since we get errors like "no
571     // type named 'Foo' in 'current_namespace'" when the user didn't write any
572     // name specifiers.
573     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
574     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
575   } else if (const CXXRecordDecl *RD =
576                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
577     // Build a DependentNameType that will perform lookup into RD at
578     // instantiation time.
579     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
580                                       RD->getTypeForDecl());
581 
582     // Diagnose that this identifier was undeclared, and retry the lookup during
583     // template instantiation.
584     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
585                                                                       << RD;
586   } else {
587     // This is not a situation that we should recover from.
588     return ParsedType();
589   }
590 
591   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
592 
593   // Build type location information.  We synthesized the qualifier, so we have
594   // to build a fake NestedNameSpecifierLoc.
595   NestedNameSpecifierLocBuilder NNSLocBuilder;
596   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
597   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
598 
599   TypeLocBuilder Builder;
600   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
601   DepTL.setNameLoc(NameLoc);
602   DepTL.setElaboratedKeywordLoc(SourceLocation());
603   DepTL.setQualifierLoc(QualifierLoc);
604   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
605 }
606 
607 /// isTagName() - This method is called *for error recovery purposes only*
608 /// to determine if the specified name is a valid tag name ("struct foo").  If
609 /// so, this returns the TST for the tag corresponding to it (TST_enum,
610 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
611 /// cases in C where the user forgot to specify the tag.
isTagName(IdentifierInfo & II,Scope * S)612 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
613   // Do a tag name lookup in this scope.
614   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
615   LookupName(R, S, false);
616   R.suppressDiagnostics();
617   if (R.getResultKind() == LookupResult::Found)
618     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
619       switch (TD->getTagKind()) {
620       case TTK_Struct: return DeclSpec::TST_struct;
621       case TTK_Interface: return DeclSpec::TST_interface;
622       case TTK_Union:  return DeclSpec::TST_union;
623       case TTK_Class:  return DeclSpec::TST_class;
624       case TTK_Enum:   return DeclSpec::TST_enum;
625       }
626     }
627 
628   return DeclSpec::TST_unspecified;
629 }
630 
631 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
632 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
633 /// then downgrade the missing typename error to a warning.
634 /// This is needed for MSVC compatibility; Example:
635 /// @code
636 /// template<class T> class A {
637 /// public:
638 ///   typedef int TYPE;
639 /// };
640 /// template<class T> class B : public A<T> {
641 /// public:
642 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
643 /// };
644 /// @endcode
isMicrosoftMissingTypename(const CXXScopeSpec * SS,Scope * S)645 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
646   if (CurContext->isRecord()) {
647     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
648       return true;
649 
650     const Type *Ty = SS->getScopeRep()->getAsType();
651 
652     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
653     for (const auto &Base : RD->bases())
654       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
655         return true;
656     return S->isFunctionPrototypeScope();
657   }
658   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
659 }
660 
DiagnoseUnknownTypeName(IdentifierInfo * & II,SourceLocation IILoc,Scope * S,CXXScopeSpec * SS,ParsedType & SuggestedType,bool IsTemplateName)661 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
662                                    SourceLocation IILoc,
663                                    Scope *S,
664                                    CXXScopeSpec *SS,
665                                    ParsedType &SuggestedType,
666                                    bool IsTemplateName) {
667   // Don't report typename errors for editor placeholders.
668   if (II->isEditorPlaceholder())
669     return;
670   // We don't have anything to suggest (yet).
671   SuggestedType = nullptr;
672 
673   // There may have been a typo in the name of the type. Look up typo
674   // results, in case we have something that we can suggest.
675   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
676                            /*AllowTemplates=*/IsTemplateName,
677                            /*AllowNonTemplates=*/!IsTemplateName);
678   if (TypoCorrection Corrected =
679           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
680                       CCC, CTK_ErrorRecovery)) {
681     // FIXME: Support error recovery for the template-name case.
682     bool CanRecover = !IsTemplateName;
683     if (Corrected.isKeyword()) {
684       // We corrected to a keyword.
685       diagnoseTypo(Corrected,
686                    PDiag(IsTemplateName ? diag::err_no_template_suggest
687                                         : diag::err_unknown_typename_suggest)
688                        << II);
689       II = Corrected.getCorrectionAsIdentifierInfo();
690     } else {
691       // We found a similarly-named type or interface; suggest that.
692       if (!SS || !SS->isSet()) {
693         diagnoseTypo(Corrected,
694                      PDiag(IsTemplateName ? diag::err_no_template_suggest
695                                           : diag::err_unknown_typename_suggest)
696                          << II, CanRecover);
697       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
698         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
699         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
700                                 II->getName().equals(CorrectedStr);
701         diagnoseTypo(Corrected,
702                      PDiag(IsTemplateName
703                                ? diag::err_no_member_template_suggest
704                                : diag::err_unknown_nested_typename_suggest)
705                          << II << DC << DroppedSpecifier << SS->getRange(),
706                      CanRecover);
707       } else {
708         llvm_unreachable("could not have corrected a typo here");
709       }
710 
711       if (!CanRecover)
712         return;
713 
714       CXXScopeSpec tmpSS;
715       if (Corrected.getCorrectionSpecifier())
716         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
717                           SourceRange(IILoc));
718       // FIXME: Support class template argument deduction here.
719       SuggestedType =
720           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
721                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
722                       /*IsCtorOrDtorName=*/false,
723                       /*WantNontrivialTypeSourceInfo=*/true);
724     }
725     return;
726   }
727 
728   if (getLangOpts().CPlusPlus && !IsTemplateName) {
729     // See if II is a class template that the user forgot to pass arguments to.
730     UnqualifiedId Name;
731     Name.setIdentifier(II, IILoc);
732     CXXScopeSpec EmptySS;
733     TemplateTy TemplateResult;
734     bool MemberOfUnknownSpecialization;
735     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
736                        Name, nullptr, true, TemplateResult,
737                        MemberOfUnknownSpecialization) == TNK_Type_template) {
738       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
739       return;
740     }
741   }
742 
743   // FIXME: Should we move the logic that tries to recover from a missing tag
744   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
745 
746   if (!SS || (!SS->isSet() && !SS->isInvalid()))
747     Diag(IILoc, IsTemplateName ? diag::err_no_template
748                                : diag::err_unknown_typename)
749         << II;
750   else if (DeclContext *DC = computeDeclContext(*SS, false))
751     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
752                                : diag::err_typename_nested_not_found)
753         << II << DC << SS->getRange();
754   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
755     SuggestedType =
756         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
757   } else if (isDependentScopeSpecifier(*SS)) {
758     unsigned DiagID = diag::err_typename_missing;
759     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
760       DiagID = diag::ext_typename_missing;
761 
762     Diag(SS->getRange().getBegin(), DiagID)
763       << SS->getScopeRep() << II->getName()
764       << SourceRange(SS->getRange().getBegin(), IILoc)
765       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
766     SuggestedType = ActOnTypenameType(S, SourceLocation(),
767                                       *SS, *II, IILoc).get();
768   } else {
769     assert(SS && SS->isInvalid() &&
770            "Invalid scope specifier has already been diagnosed");
771   }
772 }
773 
774 /// Determine whether the given result set contains either a type name
775 /// or
isResultTypeOrTemplate(LookupResult & R,const Token & NextToken)776 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
777   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
778                        NextToken.is(tok::less);
779 
780   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
781     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
782       return true;
783 
784     if (CheckTemplate && isa<TemplateDecl>(*I))
785       return true;
786   }
787 
788   return false;
789 }
790 
isTagTypeWithMissingTag(Sema & SemaRef,LookupResult & Result,Scope * S,CXXScopeSpec & SS,IdentifierInfo * & Name,SourceLocation NameLoc)791 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
792                                     Scope *S, CXXScopeSpec &SS,
793                                     IdentifierInfo *&Name,
794                                     SourceLocation NameLoc) {
795   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
796   SemaRef.LookupParsedName(R, S, &SS);
797   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
798     StringRef FixItTagName;
799     switch (Tag->getTagKind()) {
800       case TTK_Class:
801         FixItTagName = "class ";
802         break;
803 
804       case TTK_Enum:
805         FixItTagName = "enum ";
806         break;
807 
808       case TTK_Struct:
809         FixItTagName = "struct ";
810         break;
811 
812       case TTK_Interface:
813         FixItTagName = "__interface ";
814         break;
815 
816       case TTK_Union:
817         FixItTagName = "union ";
818         break;
819     }
820 
821     StringRef TagName = FixItTagName.drop_back();
822     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
823       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
824       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
825 
826     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
827          I != IEnd; ++I)
828       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
829         << Name << TagName;
830 
831     // Replace lookup results with just the tag decl.
832     Result.clear(Sema::LookupTagName);
833     SemaRef.LookupParsedName(Result, S, &SS);
834     return true;
835   }
836 
837   return false;
838 }
839 
840 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
buildNestedType(Sema & S,CXXScopeSpec & SS,QualType T,SourceLocation NameLoc)841 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
842                                   QualType T, SourceLocation NameLoc) {
843   ASTContext &Context = S.Context;
844 
845   TypeLocBuilder Builder;
846   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
847 
848   T = S.getElaboratedType(ETK_None, SS, T);
849   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
850   ElabTL.setElaboratedKeywordLoc(SourceLocation());
851   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
852   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
853 }
854 
ClassifyName(Scope * S,CXXScopeSpec & SS,IdentifierInfo * & Name,SourceLocation NameLoc,const Token & NextToken,CorrectionCandidateCallback * CCC)855 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
856                                             IdentifierInfo *&Name,
857                                             SourceLocation NameLoc,
858                                             const Token &NextToken,
859                                             CorrectionCandidateCallback *CCC) {
860   DeclarationNameInfo NameInfo(Name, NameLoc);
861   ObjCMethodDecl *CurMethod = getCurMethodDecl();
862 
863   assert(NextToken.isNot(tok::coloncolon) &&
864          "parse nested name specifiers before calling ClassifyName");
865   if (getLangOpts().CPlusPlus && SS.isSet() &&
866       isCurrentClassName(*Name, S, &SS)) {
867     // Per [class.qual]p2, this names the constructors of SS, not the
868     // injected-class-name. We don't have a classification for that.
869     // There's not much point caching this result, since the parser
870     // will reject it later.
871     return NameClassification::Unknown();
872   }
873 
874   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
875   LookupParsedName(Result, S, &SS, !CurMethod);
876 
877   if (SS.isInvalid())
878     return NameClassification::Error();
879 
880   // For unqualified lookup in a class template in MSVC mode, look into
881   // dependent base classes where the primary class template is known.
882   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
883     if (ParsedType TypeInBase =
884             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
885       return TypeInBase;
886   }
887 
888   // Perform lookup for Objective-C instance variables (including automatically
889   // synthesized instance variables), if we're in an Objective-C method.
890   // FIXME: This lookup really, really needs to be folded in to the normal
891   // unqualified lookup mechanism.
892   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
893     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
894     if (Ivar.isInvalid())
895       return NameClassification::Error();
896     if (Ivar.isUsable())
897       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
898 
899     // We defer builtin creation until after ivar lookup inside ObjC methods.
900     if (Result.empty())
901       LookupBuiltin(Result);
902   }
903 
904   bool SecondTry = false;
905   bool IsFilteredTemplateName = false;
906 
907 Corrected:
908   switch (Result.getResultKind()) {
909   case LookupResult::NotFound:
910     // If an unqualified-id is followed by a '(', then we have a function
911     // call.
912     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
913       // In C++, this is an ADL-only call.
914       // FIXME: Reference?
915       if (getLangOpts().CPlusPlus)
916         return NameClassification::UndeclaredNonType();
917 
918       // C90 6.3.2.2:
919       //   If the expression that precedes the parenthesized argument list in a
920       //   function call consists solely of an identifier, and if no
921       //   declaration is visible for this identifier, the identifier is
922       //   implicitly declared exactly as if, in the innermost block containing
923       //   the function call, the declaration
924       //
925       //     extern int identifier ();
926       //
927       //   appeared.
928       //
929       // We also allow this in C99 as an extension.
930       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
931         return NameClassification::NonType(D);
932     }
933 
934     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
935       // In C++20 onwards, this could be an ADL-only call to a function
936       // template, and we're required to assume that this is a template name.
937       //
938       // FIXME: Find a way to still do typo correction in this case.
939       TemplateName Template =
940           Context.getAssumedTemplateName(NameInfo.getName());
941       return NameClassification::UndeclaredTemplate(Template);
942     }
943 
944     // In C, we first see whether there is a tag type by the same name, in
945     // which case it's likely that the user just forgot to write "enum",
946     // "struct", or "union".
947     if (!getLangOpts().CPlusPlus && !SecondTry &&
948         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
949       break;
950     }
951 
952     // Perform typo correction to determine if there is another name that is
953     // close to this name.
954     if (!SecondTry && CCC) {
955       SecondTry = true;
956       if (TypoCorrection Corrected =
957               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
958                           &SS, *CCC, CTK_ErrorRecovery)) {
959         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
960         unsigned QualifiedDiag = diag::err_no_member_suggest;
961 
962         NamedDecl *FirstDecl = Corrected.getFoundDecl();
963         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
964         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
965             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
966           UnqualifiedDiag = diag::err_no_template_suggest;
967           QualifiedDiag = diag::err_no_member_template_suggest;
968         } else if (UnderlyingFirstDecl &&
969                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
970                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
971                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
972           UnqualifiedDiag = diag::err_unknown_typename_suggest;
973           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
974         }
975 
976         if (SS.isEmpty()) {
977           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
978         } else {// FIXME: is this even reachable? Test it.
979           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
980           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
981                                   Name->getName().equals(CorrectedStr);
982           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
983                                     << Name << computeDeclContext(SS, false)
984                                     << DroppedSpecifier << SS.getRange());
985         }
986 
987         // Update the name, so that the caller has the new name.
988         Name = Corrected.getCorrectionAsIdentifierInfo();
989 
990         // Typo correction corrected to a keyword.
991         if (Corrected.isKeyword())
992           return Name;
993 
994         // Also update the LookupResult...
995         // FIXME: This should probably go away at some point
996         Result.clear();
997         Result.setLookupName(Corrected.getCorrection());
998         if (FirstDecl)
999           Result.addDecl(FirstDecl);
1000 
1001         // If we found an Objective-C instance variable, let
1002         // LookupInObjCMethod build the appropriate expression to
1003         // reference the ivar.
1004         // FIXME: This is a gross hack.
1005         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1006           DeclResult R =
1007               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1008           if (R.isInvalid())
1009             return NameClassification::Error();
1010           if (R.isUsable())
1011             return NameClassification::NonType(Ivar);
1012         }
1013 
1014         goto Corrected;
1015       }
1016     }
1017 
1018     // We failed to correct; just fall through and let the parser deal with it.
1019     Result.suppressDiagnostics();
1020     return NameClassification::Unknown();
1021 
1022   case LookupResult::NotFoundInCurrentInstantiation: {
1023     // We performed name lookup into the current instantiation, and there were
1024     // dependent bases, so we treat this result the same way as any other
1025     // dependent nested-name-specifier.
1026 
1027     // C++ [temp.res]p2:
1028     //   A name used in a template declaration or definition and that is
1029     //   dependent on a template-parameter is assumed not to name a type
1030     //   unless the applicable name lookup finds a type name or the name is
1031     //   qualified by the keyword typename.
1032     //
1033     // FIXME: If the next token is '<', we might want to ask the parser to
1034     // perform some heroics to see if we actually have a
1035     // template-argument-list, which would indicate a missing 'template'
1036     // keyword here.
1037     return NameClassification::DependentNonType();
1038   }
1039 
1040   case LookupResult::Found:
1041   case LookupResult::FoundOverloaded:
1042   case LookupResult::FoundUnresolvedValue:
1043     break;
1044 
1045   case LookupResult::Ambiguous:
1046     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1047         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1048                                       /*AllowDependent=*/false)) {
1049       // C++ [temp.local]p3:
1050       //   A lookup that finds an injected-class-name (10.2) can result in an
1051       //   ambiguity in certain cases (for example, if it is found in more than
1052       //   one base class). If all of the injected-class-names that are found
1053       //   refer to specializations of the same class template, and if the name
1054       //   is followed by a template-argument-list, the reference refers to the
1055       //   class template itself and not a specialization thereof, and is not
1056       //   ambiguous.
1057       //
1058       // This filtering can make an ambiguous result into an unambiguous one,
1059       // so try again after filtering out template names.
1060       FilterAcceptableTemplateNames(Result);
1061       if (!Result.isAmbiguous()) {
1062         IsFilteredTemplateName = true;
1063         break;
1064       }
1065     }
1066 
1067     // Diagnose the ambiguity and return an error.
1068     return NameClassification::Error();
1069   }
1070 
1071   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1072       (IsFilteredTemplateName ||
1073        hasAnyAcceptableTemplateNames(
1074            Result, /*AllowFunctionTemplates=*/true,
1075            /*AllowDependent=*/false,
1076            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1077                getLangOpts().CPlusPlus20))) {
1078     // C++ [temp.names]p3:
1079     //   After name lookup (3.4) finds that a name is a template-name or that
1080     //   an operator-function-id or a literal- operator-id refers to a set of
1081     //   overloaded functions any member of which is a function template if
1082     //   this is followed by a <, the < is always taken as the delimiter of a
1083     //   template-argument-list and never as the less-than operator.
1084     // C++2a [temp.names]p2:
1085     //   A name is also considered to refer to a template if it is an
1086     //   unqualified-id followed by a < and name lookup finds either one
1087     //   or more functions or finds nothing.
1088     if (!IsFilteredTemplateName)
1089       FilterAcceptableTemplateNames(Result);
1090 
1091     bool IsFunctionTemplate;
1092     bool IsVarTemplate;
1093     TemplateName Template;
1094     if (Result.end() - Result.begin() > 1) {
1095       IsFunctionTemplate = true;
1096       Template = Context.getOverloadedTemplateName(Result.begin(),
1097                                                    Result.end());
1098     } else if (!Result.empty()) {
1099       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1100           *Result.begin(), /*AllowFunctionTemplates=*/true,
1101           /*AllowDependent=*/false));
1102       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1103       IsVarTemplate = isa<VarTemplateDecl>(TD);
1104 
1105       if (SS.isNotEmpty())
1106         Template =
1107             Context.getQualifiedTemplateName(SS.getScopeRep(),
1108                                              /*TemplateKeyword=*/false, TD);
1109       else
1110         Template = TemplateName(TD);
1111     } else {
1112       // All results were non-template functions. This is a function template
1113       // name.
1114       IsFunctionTemplate = true;
1115       Template = Context.getAssumedTemplateName(NameInfo.getName());
1116     }
1117 
1118     if (IsFunctionTemplate) {
1119       // Function templates always go through overload resolution, at which
1120       // point we'll perform the various checks (e.g., accessibility) we need
1121       // to based on which function we selected.
1122       Result.suppressDiagnostics();
1123 
1124       return NameClassification::FunctionTemplate(Template);
1125     }
1126 
1127     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1128                          : NameClassification::TypeTemplate(Template);
1129   }
1130 
1131   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1132   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1133     DiagnoseUseOfDecl(Type, NameLoc);
1134     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1135     QualType T = Context.getTypeDeclType(Type);
1136     if (SS.isNotEmpty())
1137       return buildNestedType(*this, SS, T, NameLoc);
1138     return ParsedType::make(T);
1139   }
1140 
1141   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1142   if (!Class) {
1143     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1144     if (ObjCCompatibleAliasDecl *Alias =
1145             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1146       Class = Alias->getClassInterface();
1147   }
1148 
1149   if (Class) {
1150     DiagnoseUseOfDecl(Class, NameLoc);
1151 
1152     if (NextToken.is(tok::period)) {
1153       // Interface. <something> is parsed as a property reference expression.
1154       // Just return "unknown" as a fall-through for now.
1155       Result.suppressDiagnostics();
1156       return NameClassification::Unknown();
1157     }
1158 
1159     QualType T = Context.getObjCInterfaceType(Class);
1160     return ParsedType::make(T);
1161   }
1162 
1163   if (isa<ConceptDecl>(FirstDecl))
1164     return NameClassification::Concept(
1165         TemplateName(cast<TemplateDecl>(FirstDecl)));
1166 
1167   // We can have a type template here if we're classifying a template argument.
1168   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1169       !isa<VarTemplateDecl>(FirstDecl))
1170     return NameClassification::TypeTemplate(
1171         TemplateName(cast<TemplateDecl>(FirstDecl)));
1172 
1173   // Check for a tag type hidden by a non-type decl in a few cases where it
1174   // seems likely a type is wanted instead of the non-type that was found.
1175   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1176   if ((NextToken.is(tok::identifier) ||
1177        (NextIsOp &&
1178         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1179       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1180     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1181     DiagnoseUseOfDecl(Type, NameLoc);
1182     QualType T = Context.getTypeDeclType(Type);
1183     if (SS.isNotEmpty())
1184       return buildNestedType(*this, SS, T, NameLoc);
1185     return ParsedType::make(T);
1186   }
1187 
1188   // FIXME: This is context-dependent. We need to defer building the member
1189   // expression until the classification is consumed.
1190   if (FirstDecl->isCXXClassMember())
1191     return NameClassification::ContextIndependentExpr(
1192         BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
1193                                         S));
1194 
1195   // If we already know which single declaration is referenced, just annotate
1196   // that declaration directly.
1197   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1198   if (Result.isSingleResult() && !ADL)
1199     return NameClassification::NonType(Result.getRepresentativeDecl());
1200 
1201   // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
1202   // context in which we performed classification, so it's safe to do now.
1203   return NameClassification::ContextIndependentExpr(
1204       BuildDeclarationNameExpr(SS, Result, ADL));
1205 }
1206 
1207 ExprResult
ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo * Name,SourceLocation NameLoc)1208 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1209                                              SourceLocation NameLoc) {
1210   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1211   CXXScopeSpec SS;
1212   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1213   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1214 }
1215 
1216 ExprResult
ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,bool IsAddressOfOperand)1217 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1218                                             IdentifierInfo *Name,
1219                                             SourceLocation NameLoc,
1220                                             bool IsAddressOfOperand) {
1221   DeclarationNameInfo NameInfo(Name, NameLoc);
1222   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1223                                     NameInfo, IsAddressOfOperand,
1224                                     /*TemplateArgs=*/nullptr);
1225 }
1226 
ActOnNameClassifiedAsNonType(Scope * S,const CXXScopeSpec & SS,NamedDecl * Found,SourceLocation NameLoc,const Token & NextToken)1227 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1228                                               NamedDecl *Found,
1229                                               SourceLocation NameLoc,
1230                                               const Token &NextToken) {
1231   if (getCurMethodDecl() && SS.isEmpty())
1232     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1233       return BuildIvarRefExpr(S, NameLoc, Ivar);
1234 
1235   // Reconstruct the lookup result.
1236   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1237   Result.addDecl(Found);
1238   Result.resolveKind();
1239 
1240   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1241   return BuildDeclarationNameExpr(SS, Result, ADL);
1242 }
1243 
1244 Sema::TemplateNameKindForDiagnostics
getTemplateNameKindForDiagnostics(TemplateName Name)1245 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1246   auto *TD = Name.getAsTemplateDecl();
1247   if (!TD)
1248     return TemplateNameKindForDiagnostics::DependentTemplate;
1249   if (isa<ClassTemplateDecl>(TD))
1250     return TemplateNameKindForDiagnostics::ClassTemplate;
1251   if (isa<FunctionTemplateDecl>(TD))
1252     return TemplateNameKindForDiagnostics::FunctionTemplate;
1253   if (isa<VarTemplateDecl>(TD))
1254     return TemplateNameKindForDiagnostics::VarTemplate;
1255   if (isa<TypeAliasTemplateDecl>(TD))
1256     return TemplateNameKindForDiagnostics::AliasTemplate;
1257   if (isa<TemplateTemplateParmDecl>(TD))
1258     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1259   if (isa<ConceptDecl>(TD))
1260     return TemplateNameKindForDiagnostics::Concept;
1261   return TemplateNameKindForDiagnostics::DependentTemplate;
1262 }
1263 
PushDeclContext(Scope * S,DeclContext * DC)1264 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1265   assert(DC->getLexicalParent() == CurContext &&
1266       "The next DeclContext should be lexically contained in the current one.");
1267   CurContext = DC;
1268   S->setEntity(DC);
1269 }
1270 
PopDeclContext()1271 void Sema::PopDeclContext() {
1272   assert(CurContext && "DeclContext imbalance!");
1273 
1274   CurContext = CurContext->getLexicalParent();
1275   assert(CurContext && "Popped translation unit!");
1276 }
1277 
ActOnTagStartSkippedDefinition(Scope * S,Decl * D)1278 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1279                                                                     Decl *D) {
1280   // Unlike PushDeclContext, the context to which we return is not necessarily
1281   // the containing DC of TD, because the new context will be some pre-existing
1282   // TagDecl definition instead of a fresh one.
1283   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1284   CurContext = cast<TagDecl>(D)->getDefinition();
1285   assert(CurContext && "skipping definition of undefined tag");
1286   // Start lookups from the parent of the current context; we don't want to look
1287   // into the pre-existing complete definition.
1288   S->setEntity(CurContext->getLookupParent());
1289   return Result;
1290 }
1291 
ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)1292 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1293   CurContext = static_cast<decltype(CurContext)>(Context);
1294 }
1295 
1296 /// EnterDeclaratorContext - Used when we must lookup names in the context
1297 /// of a declarator's nested name specifier.
1298 ///
EnterDeclaratorContext(Scope * S,DeclContext * DC)1299 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1300   // C++0x [basic.lookup.unqual]p13:
1301   //   A name used in the definition of a static data member of class
1302   //   X (after the qualified-id of the static member) is looked up as
1303   //   if the name was used in a member function of X.
1304   // C++0x [basic.lookup.unqual]p14:
1305   //   If a variable member of a namespace is defined outside of the
1306   //   scope of its namespace then any name used in the definition of
1307   //   the variable member (after the declarator-id) is looked up as
1308   //   if the definition of the variable member occurred in its
1309   //   namespace.
1310   // Both of these imply that we should push a scope whose context
1311   // is the semantic context of the declaration.  We can't use
1312   // PushDeclContext here because that context is not necessarily
1313   // lexically contained in the current context.  Fortunately,
1314   // the containing scope should have the appropriate information.
1315 
1316   assert(!S->getEntity() && "scope already has entity");
1317 
1318 #ifndef NDEBUG
1319   Scope *Ancestor = S->getParent();
1320   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1321   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1322 #endif
1323 
1324   CurContext = DC;
1325   S->setEntity(DC);
1326 
1327   if (S->getParent()->isTemplateParamScope()) {
1328     // Also set the corresponding entities for all immediately-enclosing
1329     // template parameter scopes.
1330     EnterTemplatedContext(S->getParent(), DC);
1331   }
1332 }
1333 
ExitDeclaratorContext(Scope * S)1334 void Sema::ExitDeclaratorContext(Scope *S) {
1335   assert(S->getEntity() == CurContext && "Context imbalance!");
1336 
1337   // Switch back to the lexical context.  The safety of this is
1338   // enforced by an assert in EnterDeclaratorContext.
1339   Scope *Ancestor = S->getParent();
1340   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1341   CurContext = Ancestor->getEntity();
1342 
1343   // We don't need to do anything with the scope, which is going to
1344   // disappear.
1345 }
1346 
EnterTemplatedContext(Scope * S,DeclContext * DC)1347 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1348   assert(S->isTemplateParamScope() &&
1349          "expected to be initializing a template parameter scope");
1350 
1351   // C++20 [temp.local]p7:
1352   //   In the definition of a member of a class template that appears outside
1353   //   of the class template definition, the name of a member of the class
1354   //   template hides the name of a template-parameter of any enclosing class
1355   //   templates (but not a template-parameter of the member if the member is a
1356   //   class or function template).
1357   // C++20 [temp.local]p9:
1358   //   In the definition of a class template or in the definition of a member
1359   //   of such a template that appears outside of the template definition, for
1360   //   each non-dependent base class (13.8.2.1), if the name of the base class
1361   //   or the name of a member of the base class is the same as the name of a
1362   //   template-parameter, the base class name or member name hides the
1363   //   template-parameter name (6.4.10).
1364   //
1365   // This means that a template parameter scope should be searched immediately
1366   // after searching the DeclContext for which it is a template parameter
1367   // scope. For example, for
1368   //   template<typename T> template<typename U> template<typename V>
1369   //     void N::A<T>::B<U>::f(...)
1370   // we search V then B<U> (and base classes) then U then A<T> (and base
1371   // classes) then T then N then ::.
1372   unsigned ScopeDepth = getTemplateDepth(S);
1373   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1374     DeclContext *SearchDCAfterScope = DC;
1375     for (; DC; DC = DC->getLookupParent()) {
1376       if (const TemplateParameterList *TPL =
1377               cast<Decl>(DC)->getDescribedTemplateParams()) {
1378         unsigned DCDepth = TPL->getDepth() + 1;
1379         if (DCDepth > ScopeDepth)
1380           continue;
1381         if (ScopeDepth == DCDepth)
1382           SearchDCAfterScope = DC = DC->getLookupParent();
1383         break;
1384       }
1385     }
1386     S->setLookupEntity(SearchDCAfterScope);
1387   }
1388 }
1389 
ActOnReenterFunctionContext(Scope * S,Decl * D)1390 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1391   // We assume that the caller has already called
1392   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1393   FunctionDecl *FD = D->getAsFunction();
1394   if (!FD)
1395     return;
1396 
1397   // Same implementation as PushDeclContext, but enters the context
1398   // from the lexical parent, rather than the top-level class.
1399   assert(CurContext == FD->getLexicalParent() &&
1400     "The next DeclContext should be lexically contained in the current one.");
1401   CurContext = FD;
1402   S->setEntity(CurContext);
1403 
1404   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1405     ParmVarDecl *Param = FD->getParamDecl(P);
1406     // If the parameter has an identifier, then add it to the scope
1407     if (Param->getIdentifier()) {
1408       S->AddDecl(Param);
1409       IdResolver.AddDecl(Param);
1410     }
1411   }
1412 }
1413 
ActOnExitFunctionContext()1414 void Sema::ActOnExitFunctionContext() {
1415   // Same implementation as PopDeclContext, but returns to the lexical parent,
1416   // rather than the top-level class.
1417   assert(CurContext && "DeclContext imbalance!");
1418   CurContext = CurContext->getLexicalParent();
1419   assert(CurContext && "Popped translation unit!");
1420 }
1421 
1422 /// Determine whether we allow overloading of the function
1423 /// PrevDecl with another declaration.
1424 ///
1425 /// This routine determines whether overloading is possible, not
1426 /// whether some new function is actually an overload. It will return
1427 /// true in C++ (where we can always provide overloads) or, as an
1428 /// extension, in C when the previous function is already an
1429 /// overloaded function declaration or has the "overloadable"
1430 /// attribute.
AllowOverloadingOfFunction(LookupResult & Previous,ASTContext & Context,const FunctionDecl * New)1431 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1432                                        ASTContext &Context,
1433                                        const FunctionDecl *New) {
1434   if (Context.getLangOpts().CPlusPlus)
1435     return true;
1436 
1437   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1438     return true;
1439 
1440   return Previous.getResultKind() == LookupResult::Found &&
1441          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1442           New->hasAttr<OverloadableAttr>());
1443 }
1444 
1445 /// Add this decl to the scope shadowed decl chains.
PushOnScopeChains(NamedDecl * D,Scope * S,bool AddToContext)1446 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1447   // Move up the scope chain until we find the nearest enclosing
1448   // non-transparent context. The declaration will be introduced into this
1449   // scope.
1450   while (S->getEntity() && S->getEntity()->isTransparentContext())
1451     S = S->getParent();
1452 
1453   // Add scoped declarations into their context, so that they can be
1454   // found later. Declarations without a context won't be inserted
1455   // into any context.
1456   if (AddToContext)
1457     CurContext->addDecl(D);
1458 
1459   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1460   // are function-local declarations.
1461   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1462       !D->getDeclContext()->getRedeclContext()->Equals(
1463         D->getLexicalDeclContext()->getRedeclContext()) &&
1464       !D->getLexicalDeclContext()->isFunctionOrMethod())
1465     return;
1466 
1467   // Template instantiations should also not be pushed into scope.
1468   if (isa<FunctionDecl>(D) &&
1469       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1470     return;
1471 
1472   // If this replaces anything in the current scope,
1473   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1474                                IEnd = IdResolver.end();
1475   for (; I != IEnd; ++I) {
1476     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1477       S->RemoveDecl(*I);
1478       IdResolver.RemoveDecl(*I);
1479 
1480       // Should only need to replace one decl.
1481       break;
1482     }
1483   }
1484 
1485   S->AddDecl(D);
1486 
1487   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1488     // Implicitly-generated labels may end up getting generated in an order that
1489     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1490     // the label at the appropriate place in the identifier chain.
1491     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1492       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1493       if (IDC == CurContext) {
1494         if (!S->isDeclScope(*I))
1495           continue;
1496       } else if (IDC->Encloses(CurContext))
1497         break;
1498     }
1499 
1500     IdResolver.InsertDeclAfter(I, D);
1501   } else {
1502     IdResolver.AddDecl(D);
1503   }
1504 }
1505 
isDeclInScope(NamedDecl * D,DeclContext * Ctx,Scope * S,bool AllowInlineNamespace)1506 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1507                          bool AllowInlineNamespace) {
1508   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1509 }
1510 
getScopeForDeclContext(Scope * S,DeclContext * DC)1511 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1512   DeclContext *TargetDC = DC->getPrimaryContext();
1513   do {
1514     if (DeclContext *ScopeDC = S->getEntity())
1515       if (ScopeDC->getPrimaryContext() == TargetDC)
1516         return S;
1517   } while ((S = S->getParent()));
1518 
1519   return nullptr;
1520 }
1521 
1522 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1523                                             DeclContext*,
1524                                             ASTContext&);
1525 
1526 /// Filters out lookup results that don't fall within the given scope
1527 /// as determined by isDeclInScope.
FilterLookupForScope(LookupResult & R,DeclContext * Ctx,Scope * S,bool ConsiderLinkage,bool AllowInlineNamespace)1528 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1529                                 bool ConsiderLinkage,
1530                                 bool AllowInlineNamespace) {
1531   LookupResult::Filter F = R.makeFilter();
1532   while (F.hasNext()) {
1533     NamedDecl *D = F.next();
1534 
1535     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1536       continue;
1537 
1538     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1539       continue;
1540 
1541     F.erase();
1542   }
1543 
1544   F.done();
1545 }
1546 
1547 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1548 /// have compatible owning modules.
CheckRedeclarationModuleOwnership(NamedDecl * New,NamedDecl * Old)1549 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1550   // FIXME: The Modules TS is not clear about how friend declarations are
1551   // to be treated. It's not meaningful to have different owning modules for
1552   // linkage in redeclarations of the same entity, so for now allow the
1553   // redeclaration and change the owning modules to match.
1554   if (New->getFriendObjectKind() &&
1555       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1556     New->setLocalOwningModule(Old->getOwningModule());
1557     makeMergedDefinitionVisible(New);
1558     return false;
1559   }
1560 
1561   Module *NewM = New->getOwningModule();
1562   Module *OldM = Old->getOwningModule();
1563 
1564   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1565     NewM = NewM->Parent;
1566   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1567     OldM = OldM->Parent;
1568 
1569   if (NewM == OldM)
1570     return false;
1571 
1572   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1573   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1574   if (NewIsModuleInterface || OldIsModuleInterface) {
1575     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1576     //   if a declaration of D [...] appears in the purview of a module, all
1577     //   other such declarations shall appear in the purview of the same module
1578     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1579       << New
1580       << NewIsModuleInterface
1581       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1582       << OldIsModuleInterface
1583       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1584     Diag(Old->getLocation(), diag::note_previous_declaration);
1585     New->setInvalidDecl();
1586     return true;
1587   }
1588 
1589   return false;
1590 }
1591 
isUsingDecl(NamedDecl * D)1592 static bool isUsingDecl(NamedDecl *D) {
1593   return isa<UsingShadowDecl>(D) ||
1594          isa<UnresolvedUsingTypenameDecl>(D) ||
1595          isa<UnresolvedUsingValueDecl>(D);
1596 }
1597 
1598 /// Removes using shadow declarations from the lookup results.
RemoveUsingDecls(LookupResult & R)1599 static void RemoveUsingDecls(LookupResult &R) {
1600   LookupResult::Filter F = R.makeFilter();
1601   while (F.hasNext())
1602     if (isUsingDecl(F.next()))
1603       F.erase();
1604 
1605   F.done();
1606 }
1607 
1608 /// Check for this common pattern:
1609 /// @code
1610 /// class S {
1611 ///   S(const S&); // DO NOT IMPLEMENT
1612 ///   void operator=(const S&); // DO NOT IMPLEMENT
1613 /// };
1614 /// @endcode
IsDisallowedCopyOrAssign(const CXXMethodDecl * D)1615 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1616   // FIXME: Should check for private access too but access is set after we get
1617   // the decl here.
1618   if (D->doesThisDeclarationHaveABody())
1619     return false;
1620 
1621   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1622     return CD->isCopyConstructor();
1623   return D->isCopyAssignmentOperator();
1624 }
1625 
1626 // We need this to handle
1627 //
1628 // typedef struct {
1629 //   void *foo() { return 0; }
1630 // } A;
1631 //
1632 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1633 // for example. If 'A', foo will have external linkage. If we have '*A',
1634 // foo will have no linkage. Since we can't know until we get to the end
1635 // of the typedef, this function finds out if D might have non-external linkage.
1636 // Callers should verify at the end of the TU if it D has external linkage or
1637 // not.
mightHaveNonExternalLinkage(const DeclaratorDecl * D)1638 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1639   const DeclContext *DC = D->getDeclContext();
1640   while (!DC->isTranslationUnit()) {
1641     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1642       if (!RD->hasNameForLinkage())
1643         return true;
1644     }
1645     DC = DC->getParent();
1646   }
1647 
1648   return !D->isExternallyVisible();
1649 }
1650 
1651 // FIXME: This needs to be refactored; some other isInMainFile users want
1652 // these semantics.
isMainFileLoc(const Sema & S,SourceLocation Loc)1653 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1654   if (S.TUKind != TU_Complete)
1655     return false;
1656   return S.SourceMgr.isInMainFile(Loc);
1657 }
1658 
ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl * D) const1659 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1660   assert(D);
1661 
1662   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1663     return false;
1664 
1665   // Ignore all entities declared within templates, and out-of-line definitions
1666   // of members of class templates.
1667   if (D->getDeclContext()->isDependentContext() ||
1668       D->getLexicalDeclContext()->isDependentContext())
1669     return false;
1670 
1671   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1672     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1673       return false;
1674     // A non-out-of-line declaration of a member specialization was implicitly
1675     // instantiated; it's the out-of-line declaration that we're interested in.
1676     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1677         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1678       return false;
1679 
1680     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1681       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1682         return false;
1683     } else {
1684       // 'static inline' functions are defined in headers; don't warn.
1685       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1686         return false;
1687     }
1688 
1689     if (FD->doesThisDeclarationHaveABody() &&
1690         Context.DeclMustBeEmitted(FD))
1691       return false;
1692   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1693     // Constants and utility variables are defined in headers with internal
1694     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1695     // like "inline".)
1696     if (!isMainFileLoc(*this, VD->getLocation()))
1697       return false;
1698 
1699     if (Context.DeclMustBeEmitted(VD))
1700       return false;
1701 
1702     if (VD->isStaticDataMember() &&
1703         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1704       return false;
1705     if (VD->isStaticDataMember() &&
1706         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1707         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1708       return false;
1709 
1710     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1711       return false;
1712   } else {
1713     return false;
1714   }
1715 
1716   // Only warn for unused decls internal to the translation unit.
1717   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1718   // for inline functions defined in the main source file, for instance.
1719   return mightHaveNonExternalLinkage(D);
1720 }
1721 
MarkUnusedFileScopedDecl(const DeclaratorDecl * D)1722 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1723   if (!D)
1724     return;
1725 
1726   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1727     const FunctionDecl *First = FD->getFirstDecl();
1728     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1729       return; // First should already be in the vector.
1730   }
1731 
1732   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1733     const VarDecl *First = VD->getFirstDecl();
1734     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1735       return; // First should already be in the vector.
1736   }
1737 
1738   if (ShouldWarnIfUnusedFileScopedDecl(D))
1739     UnusedFileScopedDecls.push_back(D);
1740 }
1741 
ShouldDiagnoseUnusedDecl(const NamedDecl * D)1742 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1743   if (D->isInvalidDecl())
1744     return false;
1745 
1746   bool Referenced = false;
1747   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1748     // For a decomposition declaration, warn if none of the bindings are
1749     // referenced, instead of if the variable itself is referenced (which
1750     // it is, by the bindings' expressions).
1751     for (auto *BD : DD->bindings()) {
1752       if (BD->isReferenced()) {
1753         Referenced = true;
1754         break;
1755       }
1756     }
1757   } else if (!D->getDeclName()) {
1758     return false;
1759   } else if (D->isReferenced() || D->isUsed()) {
1760     Referenced = true;
1761   }
1762 
1763   if (Referenced || D->hasAttr<UnusedAttr>() ||
1764       D->hasAttr<ObjCPreciseLifetimeAttr>())
1765     return false;
1766 
1767   if (isa<LabelDecl>(D))
1768     return true;
1769 
1770   // Except for labels, we only care about unused decls that are local to
1771   // functions.
1772   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1773   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1774     // For dependent types, the diagnostic is deferred.
1775     WithinFunction =
1776         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1777   if (!WithinFunction)
1778     return false;
1779 
1780   if (isa<TypedefNameDecl>(D))
1781     return true;
1782 
1783   // White-list anything that isn't a local variable.
1784   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1785     return false;
1786 
1787   // Types of valid local variables should be complete, so this should succeed.
1788   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1789 
1790     // White-list anything with an __attribute__((unused)) type.
1791     const auto *Ty = VD->getType().getTypePtr();
1792 
1793     // Only look at the outermost level of typedef.
1794     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1795       if (TT->getDecl()->hasAttr<UnusedAttr>())
1796         return false;
1797     }
1798 
1799     // If we failed to complete the type for some reason, or if the type is
1800     // dependent, don't diagnose the variable.
1801     if (Ty->isIncompleteType() || Ty->isDependentType())
1802       return false;
1803 
1804     // Look at the element type to ensure that the warning behaviour is
1805     // consistent for both scalars and arrays.
1806     Ty = Ty->getBaseElementTypeUnsafe();
1807 
1808     if (const TagType *TT = Ty->getAs<TagType>()) {
1809       const TagDecl *Tag = TT->getDecl();
1810       if (Tag->hasAttr<UnusedAttr>())
1811         return false;
1812 
1813       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1814         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1815           return false;
1816 
1817         if (const Expr *Init = VD->getInit()) {
1818           if (const ExprWithCleanups *Cleanups =
1819                   dyn_cast<ExprWithCleanups>(Init))
1820             Init = Cleanups->getSubExpr();
1821           const CXXConstructExpr *Construct =
1822             dyn_cast<CXXConstructExpr>(Init);
1823           if (Construct && !Construct->isElidable()) {
1824             CXXConstructorDecl *CD = Construct->getConstructor();
1825             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1826                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1827               return false;
1828           }
1829 
1830           // Suppress the warning if we don't know how this is constructed, and
1831           // it could possibly be non-trivial constructor.
1832           if (Init->isTypeDependent())
1833             for (const CXXConstructorDecl *Ctor : RD->ctors())
1834               if (!Ctor->isTrivial())
1835                 return false;
1836         }
1837       }
1838     }
1839 
1840     // TODO: __attribute__((unused)) templates?
1841   }
1842 
1843   return true;
1844 }
1845 
GenerateFixForUnusedDecl(const NamedDecl * D,ASTContext & Ctx,FixItHint & Hint)1846 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1847                                      FixItHint &Hint) {
1848   if (isa<LabelDecl>(D)) {
1849     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1850         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1851         true);
1852     if (AfterColon.isInvalid())
1853       return;
1854     Hint = FixItHint::CreateRemoval(
1855         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1856   }
1857 }
1858 
DiagnoseUnusedNestedTypedefs(const RecordDecl * D)1859 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1860   if (D->getTypeForDecl()->isDependentType())
1861     return;
1862 
1863   for (auto *TmpD : D->decls()) {
1864     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1865       DiagnoseUnusedDecl(T);
1866     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1867       DiagnoseUnusedNestedTypedefs(R);
1868   }
1869 }
1870 
1871 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1872 /// unless they are marked attr(unused).
DiagnoseUnusedDecl(const NamedDecl * D)1873 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1874   if (!ShouldDiagnoseUnusedDecl(D))
1875     return;
1876 
1877   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1878     // typedefs can be referenced later on, so the diagnostics are emitted
1879     // at end-of-translation-unit.
1880     UnusedLocalTypedefNameCandidates.insert(TD);
1881     return;
1882   }
1883 
1884   FixItHint Hint;
1885   GenerateFixForUnusedDecl(D, Context, Hint);
1886 
1887   unsigned DiagID;
1888   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1889     DiagID = diag::warn_unused_exception_param;
1890   else if (isa<LabelDecl>(D))
1891     DiagID = diag::warn_unused_label;
1892   else
1893     DiagID = diag::warn_unused_variable;
1894 
1895   Diag(D->getLocation(), DiagID) << D << Hint;
1896 }
1897 
CheckPoppedLabel(LabelDecl * L,Sema & S)1898 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1899   // Verify that we have no forward references left.  If so, there was a goto
1900   // or address of a label taken, but no definition of it.  Label fwd
1901   // definitions are indicated with a null substmt which is also not a resolved
1902   // MS inline assembly label name.
1903   bool Diagnose = false;
1904   if (L->isMSAsmLabel())
1905     Diagnose = !L->isResolvedMSAsmLabel();
1906   else
1907     Diagnose = L->getStmt() == nullptr;
1908   if (Diagnose)
1909     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1910 }
1911 
ActOnPopScope(SourceLocation Loc,Scope * S)1912 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1913   S->mergeNRVOIntoParent();
1914 
1915   if (S->decl_empty()) return;
1916   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1917          "Scope shouldn't contain decls!");
1918 
1919   for (auto *TmpD : S->decls()) {
1920     assert(TmpD && "This decl didn't get pushed??");
1921 
1922     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1923     NamedDecl *D = cast<NamedDecl>(TmpD);
1924 
1925     // Diagnose unused variables in this scope.
1926     if (!S->hasUnrecoverableErrorOccurred()) {
1927       DiagnoseUnusedDecl(D);
1928       if (const auto *RD = dyn_cast<RecordDecl>(D))
1929         DiagnoseUnusedNestedTypedefs(RD);
1930     }
1931 
1932     if (!D->getDeclName()) continue;
1933 
1934     // If this was a forward reference to a label, verify it was defined.
1935     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1936       CheckPoppedLabel(LD, *this);
1937 
1938     // Remove this name from our lexical scope, and warn on it if we haven't
1939     // already.
1940     IdResolver.RemoveDecl(D);
1941     auto ShadowI = ShadowingDecls.find(D);
1942     if (ShadowI != ShadowingDecls.end()) {
1943       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1944         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1945             << D << FD << FD->getParent();
1946         Diag(FD->getLocation(), diag::note_previous_declaration);
1947       }
1948       ShadowingDecls.erase(ShadowI);
1949     }
1950   }
1951 }
1952 
1953 /// Look for an Objective-C class in the translation unit.
1954 ///
1955 /// \param Id The name of the Objective-C class we're looking for. If
1956 /// typo-correction fixes this name, the Id will be updated
1957 /// to the fixed name.
1958 ///
1959 /// \param IdLoc The location of the name in the translation unit.
1960 ///
1961 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1962 /// if there is no class with the given name.
1963 ///
1964 /// \returns The declaration of the named Objective-C class, or NULL if the
1965 /// class could not be found.
getObjCInterfaceDecl(IdentifierInfo * & Id,SourceLocation IdLoc,bool DoTypoCorrection)1966 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1967                                               SourceLocation IdLoc,
1968                                               bool DoTypoCorrection) {
1969   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1970   // creation from this context.
1971   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1972 
1973   if (!IDecl && DoTypoCorrection) {
1974     // Perform typo correction at the given location, but only if we
1975     // find an Objective-C class name.
1976     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1977     if (TypoCorrection C =
1978             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1979                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1980       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1981       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1982       Id = IDecl->getIdentifier();
1983     }
1984   }
1985   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1986   // This routine must always return a class definition, if any.
1987   if (Def && Def->getDefinition())
1988       Def = Def->getDefinition();
1989   return Def;
1990 }
1991 
1992 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1993 /// from S, where a non-field would be declared. This routine copes
1994 /// with the difference between C and C++ scoping rules in structs and
1995 /// unions. For example, the following code is well-formed in C but
1996 /// ill-formed in C++:
1997 /// @code
1998 /// struct S6 {
1999 ///   enum { BAR } e;
2000 /// };
2001 ///
2002 /// void test_S6() {
2003 ///   struct S6 a;
2004 ///   a.e = BAR;
2005 /// }
2006 /// @endcode
2007 /// For the declaration of BAR, this routine will return a different
2008 /// scope. The scope S will be the scope of the unnamed enumeration
2009 /// within S6. In C++, this routine will return the scope associated
2010 /// with S6, because the enumeration's scope is a transparent
2011 /// context but structures can contain non-field names. In C, this
2012 /// routine will return the translation unit scope, since the
2013 /// enumeration's scope is a transparent context and structures cannot
2014 /// contain non-field names.
getNonFieldDeclScope(Scope * S)2015 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2016   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2017          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2018          (S->isClassScope() && !getLangOpts().CPlusPlus))
2019     S = S->getParent();
2020   return S;
2021 }
2022 
2023 /// Looks up the declaration of "struct objc_super" and
2024 /// saves it for later use in building builtin declaration of
2025 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2026 /// pre-existing declaration exists no action takes place.
LookupPredefedObjCSuperType(Sema & ThisSema,Scope * S,IdentifierInfo * II)2027 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2028                                         IdentifierInfo *II) {
2029   if (!II->isStr("objc_msgSendSuper"))
2030     return;
2031   ASTContext &Context = ThisSema.Context;
2032 
2033   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2034                       SourceLocation(), Sema::LookupTagName);
2035   ThisSema.LookupName(Result, S);
2036   if (Result.getResultKind() == LookupResult::Found)
2037     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2038       Context.setObjCSuperType(Context.getTagDeclType(TD));
2039 }
2040 
getHeaderName(Builtin::Context & BuiltinInfo,unsigned ID,ASTContext::GetBuiltinTypeError Error)2041 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2042                                ASTContext::GetBuiltinTypeError Error) {
2043   switch (Error) {
2044   case ASTContext::GE_None:
2045     return "";
2046   case ASTContext::GE_Missing_type:
2047     return BuiltinInfo.getHeaderName(ID);
2048   case ASTContext::GE_Missing_stdio:
2049     return "stdio.h";
2050   case ASTContext::GE_Missing_setjmp:
2051     return "setjmp.h";
2052   case ASTContext::GE_Missing_ucontext:
2053     return "ucontext.h";
2054   }
2055   llvm_unreachable("unhandled error kind");
2056 }
2057 
2058 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2059 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2060 /// if we're creating this built-in in anticipation of redeclaring the
2061 /// built-in.
LazilyCreateBuiltin(IdentifierInfo * II,unsigned ID,Scope * S,bool ForRedeclaration,SourceLocation Loc)2062 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2063                                      Scope *S, bool ForRedeclaration,
2064                                      SourceLocation Loc) {
2065   LookupPredefedObjCSuperType(*this, S, II);
2066 
2067   ASTContext::GetBuiltinTypeError Error;
2068   QualType R = Context.GetBuiltinType(ID, Error);
2069   if (Error) {
2070     if (!ForRedeclaration)
2071       return nullptr;
2072 
2073     // If we have a builtin without an associated type we should not emit a
2074     // warning when we were not able to find a type for it.
2075     if (Error == ASTContext::GE_Missing_type)
2076       return nullptr;
2077 
2078     // If we could not find a type for setjmp it is because the jmp_buf type was
2079     // not defined prior to the setjmp declaration.
2080     if (Error == ASTContext::GE_Missing_setjmp) {
2081       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2082           << Context.BuiltinInfo.getName(ID);
2083       return nullptr;
2084     }
2085 
2086     // Generally, we emit a warning that the declaration requires the
2087     // appropriate header.
2088     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2089         << getHeaderName(Context.BuiltinInfo, ID, Error)
2090         << Context.BuiltinInfo.getName(ID);
2091     return nullptr;
2092   }
2093 
2094   if (!ForRedeclaration &&
2095       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2096        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2097     Diag(Loc, diag::ext_implicit_lib_function_decl)
2098         << Context.BuiltinInfo.getName(ID) << R;
2099     if (Context.BuiltinInfo.getHeaderName(ID) &&
2100         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2101       Diag(Loc, diag::note_include_header_or_declare)
2102           << Context.BuiltinInfo.getHeaderName(ID)
2103           << Context.BuiltinInfo.getName(ID);
2104   }
2105 
2106   if (R.isNull())
2107     return nullptr;
2108 
2109   DeclContext *Parent = Context.getTranslationUnitDecl();
2110   if (getLangOpts().CPlusPlus) {
2111     LinkageSpecDecl *CLinkageDecl =
2112         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2113                                 LinkageSpecDecl::lang_c, false);
2114     CLinkageDecl->setImplicit();
2115     Parent->addDecl(CLinkageDecl);
2116     Parent = CLinkageDecl;
2117   }
2118 
2119   FunctionDecl *New = FunctionDecl::Create(Context,
2120                                            Parent,
2121                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2122                                            SC_Extern,
2123                                            false,
2124                                            R->isFunctionProtoType());
2125   New->setImplicit();
2126 
2127   // Create Decl objects for each parameter, adding them to the
2128   // FunctionDecl.
2129   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2130     SmallVector<ParmVarDecl*, 16> Params;
2131     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2132       ParmVarDecl *parm =
2133           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2134                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2135                               SC_None, nullptr);
2136       parm->setScopeInfo(0, i);
2137       Params.push_back(parm);
2138     }
2139     New->setParams(Params);
2140   }
2141 
2142   AddKnownFunctionAttributes(New);
2143   RegisterLocallyScopedExternCDecl(New, S);
2144 
2145   // TUScope is the translation-unit scope to insert this function into.
2146   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2147   // relate Scopes to DeclContexts, and probably eliminate CurContext
2148   // entirely, but we're not there yet.
2149   DeclContext *SavedContext = CurContext;
2150   CurContext = Parent;
2151   PushOnScopeChains(New, TUScope);
2152   CurContext = SavedContext;
2153   return New;
2154 }
2155 
2156 /// Typedef declarations don't have linkage, but they still denote the same
2157 /// entity if their types are the same.
2158 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2159 /// isSameEntity.
filterNonConflictingPreviousTypedefDecls(Sema & S,TypedefNameDecl * Decl,LookupResult & Previous)2160 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2161                                                      TypedefNameDecl *Decl,
2162                                                      LookupResult &Previous) {
2163   // This is only interesting when modules are enabled.
2164   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2165     return;
2166 
2167   // Empty sets are uninteresting.
2168   if (Previous.empty())
2169     return;
2170 
2171   LookupResult::Filter Filter = Previous.makeFilter();
2172   while (Filter.hasNext()) {
2173     NamedDecl *Old = Filter.next();
2174 
2175     // Non-hidden declarations are never ignored.
2176     if (S.isVisible(Old))
2177       continue;
2178 
2179     // Declarations of the same entity are not ignored, even if they have
2180     // different linkages.
2181     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2182       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2183                                 Decl->getUnderlyingType()))
2184         continue;
2185 
2186       // If both declarations give a tag declaration a typedef name for linkage
2187       // purposes, then they declare the same entity.
2188       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2189           Decl->getAnonDeclWithTypedefName())
2190         continue;
2191     }
2192 
2193     Filter.erase();
2194   }
2195 
2196   Filter.done();
2197 }
2198 
isIncompatibleTypedef(TypeDecl * Old,TypedefNameDecl * New)2199 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2200   QualType OldType;
2201   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2202     OldType = OldTypedef->getUnderlyingType();
2203   else
2204     OldType = Context.getTypeDeclType(Old);
2205   QualType NewType = New->getUnderlyingType();
2206 
2207   if (NewType->isVariablyModifiedType()) {
2208     // Must not redefine a typedef with a variably-modified type.
2209     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2210     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2211       << Kind << NewType;
2212     if (Old->getLocation().isValid())
2213       notePreviousDefinition(Old, New->getLocation());
2214     New->setInvalidDecl();
2215     return true;
2216   }
2217 
2218   if (OldType != NewType &&
2219       !OldType->isDependentType() &&
2220       !NewType->isDependentType() &&
2221       !Context.hasSameType(OldType, NewType)) {
2222     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2223     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2224       << Kind << NewType << OldType;
2225     if (Old->getLocation().isValid())
2226       notePreviousDefinition(Old, New->getLocation());
2227     New->setInvalidDecl();
2228     return true;
2229   }
2230   return false;
2231 }
2232 
2233 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2234 /// same name and scope as a previous declaration 'Old'.  Figure out
2235 /// how to resolve this situation, merging decls or emitting
2236 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2237 ///
MergeTypedefNameDecl(Scope * S,TypedefNameDecl * New,LookupResult & OldDecls)2238 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2239                                 LookupResult &OldDecls) {
2240   // If the new decl is known invalid already, don't bother doing any
2241   // merging checks.
2242   if (New->isInvalidDecl()) return;
2243 
2244   // Allow multiple definitions for ObjC built-in typedefs.
2245   // FIXME: Verify the underlying types are equivalent!
2246   if (getLangOpts().ObjC) {
2247     const IdentifierInfo *TypeID = New->getIdentifier();
2248     switch (TypeID->getLength()) {
2249     default: break;
2250     case 2:
2251       {
2252         if (!TypeID->isStr("id"))
2253           break;
2254         QualType T = New->getUnderlyingType();
2255         if (!T->isPointerType())
2256           break;
2257         if (!T->isVoidPointerType()) {
2258           QualType PT = T->castAs<PointerType>()->getPointeeType();
2259           if (!PT->isStructureType())
2260             break;
2261         }
2262         Context.setObjCIdRedefinitionType(T);
2263         // Install the built-in type for 'id', ignoring the current definition.
2264         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2265         return;
2266       }
2267     case 5:
2268       if (!TypeID->isStr("Class"))
2269         break;
2270       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2271       // Install the built-in type for 'Class', ignoring the current definition.
2272       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2273       return;
2274     case 3:
2275       if (!TypeID->isStr("SEL"))
2276         break;
2277       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2278       // Install the built-in type for 'SEL', ignoring the current definition.
2279       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2280       return;
2281     }
2282     // Fall through - the typedef name was not a builtin type.
2283   }
2284 
2285   // Verify the old decl was also a type.
2286   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2287   if (!Old) {
2288     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2289       << New->getDeclName();
2290 
2291     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2292     if (OldD->getLocation().isValid())
2293       notePreviousDefinition(OldD, New->getLocation());
2294 
2295     return New->setInvalidDecl();
2296   }
2297 
2298   // If the old declaration is invalid, just give up here.
2299   if (Old->isInvalidDecl())
2300     return New->setInvalidDecl();
2301 
2302   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2303     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2304     auto *NewTag = New->getAnonDeclWithTypedefName();
2305     NamedDecl *Hidden = nullptr;
2306     if (OldTag && NewTag &&
2307         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2308         !hasVisibleDefinition(OldTag, &Hidden)) {
2309       // There is a definition of this tag, but it is not visible. Use it
2310       // instead of our tag.
2311       New->setTypeForDecl(OldTD->getTypeForDecl());
2312       if (OldTD->isModed())
2313         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2314                                     OldTD->getUnderlyingType());
2315       else
2316         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2317 
2318       // Make the old tag definition visible.
2319       makeMergedDefinitionVisible(Hidden);
2320 
2321       // If this was an unscoped enumeration, yank all of its enumerators
2322       // out of the scope.
2323       if (isa<EnumDecl>(NewTag)) {
2324         Scope *EnumScope = getNonFieldDeclScope(S);
2325         for (auto *D : NewTag->decls()) {
2326           auto *ED = cast<EnumConstantDecl>(D);
2327           assert(EnumScope->isDeclScope(ED));
2328           EnumScope->RemoveDecl(ED);
2329           IdResolver.RemoveDecl(ED);
2330           ED->getLexicalDeclContext()->removeDecl(ED);
2331         }
2332       }
2333     }
2334   }
2335 
2336   // If the typedef types are not identical, reject them in all languages and
2337   // with any extensions enabled.
2338   if (isIncompatibleTypedef(Old, New))
2339     return;
2340 
2341   // The types match.  Link up the redeclaration chain and merge attributes if
2342   // the old declaration was a typedef.
2343   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2344     New->setPreviousDecl(Typedef);
2345     mergeDeclAttributes(New, Old);
2346   }
2347 
2348   if (getLangOpts().MicrosoftExt)
2349     return;
2350 
2351   if (getLangOpts().CPlusPlus) {
2352     // C++ [dcl.typedef]p2:
2353     //   In a given non-class scope, a typedef specifier can be used to
2354     //   redefine the name of any type declared in that scope to refer
2355     //   to the type to which it already refers.
2356     if (!isa<CXXRecordDecl>(CurContext))
2357       return;
2358 
2359     // C++0x [dcl.typedef]p4:
2360     //   In a given class scope, a typedef specifier can be used to redefine
2361     //   any class-name declared in that scope that is not also a typedef-name
2362     //   to refer to the type to which it already refers.
2363     //
2364     // This wording came in via DR424, which was a correction to the
2365     // wording in DR56, which accidentally banned code like:
2366     //
2367     //   struct S {
2368     //     typedef struct A { } A;
2369     //   };
2370     //
2371     // in the C++03 standard. We implement the C++0x semantics, which
2372     // allow the above but disallow
2373     //
2374     //   struct S {
2375     //     typedef int I;
2376     //     typedef int I;
2377     //   };
2378     //
2379     // since that was the intent of DR56.
2380     if (!isa<TypedefNameDecl>(Old))
2381       return;
2382 
2383     Diag(New->getLocation(), diag::err_redefinition)
2384       << New->getDeclName();
2385     notePreviousDefinition(Old, New->getLocation());
2386     return New->setInvalidDecl();
2387   }
2388 
2389   // Modules always permit redefinition of typedefs, as does C11.
2390   if (getLangOpts().Modules || getLangOpts().C11)
2391     return;
2392 
2393   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2394   // is normally mapped to an error, but can be controlled with
2395   // -Wtypedef-redefinition.  If either the original or the redefinition is
2396   // in a system header, don't emit this for compatibility with GCC.
2397   if (getDiagnostics().getSuppressSystemWarnings() &&
2398       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2399       (Old->isImplicit() ||
2400        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2401        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2402     return;
2403 
2404   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2405     << New->getDeclName();
2406   notePreviousDefinition(Old, New->getLocation());
2407 }
2408 
2409 /// DeclhasAttr - returns true if decl Declaration already has the target
2410 /// attribute.
DeclHasAttr(const Decl * D,const Attr * A)2411 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2412   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2413   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2414   for (const auto *i : D->attrs())
2415     if (i->getKind() == A->getKind()) {
2416       if (Ann) {
2417         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2418           return true;
2419         continue;
2420       }
2421       // FIXME: Don't hardcode this check
2422       if (OA && isa<OwnershipAttr>(i))
2423         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2424       return true;
2425     }
2426 
2427   return false;
2428 }
2429 
isAttributeTargetADefinition(Decl * D)2430 static bool isAttributeTargetADefinition(Decl *D) {
2431   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2432     return VD->isThisDeclarationADefinition();
2433   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2434     return TD->isCompleteDefinition() || TD->isBeingDefined();
2435   return true;
2436 }
2437 
2438 /// Merge alignment attributes from \p Old to \p New, taking into account the
2439 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2440 ///
2441 /// \return \c true if any attributes were added to \p New.
mergeAlignedAttrs(Sema & S,NamedDecl * New,Decl * Old)2442 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2443   // Look for alignas attributes on Old, and pick out whichever attribute
2444   // specifies the strictest alignment requirement.
2445   AlignedAttr *OldAlignasAttr = nullptr;
2446   AlignedAttr *OldStrictestAlignAttr = nullptr;
2447   unsigned OldAlign = 0;
2448   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2449     // FIXME: We have no way of representing inherited dependent alignments
2450     // in a case like:
2451     //   template<int A, int B> struct alignas(A) X;
2452     //   template<int A, int B> struct alignas(B) X {};
2453     // For now, we just ignore any alignas attributes which are not on the
2454     // definition in such a case.
2455     if (I->isAlignmentDependent())
2456       return false;
2457 
2458     if (I->isAlignas())
2459       OldAlignasAttr = I;
2460 
2461     unsigned Align = I->getAlignment(S.Context);
2462     if (Align > OldAlign) {
2463       OldAlign = Align;
2464       OldStrictestAlignAttr = I;
2465     }
2466   }
2467 
2468   // Look for alignas attributes on New.
2469   AlignedAttr *NewAlignasAttr = nullptr;
2470   unsigned NewAlign = 0;
2471   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2472     if (I->isAlignmentDependent())
2473       return false;
2474 
2475     if (I->isAlignas())
2476       NewAlignasAttr = I;
2477 
2478     unsigned Align = I->getAlignment(S.Context);
2479     if (Align > NewAlign)
2480       NewAlign = Align;
2481   }
2482 
2483   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2484     // Both declarations have 'alignas' attributes. We require them to match.
2485     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2486     // fall short. (If two declarations both have alignas, they must both match
2487     // every definition, and so must match each other if there is a definition.)
2488 
2489     // If either declaration only contains 'alignas(0)' specifiers, then it
2490     // specifies the natural alignment for the type.
2491     if (OldAlign == 0 || NewAlign == 0) {
2492       QualType Ty;
2493       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2494         Ty = VD->getType();
2495       else
2496         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2497 
2498       if (OldAlign == 0)
2499         OldAlign = S.Context.getTypeAlign(Ty);
2500       if (NewAlign == 0)
2501         NewAlign = S.Context.getTypeAlign(Ty);
2502     }
2503 
2504     if (OldAlign != NewAlign) {
2505       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2506         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2507         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2508       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2509     }
2510   }
2511 
2512   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2513     // C++11 [dcl.align]p6:
2514     //   if any declaration of an entity has an alignment-specifier,
2515     //   every defining declaration of that entity shall specify an
2516     //   equivalent alignment.
2517     // C11 6.7.5/7:
2518     //   If the definition of an object does not have an alignment
2519     //   specifier, any other declaration of that object shall also
2520     //   have no alignment specifier.
2521     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2522       << OldAlignasAttr;
2523     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2524       << OldAlignasAttr;
2525   }
2526 
2527   bool AnyAdded = false;
2528 
2529   // Ensure we have an attribute representing the strictest alignment.
2530   if (OldAlign > NewAlign) {
2531     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2532     Clone->setInherited(true);
2533     New->addAttr(Clone);
2534     AnyAdded = true;
2535   }
2536 
2537   // Ensure we have an alignas attribute if the old declaration had one.
2538   if (OldAlignasAttr && !NewAlignasAttr &&
2539       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2540     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2541     Clone->setInherited(true);
2542     New->addAttr(Clone);
2543     AnyAdded = true;
2544   }
2545 
2546   return AnyAdded;
2547 }
2548 
mergeDeclAttribute(Sema & S,NamedDecl * D,const InheritableAttr * Attr,Sema::AvailabilityMergeKind AMK)2549 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2550                                const InheritableAttr *Attr,
2551                                Sema::AvailabilityMergeKind AMK) {
2552   // This function copies an attribute Attr from a previous declaration to the
2553   // new declaration D if the new declaration doesn't itself have that attribute
2554   // yet or if that attribute allows duplicates.
2555   // If you're adding a new attribute that requires logic different from
2556   // "use explicit attribute on decl if present, else use attribute from
2557   // previous decl", for example if the attribute needs to be consistent
2558   // between redeclarations, you need to call a custom merge function here.
2559   InheritableAttr *NewAttr = nullptr;
2560   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2561     NewAttr = S.mergeAvailabilityAttr(
2562         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2563         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2564         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2565         AA->getPriority());
2566   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2567     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2568   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2569     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2570   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2571     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2572   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2573     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2574   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2575     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2576                                 FA->getFirstArg());
2577   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2578     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2579   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2580     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2581   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2582     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2583                                        IA->getInheritanceModel());
2584   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2585     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2586                                       &S.Context.Idents.get(AA->getSpelling()));
2587   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2588            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2589             isa<CUDAGlobalAttr>(Attr))) {
2590     // CUDA target attributes are part of function signature for
2591     // overloading purposes and must not be merged.
2592     return false;
2593   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2594     NewAttr = S.mergeMinSizeAttr(D, *MA);
2595   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2596     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2597   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2598     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2599   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2600     NewAttr = S.mergeCommonAttr(D, *CommonA);
2601   else if (isa<AlignedAttr>(Attr))
2602     // AlignedAttrs are handled separately, because we need to handle all
2603     // such attributes on a declaration at the same time.
2604     NewAttr = nullptr;
2605   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2606            (AMK == Sema::AMK_Override ||
2607             AMK == Sema::AMK_ProtocolImplementation))
2608     NewAttr = nullptr;
2609   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2610     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2611   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2612     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2613   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2614     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2615   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2616     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2617   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2618     NewAttr = S.mergeImportNameAttr(D, *INA);
2619   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2620     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2621 
2622   if (NewAttr) {
2623     NewAttr->setInherited(true);
2624     D->addAttr(NewAttr);
2625     if (isa<MSInheritanceAttr>(NewAttr))
2626       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2627     return true;
2628   }
2629 
2630   return false;
2631 }
2632 
getDefinition(const Decl * D)2633 static const NamedDecl *getDefinition(const Decl *D) {
2634   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2635     return TD->getDefinition();
2636   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2637     const VarDecl *Def = VD->getDefinition();
2638     if (Def)
2639       return Def;
2640     return VD->getActingDefinition();
2641   }
2642   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2643     return FD->getDefinition();
2644   return nullptr;
2645 }
2646 
hasAttribute(const Decl * D,attr::Kind Kind)2647 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2648   for (const auto *Attribute : D->attrs())
2649     if (Attribute->getKind() == Kind)
2650       return true;
2651   return false;
2652 }
2653 
2654 /// checkNewAttributesAfterDef - If we already have a definition, check that
2655 /// there are no new attributes in this declaration.
checkNewAttributesAfterDef(Sema & S,Decl * New,const Decl * Old)2656 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2657   if (!New->hasAttrs())
2658     return;
2659 
2660   const NamedDecl *Def = getDefinition(Old);
2661   if (!Def || Def == New)
2662     return;
2663 
2664   AttrVec &NewAttributes = New->getAttrs();
2665   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2666     const Attr *NewAttribute = NewAttributes[I];
2667 
2668     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2669       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2670         Sema::SkipBodyInfo SkipBody;
2671         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2672 
2673         // If we're skipping this definition, drop the "alias" attribute.
2674         if (SkipBody.ShouldSkip) {
2675           NewAttributes.erase(NewAttributes.begin() + I);
2676           --E;
2677           continue;
2678         }
2679       } else {
2680         VarDecl *VD = cast<VarDecl>(New);
2681         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2682                                 VarDecl::TentativeDefinition
2683                             ? diag::err_alias_after_tentative
2684                             : diag::err_redefinition;
2685         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2686         if (Diag == diag::err_redefinition)
2687           S.notePreviousDefinition(Def, VD->getLocation());
2688         else
2689           S.Diag(Def->getLocation(), diag::note_previous_definition);
2690         VD->setInvalidDecl();
2691       }
2692       ++I;
2693       continue;
2694     }
2695 
2696     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2697       // Tentative definitions are only interesting for the alias check above.
2698       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2699         ++I;
2700         continue;
2701       }
2702     }
2703 
2704     if (hasAttribute(Def, NewAttribute->getKind())) {
2705       ++I;
2706       continue; // regular attr merging will take care of validating this.
2707     }
2708 
2709     if (isa<C11NoReturnAttr>(NewAttribute)) {
2710       // C's _Noreturn is allowed to be added to a function after it is defined.
2711       ++I;
2712       continue;
2713     } else if (isa<UuidAttr>(NewAttribute)) {
2714       // msvc will allow a subsequent definition to add an uuid to a class
2715       ++I;
2716       continue;
2717     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2718       if (AA->isAlignas()) {
2719         // C++11 [dcl.align]p6:
2720         //   if any declaration of an entity has an alignment-specifier,
2721         //   every defining declaration of that entity shall specify an
2722         //   equivalent alignment.
2723         // C11 6.7.5/7:
2724         //   If the definition of an object does not have an alignment
2725         //   specifier, any other declaration of that object shall also
2726         //   have no alignment specifier.
2727         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2728           << AA;
2729         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2730           << AA;
2731         NewAttributes.erase(NewAttributes.begin() + I);
2732         --E;
2733         continue;
2734       }
2735     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2736       // If there is a C definition followed by a redeclaration with this
2737       // attribute then there are two different definitions. In C++, prefer the
2738       // standard diagnostics.
2739       if (!S.getLangOpts().CPlusPlus) {
2740         S.Diag(NewAttribute->getLocation(),
2741                diag::err_loader_uninitialized_redeclaration);
2742         S.Diag(Def->getLocation(), diag::note_previous_definition);
2743         NewAttributes.erase(NewAttributes.begin() + I);
2744         --E;
2745         continue;
2746       }
2747     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2748                cast<VarDecl>(New)->isInline() &&
2749                !cast<VarDecl>(New)->isInlineSpecified()) {
2750       // Don't warn about applying selectany to implicitly inline variables.
2751       // Older compilers and language modes would require the use of selectany
2752       // to make such variables inline, and it would have no effect if we
2753       // honored it.
2754       ++I;
2755       continue;
2756     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2757       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2758       // declarations after defintions.
2759       ++I;
2760       continue;
2761     }
2762 
2763     S.Diag(NewAttribute->getLocation(),
2764            diag::warn_attribute_precede_definition);
2765     S.Diag(Def->getLocation(), diag::note_previous_definition);
2766     NewAttributes.erase(NewAttributes.begin() + I);
2767     --E;
2768   }
2769 }
2770 
diagnoseMissingConstinit(Sema & S,const VarDecl * InitDecl,const ConstInitAttr * CIAttr,bool AttrBeforeInit)2771 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2772                                      const ConstInitAttr *CIAttr,
2773                                      bool AttrBeforeInit) {
2774   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2775 
2776   // Figure out a good way to write this specifier on the old declaration.
2777   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2778   // enough of the attribute list spelling information to extract that without
2779   // heroics.
2780   std::string SuitableSpelling;
2781   if (S.getLangOpts().CPlusPlus20)
2782     SuitableSpelling = std::string(
2783         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2784   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2785     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2786         InsertLoc, {tok::l_square, tok::l_square,
2787                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2788                     S.PP.getIdentifierInfo("require_constant_initialization"),
2789                     tok::r_square, tok::r_square}));
2790   if (SuitableSpelling.empty())
2791     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2792         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2793                     S.PP.getIdentifierInfo("require_constant_initialization"),
2794                     tok::r_paren, tok::r_paren}));
2795   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2796     SuitableSpelling = "constinit";
2797   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2798     SuitableSpelling = "[[clang::require_constant_initialization]]";
2799   if (SuitableSpelling.empty())
2800     SuitableSpelling = "__attribute__((require_constant_initialization))";
2801   SuitableSpelling += " ";
2802 
2803   if (AttrBeforeInit) {
2804     // extern constinit int a;
2805     // int a = 0; // error (missing 'constinit'), accepted as extension
2806     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2807     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2808         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2809     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2810   } else {
2811     // int a = 0;
2812     // constinit extern int a; // error (missing 'constinit')
2813     S.Diag(CIAttr->getLocation(),
2814            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2815                                  : diag::warn_require_const_init_added_too_late)
2816         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2817     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2818         << CIAttr->isConstinit()
2819         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2820   }
2821 }
2822 
2823 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
mergeDeclAttributes(NamedDecl * New,Decl * Old,AvailabilityMergeKind AMK)2824 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2825                                AvailabilityMergeKind AMK) {
2826   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2827     UsedAttr *NewAttr = OldAttr->clone(Context);
2828     NewAttr->setInherited(true);
2829     New->addAttr(NewAttr);
2830   }
2831 
2832   if (!Old->hasAttrs() && !New->hasAttrs())
2833     return;
2834 
2835   // [dcl.constinit]p1:
2836   //   If the [constinit] specifier is applied to any declaration of a
2837   //   variable, it shall be applied to the initializing declaration.
2838   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2839   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2840   if (bool(OldConstInit) != bool(NewConstInit)) {
2841     const auto *OldVD = cast<VarDecl>(Old);
2842     auto *NewVD = cast<VarDecl>(New);
2843 
2844     // Find the initializing declaration. Note that we might not have linked
2845     // the new declaration into the redeclaration chain yet.
2846     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2847     if (!InitDecl &&
2848         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2849       InitDecl = NewVD;
2850 
2851     if (InitDecl == NewVD) {
2852       // This is the initializing declaration. If it would inherit 'constinit',
2853       // that's ill-formed. (Note that we do not apply this to the attribute
2854       // form).
2855       if (OldConstInit && OldConstInit->isConstinit())
2856         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2857                                  /*AttrBeforeInit=*/true);
2858     } else if (NewConstInit) {
2859       // This is the first time we've been told that this declaration should
2860       // have a constant initializer. If we already saw the initializing
2861       // declaration, this is too late.
2862       if (InitDecl && InitDecl != NewVD) {
2863         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2864                                  /*AttrBeforeInit=*/false);
2865         NewVD->dropAttr<ConstInitAttr>();
2866       }
2867     }
2868   }
2869 
2870   // Attributes declared post-definition are currently ignored.
2871   checkNewAttributesAfterDef(*this, New, Old);
2872 
2873   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2874     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2875       if (!OldA->isEquivalent(NewA)) {
2876         // This redeclaration changes __asm__ label.
2877         Diag(New->getLocation(), diag::err_different_asm_label);
2878         Diag(OldA->getLocation(), diag::note_previous_declaration);
2879       }
2880     } else if (Old->isUsed()) {
2881       // This redeclaration adds an __asm__ label to a declaration that has
2882       // already been ODR-used.
2883       Diag(New->getLocation(), diag::err_late_asm_label_name)
2884         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2885     }
2886   }
2887 
2888   // Re-declaration cannot add abi_tag's.
2889   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2890     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2891       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2892         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2893                       NewTag) == OldAbiTagAttr->tags_end()) {
2894           Diag(NewAbiTagAttr->getLocation(),
2895                diag::err_new_abi_tag_on_redeclaration)
2896               << NewTag;
2897           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2898         }
2899       }
2900     } else {
2901       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2902       Diag(Old->getLocation(), diag::note_previous_declaration);
2903     }
2904   }
2905 
2906   // This redeclaration adds a section attribute.
2907   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2908     if (auto *VD = dyn_cast<VarDecl>(New)) {
2909       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2910         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2911         Diag(Old->getLocation(), diag::note_previous_declaration);
2912       }
2913     }
2914   }
2915 
2916   // Redeclaration adds code-seg attribute.
2917   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2918   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2919       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2920     Diag(New->getLocation(), diag::warn_mismatched_section)
2921          << 0 /*codeseg*/;
2922     Diag(Old->getLocation(), diag::note_previous_declaration);
2923   }
2924 
2925   if (!Old->hasAttrs())
2926     return;
2927 
2928   bool foundAny = New->hasAttrs();
2929 
2930   // Ensure that any moving of objects within the allocated map is done before
2931   // we process them.
2932   if (!foundAny) New->setAttrs(AttrVec());
2933 
2934   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2935     // Ignore deprecated/unavailable/availability attributes if requested.
2936     AvailabilityMergeKind LocalAMK = AMK_None;
2937     if (isa<DeprecatedAttr>(I) ||
2938         isa<UnavailableAttr>(I) ||
2939         isa<AvailabilityAttr>(I)) {
2940       switch (AMK) {
2941       case AMK_None:
2942         continue;
2943 
2944       case AMK_Redeclaration:
2945       case AMK_Override:
2946       case AMK_ProtocolImplementation:
2947         LocalAMK = AMK;
2948         break;
2949       }
2950     }
2951 
2952     // Already handled.
2953     if (isa<UsedAttr>(I))
2954       continue;
2955 
2956     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2957       foundAny = true;
2958   }
2959 
2960   if (mergeAlignedAttrs(*this, New, Old))
2961     foundAny = true;
2962 
2963   if (!foundAny) New->dropAttrs();
2964 }
2965 
2966 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2967 /// to the new one.
mergeParamDeclAttributes(ParmVarDecl * newDecl,const ParmVarDecl * oldDecl,Sema & S)2968 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2969                                      const ParmVarDecl *oldDecl,
2970                                      Sema &S) {
2971   // C++11 [dcl.attr.depend]p2:
2972   //   The first declaration of a function shall specify the
2973   //   carries_dependency attribute for its declarator-id if any declaration
2974   //   of the function specifies the carries_dependency attribute.
2975   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2976   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2977     S.Diag(CDA->getLocation(),
2978            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2979     // Find the first declaration of the parameter.
2980     // FIXME: Should we build redeclaration chains for function parameters?
2981     const FunctionDecl *FirstFD =
2982       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2983     const ParmVarDecl *FirstVD =
2984       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2985     S.Diag(FirstVD->getLocation(),
2986            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2987   }
2988 
2989   if (!oldDecl->hasAttrs())
2990     return;
2991 
2992   bool foundAny = newDecl->hasAttrs();
2993 
2994   // Ensure that any moving of objects within the allocated map is
2995   // done before we process them.
2996   if (!foundAny) newDecl->setAttrs(AttrVec());
2997 
2998   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2999     if (!DeclHasAttr(newDecl, I)) {
3000       InheritableAttr *newAttr =
3001         cast<InheritableParamAttr>(I->clone(S.Context));
3002       newAttr->setInherited(true);
3003       newDecl->addAttr(newAttr);
3004       foundAny = true;
3005     }
3006   }
3007 
3008   if (!foundAny) newDecl->dropAttrs();
3009 }
3010 
mergeParamDeclTypes(ParmVarDecl * NewParam,const ParmVarDecl * OldParam,Sema & S)3011 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3012                                 const ParmVarDecl *OldParam,
3013                                 Sema &S) {
3014   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3015     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3016       if (*Oldnullability != *Newnullability) {
3017         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3018           << DiagNullabilityKind(
3019                *Newnullability,
3020                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3021                 != 0))
3022           << DiagNullabilityKind(
3023                *Oldnullability,
3024                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3025                 != 0));
3026         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3027       }
3028     } else {
3029       QualType NewT = NewParam->getType();
3030       NewT = S.Context.getAttributedType(
3031                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3032                          NewT, NewT);
3033       NewParam->setType(NewT);
3034     }
3035   }
3036 }
3037 
3038 namespace {
3039 
3040 /// Used in MergeFunctionDecl to keep track of function parameters in
3041 /// C.
3042 struct GNUCompatibleParamWarning {
3043   ParmVarDecl *OldParm;
3044   ParmVarDecl *NewParm;
3045   QualType PromotedType;
3046 };
3047 
3048 } // end anonymous namespace
3049 
3050 // Determine whether the previous declaration was a definition, implicit
3051 // declaration, or a declaration.
3052 template <typename T>
3053 static std::pair<diag::kind, SourceLocation>
getNoteDiagForInvalidRedeclaration(const T * Old,const T * New)3054 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3055   diag::kind PrevDiag;
3056   SourceLocation OldLocation = Old->getLocation();
3057   if (Old->isThisDeclarationADefinition())
3058     PrevDiag = diag::note_previous_definition;
3059   else if (Old->isImplicit()) {
3060     PrevDiag = diag::note_previous_implicit_declaration;
3061     if (OldLocation.isInvalid())
3062       OldLocation = New->getLocation();
3063   } else
3064     PrevDiag = diag::note_previous_declaration;
3065   return std::make_pair(PrevDiag, OldLocation);
3066 }
3067 
3068 /// canRedefineFunction - checks if a function can be redefined. Currently,
3069 /// only extern inline functions can be redefined, and even then only in
3070 /// GNU89 mode.
canRedefineFunction(const FunctionDecl * FD,const LangOptions & LangOpts)3071 static bool canRedefineFunction(const FunctionDecl *FD,
3072                                 const LangOptions& LangOpts) {
3073   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3074           !LangOpts.CPlusPlus &&
3075           FD->isInlineSpecified() &&
3076           FD->getStorageClass() == SC_Extern);
3077 }
3078 
getCallingConvAttributedType(QualType T) const3079 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3080   const AttributedType *AT = T->getAs<AttributedType>();
3081   while (AT && !AT->isCallingConv())
3082     AT = AT->getModifiedType()->getAs<AttributedType>();
3083   return AT;
3084 }
3085 
3086 template <typename T>
haveIncompatibleLanguageLinkages(const T * Old,const T * New)3087 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3088   const DeclContext *DC = Old->getDeclContext();
3089   if (DC->isRecord())
3090     return false;
3091 
3092   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3093   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3094     return true;
3095   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3096     return true;
3097   return false;
3098 }
3099 
isExternC(T * D)3100 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
isExternC(VarTemplateDecl *)3101 static bool isExternC(VarTemplateDecl *) { return false; }
3102 
3103 /// Check whether a redeclaration of an entity introduced by a
3104 /// using-declaration is valid, given that we know it's not an overload
3105 /// (nor a hidden tag declaration).
3106 template<typename ExpectedDecl>
checkUsingShadowRedecl(Sema & S,UsingShadowDecl * OldS,ExpectedDecl * New)3107 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3108                                    ExpectedDecl *New) {
3109   // C++11 [basic.scope.declarative]p4:
3110   //   Given a set of declarations in a single declarative region, each of
3111   //   which specifies the same unqualified name,
3112   //   -- they shall all refer to the same entity, or all refer to functions
3113   //      and function templates; or
3114   //   -- exactly one declaration shall declare a class name or enumeration
3115   //      name that is not a typedef name and the other declarations shall all
3116   //      refer to the same variable or enumerator, or all refer to functions
3117   //      and function templates; in this case the class name or enumeration
3118   //      name is hidden (3.3.10).
3119 
3120   // C++11 [namespace.udecl]p14:
3121   //   If a function declaration in namespace scope or block scope has the
3122   //   same name and the same parameter-type-list as a function introduced
3123   //   by a using-declaration, and the declarations do not declare the same
3124   //   function, the program is ill-formed.
3125 
3126   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3127   if (Old &&
3128       !Old->getDeclContext()->getRedeclContext()->Equals(
3129           New->getDeclContext()->getRedeclContext()) &&
3130       !(isExternC(Old) && isExternC(New)))
3131     Old = nullptr;
3132 
3133   if (!Old) {
3134     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3135     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3136     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3137     return true;
3138   }
3139   return false;
3140 }
3141 
hasIdenticalPassObjectSizeAttrs(const FunctionDecl * A,const FunctionDecl * B)3142 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3143                                             const FunctionDecl *B) {
3144   assert(A->getNumParams() == B->getNumParams());
3145 
3146   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3147     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3148     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3149     if (AttrA == AttrB)
3150       return true;
3151     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3152            AttrA->isDynamic() == AttrB->isDynamic();
3153   };
3154 
3155   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3156 }
3157 
3158 /// If necessary, adjust the semantic declaration context for a qualified
3159 /// declaration to name the correct inline namespace within the qualifier.
adjustDeclContextForDeclaratorDecl(DeclaratorDecl * NewD,DeclaratorDecl * OldD)3160 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3161                                                DeclaratorDecl *OldD) {
3162   // The only case where we need to update the DeclContext is when
3163   // redeclaration lookup for a qualified name finds a declaration
3164   // in an inline namespace within the context named by the qualifier:
3165   //
3166   //   inline namespace N { int f(); }
3167   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3168   //
3169   // For unqualified declarations, the semantic context *can* change
3170   // along the redeclaration chain (for local extern declarations,
3171   // extern "C" declarations, and friend declarations in particular).
3172   if (!NewD->getQualifier())
3173     return;
3174 
3175   // NewD is probably already in the right context.
3176   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3177   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3178   if (NamedDC->Equals(SemaDC))
3179     return;
3180 
3181   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3182           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3183          "unexpected context for redeclaration");
3184 
3185   auto *LexDC = NewD->getLexicalDeclContext();
3186   auto FixSemaDC = [=](NamedDecl *D) {
3187     if (!D)
3188       return;
3189     D->setDeclContext(SemaDC);
3190     D->setLexicalDeclContext(LexDC);
3191   };
3192 
3193   FixSemaDC(NewD);
3194   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3195     FixSemaDC(FD->getDescribedFunctionTemplate());
3196   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3197     FixSemaDC(VD->getDescribedVarTemplate());
3198 }
3199 
3200 /// MergeFunctionDecl - We just parsed a function 'New' from
3201 /// declarator D which has the same name and scope as a previous
3202 /// declaration 'Old'.  Figure out how to resolve this situation,
3203 /// merging decls or emitting diagnostics as appropriate.
3204 ///
3205 /// In C++, New and Old must be declarations that are not
3206 /// overloaded. Use IsOverload to determine whether New and Old are
3207 /// overloaded, and to select the Old declaration that New should be
3208 /// merged with.
3209 ///
3210 /// Returns true if there was an error, false otherwise.
MergeFunctionDecl(FunctionDecl * New,NamedDecl * & OldD,Scope * S,bool MergeTypeWithOld)3211 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3212                              Scope *S, bool MergeTypeWithOld) {
3213   // Verify the old decl was also a function.
3214   FunctionDecl *Old = OldD->getAsFunction();
3215   if (!Old) {
3216     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3217       if (New->getFriendObjectKind()) {
3218         Diag(New->getLocation(), diag::err_using_decl_friend);
3219         Diag(Shadow->getTargetDecl()->getLocation(),
3220              diag::note_using_decl_target);
3221         Diag(Shadow->getUsingDecl()->getLocation(),
3222              diag::note_using_decl) << 0;
3223         return true;
3224       }
3225 
3226       // Check whether the two declarations might declare the same function.
3227       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3228         return true;
3229       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3230     } else {
3231       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3232         << New->getDeclName();
3233       notePreviousDefinition(OldD, New->getLocation());
3234       return true;
3235     }
3236   }
3237 
3238   // If the old declaration is invalid, just give up here.
3239   if (Old->isInvalidDecl())
3240     return true;
3241 
3242   // Disallow redeclaration of some builtins.
3243   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3244     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3245     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3246         << Old << Old->getType();
3247     return true;
3248   }
3249 
3250   diag::kind PrevDiag;
3251   SourceLocation OldLocation;
3252   std::tie(PrevDiag, OldLocation) =
3253       getNoteDiagForInvalidRedeclaration(Old, New);
3254 
3255   // Don't complain about this if we're in GNU89 mode and the old function
3256   // is an extern inline function.
3257   // Don't complain about specializations. They are not supposed to have
3258   // storage classes.
3259   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3260       New->getStorageClass() == SC_Static &&
3261       Old->hasExternalFormalLinkage() &&
3262       !New->getTemplateSpecializationInfo() &&
3263       !canRedefineFunction(Old, getLangOpts())) {
3264     if (getLangOpts().MicrosoftExt) {
3265       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3266       Diag(OldLocation, PrevDiag);
3267     } else {
3268       Diag(New->getLocation(), diag::err_static_non_static) << New;
3269       Diag(OldLocation, PrevDiag);
3270       return true;
3271     }
3272   }
3273 
3274   if (New->hasAttr<InternalLinkageAttr>() &&
3275       !Old->hasAttr<InternalLinkageAttr>()) {
3276     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3277         << New->getDeclName();
3278     notePreviousDefinition(Old, New->getLocation());
3279     New->dropAttr<InternalLinkageAttr>();
3280   }
3281 
3282   if (CheckRedeclarationModuleOwnership(New, Old))
3283     return true;
3284 
3285   if (!getLangOpts().CPlusPlus) {
3286     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3287     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3288       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3289         << New << OldOvl;
3290 
3291       // Try our best to find a decl that actually has the overloadable
3292       // attribute for the note. In most cases (e.g. programs with only one
3293       // broken declaration/definition), this won't matter.
3294       //
3295       // FIXME: We could do this if we juggled some extra state in
3296       // OverloadableAttr, rather than just removing it.
3297       const Decl *DiagOld = Old;
3298       if (OldOvl) {
3299         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3300           const auto *A = D->getAttr<OverloadableAttr>();
3301           return A && !A->isImplicit();
3302         });
3303         // If we've implicitly added *all* of the overloadable attrs to this
3304         // chain, emitting a "previous redecl" note is pointless.
3305         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3306       }
3307 
3308       if (DiagOld)
3309         Diag(DiagOld->getLocation(),
3310              diag::note_attribute_overloadable_prev_overload)
3311           << OldOvl;
3312 
3313       if (OldOvl)
3314         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3315       else
3316         New->dropAttr<OverloadableAttr>();
3317     }
3318   }
3319 
3320   // If a function is first declared with a calling convention, but is later
3321   // declared or defined without one, all following decls assume the calling
3322   // convention of the first.
3323   //
3324   // It's OK if a function is first declared without a calling convention,
3325   // but is later declared or defined with the default calling convention.
3326   //
3327   // To test if either decl has an explicit calling convention, we look for
3328   // AttributedType sugar nodes on the type as written.  If they are missing or
3329   // were canonicalized away, we assume the calling convention was implicit.
3330   //
3331   // Note also that we DO NOT return at this point, because we still have
3332   // other tests to run.
3333   QualType OldQType = Context.getCanonicalType(Old->getType());
3334   QualType NewQType = Context.getCanonicalType(New->getType());
3335   const FunctionType *OldType = cast<FunctionType>(OldQType);
3336   const FunctionType *NewType = cast<FunctionType>(NewQType);
3337   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3338   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3339   bool RequiresAdjustment = false;
3340 
3341   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3342     FunctionDecl *First = Old->getFirstDecl();
3343     const FunctionType *FT =
3344         First->getType().getCanonicalType()->castAs<FunctionType>();
3345     FunctionType::ExtInfo FI = FT->getExtInfo();
3346     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3347     if (!NewCCExplicit) {
3348       // Inherit the CC from the previous declaration if it was specified
3349       // there but not here.
3350       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3351       RequiresAdjustment = true;
3352     } else if (New->getBuiltinID()) {
3353       // Calling Conventions on a Builtin aren't really useful and setting a
3354       // default calling convention and cdecl'ing some builtin redeclarations is
3355       // common, so warn and ignore the calling convention on the redeclaration.
3356       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3357           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3358           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3359       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3360       RequiresAdjustment = true;
3361     } else {
3362       // Calling conventions aren't compatible, so complain.
3363       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3364       Diag(New->getLocation(), diag::err_cconv_change)
3365         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3366         << !FirstCCExplicit
3367         << (!FirstCCExplicit ? "" :
3368             FunctionType::getNameForCallConv(FI.getCC()));
3369 
3370       // Put the note on the first decl, since it is the one that matters.
3371       Diag(First->getLocation(), diag::note_previous_declaration);
3372       return true;
3373     }
3374   }
3375 
3376   // FIXME: diagnose the other way around?
3377   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3378     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3379     RequiresAdjustment = true;
3380   }
3381 
3382   // Merge regparm attribute.
3383   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3384       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3385     if (NewTypeInfo.getHasRegParm()) {
3386       Diag(New->getLocation(), diag::err_regparm_mismatch)
3387         << NewType->getRegParmType()
3388         << OldType->getRegParmType();
3389       Diag(OldLocation, diag::note_previous_declaration);
3390       return true;
3391     }
3392 
3393     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3394     RequiresAdjustment = true;
3395   }
3396 
3397   // Merge ns_returns_retained attribute.
3398   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3399     if (NewTypeInfo.getProducesResult()) {
3400       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3401           << "'ns_returns_retained'";
3402       Diag(OldLocation, diag::note_previous_declaration);
3403       return true;
3404     }
3405 
3406     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3407     RequiresAdjustment = true;
3408   }
3409 
3410   if (OldTypeInfo.getNoCallerSavedRegs() !=
3411       NewTypeInfo.getNoCallerSavedRegs()) {
3412     if (NewTypeInfo.getNoCallerSavedRegs()) {
3413       AnyX86NoCallerSavedRegistersAttr *Attr =
3414         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3415       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3416       Diag(OldLocation, diag::note_previous_declaration);
3417       return true;
3418     }
3419 
3420     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3421     RequiresAdjustment = true;
3422   }
3423 
3424   if (RequiresAdjustment) {
3425     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3426     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3427     New->setType(QualType(AdjustedType, 0));
3428     NewQType = Context.getCanonicalType(New->getType());
3429   }
3430 
3431   // If this redeclaration makes the function inline, we may need to add it to
3432   // UndefinedButUsed.
3433   if (!Old->isInlined() && New->isInlined() &&
3434       !New->hasAttr<GNUInlineAttr>() &&
3435       !getLangOpts().GNUInline &&
3436       Old->isUsed(false) &&
3437       !Old->isDefined() && !New->isThisDeclarationADefinition())
3438     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3439                                            SourceLocation()));
3440 
3441   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3442   // about it.
3443   if (New->hasAttr<GNUInlineAttr>() &&
3444       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3445     UndefinedButUsed.erase(Old->getCanonicalDecl());
3446   }
3447 
3448   // If pass_object_size params don't match up perfectly, this isn't a valid
3449   // redeclaration.
3450   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3451       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3452     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3453         << New->getDeclName();
3454     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3455     return true;
3456   }
3457 
3458   if (getLangOpts().CPlusPlus) {
3459     // C++1z [over.load]p2
3460     //   Certain function declarations cannot be overloaded:
3461     //     -- Function declarations that differ only in the return type,
3462     //        the exception specification, or both cannot be overloaded.
3463 
3464     // Check the exception specifications match. This may recompute the type of
3465     // both Old and New if it resolved exception specifications, so grab the
3466     // types again after this. Because this updates the type, we do this before
3467     // any of the other checks below, which may update the "de facto" NewQType
3468     // but do not necessarily update the type of New.
3469     if (CheckEquivalentExceptionSpec(Old, New))
3470       return true;
3471     OldQType = Context.getCanonicalType(Old->getType());
3472     NewQType = Context.getCanonicalType(New->getType());
3473 
3474     // Go back to the type source info to compare the declared return types,
3475     // per C++1y [dcl.type.auto]p13:
3476     //   Redeclarations or specializations of a function or function template
3477     //   with a declared return type that uses a placeholder type shall also
3478     //   use that placeholder, not a deduced type.
3479     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3480     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3481     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3482         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3483                                        OldDeclaredReturnType)) {
3484       QualType ResQT;
3485       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3486           OldDeclaredReturnType->isObjCObjectPointerType())
3487         // FIXME: This does the wrong thing for a deduced return type.
3488         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3489       if (ResQT.isNull()) {
3490         if (New->isCXXClassMember() && New->isOutOfLine())
3491           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3492               << New << New->getReturnTypeSourceRange();
3493         else
3494           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3495               << New->getReturnTypeSourceRange();
3496         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3497                                     << Old->getReturnTypeSourceRange();
3498         return true;
3499       }
3500       else
3501         NewQType = ResQT;
3502     }
3503 
3504     QualType OldReturnType = OldType->getReturnType();
3505     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3506     if (OldReturnType != NewReturnType) {
3507       // If this function has a deduced return type and has already been
3508       // defined, copy the deduced value from the old declaration.
3509       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3510       if (OldAT && OldAT->isDeduced()) {
3511         New->setType(
3512             SubstAutoType(New->getType(),
3513                           OldAT->isDependentType() ? Context.DependentTy
3514                                                    : OldAT->getDeducedType()));
3515         NewQType = Context.getCanonicalType(
3516             SubstAutoType(NewQType,
3517                           OldAT->isDependentType() ? Context.DependentTy
3518                                                    : OldAT->getDeducedType()));
3519       }
3520     }
3521 
3522     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3523     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3524     if (OldMethod && NewMethod) {
3525       // Preserve triviality.
3526       NewMethod->setTrivial(OldMethod->isTrivial());
3527 
3528       // MSVC allows explicit template specialization at class scope:
3529       // 2 CXXMethodDecls referring to the same function will be injected.
3530       // We don't want a redeclaration error.
3531       bool IsClassScopeExplicitSpecialization =
3532                               OldMethod->isFunctionTemplateSpecialization() &&
3533                               NewMethod->isFunctionTemplateSpecialization();
3534       bool isFriend = NewMethod->getFriendObjectKind();
3535 
3536       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3537           !IsClassScopeExplicitSpecialization) {
3538         //    -- Member function declarations with the same name and the
3539         //       same parameter types cannot be overloaded if any of them
3540         //       is a static member function declaration.
3541         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3542           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3543           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3544           return true;
3545         }
3546 
3547         // C++ [class.mem]p1:
3548         //   [...] A member shall not be declared twice in the
3549         //   member-specification, except that a nested class or member
3550         //   class template can be declared and then later defined.
3551         if (!inTemplateInstantiation()) {
3552           unsigned NewDiag;
3553           if (isa<CXXConstructorDecl>(OldMethod))
3554             NewDiag = diag::err_constructor_redeclared;
3555           else if (isa<CXXDestructorDecl>(NewMethod))
3556             NewDiag = diag::err_destructor_redeclared;
3557           else if (isa<CXXConversionDecl>(NewMethod))
3558             NewDiag = diag::err_conv_function_redeclared;
3559           else
3560             NewDiag = diag::err_member_redeclared;
3561 
3562           Diag(New->getLocation(), NewDiag);
3563         } else {
3564           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3565             << New << New->getType();
3566         }
3567         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3568         return true;
3569 
3570       // Complain if this is an explicit declaration of a special
3571       // member that was initially declared implicitly.
3572       //
3573       // As an exception, it's okay to befriend such methods in order
3574       // to permit the implicit constructor/destructor/operator calls.
3575       } else if (OldMethod->isImplicit()) {
3576         if (isFriend) {
3577           NewMethod->setImplicit();
3578         } else {
3579           Diag(NewMethod->getLocation(),
3580                diag::err_definition_of_implicitly_declared_member)
3581             << New << getSpecialMember(OldMethod);
3582           return true;
3583         }
3584       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3585         Diag(NewMethod->getLocation(),
3586              diag::err_definition_of_explicitly_defaulted_member)
3587           << getSpecialMember(OldMethod);
3588         return true;
3589       }
3590     }
3591 
3592     // C++11 [dcl.attr.noreturn]p1:
3593     //   The first declaration of a function shall specify the noreturn
3594     //   attribute if any declaration of that function specifies the noreturn
3595     //   attribute.
3596     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3597     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3598       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3599       Diag(Old->getFirstDecl()->getLocation(),
3600            diag::note_noreturn_missing_first_decl);
3601     }
3602 
3603     // C++11 [dcl.attr.depend]p2:
3604     //   The first declaration of a function shall specify the
3605     //   carries_dependency attribute for its declarator-id if any declaration
3606     //   of the function specifies the carries_dependency attribute.
3607     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3608     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3609       Diag(CDA->getLocation(),
3610            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3611       Diag(Old->getFirstDecl()->getLocation(),
3612            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3613     }
3614 
3615     // (C++98 8.3.5p3):
3616     //   All declarations for a function shall agree exactly in both the
3617     //   return type and the parameter-type-list.
3618     // We also want to respect all the extended bits except noreturn.
3619 
3620     // noreturn should now match unless the old type info didn't have it.
3621     QualType OldQTypeForComparison = OldQType;
3622     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3623       auto *OldType = OldQType->castAs<FunctionProtoType>();
3624       const FunctionType *OldTypeForComparison
3625         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3626       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3627       assert(OldQTypeForComparison.isCanonical());
3628     }
3629 
3630     if (haveIncompatibleLanguageLinkages(Old, New)) {
3631       // As a special case, retain the language linkage from previous
3632       // declarations of a friend function as an extension.
3633       //
3634       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3635       // and is useful because there's otherwise no way to specify language
3636       // linkage within class scope.
3637       //
3638       // Check cautiously as the friend object kind isn't yet complete.
3639       if (New->getFriendObjectKind() != Decl::FOK_None) {
3640         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3641         Diag(OldLocation, PrevDiag);
3642       } else {
3643         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3644         Diag(OldLocation, PrevDiag);
3645         return true;
3646       }
3647     }
3648 
3649     // If the function types are compatible, merge the declarations. Ignore the
3650     // exception specifier because it was already checked above in
3651     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3652     // about incompatible types under -fms-compatibility.
3653     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3654                                                          NewQType))
3655       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3656 
3657     // If the types are imprecise (due to dependent constructs in friends or
3658     // local extern declarations), it's OK if they differ. We'll check again
3659     // during instantiation.
3660     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3661       return false;
3662 
3663     // Fall through for conflicting redeclarations and redefinitions.
3664   }
3665 
3666   // C: Function types need to be compatible, not identical. This handles
3667   // duplicate function decls like "void f(int); void f(enum X);" properly.
3668   if (!getLangOpts().CPlusPlus &&
3669       Context.typesAreCompatible(OldQType, NewQType)) {
3670     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3671     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3672     const FunctionProtoType *OldProto = nullptr;
3673     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3674         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3675       // The old declaration provided a function prototype, but the
3676       // new declaration does not. Merge in the prototype.
3677       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3678       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3679       NewQType =
3680           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3681                                   OldProto->getExtProtoInfo());
3682       New->setType(NewQType);
3683       New->setHasInheritedPrototype();
3684 
3685       // Synthesize parameters with the same types.
3686       SmallVector<ParmVarDecl*, 16> Params;
3687       for (const auto &ParamType : OldProto->param_types()) {
3688         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3689                                                  SourceLocation(), nullptr,
3690                                                  ParamType, /*TInfo=*/nullptr,
3691                                                  SC_None, nullptr);
3692         Param->setScopeInfo(0, Params.size());
3693         Param->setImplicit();
3694         Params.push_back(Param);
3695       }
3696 
3697       New->setParams(Params);
3698     }
3699 
3700     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3701   }
3702 
3703   // Check if the function types are compatible when pointer size address
3704   // spaces are ignored.
3705   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3706     return false;
3707 
3708   // GNU C permits a K&R definition to follow a prototype declaration
3709   // if the declared types of the parameters in the K&R definition
3710   // match the types in the prototype declaration, even when the
3711   // promoted types of the parameters from the K&R definition differ
3712   // from the types in the prototype. GCC then keeps the types from
3713   // the prototype.
3714   //
3715   // If a variadic prototype is followed by a non-variadic K&R definition,
3716   // the K&R definition becomes variadic.  This is sort of an edge case, but
3717   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3718   // C99 6.9.1p8.
3719   if (!getLangOpts().CPlusPlus &&
3720       Old->hasPrototype() && !New->hasPrototype() &&
3721       New->getType()->getAs<FunctionProtoType>() &&
3722       Old->getNumParams() == New->getNumParams()) {
3723     SmallVector<QualType, 16> ArgTypes;
3724     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3725     const FunctionProtoType *OldProto
3726       = Old->getType()->getAs<FunctionProtoType>();
3727     const FunctionProtoType *NewProto
3728       = New->getType()->getAs<FunctionProtoType>();
3729 
3730     // Determine whether this is the GNU C extension.
3731     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3732                                                NewProto->getReturnType());
3733     bool LooseCompatible = !MergedReturn.isNull();
3734     for (unsigned Idx = 0, End = Old->getNumParams();
3735          LooseCompatible && Idx != End; ++Idx) {
3736       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3737       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3738       if (Context.typesAreCompatible(OldParm->getType(),
3739                                      NewProto->getParamType(Idx))) {
3740         ArgTypes.push_back(NewParm->getType());
3741       } else if (Context.typesAreCompatible(OldParm->getType(),
3742                                             NewParm->getType(),
3743                                             /*CompareUnqualified=*/true)) {
3744         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3745                                            NewProto->getParamType(Idx) };
3746         Warnings.push_back(Warn);
3747         ArgTypes.push_back(NewParm->getType());
3748       } else
3749         LooseCompatible = false;
3750     }
3751 
3752     if (LooseCompatible) {
3753       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3754         Diag(Warnings[Warn].NewParm->getLocation(),
3755              diag::ext_param_promoted_not_compatible_with_prototype)
3756           << Warnings[Warn].PromotedType
3757           << Warnings[Warn].OldParm->getType();
3758         if (Warnings[Warn].OldParm->getLocation().isValid())
3759           Diag(Warnings[Warn].OldParm->getLocation(),
3760                diag::note_previous_declaration);
3761       }
3762 
3763       if (MergeTypeWithOld)
3764         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3765                                              OldProto->getExtProtoInfo()));
3766       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3767     }
3768 
3769     // Fall through to diagnose conflicting types.
3770   }
3771 
3772   // A function that has already been declared has been redeclared or
3773   // defined with a different type; show an appropriate diagnostic.
3774 
3775   // If the previous declaration was an implicitly-generated builtin
3776   // declaration, then at the very least we should use a specialized note.
3777   unsigned BuiltinID;
3778   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3779     // If it's actually a library-defined builtin function like 'malloc'
3780     // or 'printf', just warn about the incompatible redeclaration.
3781     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3782       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3783       Diag(OldLocation, diag::note_previous_builtin_declaration)
3784         << Old << Old->getType();
3785 
3786       // If this is a global redeclaration, just forget hereafter
3787       // about the "builtin-ness" of the function.
3788       //
3789       // Doing this for local extern declarations is problematic.  If
3790       // the builtin declaration remains visible, a second invalid
3791       // local declaration will produce a hard error; if it doesn't
3792       // remain visible, a single bogus local redeclaration (which is
3793       // actually only a warning) could break all the downstream code.
3794       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3795         New->getIdentifier()->revertBuiltin();
3796 
3797       return false;
3798     }
3799 
3800     PrevDiag = diag::note_previous_builtin_declaration;
3801   }
3802 
3803   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3804   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3805   return true;
3806 }
3807 
3808 /// Completes the merge of two function declarations that are
3809 /// known to be compatible.
3810 ///
3811 /// This routine handles the merging of attributes and other
3812 /// properties of function declarations from the old declaration to
3813 /// the new declaration, once we know that New is in fact a
3814 /// redeclaration of Old.
3815 ///
3816 /// \returns false
MergeCompatibleFunctionDecls(FunctionDecl * New,FunctionDecl * Old,Scope * S,bool MergeTypeWithOld)3817 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3818                                         Scope *S, bool MergeTypeWithOld) {
3819   // Merge the attributes
3820   mergeDeclAttributes(New, Old);
3821 
3822   // Merge "pure" flag.
3823   if (Old->isPure())
3824     New->setPure();
3825 
3826   // Merge "used" flag.
3827   if (Old->getMostRecentDecl()->isUsed(false))
3828     New->setIsUsed();
3829 
3830   // Merge attributes from the parameters.  These can mismatch with K&R
3831   // declarations.
3832   if (New->getNumParams() == Old->getNumParams())
3833       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3834         ParmVarDecl *NewParam = New->getParamDecl(i);
3835         ParmVarDecl *OldParam = Old->getParamDecl(i);
3836         mergeParamDeclAttributes(NewParam, OldParam, *this);
3837         mergeParamDeclTypes(NewParam, OldParam, *this);
3838       }
3839 
3840   if (getLangOpts().CPlusPlus)
3841     return MergeCXXFunctionDecl(New, Old, S);
3842 
3843   // Merge the function types so the we get the composite types for the return
3844   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3845   // was visible.
3846   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3847   if (!Merged.isNull() && MergeTypeWithOld)
3848     New->setType(Merged);
3849 
3850   return false;
3851 }
3852 
mergeObjCMethodDecls(ObjCMethodDecl * newMethod,ObjCMethodDecl * oldMethod)3853 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3854                                 ObjCMethodDecl *oldMethod) {
3855   // Merge the attributes, including deprecated/unavailable
3856   AvailabilityMergeKind MergeKind =
3857     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3858       ? AMK_ProtocolImplementation
3859       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3860                                                        : AMK_Override;
3861 
3862   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3863 
3864   // Merge attributes from the parameters.
3865   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3866                                        oe = oldMethod->param_end();
3867   for (ObjCMethodDecl::param_iterator
3868          ni = newMethod->param_begin(), ne = newMethod->param_end();
3869        ni != ne && oi != oe; ++ni, ++oi)
3870     mergeParamDeclAttributes(*ni, *oi, *this);
3871 
3872   CheckObjCMethodOverride(newMethod, oldMethod);
3873 }
3874 
diagnoseVarDeclTypeMismatch(Sema & S,VarDecl * New,VarDecl * Old)3875 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3876   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3877 
3878   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3879          ? diag::err_redefinition_different_type
3880          : diag::err_redeclaration_different_type)
3881     << New->getDeclName() << New->getType() << Old->getType();
3882 
3883   diag::kind PrevDiag;
3884   SourceLocation OldLocation;
3885   std::tie(PrevDiag, OldLocation)
3886     = getNoteDiagForInvalidRedeclaration(Old, New);
3887   S.Diag(OldLocation, PrevDiag);
3888   New->setInvalidDecl();
3889 }
3890 
3891 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3892 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3893 /// emitting diagnostics as appropriate.
3894 ///
3895 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3896 /// to here in AddInitializerToDecl. We can't check them before the initializer
3897 /// is attached.
MergeVarDeclTypes(VarDecl * New,VarDecl * Old,bool MergeTypeWithOld)3898 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3899                              bool MergeTypeWithOld) {
3900   if (New->isInvalidDecl() || Old->isInvalidDecl())
3901     return;
3902 
3903   QualType MergedT;
3904   if (getLangOpts().CPlusPlus) {
3905     if (New->getType()->isUndeducedType()) {
3906       // We don't know what the new type is until the initializer is attached.
3907       return;
3908     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3909       // These could still be something that needs exception specs checked.
3910       return MergeVarDeclExceptionSpecs(New, Old);
3911     }
3912     // C++ [basic.link]p10:
3913     //   [...] the types specified by all declarations referring to a given
3914     //   object or function shall be identical, except that declarations for an
3915     //   array object can specify array types that differ by the presence or
3916     //   absence of a major array bound (8.3.4).
3917     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3918       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3919       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3920 
3921       // We are merging a variable declaration New into Old. If it has an array
3922       // bound, and that bound differs from Old's bound, we should diagnose the
3923       // mismatch.
3924       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3925         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3926              PrevVD = PrevVD->getPreviousDecl()) {
3927           QualType PrevVDTy = PrevVD->getType();
3928           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3929             continue;
3930 
3931           if (!Context.hasSameType(New->getType(), PrevVDTy))
3932             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3933         }
3934       }
3935 
3936       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3937         if (Context.hasSameType(OldArray->getElementType(),
3938                                 NewArray->getElementType()))
3939           MergedT = New->getType();
3940       }
3941       // FIXME: Check visibility. New is hidden but has a complete type. If New
3942       // has no array bound, it should not inherit one from Old, if Old is not
3943       // visible.
3944       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3945         if (Context.hasSameType(OldArray->getElementType(),
3946                                 NewArray->getElementType()))
3947           MergedT = Old->getType();
3948       }
3949     }
3950     else if (New->getType()->isObjCObjectPointerType() &&
3951                Old->getType()->isObjCObjectPointerType()) {
3952       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3953                                               Old->getType());
3954     }
3955   } else {
3956     // C 6.2.7p2:
3957     //   All declarations that refer to the same object or function shall have
3958     //   compatible type.
3959     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3960   }
3961   if (MergedT.isNull()) {
3962     // It's OK if we couldn't merge types if either type is dependent, for a
3963     // block-scope variable. In other cases (static data members of class
3964     // templates, variable templates, ...), we require the types to be
3965     // equivalent.
3966     // FIXME: The C++ standard doesn't say anything about this.
3967     if ((New->getType()->isDependentType() ||
3968          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3969       // If the old type was dependent, we can't merge with it, so the new type
3970       // becomes dependent for now. We'll reproduce the original type when we
3971       // instantiate the TypeSourceInfo for the variable.
3972       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3973         New->setType(Context.DependentTy);
3974       return;
3975     }
3976     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3977   }
3978 
3979   // Don't actually update the type on the new declaration if the old
3980   // declaration was an extern declaration in a different scope.
3981   if (MergeTypeWithOld)
3982     New->setType(MergedT);
3983 }
3984 
mergeTypeWithPrevious(Sema & S,VarDecl * NewVD,VarDecl * OldVD,LookupResult & Previous)3985 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3986                                   LookupResult &Previous) {
3987   // C11 6.2.7p4:
3988   //   For an identifier with internal or external linkage declared
3989   //   in a scope in which a prior declaration of that identifier is
3990   //   visible, if the prior declaration specifies internal or
3991   //   external linkage, the type of the identifier at the later
3992   //   declaration becomes the composite type.
3993   //
3994   // If the variable isn't visible, we do not merge with its type.
3995   if (Previous.isShadowed())
3996     return false;
3997 
3998   if (S.getLangOpts().CPlusPlus) {
3999     // C++11 [dcl.array]p3:
4000     //   If there is a preceding declaration of the entity in the same
4001     //   scope in which the bound was specified, an omitted array bound
4002     //   is taken to be the same as in that earlier declaration.
4003     return NewVD->isPreviousDeclInSameBlockScope() ||
4004            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4005             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4006   } else {
4007     // If the old declaration was function-local, don't merge with its
4008     // type unless we're in the same function.
4009     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4010            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4011   }
4012 }
4013 
4014 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4015 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4016 /// situation, merging decls or emitting diagnostics as appropriate.
4017 ///
4018 /// Tentative definition rules (C99 6.9.2p2) are checked by
4019 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4020 /// definitions here, since the initializer hasn't been attached.
4021 ///
MergeVarDecl(VarDecl * New,LookupResult & Previous)4022 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4023   // If the new decl is already invalid, don't do any other checking.
4024   if (New->isInvalidDecl())
4025     return;
4026 
4027   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4028     return;
4029 
4030   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4031 
4032   // Verify the old decl was also a variable or variable template.
4033   VarDecl *Old = nullptr;
4034   VarTemplateDecl *OldTemplate = nullptr;
4035   if (Previous.isSingleResult()) {
4036     if (NewTemplate) {
4037       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4038       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4039 
4040       if (auto *Shadow =
4041               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4042         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4043           return New->setInvalidDecl();
4044     } else {
4045       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4046 
4047       if (auto *Shadow =
4048               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4049         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4050           return New->setInvalidDecl();
4051     }
4052   }
4053   if (!Old) {
4054     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4055         << New->getDeclName();
4056     notePreviousDefinition(Previous.getRepresentativeDecl(),
4057                            New->getLocation());
4058     return New->setInvalidDecl();
4059   }
4060 
4061   // Ensure the template parameters are compatible.
4062   if (NewTemplate &&
4063       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4064                                       OldTemplate->getTemplateParameters(),
4065                                       /*Complain=*/true, TPL_TemplateMatch))
4066     return New->setInvalidDecl();
4067 
4068   // C++ [class.mem]p1:
4069   //   A member shall not be declared twice in the member-specification [...]
4070   //
4071   // Here, we need only consider static data members.
4072   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4073     Diag(New->getLocation(), diag::err_duplicate_member)
4074       << New->getIdentifier();
4075     Diag(Old->getLocation(), diag::note_previous_declaration);
4076     New->setInvalidDecl();
4077   }
4078 
4079   mergeDeclAttributes(New, Old);
4080   // Warn if an already-declared variable is made a weak_import in a subsequent
4081   // declaration
4082   if (New->hasAttr<WeakImportAttr>() &&
4083       Old->getStorageClass() == SC_None &&
4084       !Old->hasAttr<WeakImportAttr>()) {
4085     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4086     notePreviousDefinition(Old, New->getLocation());
4087     // Remove weak_import attribute on new declaration.
4088     New->dropAttr<WeakImportAttr>();
4089   }
4090 
4091   if (New->hasAttr<InternalLinkageAttr>() &&
4092       !Old->hasAttr<InternalLinkageAttr>()) {
4093     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4094         << New->getDeclName();
4095     notePreviousDefinition(Old, New->getLocation());
4096     New->dropAttr<InternalLinkageAttr>();
4097   }
4098 
4099   // Merge the types.
4100   VarDecl *MostRecent = Old->getMostRecentDecl();
4101   if (MostRecent != Old) {
4102     MergeVarDeclTypes(New, MostRecent,
4103                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4104     if (New->isInvalidDecl())
4105       return;
4106   }
4107 
4108   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4109   if (New->isInvalidDecl())
4110     return;
4111 
4112   diag::kind PrevDiag;
4113   SourceLocation OldLocation;
4114   std::tie(PrevDiag, OldLocation) =
4115       getNoteDiagForInvalidRedeclaration(Old, New);
4116 
4117   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4118   if (New->getStorageClass() == SC_Static &&
4119       !New->isStaticDataMember() &&
4120       Old->hasExternalFormalLinkage()) {
4121     if (getLangOpts().MicrosoftExt) {
4122       Diag(New->getLocation(), diag::ext_static_non_static)
4123           << New->getDeclName();
4124       Diag(OldLocation, PrevDiag);
4125     } else {
4126       Diag(New->getLocation(), diag::err_static_non_static)
4127           << New->getDeclName();
4128       Diag(OldLocation, PrevDiag);
4129       return New->setInvalidDecl();
4130     }
4131   }
4132   // C99 6.2.2p4:
4133   //   For an identifier declared with the storage-class specifier
4134   //   extern in a scope in which a prior declaration of that
4135   //   identifier is visible,23) if the prior declaration specifies
4136   //   internal or external linkage, the linkage of the identifier at
4137   //   the later declaration is the same as the linkage specified at
4138   //   the prior declaration. If no prior declaration is visible, or
4139   //   if the prior declaration specifies no linkage, then the
4140   //   identifier has external linkage.
4141   if (New->hasExternalStorage() && Old->hasLinkage())
4142     /* Okay */;
4143   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4144            !New->isStaticDataMember() &&
4145            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4146     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4147     Diag(OldLocation, PrevDiag);
4148     return New->setInvalidDecl();
4149   }
4150 
4151   // Check if extern is followed by non-extern and vice-versa.
4152   if (New->hasExternalStorage() &&
4153       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4154     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4155     Diag(OldLocation, PrevDiag);
4156     return New->setInvalidDecl();
4157   }
4158   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4159       !New->hasExternalStorage()) {
4160     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4161     Diag(OldLocation, PrevDiag);
4162     return New->setInvalidDecl();
4163   }
4164 
4165   if (CheckRedeclarationModuleOwnership(New, Old))
4166     return;
4167 
4168   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4169 
4170   // FIXME: The test for external storage here seems wrong? We still
4171   // need to check for mismatches.
4172   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4173       // Don't complain about out-of-line definitions of static members.
4174       !(Old->getLexicalDeclContext()->isRecord() &&
4175         !New->getLexicalDeclContext()->isRecord())) {
4176     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4177     Diag(OldLocation, PrevDiag);
4178     return New->setInvalidDecl();
4179   }
4180 
4181   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4182     if (VarDecl *Def = Old->getDefinition()) {
4183       // C++1z [dcl.fcn.spec]p4:
4184       //   If the definition of a variable appears in a translation unit before
4185       //   its first declaration as inline, the program is ill-formed.
4186       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4187       Diag(Def->getLocation(), diag::note_previous_definition);
4188     }
4189   }
4190 
4191   // If this redeclaration makes the variable inline, we may need to add it to
4192   // UndefinedButUsed.
4193   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4194       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4195     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4196                                            SourceLocation()));
4197 
4198   if (New->getTLSKind() != Old->getTLSKind()) {
4199     if (!Old->getTLSKind()) {
4200       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4201       Diag(OldLocation, PrevDiag);
4202     } else if (!New->getTLSKind()) {
4203       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4204       Diag(OldLocation, PrevDiag);
4205     } else {
4206       // Do not allow redeclaration to change the variable between requiring
4207       // static and dynamic initialization.
4208       // FIXME: GCC allows this, but uses the TLS keyword on the first
4209       // declaration to determine the kind. Do we need to be compatible here?
4210       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4211         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4212       Diag(OldLocation, PrevDiag);
4213     }
4214   }
4215 
4216   // C++ doesn't have tentative definitions, so go right ahead and check here.
4217   if (getLangOpts().CPlusPlus &&
4218       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4219     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4220         Old->getCanonicalDecl()->isConstexpr()) {
4221       // This definition won't be a definition any more once it's been merged.
4222       Diag(New->getLocation(),
4223            diag::warn_deprecated_redundant_constexpr_static_def);
4224     } else if (VarDecl *Def = Old->getDefinition()) {
4225       if (checkVarDeclRedefinition(Def, New))
4226         return;
4227     }
4228   }
4229 
4230   if (haveIncompatibleLanguageLinkages(Old, New)) {
4231     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4232     Diag(OldLocation, PrevDiag);
4233     New->setInvalidDecl();
4234     return;
4235   }
4236 
4237   // Merge "used" flag.
4238   if (Old->getMostRecentDecl()->isUsed(false))
4239     New->setIsUsed();
4240 
4241   // Keep a chain of previous declarations.
4242   New->setPreviousDecl(Old);
4243   if (NewTemplate)
4244     NewTemplate->setPreviousDecl(OldTemplate);
4245   adjustDeclContextForDeclaratorDecl(New, Old);
4246 
4247   // Inherit access appropriately.
4248   New->setAccess(Old->getAccess());
4249   if (NewTemplate)
4250     NewTemplate->setAccess(New->getAccess());
4251 
4252   if (Old->isInline())
4253     New->setImplicitlyInline();
4254 }
4255 
notePreviousDefinition(const NamedDecl * Old,SourceLocation New)4256 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4257   SourceManager &SrcMgr = getSourceManager();
4258   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4259   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4260   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4261   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4262   auto &HSI = PP.getHeaderSearchInfo();
4263   StringRef HdrFilename =
4264       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4265 
4266   auto noteFromModuleOrInclude = [&](Module *Mod,
4267                                      SourceLocation IncLoc) -> bool {
4268     // Redefinition errors with modules are common with non modular mapped
4269     // headers, example: a non-modular header H in module A that also gets
4270     // included directly in a TU. Pointing twice to the same header/definition
4271     // is confusing, try to get better diagnostics when modules is on.
4272     if (IncLoc.isValid()) {
4273       if (Mod) {
4274         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4275             << HdrFilename.str() << Mod->getFullModuleName();
4276         if (!Mod->DefinitionLoc.isInvalid())
4277           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4278               << Mod->getFullModuleName();
4279       } else {
4280         Diag(IncLoc, diag::note_redefinition_include_same_file)
4281             << HdrFilename.str();
4282       }
4283       return true;
4284     }
4285 
4286     return false;
4287   };
4288 
4289   // Is it the same file and same offset? Provide more information on why
4290   // this leads to a redefinition error.
4291   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4292     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4293     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4294     bool EmittedDiag =
4295         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4296     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4297 
4298     // If the header has no guards, emit a note suggesting one.
4299     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4300       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4301 
4302     if (EmittedDiag)
4303       return;
4304   }
4305 
4306   // Redefinition coming from different files or couldn't do better above.
4307   if (Old->getLocation().isValid())
4308     Diag(Old->getLocation(), diag::note_previous_definition);
4309 }
4310 
4311 /// We've just determined that \p Old and \p New both appear to be definitions
4312 /// of the same variable. Either diagnose or fix the problem.
checkVarDeclRedefinition(VarDecl * Old,VarDecl * New)4313 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4314   if (!hasVisibleDefinition(Old) &&
4315       (New->getFormalLinkage() == InternalLinkage ||
4316        New->isInline() ||
4317        New->getDescribedVarTemplate() ||
4318        New->getNumTemplateParameterLists() ||
4319        New->getDeclContext()->isDependentContext())) {
4320     // The previous definition is hidden, and multiple definitions are
4321     // permitted (in separate TUs). Demote this to a declaration.
4322     New->demoteThisDefinitionToDeclaration();
4323 
4324     // Make the canonical definition visible.
4325     if (auto *OldTD = Old->getDescribedVarTemplate())
4326       makeMergedDefinitionVisible(OldTD);
4327     makeMergedDefinitionVisible(Old);
4328     return false;
4329   } else {
4330     Diag(New->getLocation(), diag::err_redefinition) << New;
4331     notePreviousDefinition(Old, New->getLocation());
4332     New->setInvalidDecl();
4333     return true;
4334   }
4335 }
4336 
4337 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4338 /// no declarator (e.g. "struct foo;") is parsed.
4339 Decl *
ParsedFreeStandingDeclSpec(Scope * S,AccessSpecifier AS,DeclSpec & DS,RecordDecl * & AnonRecord)4340 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4341                                  RecordDecl *&AnonRecord) {
4342   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4343                                     AnonRecord);
4344 }
4345 
4346 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4347 // disambiguate entities defined in different scopes.
4348 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4349 // compatibility.
4350 // We will pick our mangling number depending on which version of MSVC is being
4351 // targeted.
getMSManglingNumber(const LangOptions & LO,Scope * S)4352 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4353   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4354              ? S->getMSCurManglingNumber()
4355              : S->getMSLastManglingNumber();
4356 }
4357 
handleTagNumbering(const TagDecl * Tag,Scope * TagScope)4358 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4359   if (!Context.getLangOpts().CPlusPlus)
4360     return;
4361 
4362   if (isa<CXXRecordDecl>(Tag->getParent())) {
4363     // If this tag is the direct child of a class, number it if
4364     // it is anonymous.
4365     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4366       return;
4367     MangleNumberingContext &MCtx =
4368         Context.getManglingNumberContext(Tag->getParent());
4369     Context.setManglingNumber(
4370         Tag, MCtx.getManglingNumber(
4371                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4372     return;
4373   }
4374 
4375   // If this tag isn't a direct child of a class, number it if it is local.
4376   MangleNumberingContext *MCtx;
4377   Decl *ManglingContextDecl;
4378   std::tie(MCtx, ManglingContextDecl) =
4379       getCurrentMangleNumberContext(Tag->getDeclContext());
4380   if (MCtx) {
4381     Context.setManglingNumber(
4382         Tag, MCtx->getManglingNumber(
4383                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4384   }
4385 }
4386 
4387 namespace {
4388 struct NonCLikeKind {
4389   enum {
4390     None,
4391     BaseClass,
4392     DefaultMemberInit,
4393     Lambda,
4394     Friend,
4395     OtherMember,
4396     Invalid,
4397   } Kind = None;
4398   SourceRange Range;
4399 
operator bool__anon87d11b5b0811::NonCLikeKind4400   explicit operator bool() { return Kind != None; }
4401 };
4402 }
4403 
4404 /// Determine whether a class is C-like, according to the rules of C++
4405 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
getNonCLikeKindForAnonymousStruct(const CXXRecordDecl * RD)4406 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4407   if (RD->isInvalidDecl())
4408     return {NonCLikeKind::Invalid, {}};
4409 
4410   // C++ [dcl.typedef]p9: [P1766R1]
4411   //   An unnamed class with a typedef name for linkage purposes shall not
4412   //
4413   //    -- have any base classes
4414   if (RD->getNumBases())
4415     return {NonCLikeKind::BaseClass,
4416             SourceRange(RD->bases_begin()->getBeginLoc(),
4417                         RD->bases_end()[-1].getEndLoc())};
4418   bool Invalid = false;
4419   for (Decl *D : RD->decls()) {
4420     // Don't complain about things we already diagnosed.
4421     if (D->isInvalidDecl()) {
4422       Invalid = true;
4423       continue;
4424     }
4425 
4426     //  -- have any [...] default member initializers
4427     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4428       if (FD->hasInClassInitializer()) {
4429         auto *Init = FD->getInClassInitializer();
4430         return {NonCLikeKind::DefaultMemberInit,
4431                 Init ? Init->getSourceRange() : D->getSourceRange()};
4432       }
4433       continue;
4434     }
4435 
4436     // FIXME: We don't allow friend declarations. This violates the wording of
4437     // P1766, but not the intent.
4438     if (isa<FriendDecl>(D))
4439       return {NonCLikeKind::Friend, D->getSourceRange()};
4440 
4441     //  -- declare any members other than non-static data members, member
4442     //     enumerations, or member classes,
4443     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4444         isa<EnumDecl>(D))
4445       continue;
4446     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4447     if (!MemberRD) {
4448       if (D->isImplicit())
4449         continue;
4450       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4451     }
4452 
4453     //  -- contain a lambda-expression,
4454     if (MemberRD->isLambda())
4455       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4456 
4457     //  and all member classes shall also satisfy these requirements
4458     //  (recursively).
4459     if (MemberRD->isThisDeclarationADefinition()) {
4460       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4461         return Kind;
4462     }
4463   }
4464 
4465   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4466 }
4467 
setTagNameForLinkagePurposes(TagDecl * TagFromDeclSpec,TypedefNameDecl * NewTD)4468 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4469                                         TypedefNameDecl *NewTD) {
4470   if (TagFromDeclSpec->isInvalidDecl())
4471     return;
4472 
4473   // Do nothing if the tag already has a name for linkage purposes.
4474   if (TagFromDeclSpec->hasNameForLinkage())
4475     return;
4476 
4477   // A well-formed anonymous tag must always be a TUK_Definition.
4478   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4479 
4480   // The type must match the tag exactly;  no qualifiers allowed.
4481   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4482                            Context.getTagDeclType(TagFromDeclSpec))) {
4483     if (getLangOpts().CPlusPlus)
4484       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4485     return;
4486   }
4487 
4488   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4489   //   An unnamed class with a typedef name for linkage purposes shall [be
4490   //   C-like].
4491   //
4492   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4493   // shouldn't happen, but there are constructs that the language rule doesn't
4494   // disallow for which we can't reasonably avoid computing linkage early.
4495   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4496   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4497                              : NonCLikeKind();
4498   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4499   if (NonCLike || ChangesLinkage) {
4500     if (NonCLike.Kind == NonCLikeKind::Invalid)
4501       return;
4502 
4503     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4504     if (ChangesLinkage) {
4505       // If the linkage changes, we can't accept this as an extension.
4506       if (NonCLike.Kind == NonCLikeKind::None)
4507         DiagID = diag::err_typedef_changes_linkage;
4508       else
4509         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4510     }
4511 
4512     SourceLocation FixitLoc =
4513         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4514     llvm::SmallString<40> TextToInsert;
4515     TextToInsert += ' ';
4516     TextToInsert += NewTD->getIdentifier()->getName();
4517 
4518     Diag(FixitLoc, DiagID)
4519       << isa<TypeAliasDecl>(NewTD)
4520       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4521     if (NonCLike.Kind != NonCLikeKind::None) {
4522       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4523         << NonCLike.Kind - 1 << NonCLike.Range;
4524     }
4525     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4526       << NewTD << isa<TypeAliasDecl>(NewTD);
4527 
4528     if (ChangesLinkage)
4529       return;
4530   }
4531 
4532   // Otherwise, set this as the anon-decl typedef for the tag.
4533   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4534 }
4535 
GetDiagnosticTypeSpecifierID(DeclSpec::TST T)4536 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4537   switch (T) {
4538   case DeclSpec::TST_class:
4539     return 0;
4540   case DeclSpec::TST_struct:
4541     return 1;
4542   case DeclSpec::TST_interface:
4543     return 2;
4544   case DeclSpec::TST_union:
4545     return 3;
4546   case DeclSpec::TST_enum:
4547     return 4;
4548   default:
4549     llvm_unreachable("unexpected type specifier");
4550   }
4551 }
4552 
4553 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4554 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4555 /// parameters to cope with template friend declarations.
4556 Decl *
ParsedFreeStandingDeclSpec(Scope * S,AccessSpecifier AS,DeclSpec & DS,MultiTemplateParamsArg TemplateParams,bool IsExplicitInstantiation,RecordDecl * & AnonRecord)4557 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4558                                  MultiTemplateParamsArg TemplateParams,
4559                                  bool IsExplicitInstantiation,
4560                                  RecordDecl *&AnonRecord) {
4561   Decl *TagD = nullptr;
4562   TagDecl *Tag = nullptr;
4563   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4564       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4565       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4566       DS.getTypeSpecType() == DeclSpec::TST_union ||
4567       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4568     TagD = DS.getRepAsDecl();
4569 
4570     if (!TagD) // We probably had an error
4571       return nullptr;
4572 
4573     // Note that the above type specs guarantee that the
4574     // type rep is a Decl, whereas in many of the others
4575     // it's a Type.
4576     if (isa<TagDecl>(TagD))
4577       Tag = cast<TagDecl>(TagD);
4578     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4579       Tag = CTD->getTemplatedDecl();
4580   }
4581 
4582   if (Tag) {
4583     handleTagNumbering(Tag, S);
4584     Tag->setFreeStanding();
4585     if (Tag->isInvalidDecl())
4586       return Tag;
4587   }
4588 
4589   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4590     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4591     // or incomplete types shall not be restrict-qualified."
4592     if (TypeQuals & DeclSpec::TQ_restrict)
4593       Diag(DS.getRestrictSpecLoc(),
4594            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4595            << DS.getSourceRange();
4596   }
4597 
4598   if (DS.isInlineSpecified())
4599     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4600         << getLangOpts().CPlusPlus17;
4601 
4602   if (DS.hasConstexprSpecifier()) {
4603     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4604     // and definitions of functions and variables.
4605     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4606     // the declaration of a function or function template
4607     if (Tag)
4608       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4609           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4610           << DS.getConstexprSpecifier();
4611     else
4612       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4613           << DS.getConstexprSpecifier();
4614     // Don't emit warnings after this error.
4615     return TagD;
4616   }
4617 
4618   DiagnoseFunctionSpecifiers(DS);
4619 
4620   if (DS.isFriendSpecified()) {
4621     // If we're dealing with a decl but not a TagDecl, assume that
4622     // whatever routines created it handled the friendship aspect.
4623     if (TagD && !Tag)
4624       return nullptr;
4625     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4626   }
4627 
4628   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4629   bool IsExplicitSpecialization =
4630     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4631   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4632       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4633       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4634     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4635     // nested-name-specifier unless it is an explicit instantiation
4636     // or an explicit specialization.
4637     //
4638     // FIXME: We allow class template partial specializations here too, per the
4639     // obvious intent of DR1819.
4640     //
4641     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4642     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4643         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4644     return nullptr;
4645   }
4646 
4647   // Track whether this decl-specifier declares anything.
4648   bool DeclaresAnything = true;
4649 
4650   // Handle anonymous struct definitions.
4651   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4652     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4653         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4654       if (getLangOpts().CPlusPlus ||
4655           Record->getDeclContext()->isRecord()) {
4656         // If CurContext is a DeclContext that can contain statements,
4657         // RecursiveASTVisitor won't visit the decls that
4658         // BuildAnonymousStructOrUnion() will put into CurContext.
4659         // Also store them here so that they can be part of the
4660         // DeclStmt that gets created in this case.
4661         // FIXME: Also return the IndirectFieldDecls created by
4662         // BuildAnonymousStructOr union, for the same reason?
4663         if (CurContext->isFunctionOrMethod())
4664           AnonRecord = Record;
4665         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4666                                            Context.getPrintingPolicy());
4667       }
4668 
4669       DeclaresAnything = false;
4670     }
4671   }
4672 
4673   // C11 6.7.2.1p2:
4674   //   A struct-declaration that does not declare an anonymous structure or
4675   //   anonymous union shall contain a struct-declarator-list.
4676   //
4677   // This rule also existed in C89 and C99; the grammar for struct-declaration
4678   // did not permit a struct-declaration without a struct-declarator-list.
4679   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4680       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4681     // Check for Microsoft C extension: anonymous struct/union member.
4682     // Handle 2 kinds of anonymous struct/union:
4683     //   struct STRUCT;
4684     //   union UNION;
4685     // and
4686     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4687     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4688     if ((Tag && Tag->getDeclName()) ||
4689         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4690       RecordDecl *Record = nullptr;
4691       if (Tag)
4692         Record = dyn_cast<RecordDecl>(Tag);
4693       else if (const RecordType *RT =
4694                    DS.getRepAsType().get()->getAsStructureType())
4695         Record = RT->getDecl();
4696       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4697         Record = UT->getDecl();
4698 
4699       if (Record && getLangOpts().MicrosoftExt) {
4700         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4701             << Record->isUnion() << DS.getSourceRange();
4702         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4703       }
4704 
4705       DeclaresAnything = false;
4706     }
4707   }
4708 
4709   // Skip all the checks below if we have a type error.
4710   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4711       (TagD && TagD->isInvalidDecl()))
4712     return TagD;
4713 
4714   if (getLangOpts().CPlusPlus &&
4715       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4716     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4717       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4718           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4719         DeclaresAnything = false;
4720 
4721   if (!DS.isMissingDeclaratorOk()) {
4722     // Customize diagnostic for a typedef missing a name.
4723     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4724       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4725           << DS.getSourceRange();
4726     else
4727       DeclaresAnything = false;
4728   }
4729 
4730   if (DS.isModulePrivateSpecified() &&
4731       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4732     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4733       << Tag->getTagKind()
4734       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4735 
4736   ActOnDocumentableDecl(TagD);
4737 
4738   // C 6.7/2:
4739   //   A declaration [...] shall declare at least a declarator [...], a tag,
4740   //   or the members of an enumeration.
4741   // C++ [dcl.dcl]p3:
4742   //   [If there are no declarators], and except for the declaration of an
4743   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4744   //   names into the program, or shall redeclare a name introduced by a
4745   //   previous declaration.
4746   if (!DeclaresAnything) {
4747     // In C, we allow this as a (popular) extension / bug. Don't bother
4748     // producing further diagnostics for redundant qualifiers after this.
4749     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4750     return TagD;
4751   }
4752 
4753   // C++ [dcl.stc]p1:
4754   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4755   //   init-declarator-list of the declaration shall not be empty.
4756   // C++ [dcl.fct.spec]p1:
4757   //   If a cv-qualifier appears in a decl-specifier-seq, the
4758   //   init-declarator-list of the declaration shall not be empty.
4759   //
4760   // Spurious qualifiers here appear to be valid in C.
4761   unsigned DiagID = diag::warn_standalone_specifier;
4762   if (getLangOpts().CPlusPlus)
4763     DiagID = diag::ext_standalone_specifier;
4764 
4765   // Note that a linkage-specification sets a storage class, but
4766   // 'extern "C" struct foo;' is actually valid and not theoretically
4767   // useless.
4768   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4769     if (SCS == DeclSpec::SCS_mutable)
4770       // Since mutable is not a viable storage class specifier in C, there is
4771       // no reason to treat it as an extension. Instead, diagnose as an error.
4772       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4773     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4774       Diag(DS.getStorageClassSpecLoc(), DiagID)
4775         << DeclSpec::getSpecifierName(SCS);
4776   }
4777 
4778   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4779     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4780       << DeclSpec::getSpecifierName(TSCS);
4781   if (DS.getTypeQualifiers()) {
4782     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4783       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4784     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4785       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4786     // Restrict is covered above.
4787     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4788       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4789     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4790       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4791   }
4792 
4793   // Warn about ignored type attributes, for example:
4794   // __attribute__((aligned)) struct A;
4795   // Attributes should be placed after tag to apply to type declaration.
4796   if (!DS.getAttributes().empty()) {
4797     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4798     if (TypeSpecType == DeclSpec::TST_class ||
4799         TypeSpecType == DeclSpec::TST_struct ||
4800         TypeSpecType == DeclSpec::TST_interface ||
4801         TypeSpecType == DeclSpec::TST_union ||
4802         TypeSpecType == DeclSpec::TST_enum) {
4803       for (const ParsedAttr &AL : DS.getAttributes())
4804         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4805             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4806     }
4807   }
4808 
4809   return TagD;
4810 }
4811 
4812 /// We are trying to inject an anonymous member into the given scope;
4813 /// check if there's an existing declaration that can't be overloaded.
4814 ///
4815 /// \return true if this is a forbidden redeclaration
CheckAnonMemberRedeclaration(Sema & SemaRef,Scope * S,DeclContext * Owner,DeclarationName Name,SourceLocation NameLoc,bool IsUnion)4816 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4817                                          Scope *S,
4818                                          DeclContext *Owner,
4819                                          DeclarationName Name,
4820                                          SourceLocation NameLoc,
4821                                          bool IsUnion) {
4822   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4823                  Sema::ForVisibleRedeclaration);
4824   if (!SemaRef.LookupName(R, S)) return false;
4825 
4826   // Pick a representative declaration.
4827   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4828   assert(PrevDecl && "Expected a non-null Decl");
4829 
4830   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4831     return false;
4832 
4833   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4834     << IsUnion << Name;
4835   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4836 
4837   return true;
4838 }
4839 
4840 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4841 /// anonymous struct or union AnonRecord into the owning context Owner
4842 /// and scope S. This routine will be invoked just after we realize
4843 /// that an unnamed union or struct is actually an anonymous union or
4844 /// struct, e.g.,
4845 ///
4846 /// @code
4847 /// union {
4848 ///   int i;
4849 ///   float f;
4850 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4851 ///    // f into the surrounding scope.x
4852 /// @endcode
4853 ///
4854 /// This routine is recursive, injecting the names of nested anonymous
4855 /// structs/unions into the owning context and scope as well.
4856 static bool
InjectAnonymousStructOrUnionMembers(Sema & SemaRef,Scope * S,DeclContext * Owner,RecordDecl * AnonRecord,AccessSpecifier AS,SmallVectorImpl<NamedDecl * > & Chaining)4857 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4858                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4859                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4860   bool Invalid = false;
4861 
4862   // Look every FieldDecl and IndirectFieldDecl with a name.
4863   for (auto *D : AnonRecord->decls()) {
4864     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4865         cast<NamedDecl>(D)->getDeclName()) {
4866       ValueDecl *VD = cast<ValueDecl>(D);
4867       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4868                                        VD->getLocation(),
4869                                        AnonRecord->isUnion())) {
4870         // C++ [class.union]p2:
4871         //   The names of the members of an anonymous union shall be
4872         //   distinct from the names of any other entity in the
4873         //   scope in which the anonymous union is declared.
4874         Invalid = true;
4875       } else {
4876         // C++ [class.union]p2:
4877         //   For the purpose of name lookup, after the anonymous union
4878         //   definition, the members of the anonymous union are
4879         //   considered to have been defined in the scope in which the
4880         //   anonymous union is declared.
4881         unsigned OldChainingSize = Chaining.size();
4882         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4883           Chaining.append(IF->chain_begin(), IF->chain_end());
4884         else
4885           Chaining.push_back(VD);
4886 
4887         assert(Chaining.size() >= 2);
4888         NamedDecl **NamedChain =
4889           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4890         for (unsigned i = 0; i < Chaining.size(); i++)
4891           NamedChain[i] = Chaining[i];
4892 
4893         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4894             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4895             VD->getType(), {NamedChain, Chaining.size()});
4896 
4897         for (const auto *Attr : VD->attrs())
4898           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4899 
4900         IndirectField->setAccess(AS);
4901         IndirectField->setImplicit();
4902         SemaRef.PushOnScopeChains(IndirectField, S);
4903 
4904         // That includes picking up the appropriate access specifier.
4905         if (AS != AS_none) IndirectField->setAccess(AS);
4906 
4907         Chaining.resize(OldChainingSize);
4908       }
4909     }
4910   }
4911 
4912   return Invalid;
4913 }
4914 
4915 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4916 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4917 /// illegal input values are mapped to SC_None.
4918 static StorageClass
StorageClassSpecToVarDeclStorageClass(const DeclSpec & DS)4919 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4920   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4921   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4922          "Parser allowed 'typedef' as storage class VarDecl.");
4923   switch (StorageClassSpec) {
4924   case DeclSpec::SCS_unspecified:    return SC_None;
4925   case DeclSpec::SCS_extern:
4926     if (DS.isExternInLinkageSpec())
4927       return SC_None;
4928     return SC_Extern;
4929   case DeclSpec::SCS_static:         return SC_Static;
4930   case DeclSpec::SCS_auto:           return SC_Auto;
4931   case DeclSpec::SCS_register:       return SC_Register;
4932   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4933     // Illegal SCSs map to None: error reporting is up to the caller.
4934   case DeclSpec::SCS_mutable:        // Fall through.
4935   case DeclSpec::SCS_typedef:        return SC_None;
4936   }
4937   llvm_unreachable("unknown storage class specifier");
4938 }
4939 
findDefaultInitializer(const CXXRecordDecl * Record)4940 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4941   assert(Record->hasInClassInitializer());
4942 
4943   for (const auto *I : Record->decls()) {
4944     const auto *FD = dyn_cast<FieldDecl>(I);
4945     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4946       FD = IFD->getAnonField();
4947     if (FD && FD->hasInClassInitializer())
4948       return FD->getLocation();
4949   }
4950 
4951   llvm_unreachable("couldn't find in-class initializer");
4952 }
4953 
checkDuplicateDefaultInit(Sema & S,CXXRecordDecl * Parent,SourceLocation DefaultInitLoc)4954 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4955                                       SourceLocation DefaultInitLoc) {
4956   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4957     return;
4958 
4959   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4960   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4961 }
4962 
checkDuplicateDefaultInit(Sema & S,CXXRecordDecl * Parent,CXXRecordDecl * AnonUnion)4963 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4964                                       CXXRecordDecl *AnonUnion) {
4965   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4966     return;
4967 
4968   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4969 }
4970 
4971 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4972 /// anonymous structure or union. Anonymous unions are a C++ feature
4973 /// (C++ [class.union]) and a C11 feature; anonymous structures
4974 /// are a C11 feature and GNU C++ extension.
BuildAnonymousStructOrUnion(Scope * S,DeclSpec & DS,AccessSpecifier AS,RecordDecl * Record,const PrintingPolicy & Policy)4975 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4976                                         AccessSpecifier AS,
4977                                         RecordDecl *Record,
4978                                         const PrintingPolicy &Policy) {
4979   DeclContext *Owner = Record->getDeclContext();
4980 
4981   // Diagnose whether this anonymous struct/union is an extension.
4982   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4983     Diag(Record->getLocation(), diag::ext_anonymous_union);
4984   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4985     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4986   else if (!Record->isUnion() && !getLangOpts().C11)
4987     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4988 
4989   // C and C++ require different kinds of checks for anonymous
4990   // structs/unions.
4991   bool Invalid = false;
4992   if (getLangOpts().CPlusPlus) {
4993     const char *PrevSpec = nullptr;
4994     if (Record->isUnion()) {
4995       // C++ [class.union]p6:
4996       // C++17 [class.union.anon]p2:
4997       //   Anonymous unions declared in a named namespace or in the
4998       //   global namespace shall be declared static.
4999       unsigned DiagID;
5000       DeclContext *OwnerScope = Owner->getRedeclContext();
5001       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5002           (OwnerScope->isTranslationUnit() ||
5003            (OwnerScope->isNamespace() &&
5004             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5005         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5006           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5007 
5008         // Recover by adding 'static'.
5009         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5010                                PrevSpec, DiagID, Policy);
5011       }
5012       // C++ [class.union]p6:
5013       //   A storage class is not allowed in a declaration of an
5014       //   anonymous union in a class scope.
5015       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5016                isa<RecordDecl>(Owner)) {
5017         Diag(DS.getStorageClassSpecLoc(),
5018              diag::err_anonymous_union_with_storage_spec)
5019           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5020 
5021         // Recover by removing the storage specifier.
5022         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5023                                SourceLocation(),
5024                                PrevSpec, DiagID, Context.getPrintingPolicy());
5025       }
5026     }
5027 
5028     // Ignore const/volatile/restrict qualifiers.
5029     if (DS.getTypeQualifiers()) {
5030       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5031         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5032           << Record->isUnion() << "const"
5033           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5034       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5035         Diag(DS.getVolatileSpecLoc(),
5036              diag::ext_anonymous_struct_union_qualified)
5037           << Record->isUnion() << "volatile"
5038           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5039       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5040         Diag(DS.getRestrictSpecLoc(),
5041              diag::ext_anonymous_struct_union_qualified)
5042           << Record->isUnion() << "restrict"
5043           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5044       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5045         Diag(DS.getAtomicSpecLoc(),
5046              diag::ext_anonymous_struct_union_qualified)
5047           << Record->isUnion() << "_Atomic"
5048           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5049       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5050         Diag(DS.getUnalignedSpecLoc(),
5051              diag::ext_anonymous_struct_union_qualified)
5052           << Record->isUnion() << "__unaligned"
5053           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5054 
5055       DS.ClearTypeQualifiers();
5056     }
5057 
5058     // C++ [class.union]p2:
5059     //   The member-specification of an anonymous union shall only
5060     //   define non-static data members. [Note: nested types and
5061     //   functions cannot be declared within an anonymous union. ]
5062     for (auto *Mem : Record->decls()) {
5063       // Ignore invalid declarations; we already diagnosed them.
5064       if (Mem->isInvalidDecl())
5065         continue;
5066 
5067       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5068         // C++ [class.union]p3:
5069         //   An anonymous union shall not have private or protected
5070         //   members (clause 11).
5071         assert(FD->getAccess() != AS_none);
5072         if (FD->getAccess() != AS_public) {
5073           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5074             << Record->isUnion() << (FD->getAccess() == AS_protected);
5075           Invalid = true;
5076         }
5077 
5078         // C++ [class.union]p1
5079         //   An object of a class with a non-trivial constructor, a non-trivial
5080         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5081         //   assignment operator cannot be a member of a union, nor can an
5082         //   array of such objects.
5083         if (CheckNontrivialField(FD))
5084           Invalid = true;
5085       } else if (Mem->isImplicit()) {
5086         // Any implicit members are fine.
5087       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5088         // This is a type that showed up in an
5089         // elaborated-type-specifier inside the anonymous struct or
5090         // union, but which actually declares a type outside of the
5091         // anonymous struct or union. It's okay.
5092       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5093         if (!MemRecord->isAnonymousStructOrUnion() &&
5094             MemRecord->getDeclName()) {
5095           // Visual C++ allows type definition in anonymous struct or union.
5096           if (getLangOpts().MicrosoftExt)
5097             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5098               << Record->isUnion();
5099           else {
5100             // This is a nested type declaration.
5101             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5102               << Record->isUnion();
5103             Invalid = true;
5104           }
5105         } else {
5106           // This is an anonymous type definition within another anonymous type.
5107           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5108           // not part of standard C++.
5109           Diag(MemRecord->getLocation(),
5110                diag::ext_anonymous_record_with_anonymous_type)
5111             << Record->isUnion();
5112         }
5113       } else if (isa<AccessSpecDecl>(Mem)) {
5114         // Any access specifier is fine.
5115       } else if (isa<StaticAssertDecl>(Mem)) {
5116         // In C++1z, static_assert declarations are also fine.
5117       } else {
5118         // We have something that isn't a non-static data
5119         // member. Complain about it.
5120         unsigned DK = diag::err_anonymous_record_bad_member;
5121         if (isa<TypeDecl>(Mem))
5122           DK = diag::err_anonymous_record_with_type;
5123         else if (isa<FunctionDecl>(Mem))
5124           DK = diag::err_anonymous_record_with_function;
5125         else if (isa<VarDecl>(Mem))
5126           DK = diag::err_anonymous_record_with_static;
5127 
5128         // Visual C++ allows type definition in anonymous struct or union.
5129         if (getLangOpts().MicrosoftExt &&
5130             DK == diag::err_anonymous_record_with_type)
5131           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5132             << Record->isUnion();
5133         else {
5134           Diag(Mem->getLocation(), DK) << Record->isUnion();
5135           Invalid = true;
5136         }
5137       }
5138     }
5139 
5140     // C++11 [class.union]p8 (DR1460):
5141     //   At most one variant member of a union may have a
5142     //   brace-or-equal-initializer.
5143     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5144         Owner->isRecord())
5145       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5146                                 cast<CXXRecordDecl>(Record));
5147   }
5148 
5149   if (!Record->isUnion() && !Owner->isRecord()) {
5150     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5151       << getLangOpts().CPlusPlus;
5152     Invalid = true;
5153   }
5154 
5155   // C++ [dcl.dcl]p3:
5156   //   [If there are no declarators], and except for the declaration of an
5157   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5158   //   names into the program
5159   // C++ [class.mem]p2:
5160   //   each such member-declaration shall either declare at least one member
5161   //   name of the class or declare at least one unnamed bit-field
5162   //
5163   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5164   if (getLangOpts().CPlusPlus && Record->field_empty())
5165     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5166 
5167   // Mock up a declarator.
5168   Declarator Dc(DS, DeclaratorContext::MemberContext);
5169   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5170   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5171 
5172   // Create a declaration for this anonymous struct/union.
5173   NamedDecl *Anon = nullptr;
5174   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5175     Anon = FieldDecl::Create(
5176         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5177         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5178         /*BitWidth=*/nullptr, /*Mutable=*/false,
5179         /*InitStyle=*/ICIS_NoInit);
5180     Anon->setAccess(AS);
5181     ProcessDeclAttributes(S, Anon, Dc);
5182 
5183     if (getLangOpts().CPlusPlus)
5184       FieldCollector->Add(cast<FieldDecl>(Anon));
5185   } else {
5186     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5187     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5188     if (SCSpec == DeclSpec::SCS_mutable) {
5189       // mutable can only appear on non-static class members, so it's always
5190       // an error here
5191       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5192       Invalid = true;
5193       SC = SC_None;
5194     }
5195 
5196     assert(DS.getAttributes().empty() && "No attribute expected");
5197     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5198                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5199                            Context.getTypeDeclType(Record), TInfo, SC);
5200 
5201     // Default-initialize the implicit variable. This initialization will be
5202     // trivial in almost all cases, except if a union member has an in-class
5203     // initializer:
5204     //   union { int n = 0; };
5205     ActOnUninitializedDecl(Anon);
5206   }
5207   Anon->setImplicit();
5208 
5209   // Mark this as an anonymous struct/union type.
5210   Record->setAnonymousStructOrUnion(true);
5211 
5212   // Add the anonymous struct/union object to the current
5213   // context. We'll be referencing this object when we refer to one of
5214   // its members.
5215   Owner->addDecl(Anon);
5216 
5217   // Inject the members of the anonymous struct/union into the owning
5218   // context and into the identifier resolver chain for name lookup
5219   // purposes.
5220   SmallVector<NamedDecl*, 2> Chain;
5221   Chain.push_back(Anon);
5222 
5223   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5224     Invalid = true;
5225 
5226   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5227     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5228       MangleNumberingContext *MCtx;
5229       Decl *ManglingContextDecl;
5230       std::tie(MCtx, ManglingContextDecl) =
5231           getCurrentMangleNumberContext(NewVD->getDeclContext());
5232       if (MCtx) {
5233         Context.setManglingNumber(
5234             NewVD, MCtx->getManglingNumber(
5235                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5236         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5237       }
5238     }
5239   }
5240 
5241   if (Invalid)
5242     Anon->setInvalidDecl();
5243 
5244   return Anon;
5245 }
5246 
5247 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5248 /// Microsoft C anonymous structure.
5249 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5250 /// Example:
5251 ///
5252 /// struct A { int a; };
5253 /// struct B { struct A; int b; };
5254 ///
5255 /// void foo() {
5256 ///   B var;
5257 ///   var.a = 3;
5258 /// }
5259 ///
BuildMicrosoftCAnonymousStruct(Scope * S,DeclSpec & DS,RecordDecl * Record)5260 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5261                                            RecordDecl *Record) {
5262   assert(Record && "expected a record!");
5263 
5264   // Mock up a declarator.
5265   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5266   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5267   assert(TInfo && "couldn't build declarator info for anonymous struct");
5268 
5269   auto *ParentDecl = cast<RecordDecl>(CurContext);
5270   QualType RecTy = Context.getTypeDeclType(Record);
5271 
5272   // Create a declaration for this anonymous struct.
5273   NamedDecl *Anon =
5274       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5275                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5276                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5277                         /*InitStyle=*/ICIS_NoInit);
5278   Anon->setImplicit();
5279 
5280   // Add the anonymous struct object to the current context.
5281   CurContext->addDecl(Anon);
5282 
5283   // Inject the members of the anonymous struct into the current
5284   // context and into the identifier resolver chain for name lookup
5285   // purposes.
5286   SmallVector<NamedDecl*, 2> Chain;
5287   Chain.push_back(Anon);
5288 
5289   RecordDecl *RecordDef = Record->getDefinition();
5290   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5291                                diag::err_field_incomplete_or_sizeless) ||
5292       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5293                                           AS_none, Chain)) {
5294     Anon->setInvalidDecl();
5295     ParentDecl->setInvalidDecl();
5296   }
5297 
5298   return Anon;
5299 }
5300 
5301 /// GetNameForDeclarator - Determine the full declaration name for the
5302 /// given Declarator.
GetNameForDeclarator(Declarator & D)5303 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5304   return GetNameFromUnqualifiedId(D.getName());
5305 }
5306 
5307 /// Retrieves the declaration name from a parsed unqualified-id.
5308 DeclarationNameInfo
GetNameFromUnqualifiedId(const UnqualifiedId & Name)5309 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5310   DeclarationNameInfo NameInfo;
5311   NameInfo.setLoc(Name.StartLocation);
5312 
5313   switch (Name.getKind()) {
5314 
5315   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5316   case UnqualifiedIdKind::IK_Identifier:
5317     NameInfo.setName(Name.Identifier);
5318     return NameInfo;
5319 
5320   case UnqualifiedIdKind::IK_DeductionGuideName: {
5321     // C++ [temp.deduct.guide]p3:
5322     //   The simple-template-id shall name a class template specialization.
5323     //   The template-name shall be the same identifier as the template-name
5324     //   of the simple-template-id.
5325     // These together intend to imply that the template-name shall name a
5326     // class template.
5327     // FIXME: template<typename T> struct X {};
5328     //        template<typename T> using Y = X<T>;
5329     //        Y(int) -> Y<int>;
5330     //   satisfies these rules but does not name a class template.
5331     TemplateName TN = Name.TemplateName.get().get();
5332     auto *Template = TN.getAsTemplateDecl();
5333     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5334       Diag(Name.StartLocation,
5335            diag::err_deduction_guide_name_not_class_template)
5336         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5337       if (Template)
5338         Diag(Template->getLocation(), diag::note_template_decl_here);
5339       return DeclarationNameInfo();
5340     }
5341 
5342     NameInfo.setName(
5343         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5344     return NameInfo;
5345   }
5346 
5347   case UnqualifiedIdKind::IK_OperatorFunctionId:
5348     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5349                                            Name.OperatorFunctionId.Operator));
5350     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5351       = Name.OperatorFunctionId.SymbolLocations[0];
5352     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5353       = Name.EndLocation.getRawEncoding();
5354     return NameInfo;
5355 
5356   case UnqualifiedIdKind::IK_LiteralOperatorId:
5357     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5358                                                            Name.Identifier));
5359     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5360     return NameInfo;
5361 
5362   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5363     TypeSourceInfo *TInfo;
5364     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5365     if (Ty.isNull())
5366       return DeclarationNameInfo();
5367     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5368                                                Context.getCanonicalType(Ty)));
5369     NameInfo.setNamedTypeInfo(TInfo);
5370     return NameInfo;
5371   }
5372 
5373   case UnqualifiedIdKind::IK_ConstructorName: {
5374     TypeSourceInfo *TInfo;
5375     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5376     if (Ty.isNull())
5377       return DeclarationNameInfo();
5378     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5379                                               Context.getCanonicalType(Ty)));
5380     NameInfo.setNamedTypeInfo(TInfo);
5381     return NameInfo;
5382   }
5383 
5384   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5385     // In well-formed code, we can only have a constructor
5386     // template-id that refers to the current context, so go there
5387     // to find the actual type being constructed.
5388     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5389     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5390       return DeclarationNameInfo();
5391 
5392     // Determine the type of the class being constructed.
5393     QualType CurClassType = Context.getTypeDeclType(CurClass);
5394 
5395     // FIXME: Check two things: that the template-id names the same type as
5396     // CurClassType, and that the template-id does not occur when the name
5397     // was qualified.
5398 
5399     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5400                                     Context.getCanonicalType(CurClassType)));
5401     // FIXME: should we retrieve TypeSourceInfo?
5402     NameInfo.setNamedTypeInfo(nullptr);
5403     return NameInfo;
5404   }
5405 
5406   case UnqualifiedIdKind::IK_DestructorName: {
5407     TypeSourceInfo *TInfo;
5408     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5409     if (Ty.isNull())
5410       return DeclarationNameInfo();
5411     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5412                                               Context.getCanonicalType(Ty)));
5413     NameInfo.setNamedTypeInfo(TInfo);
5414     return NameInfo;
5415   }
5416 
5417   case UnqualifiedIdKind::IK_TemplateId: {
5418     TemplateName TName = Name.TemplateId->Template.get();
5419     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5420     return Context.getNameForTemplate(TName, TNameLoc);
5421   }
5422 
5423   } // switch (Name.getKind())
5424 
5425   llvm_unreachable("Unknown name kind");
5426 }
5427 
getCoreType(QualType Ty)5428 static QualType getCoreType(QualType Ty) {
5429   do {
5430     if (Ty->isPointerType() || Ty->isReferenceType())
5431       Ty = Ty->getPointeeType();
5432     else if (Ty->isArrayType())
5433       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5434     else
5435       return Ty.withoutLocalFastQualifiers();
5436   } while (true);
5437 }
5438 
5439 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5440 /// and Definition have "nearly" matching parameters. This heuristic is
5441 /// used to improve diagnostics in the case where an out-of-line function
5442 /// definition doesn't match any declaration within the class or namespace.
5443 /// Also sets Params to the list of indices to the parameters that differ
5444 /// between the declaration and the definition. If hasSimilarParameters
5445 /// returns true and Params is empty, then all of the parameters match.
hasSimilarParameters(ASTContext & Context,FunctionDecl * Declaration,FunctionDecl * Definition,SmallVectorImpl<unsigned> & Params)5446 static bool hasSimilarParameters(ASTContext &Context,
5447                                      FunctionDecl *Declaration,
5448                                      FunctionDecl *Definition,
5449                                      SmallVectorImpl<unsigned> &Params) {
5450   Params.clear();
5451   if (Declaration->param_size() != Definition->param_size())
5452     return false;
5453   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5454     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5455     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5456 
5457     // The parameter types are identical
5458     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5459       continue;
5460 
5461     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5462     QualType DefParamBaseTy = getCoreType(DefParamTy);
5463     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5464     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5465 
5466     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5467         (DeclTyName && DeclTyName == DefTyName))
5468       Params.push_back(Idx);
5469     else  // The two parameters aren't even close
5470       return false;
5471   }
5472 
5473   return true;
5474 }
5475 
5476 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5477 /// declarator needs to be rebuilt in the current instantiation.
5478 /// Any bits of declarator which appear before the name are valid for
5479 /// consideration here.  That's specifically the type in the decl spec
5480 /// and the base type in any member-pointer chunks.
RebuildDeclaratorInCurrentInstantiation(Sema & S,Declarator & D,DeclarationName Name)5481 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5482                                                     DeclarationName Name) {
5483   // The types we specifically need to rebuild are:
5484   //   - typenames, typeofs, and decltypes
5485   //   - types which will become injected class names
5486   // Of course, we also need to rebuild any type referencing such a
5487   // type.  It's safest to just say "dependent", but we call out a
5488   // few cases here.
5489 
5490   DeclSpec &DS = D.getMutableDeclSpec();
5491   switch (DS.getTypeSpecType()) {
5492   case DeclSpec::TST_typename:
5493   case DeclSpec::TST_typeofType:
5494   case DeclSpec::TST_underlyingType:
5495   case DeclSpec::TST_atomic: {
5496     // Grab the type from the parser.
5497     TypeSourceInfo *TSI = nullptr;
5498     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5499     if (T.isNull() || !T->isDependentType()) break;
5500 
5501     // Make sure there's a type source info.  This isn't really much
5502     // of a waste; most dependent types should have type source info
5503     // attached already.
5504     if (!TSI)
5505       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5506 
5507     // Rebuild the type in the current instantiation.
5508     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5509     if (!TSI) return true;
5510 
5511     // Store the new type back in the decl spec.
5512     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5513     DS.UpdateTypeRep(LocType);
5514     break;
5515   }
5516 
5517   case DeclSpec::TST_decltype:
5518   case DeclSpec::TST_typeofExpr: {
5519     Expr *E = DS.getRepAsExpr();
5520     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5521     if (Result.isInvalid()) return true;
5522     DS.UpdateExprRep(Result.get());
5523     break;
5524   }
5525 
5526   default:
5527     // Nothing to do for these decl specs.
5528     break;
5529   }
5530 
5531   // It doesn't matter what order we do this in.
5532   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5533     DeclaratorChunk &Chunk = D.getTypeObject(I);
5534 
5535     // The only type information in the declarator which can come
5536     // before the declaration name is the base type of a member
5537     // pointer.
5538     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5539       continue;
5540 
5541     // Rebuild the scope specifier in-place.
5542     CXXScopeSpec &SS = Chunk.Mem.Scope();
5543     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5544       return true;
5545   }
5546 
5547   return false;
5548 }
5549 
ActOnDeclarator(Scope * S,Declarator & D)5550 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5551   D.setFunctionDefinitionKind(FDK_Declaration);
5552   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5553 
5554   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5555       Dcl && Dcl->getDeclContext()->isFileContext())
5556     Dcl->setTopLevelDeclInObjCContainer();
5557 
5558   if (getLangOpts().OpenCL)
5559     setCurrentOpenCLExtensionForDecl(Dcl);
5560 
5561   return Dcl;
5562 }
5563 
5564 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5565 ///   If T is the name of a class, then each of the following shall have a
5566 ///   name different from T:
5567 ///     - every static data member of class T;
5568 ///     - every member function of class T
5569 ///     - every member of class T that is itself a type;
5570 /// \returns true if the declaration name violates these rules.
DiagnoseClassNameShadow(DeclContext * DC,DeclarationNameInfo NameInfo)5571 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5572                                    DeclarationNameInfo NameInfo) {
5573   DeclarationName Name = NameInfo.getName();
5574 
5575   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5576   while (Record && Record->isAnonymousStructOrUnion())
5577     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5578   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5579     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5580     return true;
5581   }
5582 
5583   return false;
5584 }
5585 
5586 /// Diagnose a declaration whose declarator-id has the given
5587 /// nested-name-specifier.
5588 ///
5589 /// \param SS The nested-name-specifier of the declarator-id.
5590 ///
5591 /// \param DC The declaration context to which the nested-name-specifier
5592 /// resolves.
5593 ///
5594 /// \param Name The name of the entity being declared.
5595 ///
5596 /// \param Loc The location of the name of the entity being declared.
5597 ///
5598 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5599 /// we're declaring an explicit / partial specialization / instantiation.
5600 ///
5601 /// \returns true if we cannot safely recover from this error, false otherwise.
diagnoseQualifiedDeclaration(CXXScopeSpec & SS,DeclContext * DC,DeclarationName Name,SourceLocation Loc,bool IsTemplateId)5602 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5603                                         DeclarationName Name,
5604                                         SourceLocation Loc, bool IsTemplateId) {
5605   DeclContext *Cur = CurContext;
5606   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5607     Cur = Cur->getParent();
5608 
5609   // If the user provided a superfluous scope specifier that refers back to the
5610   // class in which the entity is already declared, diagnose and ignore it.
5611   //
5612   // class X {
5613   //   void X::f();
5614   // };
5615   //
5616   // Note, it was once ill-formed to give redundant qualification in all
5617   // contexts, but that rule was removed by DR482.
5618   if (Cur->Equals(DC)) {
5619     if (Cur->isRecord()) {
5620       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5621                                       : diag::err_member_extra_qualification)
5622         << Name << FixItHint::CreateRemoval(SS.getRange());
5623       SS.clear();
5624     } else {
5625       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5626     }
5627     return false;
5628   }
5629 
5630   // Check whether the qualifying scope encloses the scope of the original
5631   // declaration. For a template-id, we perform the checks in
5632   // CheckTemplateSpecializationScope.
5633   if (!Cur->Encloses(DC) && !IsTemplateId) {
5634     if (Cur->isRecord())
5635       Diag(Loc, diag::err_member_qualification)
5636         << Name << SS.getRange();
5637     else if (isa<TranslationUnitDecl>(DC))
5638       Diag(Loc, diag::err_invalid_declarator_global_scope)
5639         << Name << SS.getRange();
5640     else if (isa<FunctionDecl>(Cur))
5641       Diag(Loc, diag::err_invalid_declarator_in_function)
5642         << Name << SS.getRange();
5643     else if (isa<BlockDecl>(Cur))
5644       Diag(Loc, diag::err_invalid_declarator_in_block)
5645         << Name << SS.getRange();
5646     else
5647       Diag(Loc, diag::err_invalid_declarator_scope)
5648       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5649 
5650     return true;
5651   }
5652 
5653   if (Cur->isRecord()) {
5654     // Cannot qualify members within a class.
5655     Diag(Loc, diag::err_member_qualification)
5656       << Name << SS.getRange();
5657     SS.clear();
5658 
5659     // C++ constructors and destructors with incorrect scopes can break
5660     // our AST invariants by having the wrong underlying types. If
5661     // that's the case, then drop this declaration entirely.
5662     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5663          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5664         !Context.hasSameType(Name.getCXXNameType(),
5665                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5666       return true;
5667 
5668     return false;
5669   }
5670 
5671   // C++11 [dcl.meaning]p1:
5672   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5673   //   not begin with a decltype-specifer"
5674   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5675   while (SpecLoc.getPrefix())
5676     SpecLoc = SpecLoc.getPrefix();
5677   if (dyn_cast_or_null<DecltypeType>(
5678         SpecLoc.getNestedNameSpecifier()->getAsType()))
5679     Diag(Loc, diag::err_decltype_in_declarator)
5680       << SpecLoc.getTypeLoc().getSourceRange();
5681 
5682   return false;
5683 }
5684 
HandleDeclarator(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParamLists)5685 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5686                                   MultiTemplateParamsArg TemplateParamLists) {
5687   // TODO: consider using NameInfo for diagnostic.
5688   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5689   DeclarationName Name = NameInfo.getName();
5690 
5691   // All of these full declarators require an identifier.  If it doesn't have
5692   // one, the ParsedFreeStandingDeclSpec action should be used.
5693   if (D.isDecompositionDeclarator()) {
5694     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5695   } else if (!Name) {
5696     if (!D.isInvalidType())  // Reject this if we think it is valid.
5697       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5698           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5699     return nullptr;
5700   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5701     return nullptr;
5702 
5703   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5704   // we find one that is.
5705   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5706          (S->getFlags() & Scope::TemplateParamScope) != 0)
5707     S = S->getParent();
5708 
5709   DeclContext *DC = CurContext;
5710   if (D.getCXXScopeSpec().isInvalid())
5711     D.setInvalidType();
5712   else if (D.getCXXScopeSpec().isSet()) {
5713     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5714                                         UPPC_DeclarationQualifier))
5715       return nullptr;
5716 
5717     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5718     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5719     if (!DC || isa<EnumDecl>(DC)) {
5720       // If we could not compute the declaration context, it's because the
5721       // declaration context is dependent but does not refer to a class,
5722       // class template, or class template partial specialization. Complain
5723       // and return early, to avoid the coming semantic disaster.
5724       Diag(D.getIdentifierLoc(),
5725            diag::err_template_qualified_declarator_no_match)
5726         << D.getCXXScopeSpec().getScopeRep()
5727         << D.getCXXScopeSpec().getRange();
5728       return nullptr;
5729     }
5730     bool IsDependentContext = DC->isDependentContext();
5731 
5732     if (!IsDependentContext &&
5733         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5734       return nullptr;
5735 
5736     // If a class is incomplete, do not parse entities inside it.
5737     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5738       Diag(D.getIdentifierLoc(),
5739            diag::err_member_def_undefined_record)
5740         << Name << DC << D.getCXXScopeSpec().getRange();
5741       return nullptr;
5742     }
5743     if (!D.getDeclSpec().isFriendSpecified()) {
5744       if (diagnoseQualifiedDeclaration(
5745               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5746               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5747         if (DC->isRecord())
5748           return nullptr;
5749 
5750         D.setInvalidType();
5751       }
5752     }
5753 
5754     // Check whether we need to rebuild the type of the given
5755     // declaration in the current instantiation.
5756     if (EnteringContext && IsDependentContext &&
5757         TemplateParamLists.size() != 0) {
5758       ContextRAII SavedContext(*this, DC);
5759       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5760         D.setInvalidType();
5761     }
5762   }
5763 
5764   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5765   QualType R = TInfo->getType();
5766 
5767   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5768                                       UPPC_DeclarationType))
5769     D.setInvalidType();
5770 
5771   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5772                         forRedeclarationInCurContext());
5773 
5774   // See if this is a redefinition of a variable in the same scope.
5775   if (!D.getCXXScopeSpec().isSet()) {
5776     bool IsLinkageLookup = false;
5777     bool CreateBuiltins = false;
5778 
5779     // If the declaration we're planning to build will be a function
5780     // or object with linkage, then look for another declaration with
5781     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5782     //
5783     // If the declaration we're planning to build will be declared with
5784     // external linkage in the translation unit, create any builtin with
5785     // the same name.
5786     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5787       /* Do nothing*/;
5788     else if (CurContext->isFunctionOrMethod() &&
5789              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5790               R->isFunctionType())) {
5791       IsLinkageLookup = true;
5792       CreateBuiltins =
5793           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5794     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5795                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5796       CreateBuiltins = true;
5797 
5798     if (IsLinkageLookup) {
5799       Previous.clear(LookupRedeclarationWithLinkage);
5800       Previous.setRedeclarationKind(ForExternalRedeclaration);
5801     }
5802 
5803     LookupName(Previous, S, CreateBuiltins);
5804   } else { // Something like "int foo::x;"
5805     LookupQualifiedName(Previous, DC);
5806 
5807     // C++ [dcl.meaning]p1:
5808     //   When the declarator-id is qualified, the declaration shall refer to a
5809     //  previously declared member of the class or namespace to which the
5810     //  qualifier refers (or, in the case of a namespace, of an element of the
5811     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5812     //  thereof; [...]
5813     //
5814     // Note that we already checked the context above, and that we do not have
5815     // enough information to make sure that Previous contains the declaration
5816     // we want to match. For example, given:
5817     //
5818     //   class X {
5819     //     void f();
5820     //     void f(float);
5821     //   };
5822     //
5823     //   void X::f(int) { } // ill-formed
5824     //
5825     // In this case, Previous will point to the overload set
5826     // containing the two f's declared in X, but neither of them
5827     // matches.
5828 
5829     // C++ [dcl.meaning]p1:
5830     //   [...] the member shall not merely have been introduced by a
5831     //   using-declaration in the scope of the class or namespace nominated by
5832     //   the nested-name-specifier of the declarator-id.
5833     RemoveUsingDecls(Previous);
5834   }
5835 
5836   if (Previous.isSingleResult() &&
5837       Previous.getFoundDecl()->isTemplateParameter()) {
5838     // Maybe we will complain about the shadowed template parameter.
5839     if (!D.isInvalidType())
5840       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5841                                       Previous.getFoundDecl());
5842 
5843     // Just pretend that we didn't see the previous declaration.
5844     Previous.clear();
5845   }
5846 
5847   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5848     // Forget that the previous declaration is the injected-class-name.
5849     Previous.clear();
5850 
5851   // In C++, the previous declaration we find might be a tag type
5852   // (class or enum). In this case, the new declaration will hide the
5853   // tag type. Note that this applies to functions, function templates, and
5854   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5855   if (Previous.isSingleTagDecl() &&
5856       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5857       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5858     Previous.clear();
5859 
5860   // Check that there are no default arguments other than in the parameters
5861   // of a function declaration (C++ only).
5862   if (getLangOpts().CPlusPlus)
5863     CheckExtraCXXDefaultArguments(D);
5864 
5865   NamedDecl *New;
5866 
5867   bool AddToScope = true;
5868   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5869     if (TemplateParamLists.size()) {
5870       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5871       return nullptr;
5872     }
5873 
5874     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5875   } else if (R->isFunctionType()) {
5876     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5877                                   TemplateParamLists,
5878                                   AddToScope);
5879   } else {
5880     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5881                                   AddToScope);
5882   }
5883 
5884   if (!New)
5885     return nullptr;
5886 
5887   // If this has an identifier and is not a function template specialization,
5888   // add it to the scope stack.
5889   if (New->getDeclName() && AddToScope)
5890     PushOnScopeChains(New, S);
5891 
5892   if (isInOpenMPDeclareTargetContext())
5893     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5894 
5895   return New;
5896 }
5897 
5898 /// Helper method to turn variable array types into constant array
5899 /// types in certain situations which would otherwise be errors (for
5900 /// GCC compatibility).
TryToFixInvalidVariablyModifiedType(QualType T,ASTContext & Context,bool & SizeIsNegative,llvm::APSInt & Oversized)5901 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5902                                                     ASTContext &Context,
5903                                                     bool &SizeIsNegative,
5904                                                     llvm::APSInt &Oversized) {
5905   // This method tries to turn a variable array into a constant
5906   // array even when the size isn't an ICE.  This is necessary
5907   // for compatibility with code that depends on gcc's buggy
5908   // constant expression folding, like struct {char x[(int)(char*)2];}
5909   SizeIsNegative = false;
5910   Oversized = 0;
5911 
5912   if (T->isDependentType())
5913     return QualType();
5914 
5915   QualifierCollector Qs;
5916   const Type *Ty = Qs.strip(T);
5917 
5918   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5919     QualType Pointee = PTy->getPointeeType();
5920     QualType FixedType =
5921         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5922                                             Oversized);
5923     if (FixedType.isNull()) return FixedType;
5924     FixedType = Context.getPointerType(FixedType);
5925     return Qs.apply(Context, FixedType);
5926   }
5927   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5928     QualType Inner = PTy->getInnerType();
5929     QualType FixedType =
5930         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5931                                             Oversized);
5932     if (FixedType.isNull()) return FixedType;
5933     FixedType = Context.getParenType(FixedType);
5934     return Qs.apply(Context, FixedType);
5935   }
5936 
5937   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5938   if (!VLATy)
5939     return QualType();
5940   // FIXME: We should probably handle this case
5941   if (VLATy->getElementType()->isVariablyModifiedType())
5942     return QualType();
5943 
5944   Expr::EvalResult Result;
5945   if (!VLATy->getSizeExpr() ||
5946       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5947     return QualType();
5948 
5949   llvm::APSInt Res = Result.Val.getInt();
5950 
5951   // Check whether the array size is negative.
5952   if (Res.isSigned() && Res.isNegative()) {
5953     SizeIsNegative = true;
5954     return QualType();
5955   }
5956 
5957   // Check whether the array is too large to be addressed.
5958   unsigned ActiveSizeBits
5959     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5960                                               Res);
5961   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5962     Oversized = Res;
5963     return QualType();
5964   }
5965 
5966   return Context.getConstantArrayType(
5967       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5968 }
5969 
5970 static void
FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL,TypeLoc DstTL)5971 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5972   SrcTL = SrcTL.getUnqualifiedLoc();
5973   DstTL = DstTL.getUnqualifiedLoc();
5974   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5975     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5976     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5977                                       DstPTL.getPointeeLoc());
5978     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5979     return;
5980   }
5981   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5982     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5983     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5984                                       DstPTL.getInnerLoc());
5985     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5986     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5987     return;
5988   }
5989   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5990   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5991   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5992   TypeLoc DstElemTL = DstATL.getElementLoc();
5993   DstElemTL.initializeFullCopy(SrcElemTL);
5994   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5995   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5996   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5997 }
5998 
5999 /// Helper method to turn variable array types into constant array
6000 /// types in certain situations which would otherwise be errors (for
6001 /// GCC compatibility).
6002 static TypeSourceInfo*
TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo * TInfo,ASTContext & Context,bool & SizeIsNegative,llvm::APSInt & Oversized)6003 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6004                                               ASTContext &Context,
6005                                               bool &SizeIsNegative,
6006                                               llvm::APSInt &Oversized) {
6007   QualType FixedTy
6008     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6009                                           SizeIsNegative, Oversized);
6010   if (FixedTy.isNull())
6011     return nullptr;
6012   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6013   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6014                                     FixedTInfo->getTypeLoc());
6015   return FixedTInfo;
6016 }
6017 
6018 /// Register the given locally-scoped extern "C" declaration so
6019 /// that it can be found later for redeclarations. We include any extern "C"
6020 /// declaration that is not visible in the translation unit here, not just
6021 /// function-scope declarations.
6022 void
RegisterLocallyScopedExternCDecl(NamedDecl * ND,Scope * S)6023 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6024   if (!getLangOpts().CPlusPlus &&
6025       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6026     // Don't need to track declarations in the TU in C.
6027     return;
6028 
6029   // Note that we have a locally-scoped external with this name.
6030   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6031 }
6032 
findLocallyScopedExternCDecl(DeclarationName Name)6033 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6034   // FIXME: We can have multiple results via __attribute__((overloadable)).
6035   auto Result = Context.getExternCContextDecl()->lookup(Name);
6036   return Result.empty() ? nullptr : *Result.begin();
6037 }
6038 
6039 /// Diagnose function specifiers on a declaration of an identifier that
6040 /// does not identify a function.
DiagnoseFunctionSpecifiers(const DeclSpec & DS)6041 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6042   // FIXME: We should probably indicate the identifier in question to avoid
6043   // confusion for constructs like "virtual int a(), b;"
6044   if (DS.isVirtualSpecified())
6045     Diag(DS.getVirtualSpecLoc(),
6046          diag::err_virtual_non_function);
6047 
6048   if (DS.hasExplicitSpecifier())
6049     Diag(DS.getExplicitSpecLoc(),
6050          diag::err_explicit_non_function);
6051 
6052   if (DS.isNoreturnSpecified())
6053     Diag(DS.getNoreturnSpecLoc(),
6054          diag::err_noreturn_non_function);
6055 }
6056 
6057 NamedDecl*
ActOnTypedefDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous)6058 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6059                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6060   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6061   if (D.getCXXScopeSpec().isSet()) {
6062     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6063       << D.getCXXScopeSpec().getRange();
6064     D.setInvalidType();
6065     // Pretend we didn't see the scope specifier.
6066     DC = CurContext;
6067     Previous.clear();
6068   }
6069 
6070   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6071 
6072   if (D.getDeclSpec().isInlineSpecified())
6073     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6074         << getLangOpts().CPlusPlus17;
6075   if (D.getDeclSpec().hasConstexprSpecifier())
6076     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6077         << 1 << D.getDeclSpec().getConstexprSpecifier();
6078 
6079   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6080     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6081       Diag(D.getName().StartLocation,
6082            diag::err_deduction_guide_invalid_specifier)
6083           << "typedef";
6084     else
6085       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6086           << D.getName().getSourceRange();
6087     return nullptr;
6088   }
6089 
6090   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6091   if (!NewTD) return nullptr;
6092 
6093   // Handle attributes prior to checking for duplicates in MergeVarDecl
6094   ProcessDeclAttributes(S, NewTD, D);
6095 
6096   CheckTypedefForVariablyModifiedType(S, NewTD);
6097 
6098   bool Redeclaration = D.isRedeclaration();
6099   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6100   D.setRedeclaration(Redeclaration);
6101   return ND;
6102 }
6103 
6104 void
CheckTypedefForVariablyModifiedType(Scope * S,TypedefNameDecl * NewTD)6105 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6106   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6107   // then it shall have block scope.
6108   // Note that variably modified types must be fixed before merging the decl so
6109   // that redeclarations will match.
6110   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6111   QualType T = TInfo->getType();
6112   if (T->isVariablyModifiedType()) {
6113     setFunctionHasBranchProtectedScope();
6114 
6115     if (S->getFnParent() == nullptr) {
6116       bool SizeIsNegative;
6117       llvm::APSInt Oversized;
6118       TypeSourceInfo *FixedTInfo =
6119         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6120                                                       SizeIsNegative,
6121                                                       Oversized);
6122       if (FixedTInfo) {
6123         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
6124         NewTD->setTypeSourceInfo(FixedTInfo);
6125       } else {
6126         if (SizeIsNegative)
6127           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6128         else if (T->isVariableArrayType())
6129           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6130         else if (Oversized.getBoolValue())
6131           Diag(NewTD->getLocation(), diag::err_array_too_large)
6132             << Oversized.toString(10);
6133         else
6134           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6135         NewTD->setInvalidDecl();
6136       }
6137     }
6138   }
6139 }
6140 
6141 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6142 /// declares a typedef-name, either using the 'typedef' type specifier or via
6143 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6144 NamedDecl*
ActOnTypedefNameDecl(Scope * S,DeclContext * DC,TypedefNameDecl * NewTD,LookupResult & Previous,bool & Redeclaration)6145 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6146                            LookupResult &Previous, bool &Redeclaration) {
6147 
6148   // Find the shadowed declaration before filtering for scope.
6149   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6150 
6151   // Merge the decl with the existing one if appropriate. If the decl is
6152   // in an outer scope, it isn't the same thing.
6153   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6154                        /*AllowInlineNamespace*/false);
6155   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6156   if (!Previous.empty()) {
6157     Redeclaration = true;
6158     MergeTypedefNameDecl(S, NewTD, Previous);
6159   } else {
6160     inferGslPointerAttribute(NewTD);
6161   }
6162 
6163   if (ShadowedDecl && !Redeclaration)
6164     CheckShadow(NewTD, ShadowedDecl, Previous);
6165 
6166   // If this is the C FILE type, notify the AST context.
6167   if (IdentifierInfo *II = NewTD->getIdentifier())
6168     if (!NewTD->isInvalidDecl() &&
6169         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6170       if (II->isStr("FILE"))
6171         Context.setFILEDecl(NewTD);
6172       else if (II->isStr("jmp_buf"))
6173         Context.setjmp_bufDecl(NewTD);
6174       else if (II->isStr("sigjmp_buf"))
6175         Context.setsigjmp_bufDecl(NewTD);
6176       else if (II->isStr("ucontext_t"))
6177         Context.setucontext_tDecl(NewTD);
6178     }
6179 
6180   if (isa<TypedefDecl>(NewTD) && NewTD->hasAttrs())
6181     CheckAlignasUnderalignment(NewTD);
6182 
6183   return NewTD;
6184 }
6185 
6186 /// Determines whether the given declaration is an out-of-scope
6187 /// previous declaration.
6188 ///
6189 /// This routine should be invoked when name lookup has found a
6190 /// previous declaration (PrevDecl) that is not in the scope where a
6191 /// new declaration by the same name is being introduced. If the new
6192 /// declaration occurs in a local scope, previous declarations with
6193 /// linkage may still be considered previous declarations (C99
6194 /// 6.2.2p4-5, C++ [basic.link]p6).
6195 ///
6196 /// \param PrevDecl the previous declaration found by name
6197 /// lookup
6198 ///
6199 /// \param DC the context in which the new declaration is being
6200 /// declared.
6201 ///
6202 /// \returns true if PrevDecl is an out-of-scope previous declaration
6203 /// for a new delcaration with the same name.
6204 static bool
isOutOfScopePreviousDeclaration(NamedDecl * PrevDecl,DeclContext * DC,ASTContext & Context)6205 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6206                                 ASTContext &Context) {
6207   if (!PrevDecl)
6208     return false;
6209 
6210   if (!PrevDecl->hasLinkage())
6211     return false;
6212 
6213   if (Context.getLangOpts().CPlusPlus) {
6214     // C++ [basic.link]p6:
6215     //   If there is a visible declaration of an entity with linkage
6216     //   having the same name and type, ignoring entities declared
6217     //   outside the innermost enclosing namespace scope, the block
6218     //   scope declaration declares that same entity and receives the
6219     //   linkage of the previous declaration.
6220     DeclContext *OuterContext = DC->getRedeclContext();
6221     if (!OuterContext->isFunctionOrMethod())
6222       // This rule only applies to block-scope declarations.
6223       return false;
6224 
6225     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6226     if (PrevOuterContext->isRecord())
6227       // We found a member function: ignore it.
6228       return false;
6229 
6230     // Find the innermost enclosing namespace for the new and
6231     // previous declarations.
6232     OuterContext = OuterContext->getEnclosingNamespaceContext();
6233     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6234 
6235     // The previous declaration is in a different namespace, so it
6236     // isn't the same function.
6237     if (!OuterContext->Equals(PrevOuterContext))
6238       return false;
6239   }
6240 
6241   return true;
6242 }
6243 
SetNestedNameSpecifier(Sema & S,DeclaratorDecl * DD,Declarator & D)6244 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6245   CXXScopeSpec &SS = D.getCXXScopeSpec();
6246   if (!SS.isSet()) return;
6247   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6248 }
6249 
inferObjCARCLifetime(ValueDecl * decl)6250 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6251   QualType type = decl->getType();
6252   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6253   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6254     // Various kinds of declaration aren't allowed to be __autoreleasing.
6255     unsigned kind = -1U;
6256     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6257       if (var->hasAttr<BlocksAttr>())
6258         kind = 0; // __block
6259       else if (!var->hasLocalStorage())
6260         kind = 1; // global
6261     } else if (isa<ObjCIvarDecl>(decl)) {
6262       kind = 3; // ivar
6263     } else if (isa<FieldDecl>(decl)) {
6264       kind = 2; // field
6265     }
6266 
6267     if (kind != -1U) {
6268       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6269         << kind;
6270     }
6271   } else if (lifetime == Qualifiers::OCL_None) {
6272     // Try to infer lifetime.
6273     if (!type->isObjCLifetimeType())
6274       return false;
6275 
6276     lifetime = type->getObjCARCImplicitLifetime();
6277     type = Context.getLifetimeQualifiedType(type, lifetime);
6278     decl->setType(type);
6279   }
6280 
6281   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6282     // Thread-local variables cannot have lifetime.
6283     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6284         var->getTLSKind()) {
6285       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6286         << var->getType();
6287       return true;
6288     }
6289   }
6290 
6291   return false;
6292 }
6293 
deduceOpenCLAddressSpace(ValueDecl * Decl)6294 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6295   if (Decl->getType().hasAddressSpace())
6296     return;
6297   if (Decl->getType()->isDependentType())
6298     return;
6299   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6300     QualType Type = Var->getType();
6301     if (Type->isSamplerT() || Type->isVoidType())
6302       return;
6303     LangAS ImplAS = LangAS::opencl_private;
6304     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6305         Var->hasGlobalStorage())
6306       ImplAS = LangAS::opencl_global;
6307     // If the original type from a decayed type is an array type and that array
6308     // type has no address space yet, deduce it now.
6309     if (auto DT = dyn_cast<DecayedType>(Type)) {
6310       auto OrigTy = DT->getOriginalType();
6311       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6312         // Add the address space to the original array type and then propagate
6313         // that to the element type through `getAsArrayType`.
6314         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6315         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6316         // Re-generate the decayed type.
6317         Type = Context.getDecayedType(OrigTy);
6318       }
6319     }
6320     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6321     // Apply any qualifiers (including address space) from the array type to
6322     // the element type. This implements C99 6.7.3p8: "If the specification of
6323     // an array type includes any type qualifiers, the element type is so
6324     // qualified, not the array type."
6325     if (Type->isArrayType())
6326       Type = QualType(Context.getAsArrayType(Type), 0);
6327     Decl->setType(Type);
6328   }
6329 }
6330 
checkAttributesAfterMerging(Sema & S,NamedDecl & ND)6331 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6332   // Ensure that an auto decl is deduced otherwise the checks below might cache
6333   // the wrong linkage.
6334   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6335 
6336   // 'weak' only applies to declarations with external linkage.
6337   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6338     if (!ND.isExternallyVisible()) {
6339       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6340       ND.dropAttr<WeakAttr>();
6341     }
6342   }
6343   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6344     if (ND.isExternallyVisible()) {
6345       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6346       ND.dropAttr<WeakRefAttr>();
6347       ND.dropAttr<AliasAttr>();
6348     }
6349   }
6350 
6351   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6352     if (VD->hasInit()) {
6353       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6354         assert(VD->isThisDeclarationADefinition() &&
6355                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6356         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6357         VD->dropAttr<AliasAttr>();
6358       }
6359     }
6360   }
6361 
6362   // 'selectany' only applies to externally visible variable declarations.
6363   // It does not apply to functions.
6364   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6365     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6366       S.Diag(Attr->getLocation(),
6367              diag::err_attribute_selectany_non_extern_data);
6368       ND.dropAttr<SelectAnyAttr>();
6369     }
6370   }
6371 
6372   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6373     auto *VD = dyn_cast<VarDecl>(&ND);
6374     bool IsAnonymousNS = false;
6375     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6376     if (VD) {
6377       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6378       while (NS && !IsAnonymousNS) {
6379         IsAnonymousNS = NS->isAnonymousNamespace();
6380         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6381       }
6382     }
6383     // dll attributes require external linkage. Static locals may have external
6384     // linkage but still cannot be explicitly imported or exported.
6385     // In Microsoft mode, a variable defined in anonymous namespace must have
6386     // external linkage in order to be exported.
6387     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6388     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6389         (!AnonNSInMicrosoftMode &&
6390          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6391       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6392         << &ND << Attr;
6393       ND.setInvalidDecl();
6394     }
6395   }
6396 
6397   // Virtual functions cannot be marked as 'notail'.
6398   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6399     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6400       if (MD->isVirtual()) {
6401         S.Diag(ND.getLocation(),
6402                diag::err_invalid_attribute_on_virtual_function)
6403             << Attr;
6404         ND.dropAttr<NotTailCalledAttr>();
6405       }
6406 
6407   // Check the attributes on the function type, if any.
6408   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6409     // Don't declare this variable in the second operand of the for-statement;
6410     // GCC miscompiles that by ending its lifetime before evaluating the
6411     // third operand. See gcc.gnu.org/PR86769.
6412     AttributedTypeLoc ATL;
6413     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6414          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6415          TL = ATL.getModifiedLoc()) {
6416       // The [[lifetimebound]] attribute can be applied to the implicit object
6417       // parameter of a non-static member function (other than a ctor or dtor)
6418       // by applying it to the function type.
6419       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6420         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6421         if (!MD || MD->isStatic()) {
6422           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6423               << !MD << A->getRange();
6424         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6425           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6426               << isa<CXXDestructorDecl>(MD) << A->getRange();
6427         }
6428       }
6429     }
6430   }
6431 }
6432 
checkDLLAttributeRedeclaration(Sema & S,NamedDecl * OldDecl,NamedDecl * NewDecl,bool IsSpecialization,bool IsDefinition)6433 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6434                                            NamedDecl *NewDecl,
6435                                            bool IsSpecialization,
6436                                            bool IsDefinition) {
6437   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6438     return;
6439 
6440   bool IsTemplate = false;
6441   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6442     OldDecl = OldTD->getTemplatedDecl();
6443     IsTemplate = true;
6444     if (!IsSpecialization)
6445       IsDefinition = false;
6446   }
6447   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6448     NewDecl = NewTD->getTemplatedDecl();
6449     IsTemplate = true;
6450   }
6451 
6452   if (!OldDecl || !NewDecl)
6453     return;
6454 
6455   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6456   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6457   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6458   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6459 
6460   // dllimport and dllexport are inheritable attributes so we have to exclude
6461   // inherited attribute instances.
6462   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6463                     (NewExportAttr && !NewExportAttr->isInherited());
6464 
6465   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6466   // the only exception being explicit specializations.
6467   // Implicitly generated declarations are also excluded for now because there
6468   // is no other way to switch these to use dllimport or dllexport.
6469   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6470 
6471   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6472     // Allow with a warning for free functions and global variables.
6473     bool JustWarn = false;
6474     if (!OldDecl->isCXXClassMember()) {
6475       auto *VD = dyn_cast<VarDecl>(OldDecl);
6476       if (VD && !VD->getDescribedVarTemplate())
6477         JustWarn = true;
6478       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6479       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6480         JustWarn = true;
6481     }
6482 
6483     // We cannot change a declaration that's been used because IR has already
6484     // been emitted. Dllimported functions will still work though (modulo
6485     // address equality) as they can use the thunk.
6486     if (OldDecl->isUsed())
6487       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6488         JustWarn = false;
6489 
6490     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6491                                : diag::err_attribute_dll_redeclaration;
6492     S.Diag(NewDecl->getLocation(), DiagID)
6493         << NewDecl
6494         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6495     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6496     if (!JustWarn) {
6497       NewDecl->setInvalidDecl();
6498       return;
6499     }
6500   }
6501 
6502   // A redeclaration is not allowed to drop a dllimport attribute, the only
6503   // exceptions being inline function definitions (except for function
6504   // templates), local extern declarations, qualified friend declarations or
6505   // special MSVC extension: in the last case, the declaration is treated as if
6506   // it were marked dllexport.
6507   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6508   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6509   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6510     // Ignore static data because out-of-line definitions are diagnosed
6511     // separately.
6512     IsStaticDataMember = VD->isStaticDataMember();
6513     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6514                    VarDecl::DeclarationOnly;
6515   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6516     IsInline = FD->isInlined();
6517     IsQualifiedFriend = FD->getQualifier() &&
6518                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6519   }
6520 
6521   if (OldImportAttr && !HasNewAttr &&
6522       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6523       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6524     if (IsMicrosoft && IsDefinition) {
6525       S.Diag(NewDecl->getLocation(),
6526              diag::warn_redeclaration_without_import_attribute)
6527           << NewDecl;
6528       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6529       NewDecl->dropAttr<DLLImportAttr>();
6530       NewDecl->addAttr(
6531           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6532     } else {
6533       S.Diag(NewDecl->getLocation(),
6534              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6535           << NewDecl << OldImportAttr;
6536       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6537       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6538       OldDecl->dropAttr<DLLImportAttr>();
6539       NewDecl->dropAttr<DLLImportAttr>();
6540     }
6541   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6542     // In MinGW, seeing a function declared inline drops the dllimport
6543     // attribute.
6544     OldDecl->dropAttr<DLLImportAttr>();
6545     NewDecl->dropAttr<DLLImportAttr>();
6546     S.Diag(NewDecl->getLocation(),
6547            diag::warn_dllimport_dropped_from_inline_function)
6548         << NewDecl << OldImportAttr;
6549   }
6550 
6551   // A specialization of a class template member function is processed here
6552   // since it's a redeclaration. If the parent class is dllexport, the
6553   // specialization inherits that attribute. This doesn't happen automatically
6554   // since the parent class isn't instantiated until later.
6555   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6556     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6557         !NewImportAttr && !NewExportAttr) {
6558       if (const DLLExportAttr *ParentExportAttr =
6559               MD->getParent()->getAttr<DLLExportAttr>()) {
6560         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6561         NewAttr->setInherited(true);
6562         NewDecl->addAttr(NewAttr);
6563       }
6564     }
6565   }
6566 }
6567 
6568 /// Given that we are within the definition of the given function,
6569 /// will that definition behave like C99's 'inline', where the
6570 /// definition is discarded except for optimization purposes?
isFunctionDefinitionDiscarded(Sema & S,FunctionDecl * FD)6571 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6572   // Try to avoid calling GetGVALinkageForFunction.
6573 
6574   // All cases of this require the 'inline' keyword.
6575   if (!FD->isInlined()) return false;
6576 
6577   // This is only possible in C++ with the gnu_inline attribute.
6578   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6579     return false;
6580 
6581   // Okay, go ahead and call the relatively-more-expensive function.
6582   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6583 }
6584 
6585 /// Determine whether a variable is extern "C" prior to attaching
6586 /// an initializer. We can't just call isExternC() here, because that
6587 /// will also compute and cache whether the declaration is externally
6588 /// visible, which might change when we attach the initializer.
6589 ///
6590 /// This can only be used if the declaration is known to not be a
6591 /// redeclaration of an internal linkage declaration.
6592 ///
6593 /// For instance:
6594 ///
6595 ///   auto x = []{};
6596 ///
6597 /// Attaching the initializer here makes this declaration not externally
6598 /// visible, because its type has internal linkage.
6599 ///
6600 /// FIXME: This is a hack.
6601 template<typename T>
isIncompleteDeclExternC(Sema & S,const T * D)6602 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6603   if (S.getLangOpts().CPlusPlus) {
6604     // In C++, the overloadable attribute negates the effects of extern "C".
6605     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6606       return false;
6607 
6608     // So do CUDA's host/device attributes.
6609     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6610                                  D->template hasAttr<CUDAHostAttr>()))
6611       return false;
6612   }
6613   return D->isExternC();
6614 }
6615 
shouldConsiderLinkage(const VarDecl * VD)6616 static bool shouldConsiderLinkage(const VarDecl *VD) {
6617   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6618   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6619       isa<OMPDeclareMapperDecl>(DC))
6620     return VD->hasExternalStorage();
6621   if (DC->isFileContext())
6622     return true;
6623   if (DC->isRecord())
6624     return false;
6625   if (isa<RequiresExprBodyDecl>(DC))
6626     return false;
6627   llvm_unreachable("Unexpected context");
6628 }
6629 
shouldConsiderLinkage(const FunctionDecl * FD)6630 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6631   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6632   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6633       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6634     return true;
6635   if (DC->isRecord())
6636     return false;
6637   llvm_unreachable("Unexpected context");
6638 }
6639 
hasParsedAttr(Scope * S,const Declarator & PD,ParsedAttr::Kind Kind)6640 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6641                           ParsedAttr::Kind Kind) {
6642   // Check decl attributes on the DeclSpec.
6643   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6644     return true;
6645 
6646   // Walk the declarator structure, checking decl attributes that were in a type
6647   // position to the decl itself.
6648   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6649     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6650       return true;
6651   }
6652 
6653   // Finally, check attributes on the decl itself.
6654   return PD.getAttributes().hasAttribute(Kind);
6655 }
6656 
6657 /// Adjust the \c DeclContext for a function or variable that might be a
6658 /// function-local external declaration.
adjustContextForLocalExternDecl(DeclContext * & DC)6659 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6660   if (!DC->isFunctionOrMethod())
6661     return false;
6662 
6663   // If this is a local extern function or variable declared within a function
6664   // template, don't add it into the enclosing namespace scope until it is
6665   // instantiated; it might have a dependent type right now.
6666   if (DC->isDependentContext())
6667     return true;
6668 
6669   // C++11 [basic.link]p7:
6670   //   When a block scope declaration of an entity with linkage is not found to
6671   //   refer to some other declaration, then that entity is a member of the
6672   //   innermost enclosing namespace.
6673   //
6674   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6675   // semantically-enclosing namespace, not a lexically-enclosing one.
6676   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6677     DC = DC->getParent();
6678   return true;
6679 }
6680 
6681 /// Returns true if given declaration has external C language linkage.
isDeclExternC(const Decl * D)6682 static bool isDeclExternC(const Decl *D) {
6683   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6684     return FD->isExternC();
6685   if (const auto *VD = dyn_cast<VarDecl>(D))
6686     return VD->isExternC();
6687 
6688   llvm_unreachable("Unknown type of decl!");
6689 }
6690 /// Returns true if there hasn't been any invalid type diagnosed.
diagnoseOpenCLTypes(Scope * S,Sema & Se,Declarator & D,DeclContext * DC,QualType R)6691 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6692                                 DeclContext *DC, QualType R) {
6693   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6694   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6695   // argument.
6696   if (R->isImageType() || R->isPipeType()) {
6697     Se.Diag(D.getIdentifierLoc(),
6698             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6699         << R;
6700     D.setInvalidType();
6701     return false;
6702   }
6703 
6704   // OpenCL v1.2 s6.9.r:
6705   // The event type cannot be used to declare a program scope variable.
6706   // OpenCL v2.0 s6.9.q:
6707   // The clk_event_t and reserve_id_t types cannot be declared in program
6708   // scope.
6709   if (NULL == S->getParent()) {
6710     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6711       Se.Diag(D.getIdentifierLoc(),
6712               diag::err_invalid_type_for_program_scope_var)
6713           << R;
6714       D.setInvalidType();
6715       return false;
6716     }
6717   }
6718 
6719   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6720   QualType NR = R;
6721   while (NR->isPointerType()) {
6722     if (NR->isFunctionPointerType()) {
6723       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6724       D.setInvalidType();
6725       return false;
6726     }
6727     NR = NR->getPointeeType();
6728   }
6729 
6730   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6731     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6732     // half array type (unless the cl_khr_fp16 extension is enabled).
6733     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6734       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6735       D.setInvalidType();
6736       return false;
6737     }
6738   }
6739 
6740   // OpenCL v1.2 s6.9.r:
6741   // The event type cannot be used with the __local, __constant and __global
6742   // address space qualifiers.
6743   if (R->isEventT()) {
6744     if (R.getAddressSpace() != LangAS::opencl_private) {
6745       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6746       D.setInvalidType();
6747       return false;
6748     }
6749   }
6750 
6751   // C++ for OpenCL does not allow the thread_local storage qualifier.
6752   // OpenCL C does not support thread_local either, and
6753   // also reject all other thread storage class specifiers.
6754   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6755   if (TSC != TSCS_unspecified) {
6756     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6757     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6758             diag::err_opencl_unknown_type_specifier)
6759         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6760         << DeclSpec::getSpecifierName(TSC) << 1;
6761     D.setInvalidType();
6762     return false;
6763   }
6764 
6765   if (R->isSamplerT()) {
6766     // OpenCL v1.2 s6.9.b p4:
6767     // The sampler type cannot be used with the __local and __global address
6768     // space qualifiers.
6769     if (R.getAddressSpace() == LangAS::opencl_local ||
6770         R.getAddressSpace() == LangAS::opencl_global) {
6771       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6772       D.setInvalidType();
6773     }
6774 
6775     // OpenCL v1.2 s6.12.14.1:
6776     // A global sampler must be declared with either the constant address
6777     // space qualifier or with the const qualifier.
6778     if (DC->isTranslationUnit() &&
6779         !(R.getAddressSpace() == LangAS::opencl_constant ||
6780           R.isConstQualified())) {
6781       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6782       D.setInvalidType();
6783     }
6784     if (D.isInvalidType())
6785       return false;
6786   }
6787   return true;
6788 }
6789 
6790 template <typename AttrTy>
copyAttrFromTypedefToDecl(Sema & S,Decl * D,const TypedefType * TT)6791 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6792   const TypedefNameDecl *TND = TT->getDecl();
6793   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6794     AttrTy *Clone = Attribute->clone(S.Context);
6795     Clone->setInherited(true);
6796     D->addAttr(Clone);
6797   }
6798 }
6799 
ActOnVariableDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous,MultiTemplateParamsArg TemplateParamLists,bool & AddToScope,ArrayRef<BindingDecl * > Bindings)6800 NamedDecl *Sema::ActOnVariableDeclarator(
6801     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6802     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6803     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6804   QualType R = TInfo->getType();
6805   DeclarationName Name = GetNameForDeclarator(D).getName();
6806 
6807   IdentifierInfo *II = Name.getAsIdentifierInfo();
6808 
6809   if (D.isDecompositionDeclarator()) {
6810     // Take the name of the first declarator as our name for diagnostic
6811     // purposes.
6812     auto &Decomp = D.getDecompositionDeclarator();
6813     if (!Decomp.bindings().empty()) {
6814       II = Decomp.bindings()[0].Name;
6815       Name = II;
6816     }
6817   } else if (!II) {
6818     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6819     return nullptr;
6820   }
6821 
6822 
6823   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6824   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6825 
6826   // dllimport globals without explicit storage class are treated as extern. We
6827   // have to change the storage class this early to get the right DeclContext.
6828   if (SC == SC_None && !DC->isRecord() &&
6829       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6830       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6831     SC = SC_Extern;
6832 
6833   DeclContext *OriginalDC = DC;
6834   bool IsLocalExternDecl = SC == SC_Extern &&
6835                            adjustContextForLocalExternDecl(DC);
6836 
6837   if (SCSpec == DeclSpec::SCS_mutable) {
6838     // mutable can only appear on non-static class members, so it's always
6839     // an error here
6840     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6841     D.setInvalidType();
6842     SC = SC_None;
6843   }
6844 
6845   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6846       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6847                               D.getDeclSpec().getStorageClassSpecLoc())) {
6848     // In C++11, the 'register' storage class specifier is deprecated.
6849     // Suppress the warning in system macros, it's used in macros in some
6850     // popular C system headers, such as in glibc's htonl() macro.
6851     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6852          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6853                                    : diag::warn_deprecated_register)
6854       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6855   }
6856 
6857   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6858 
6859   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6860     // C99 6.9p2: The storage-class specifiers auto and register shall not
6861     // appear in the declaration specifiers in an external declaration.
6862     // Global Register+Asm is a GNU extension we support.
6863     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6864       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6865       D.setInvalidType();
6866     }
6867   }
6868 
6869   bool IsMemberSpecialization = false;
6870   bool IsVariableTemplateSpecialization = false;
6871   bool IsPartialSpecialization = false;
6872   bool IsVariableTemplate = false;
6873   VarDecl *NewVD = nullptr;
6874   VarTemplateDecl *NewTemplate = nullptr;
6875   TemplateParameterList *TemplateParams = nullptr;
6876   if (!getLangOpts().CPlusPlus) {
6877     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6878                             II, R, TInfo, SC);
6879 
6880     if (R->getContainedDeducedType())
6881       ParsingInitForAutoVars.insert(NewVD);
6882 
6883     if (D.isInvalidType())
6884       NewVD->setInvalidDecl();
6885 
6886     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6887         NewVD->hasLocalStorage())
6888       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6889                             NTCUC_AutoVar, NTCUK_Destruct);
6890   } else {
6891     bool Invalid = false;
6892 
6893     if (DC->isRecord() && !CurContext->isRecord()) {
6894       // This is an out-of-line definition of a static data member.
6895       switch (SC) {
6896       case SC_None:
6897         break;
6898       case SC_Static:
6899         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6900              diag::err_static_out_of_line)
6901           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6902         break;
6903       case SC_Auto:
6904       case SC_Register:
6905       case SC_Extern:
6906         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6907         // to names of variables declared in a block or to function parameters.
6908         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6909         // of class members
6910 
6911         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6912              diag::err_storage_class_for_static_member)
6913           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6914         break;
6915       case SC_PrivateExtern:
6916         llvm_unreachable("C storage class in c++!");
6917       }
6918     }
6919 
6920     if (SC == SC_Static && CurContext->isRecord()) {
6921       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6922         // Walk up the enclosing DeclContexts to check for any that are
6923         // incompatible with static data members.
6924         const DeclContext *FunctionOrMethod = nullptr;
6925         const CXXRecordDecl *AnonStruct = nullptr;
6926         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6927           if (Ctxt->isFunctionOrMethod()) {
6928             FunctionOrMethod = Ctxt;
6929             break;
6930           }
6931           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6932           if (ParentDecl && !ParentDecl->getDeclName()) {
6933             AnonStruct = ParentDecl;
6934             break;
6935           }
6936         }
6937         if (FunctionOrMethod) {
6938           // C++ [class.static.data]p5: A local class shall not have static data
6939           // members.
6940           Diag(D.getIdentifierLoc(),
6941                diag::err_static_data_member_not_allowed_in_local_class)
6942             << Name << RD->getDeclName() << RD->getTagKind();
6943         } else if (AnonStruct) {
6944           // C++ [class.static.data]p4: Unnamed classes and classes contained
6945           // directly or indirectly within unnamed classes shall not contain
6946           // static data members.
6947           Diag(D.getIdentifierLoc(),
6948                diag::err_static_data_member_not_allowed_in_anon_struct)
6949             << Name << AnonStruct->getTagKind();
6950           Invalid = true;
6951         } else if (RD->isUnion()) {
6952           // C++98 [class.union]p1: If a union contains a static data member,
6953           // the program is ill-formed. C++11 drops this restriction.
6954           Diag(D.getIdentifierLoc(),
6955                getLangOpts().CPlusPlus11
6956                  ? diag::warn_cxx98_compat_static_data_member_in_union
6957                  : diag::ext_static_data_member_in_union) << Name;
6958         }
6959       }
6960     }
6961 
6962     // Match up the template parameter lists with the scope specifier, then
6963     // determine whether we have a template or a template specialization.
6964     bool InvalidScope = false;
6965     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6966         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6967         D.getCXXScopeSpec(),
6968         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6969             ? D.getName().TemplateId
6970             : nullptr,
6971         TemplateParamLists,
6972         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
6973     Invalid |= InvalidScope;
6974 
6975     if (TemplateParams) {
6976       if (!TemplateParams->size() &&
6977           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6978         // There is an extraneous 'template<>' for this variable. Complain
6979         // about it, but allow the declaration of the variable.
6980         Diag(TemplateParams->getTemplateLoc(),
6981              diag::err_template_variable_noparams)
6982           << II
6983           << SourceRange(TemplateParams->getTemplateLoc(),
6984                          TemplateParams->getRAngleLoc());
6985         TemplateParams = nullptr;
6986       } else {
6987         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6988           // This is an explicit specialization or a partial specialization.
6989           // FIXME: Check that we can declare a specialization here.
6990           IsVariableTemplateSpecialization = true;
6991           IsPartialSpecialization = TemplateParams->size() > 0;
6992         } else { // if (TemplateParams->size() > 0)
6993           // This is a template declaration.
6994           IsVariableTemplate = true;
6995 
6996           // Check that we can declare a template here.
6997           if (CheckTemplateDeclScope(S, TemplateParams))
6998             return nullptr;
6999 
7000           // Only C++1y supports variable templates (N3651).
7001           Diag(D.getIdentifierLoc(),
7002                getLangOpts().CPlusPlus14
7003                    ? diag::warn_cxx11_compat_variable_template
7004                    : diag::ext_variable_template);
7005         }
7006       }
7007     } else {
7008       assert((Invalid ||
7009               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7010              "should have a 'template<>' for this decl");
7011     }
7012 
7013     if (IsVariableTemplateSpecialization) {
7014       SourceLocation TemplateKWLoc =
7015           TemplateParamLists.size() > 0
7016               ? TemplateParamLists[0]->getTemplateLoc()
7017               : SourceLocation();
7018       DeclResult Res = ActOnVarTemplateSpecialization(
7019           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7020           IsPartialSpecialization);
7021       if (Res.isInvalid())
7022         return nullptr;
7023       NewVD = cast<VarDecl>(Res.get());
7024       AddToScope = false;
7025     } else if (D.isDecompositionDeclarator()) {
7026       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7027                                         D.getIdentifierLoc(), R, TInfo, SC,
7028                                         Bindings);
7029     } else
7030       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7031                               D.getIdentifierLoc(), II, R, TInfo, SC);
7032 
7033     // If this is supposed to be a variable template, create it as such.
7034     if (IsVariableTemplate) {
7035       NewTemplate =
7036           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7037                                   TemplateParams, NewVD);
7038       NewVD->setDescribedVarTemplate(NewTemplate);
7039     }
7040 
7041     // If this decl has an auto type in need of deduction, make a note of the
7042     // Decl so we can diagnose uses of it in its own initializer.
7043     if (R->getContainedDeducedType())
7044       ParsingInitForAutoVars.insert(NewVD);
7045 
7046     if (D.isInvalidType() || Invalid) {
7047       NewVD->setInvalidDecl();
7048       if (NewTemplate)
7049         NewTemplate->setInvalidDecl();
7050     }
7051 
7052     SetNestedNameSpecifier(*this, NewVD, D);
7053 
7054     // If we have any template parameter lists that don't directly belong to
7055     // the variable (matching the scope specifier), store them.
7056     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7057     if (TemplateParamLists.size() > VDTemplateParamLists)
7058       NewVD->setTemplateParameterListsInfo(
7059           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7060   }
7061 
7062   if (D.getDeclSpec().isInlineSpecified()) {
7063     if (!getLangOpts().CPlusPlus) {
7064       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7065           << 0;
7066     } else if (CurContext->isFunctionOrMethod()) {
7067       // 'inline' is not allowed on block scope variable declaration.
7068       Diag(D.getDeclSpec().getInlineSpecLoc(),
7069            diag::err_inline_declaration_block_scope) << Name
7070         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7071     } else {
7072       Diag(D.getDeclSpec().getInlineSpecLoc(),
7073            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7074                                      : diag::ext_inline_variable);
7075       NewVD->setInlineSpecified();
7076     }
7077   }
7078 
7079   // Set the lexical context. If the declarator has a C++ scope specifier, the
7080   // lexical context will be different from the semantic context.
7081   NewVD->setLexicalDeclContext(CurContext);
7082   if (NewTemplate)
7083     NewTemplate->setLexicalDeclContext(CurContext);
7084 
7085   if (IsLocalExternDecl) {
7086     if (D.isDecompositionDeclarator())
7087       for (auto *B : Bindings)
7088         B->setLocalExternDecl();
7089     else
7090       NewVD->setLocalExternDecl();
7091   }
7092 
7093   bool EmitTLSUnsupportedError = false;
7094   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7095     // C++11 [dcl.stc]p4:
7096     //   When thread_local is applied to a variable of block scope the
7097     //   storage-class-specifier static is implied if it does not appear
7098     //   explicitly.
7099     // Core issue: 'static' is not implied if the variable is declared
7100     //   'extern'.
7101     if (NewVD->hasLocalStorage() &&
7102         (SCSpec != DeclSpec::SCS_unspecified ||
7103          TSCS != DeclSpec::TSCS_thread_local ||
7104          !DC->isFunctionOrMethod()))
7105       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7106            diag::err_thread_non_global)
7107         << DeclSpec::getSpecifierName(TSCS);
7108     else if (!Context.getTargetInfo().isTLSSupported()) {
7109       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7110           getLangOpts().SYCLIsDevice) {
7111         // Postpone error emission until we've collected attributes required to
7112         // figure out whether it's a host or device variable and whether the
7113         // error should be ignored.
7114         EmitTLSUnsupportedError = true;
7115         // We still need to mark the variable as TLS so it shows up in AST with
7116         // proper storage class for other tools to use even if we're not going
7117         // to emit any code for it.
7118         NewVD->setTSCSpec(TSCS);
7119       } else
7120         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7121              diag::err_thread_unsupported);
7122     } else
7123       NewVD->setTSCSpec(TSCS);
7124   }
7125 
7126   switch (D.getDeclSpec().getConstexprSpecifier()) {
7127   case CSK_unspecified:
7128     break;
7129 
7130   case CSK_consteval:
7131     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7132         diag::err_constexpr_wrong_decl_kind)
7133       << D.getDeclSpec().getConstexprSpecifier();
7134     LLVM_FALLTHROUGH;
7135 
7136   case CSK_constexpr:
7137     NewVD->setConstexpr(true);
7138     MaybeAddCUDAConstantAttr(NewVD);
7139     // C++1z [dcl.spec.constexpr]p1:
7140     //   A static data member declared with the constexpr specifier is
7141     //   implicitly an inline variable.
7142     if (NewVD->isStaticDataMember() &&
7143         (getLangOpts().CPlusPlus17 ||
7144          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7145       NewVD->setImplicitlyInline();
7146     break;
7147 
7148   case CSK_constinit:
7149     if (!NewVD->hasGlobalStorage())
7150       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7151            diag::err_constinit_local_variable);
7152     else
7153       NewVD->addAttr(ConstInitAttr::Create(
7154           Context, D.getDeclSpec().getConstexprSpecLoc(),
7155           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7156     break;
7157   }
7158 
7159   // C99 6.7.4p3
7160   //   An inline definition of a function with external linkage shall
7161   //   not contain a definition of a modifiable object with static or
7162   //   thread storage duration...
7163   // We only apply this when the function is required to be defined
7164   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7165   // that a local variable with thread storage duration still has to
7166   // be marked 'static'.  Also note that it's possible to get these
7167   // semantics in C++ using __attribute__((gnu_inline)).
7168   if (SC == SC_Static && S->getFnParent() != nullptr &&
7169       !NewVD->getType().isConstQualified()) {
7170     FunctionDecl *CurFD = getCurFunctionDecl();
7171     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7172       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7173            diag::warn_static_local_in_extern_inline);
7174       MaybeSuggestAddingStaticToDecl(CurFD);
7175     }
7176   }
7177 
7178   if (D.getDeclSpec().isModulePrivateSpecified()) {
7179     if (IsVariableTemplateSpecialization)
7180       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7181           << (IsPartialSpecialization ? 1 : 0)
7182           << FixItHint::CreateRemoval(
7183                  D.getDeclSpec().getModulePrivateSpecLoc());
7184     else if (IsMemberSpecialization)
7185       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7186         << 2
7187         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7188     else if (NewVD->hasLocalStorage())
7189       Diag(NewVD->getLocation(), diag::err_module_private_local)
7190         << 0 << NewVD->getDeclName()
7191         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7192         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7193     else {
7194       NewVD->setModulePrivate();
7195       if (NewTemplate)
7196         NewTemplate->setModulePrivate();
7197       for (auto *B : Bindings)
7198         B->setModulePrivate();
7199     }
7200   }
7201 
7202   if (getLangOpts().OpenCL) {
7203 
7204     deduceOpenCLAddressSpace(NewVD);
7205 
7206     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7207   }
7208 
7209   // Handle attributes prior to checking for duplicates in MergeVarDecl
7210   ProcessDeclAttributes(S, NewVD, D);
7211 
7212   // FIXME: this is probably the wrong location to be doing this and we should
7213   // probably be doing this for more attributes (especially for function
7214   // pointer attributes (such as format, warn_unused_result, etc)
7215   if (R->isFunctionPointerType())
7216     if (const auto* TT = R->getAs<TypedefType>())
7217       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7218 
7219 
7220   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7221       getLangOpts().SYCLIsDevice) {
7222     if (EmitTLSUnsupportedError &&
7223         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7224          (getLangOpts().OpenMPIsDevice &&
7225           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7226       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7227            diag::err_thread_unsupported);
7228 
7229     if (EmitTLSUnsupportedError &&
7230         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7231       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7232     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7233     // storage [duration]."
7234     if (SC == SC_None && S->getFnParent() != nullptr &&
7235         (NewVD->hasAttr<CUDASharedAttr>() ||
7236          NewVD->hasAttr<CUDAConstantAttr>())) {
7237       NewVD->setStorageClass(SC_Static);
7238     }
7239   }
7240 
7241   // Ensure that dllimport globals without explicit storage class are treated as
7242   // extern. The storage class is set above using parsed attributes. Now we can
7243   // check the VarDecl itself.
7244   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7245          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7246          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7247 
7248   // In auto-retain/release, infer strong retension for variables of
7249   // retainable type.
7250   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7251     NewVD->setInvalidDecl();
7252 
7253   // Handle GNU asm-label extension (encoded as an attribute).
7254   if (Expr *E = (Expr*)D.getAsmLabel()) {
7255     // The parser guarantees this is a string.
7256     StringLiteral *SE = cast<StringLiteral>(E);
7257     StringRef Label = SE->getString();
7258     if (S->getFnParent() != nullptr) {
7259       switch (SC) {
7260       case SC_None:
7261       case SC_Auto:
7262         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7263         break;
7264       case SC_Register:
7265         // Local Named register
7266         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7267             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7268           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7269         break;
7270       case SC_Static:
7271       case SC_Extern:
7272       case SC_PrivateExtern:
7273         break;
7274       }
7275     } else if (SC == SC_Register) {
7276       // Global Named register
7277       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7278         const auto &TI = Context.getTargetInfo();
7279         bool HasSizeMismatch;
7280 
7281         if (!TI.isValidGCCRegisterName(Label))
7282           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7283         else if (!TI.validateGlobalRegisterVariable(Label,
7284                                                     Context.getTypeSize(R),
7285                                                     HasSizeMismatch))
7286           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7287         else if (HasSizeMismatch)
7288           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7289       }
7290 
7291       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7292         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7293         NewVD->setInvalidDecl(true);
7294       }
7295     }
7296 
7297     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7298                                         /*IsLiteralLabel=*/true,
7299                                         SE->getStrTokenLoc(0)));
7300   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7301     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7302       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7303     if (I != ExtnameUndeclaredIdentifiers.end()) {
7304       if (isDeclExternC(NewVD)) {
7305         NewVD->addAttr(I->second);
7306         ExtnameUndeclaredIdentifiers.erase(I);
7307       } else
7308         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7309             << /*Variable*/1 << NewVD;
7310     }
7311   }
7312 
7313   // Find the shadowed declaration before filtering for scope.
7314   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7315                                 ? getShadowedDeclaration(NewVD, Previous)
7316                                 : nullptr;
7317 
7318   // Don't consider existing declarations that are in a different
7319   // scope and are out-of-semantic-context declarations (if the new
7320   // declaration has linkage).
7321   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7322                        D.getCXXScopeSpec().isNotEmpty() ||
7323                        IsMemberSpecialization ||
7324                        IsVariableTemplateSpecialization);
7325 
7326   // Check whether the previous declaration is in the same block scope. This
7327   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7328   if (getLangOpts().CPlusPlus &&
7329       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7330     NewVD->setPreviousDeclInSameBlockScope(
7331         Previous.isSingleResult() && !Previous.isShadowed() &&
7332         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7333 
7334   if (!getLangOpts().CPlusPlus) {
7335     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7336   } else {
7337     // If this is an explicit specialization of a static data member, check it.
7338     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7339         CheckMemberSpecialization(NewVD, Previous))
7340       NewVD->setInvalidDecl();
7341 
7342     // Merge the decl with the existing one if appropriate.
7343     if (!Previous.empty()) {
7344       if (Previous.isSingleResult() &&
7345           isa<FieldDecl>(Previous.getFoundDecl()) &&
7346           D.getCXXScopeSpec().isSet()) {
7347         // The user tried to define a non-static data member
7348         // out-of-line (C++ [dcl.meaning]p1).
7349         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7350           << D.getCXXScopeSpec().getRange();
7351         Previous.clear();
7352         NewVD->setInvalidDecl();
7353       }
7354     } else if (D.getCXXScopeSpec().isSet()) {
7355       // No previous declaration in the qualifying scope.
7356       Diag(D.getIdentifierLoc(), diag::err_no_member)
7357         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7358         << D.getCXXScopeSpec().getRange();
7359       NewVD->setInvalidDecl();
7360     }
7361 
7362     if (!IsVariableTemplateSpecialization)
7363       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7364 
7365     if (NewTemplate) {
7366       VarTemplateDecl *PrevVarTemplate =
7367           NewVD->getPreviousDecl()
7368               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7369               : nullptr;
7370 
7371       // Check the template parameter list of this declaration, possibly
7372       // merging in the template parameter list from the previous variable
7373       // template declaration.
7374       if (CheckTemplateParameterList(
7375               TemplateParams,
7376               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7377                               : nullptr,
7378               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7379                DC->isDependentContext())
7380                   ? TPC_ClassTemplateMember
7381                   : TPC_VarTemplate))
7382         NewVD->setInvalidDecl();
7383 
7384       // If we are providing an explicit specialization of a static variable
7385       // template, make a note of that.
7386       if (PrevVarTemplate &&
7387           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7388         PrevVarTemplate->setMemberSpecialization();
7389     }
7390   }
7391 
7392   // Diagnose shadowed variables iff this isn't a redeclaration.
7393   if (ShadowedDecl && !D.isRedeclaration())
7394     CheckShadow(NewVD, ShadowedDecl, Previous);
7395 
7396   ProcessPragmaWeak(S, NewVD);
7397 
7398   // If this is the first declaration of an extern C variable, update
7399   // the map of such variables.
7400   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7401       isIncompleteDeclExternC(*this, NewVD))
7402     RegisterLocallyScopedExternCDecl(NewVD, S);
7403 
7404   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7405     MangleNumberingContext *MCtx;
7406     Decl *ManglingContextDecl;
7407     std::tie(MCtx, ManglingContextDecl) =
7408         getCurrentMangleNumberContext(NewVD->getDeclContext());
7409     if (MCtx) {
7410       Context.setManglingNumber(
7411           NewVD, MCtx->getManglingNumber(
7412                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7413       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7414     }
7415   }
7416 
7417   // Special handling of variable named 'main'.
7418   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7419       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7420       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7421 
7422     // C++ [basic.start.main]p3
7423     // A program that declares a variable main at global scope is ill-formed.
7424     if (getLangOpts().CPlusPlus)
7425       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7426 
7427     // In C, and external-linkage variable named main results in undefined
7428     // behavior.
7429     else if (NewVD->hasExternalFormalLinkage())
7430       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7431   }
7432 
7433   if (D.isRedeclaration() && !Previous.empty()) {
7434     NamedDecl *Prev = Previous.getRepresentativeDecl();
7435     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7436                                    D.isFunctionDefinition());
7437   }
7438 
7439   if (NewTemplate) {
7440     if (NewVD->isInvalidDecl())
7441       NewTemplate->setInvalidDecl();
7442     ActOnDocumentableDecl(NewTemplate);
7443     return NewTemplate;
7444   }
7445 
7446   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7447     CompleteMemberSpecialization(NewVD, Previous);
7448 
7449   return NewVD;
7450 }
7451 
7452 /// Enum describing the %select options in diag::warn_decl_shadow.
7453 enum ShadowedDeclKind {
7454   SDK_Local,
7455   SDK_Global,
7456   SDK_StaticMember,
7457   SDK_Field,
7458   SDK_Typedef,
7459   SDK_Using
7460 };
7461 
7462 /// Determine what kind of declaration we're shadowing.
computeShadowedDeclKind(const NamedDecl * ShadowedDecl,const DeclContext * OldDC)7463 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7464                                                 const DeclContext *OldDC) {
7465   if (isa<TypeAliasDecl>(ShadowedDecl))
7466     return SDK_Using;
7467   else if (isa<TypedefDecl>(ShadowedDecl))
7468     return SDK_Typedef;
7469   else if (isa<RecordDecl>(OldDC))
7470     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7471 
7472   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7473 }
7474 
7475 /// Return the location of the capture if the given lambda captures the given
7476 /// variable \p VD, or an invalid source location otherwise.
getCaptureLocation(const LambdaScopeInfo * LSI,const VarDecl * VD)7477 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7478                                          const VarDecl *VD) {
7479   for (const Capture &Capture : LSI->Captures) {
7480     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7481       return Capture.getLocation();
7482   }
7483   return SourceLocation();
7484 }
7485 
shouldWarnIfShadowedDecl(const DiagnosticsEngine & Diags,const LookupResult & R)7486 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7487                                      const LookupResult &R) {
7488   // Only diagnose if we're shadowing an unambiguous field or variable.
7489   if (R.getResultKind() != LookupResult::Found)
7490     return false;
7491 
7492   // Return false if warning is ignored.
7493   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7494 }
7495 
7496 /// Return the declaration shadowed by the given variable \p D, or null
7497 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
getShadowedDeclaration(const VarDecl * D,const LookupResult & R)7498 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7499                                         const LookupResult &R) {
7500   if (!shouldWarnIfShadowedDecl(Diags, R))
7501     return nullptr;
7502 
7503   // Don't diagnose declarations at file scope.
7504   if (D->hasGlobalStorage())
7505     return nullptr;
7506 
7507   NamedDecl *ShadowedDecl = R.getFoundDecl();
7508   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7509              ? ShadowedDecl
7510              : nullptr;
7511 }
7512 
7513 /// Return the declaration shadowed by the given typedef \p D, or null
7514 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
getShadowedDeclaration(const TypedefNameDecl * D,const LookupResult & R)7515 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7516                                         const LookupResult &R) {
7517   // Don't warn if typedef declaration is part of a class
7518   if (D->getDeclContext()->isRecord())
7519     return nullptr;
7520 
7521   if (!shouldWarnIfShadowedDecl(Diags, R))
7522     return nullptr;
7523 
7524   NamedDecl *ShadowedDecl = R.getFoundDecl();
7525   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7526 }
7527 
7528 /// Diagnose variable or built-in function shadowing.  Implements
7529 /// -Wshadow.
7530 ///
7531 /// This method is called whenever a VarDecl is added to a "useful"
7532 /// scope.
7533 ///
7534 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7535 /// \param R the lookup of the name
7536 ///
CheckShadow(NamedDecl * D,NamedDecl * ShadowedDecl,const LookupResult & R)7537 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7538                        const LookupResult &R) {
7539   DeclContext *NewDC = D->getDeclContext();
7540 
7541   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7542     // Fields are not shadowed by variables in C++ static methods.
7543     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7544       if (MD->isStatic())
7545         return;
7546 
7547     // Fields shadowed by constructor parameters are a special case. Usually
7548     // the constructor initializes the field with the parameter.
7549     if (isa<CXXConstructorDecl>(NewDC))
7550       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7551         // Remember that this was shadowed so we can either warn about its
7552         // modification or its existence depending on warning settings.
7553         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7554         return;
7555       }
7556   }
7557 
7558   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7559     if (shadowedVar->isExternC()) {
7560       // For shadowing external vars, make sure that we point to the global
7561       // declaration, not a locally scoped extern declaration.
7562       for (auto I : shadowedVar->redecls())
7563         if (I->isFileVarDecl()) {
7564           ShadowedDecl = I;
7565           break;
7566         }
7567     }
7568 
7569   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7570 
7571   unsigned WarningDiag = diag::warn_decl_shadow;
7572   SourceLocation CaptureLoc;
7573   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7574       isa<CXXMethodDecl>(NewDC)) {
7575     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7576       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7577         if (RD->getLambdaCaptureDefault() == LCD_None) {
7578           // Try to avoid warnings for lambdas with an explicit capture list.
7579           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7580           // Warn only when the lambda captures the shadowed decl explicitly.
7581           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7582           if (CaptureLoc.isInvalid())
7583             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7584         } else {
7585           // Remember that this was shadowed so we can avoid the warning if the
7586           // shadowed decl isn't captured and the warning settings allow it.
7587           cast<LambdaScopeInfo>(getCurFunction())
7588               ->ShadowingDecls.push_back(
7589                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7590           return;
7591         }
7592       }
7593 
7594       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7595         // A variable can't shadow a local variable in an enclosing scope, if
7596         // they are separated by a non-capturing declaration context.
7597         for (DeclContext *ParentDC = NewDC;
7598              ParentDC && !ParentDC->Equals(OldDC);
7599              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7600           // Only block literals, captured statements, and lambda expressions
7601           // can capture; other scopes don't.
7602           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7603               !isLambdaCallOperator(ParentDC)) {
7604             return;
7605           }
7606         }
7607       }
7608     }
7609   }
7610 
7611   // Only warn about certain kinds of shadowing for class members.
7612   if (NewDC && NewDC->isRecord()) {
7613     // In particular, don't warn about shadowing non-class members.
7614     if (!OldDC->isRecord())
7615       return;
7616 
7617     // TODO: should we warn about static data members shadowing
7618     // static data members from base classes?
7619 
7620     // TODO: don't diagnose for inaccessible shadowed members.
7621     // This is hard to do perfectly because we might friend the
7622     // shadowing context, but that's just a false negative.
7623   }
7624 
7625 
7626   DeclarationName Name = R.getLookupName();
7627 
7628   // Emit warning and note.
7629   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7630     return;
7631   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7632   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7633   if (!CaptureLoc.isInvalid())
7634     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7635         << Name << /*explicitly*/ 1;
7636   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7637 }
7638 
7639 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7640 /// when these variables are captured by the lambda.
DiagnoseShadowingLambdaDecls(const LambdaScopeInfo * LSI)7641 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7642   for (const auto &Shadow : LSI->ShadowingDecls) {
7643     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7644     // Try to avoid the warning when the shadowed decl isn't captured.
7645     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7646     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7647     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7648                                        ? diag::warn_decl_shadow_uncaptured_local
7649                                        : diag::warn_decl_shadow)
7650         << Shadow.VD->getDeclName()
7651         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7652     if (!CaptureLoc.isInvalid())
7653       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7654           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7655     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7656   }
7657 }
7658 
7659 /// Check -Wshadow without the advantage of a previous lookup.
CheckShadow(Scope * S,VarDecl * D)7660 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7661   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7662     return;
7663 
7664   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7665                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7666   LookupName(R, S);
7667   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7668     CheckShadow(D, ShadowedDecl, R);
7669 }
7670 
7671 /// Check if 'E', which is an expression that is about to be modified, refers
7672 /// to a constructor parameter that shadows a field.
CheckShadowingDeclModification(Expr * E,SourceLocation Loc)7673 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7674   // Quickly ignore expressions that can't be shadowing ctor parameters.
7675   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7676     return;
7677   E = E->IgnoreParenImpCasts();
7678   auto *DRE = dyn_cast<DeclRefExpr>(E);
7679   if (!DRE)
7680     return;
7681   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7682   auto I = ShadowingDecls.find(D);
7683   if (I == ShadowingDecls.end())
7684     return;
7685   const NamedDecl *ShadowedDecl = I->second;
7686   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7687   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7688   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7689   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7690 
7691   // Avoid issuing multiple warnings about the same decl.
7692   ShadowingDecls.erase(I);
7693 }
7694 
7695 /// Check for conflict between this global or extern "C" declaration and
7696 /// previous global or extern "C" declarations. This is only used in C++.
7697 template<typename T>
checkGlobalOrExternCConflict(Sema & S,const T * ND,bool IsGlobal,LookupResult & Previous)7698 static bool checkGlobalOrExternCConflict(
7699     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7700   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7701   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7702 
7703   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7704     // The common case: this global doesn't conflict with any extern "C"
7705     // declaration.
7706     return false;
7707   }
7708 
7709   if (Prev) {
7710     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7711       // Both the old and new declarations have C language linkage. This is a
7712       // redeclaration.
7713       Previous.clear();
7714       Previous.addDecl(Prev);
7715       return true;
7716     }
7717 
7718     // This is a global, non-extern "C" declaration, and there is a previous
7719     // non-global extern "C" declaration. Diagnose if this is a variable
7720     // declaration.
7721     if (!isa<VarDecl>(ND))
7722       return false;
7723   } else {
7724     // The declaration is extern "C". Check for any declaration in the
7725     // translation unit which might conflict.
7726     if (IsGlobal) {
7727       // We have already performed the lookup into the translation unit.
7728       IsGlobal = false;
7729       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7730            I != E; ++I) {
7731         if (isa<VarDecl>(*I)) {
7732           Prev = *I;
7733           break;
7734         }
7735       }
7736     } else {
7737       DeclContext::lookup_result R =
7738           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7739       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7740            I != E; ++I) {
7741         if (isa<VarDecl>(*I)) {
7742           Prev = *I;
7743           break;
7744         }
7745         // FIXME: If we have any other entity with this name in global scope,
7746         // the declaration is ill-formed, but that is a defect: it breaks the
7747         // 'stat' hack, for instance. Only variables can have mangled name
7748         // clashes with extern "C" declarations, so only they deserve a
7749         // diagnostic.
7750       }
7751     }
7752 
7753     if (!Prev)
7754       return false;
7755   }
7756 
7757   // Use the first declaration's location to ensure we point at something which
7758   // is lexically inside an extern "C" linkage-spec.
7759   assert(Prev && "should have found a previous declaration to diagnose");
7760   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7761     Prev = FD->getFirstDecl();
7762   else
7763     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7764 
7765   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7766     << IsGlobal << ND;
7767   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7768     << IsGlobal;
7769   return false;
7770 }
7771 
7772 /// Apply special rules for handling extern "C" declarations. Returns \c true
7773 /// if we have found that this is a redeclaration of some prior entity.
7774 ///
7775 /// Per C++ [dcl.link]p6:
7776 ///   Two declarations [for a function or variable] with C language linkage
7777 ///   with the same name that appear in different scopes refer to the same
7778 ///   [entity]. An entity with C language linkage shall not be declared with
7779 ///   the same name as an entity in global scope.
7780 template<typename T>
checkForConflictWithNonVisibleExternC(Sema & S,const T * ND,LookupResult & Previous)7781 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7782                                                   LookupResult &Previous) {
7783   if (!S.getLangOpts().CPlusPlus) {
7784     // In C, when declaring a global variable, look for a corresponding 'extern'
7785     // variable declared in function scope. We don't need this in C++, because
7786     // we find local extern decls in the surrounding file-scope DeclContext.
7787     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7788       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7789         Previous.clear();
7790         Previous.addDecl(Prev);
7791         return true;
7792       }
7793     }
7794     return false;
7795   }
7796 
7797   // A declaration in the translation unit can conflict with an extern "C"
7798   // declaration.
7799   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7800     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7801 
7802   // An extern "C" declaration can conflict with a declaration in the
7803   // translation unit or can be a redeclaration of an extern "C" declaration
7804   // in another scope.
7805   if (isIncompleteDeclExternC(S,ND))
7806     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7807 
7808   // Neither global nor extern "C": nothing to do.
7809   return false;
7810 }
7811 
CheckVariableDeclarationType(VarDecl * NewVD)7812 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7813   // If the decl is already known invalid, don't check it.
7814   if (NewVD->isInvalidDecl())
7815     return;
7816 
7817   QualType T = NewVD->getType();
7818 
7819   // Defer checking an 'auto' type until its initializer is attached.
7820   if (T->isUndeducedType())
7821     return;
7822 
7823   if (NewVD->hasAttrs())
7824     CheckAlignasUnderalignment(NewVD);
7825 
7826   if (T->isObjCObjectType()) {
7827     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7828       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7829     T = Context.getObjCObjectPointerType(T);
7830     NewVD->setType(T);
7831   }
7832 
7833   // Emit an error if an address space was applied to decl with local storage.
7834   // This includes arrays of objects with address space qualifiers, but not
7835   // automatic variables that point to other address spaces.
7836   // ISO/IEC TR 18037 S5.1.2
7837   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7838       T.getAddressSpace() != LangAS::Default) {
7839     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7840     NewVD->setInvalidDecl();
7841     return;
7842   }
7843 
7844   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7845   // scope.
7846   if (getLangOpts().OpenCLVersion == 120 &&
7847       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7848       NewVD->isStaticLocal()) {
7849     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7850     NewVD->setInvalidDecl();
7851     return;
7852   }
7853 
7854   if (getLangOpts().OpenCL) {
7855     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7856     if (NewVD->hasAttr<BlocksAttr>()) {
7857       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7858       return;
7859     }
7860 
7861     if (T->isBlockPointerType()) {
7862       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7863       // can't use 'extern' storage class.
7864       if (!T.isConstQualified()) {
7865         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7866             << 0 /*const*/;
7867         NewVD->setInvalidDecl();
7868         return;
7869       }
7870       if (NewVD->hasExternalStorage()) {
7871         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7872         NewVD->setInvalidDecl();
7873         return;
7874       }
7875     }
7876     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7877     // __constant address space.
7878     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7879     // variables inside a function can also be declared in the global
7880     // address space.
7881     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7882     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7883     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7884         NewVD->hasExternalStorage()) {
7885       if (!T->isSamplerT() &&
7886           !T->isDependentType() &&
7887           !(T.getAddressSpace() == LangAS::opencl_constant ||
7888             (T.getAddressSpace() == LangAS::opencl_global &&
7889              (getLangOpts().OpenCLVersion == 200 ||
7890               getLangOpts().OpenCLCPlusPlus)))) {
7891         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7892         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7893           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7894               << Scope << "global or constant";
7895         else
7896           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7897               << Scope << "constant";
7898         NewVD->setInvalidDecl();
7899         return;
7900       }
7901     } else {
7902       if (T.getAddressSpace() == LangAS::opencl_global) {
7903         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7904             << 1 /*is any function*/ << "global";
7905         NewVD->setInvalidDecl();
7906         return;
7907       }
7908       if (T.getAddressSpace() == LangAS::opencl_constant ||
7909           T.getAddressSpace() == LangAS::opencl_local) {
7910         FunctionDecl *FD = getCurFunctionDecl();
7911         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7912         // in functions.
7913         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7914           if (T.getAddressSpace() == LangAS::opencl_constant)
7915             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7916                 << 0 /*non-kernel only*/ << "constant";
7917           else
7918             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7919                 << 0 /*non-kernel only*/ << "local";
7920           NewVD->setInvalidDecl();
7921           return;
7922         }
7923         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7924         // in the outermost scope of a kernel function.
7925         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7926           if (!getCurScope()->isFunctionScope()) {
7927             if (T.getAddressSpace() == LangAS::opencl_constant)
7928               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7929                   << "constant";
7930             else
7931               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7932                   << "local";
7933             NewVD->setInvalidDecl();
7934             return;
7935           }
7936         }
7937       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7938                  // If we are parsing a template we didn't deduce an addr
7939                  // space yet.
7940                  T.getAddressSpace() != LangAS::Default) {
7941         // Do not allow other address spaces on automatic variable.
7942         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7943         NewVD->setInvalidDecl();
7944         return;
7945       }
7946     }
7947   }
7948 
7949   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7950       && !NewVD->hasAttr<BlocksAttr>()) {
7951     if (getLangOpts().getGC() != LangOptions::NonGC)
7952       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7953     else {
7954       assert(!getLangOpts().ObjCAutoRefCount);
7955       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7956     }
7957   }
7958 
7959   bool isVM = T->isVariablyModifiedType();
7960   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7961       NewVD->hasAttr<BlocksAttr>())
7962     setFunctionHasBranchProtectedScope();
7963 
7964   if ((isVM && NewVD->hasLinkage()) ||
7965       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7966     bool SizeIsNegative;
7967     llvm::APSInt Oversized;
7968     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7969         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7970     QualType FixedT;
7971     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7972       FixedT = FixedTInfo->getType();
7973     else if (FixedTInfo) {
7974       // Type and type-as-written are canonically different. We need to fix up
7975       // both types separately.
7976       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7977                                                    Oversized);
7978     }
7979     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7980       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7981       // FIXME: This won't give the correct result for
7982       // int a[10][n];
7983       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7984 
7985       if (NewVD->isFileVarDecl())
7986         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7987         << SizeRange;
7988       else if (NewVD->isStaticLocal())
7989         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7990         << SizeRange;
7991       else
7992         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7993         << SizeRange;
7994       NewVD->setInvalidDecl();
7995       return;
7996     }
7997 
7998     if (!FixedTInfo) {
7999       if (NewVD->isFileVarDecl())
8000         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8001       else
8002         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8003       NewVD->setInvalidDecl();
8004       return;
8005     }
8006 
8007     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
8008     NewVD->setType(FixedT);
8009     NewVD->setTypeSourceInfo(FixedTInfo);
8010   }
8011 
8012   if (T->isVoidType()) {
8013     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8014     //                    of objects and functions.
8015     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8016       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8017         << T;
8018       NewVD->setInvalidDecl();
8019       return;
8020     }
8021   }
8022 
8023   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8024     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8025     NewVD->setInvalidDecl();
8026     return;
8027   }
8028 
8029   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8030     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8031     NewVD->setInvalidDecl();
8032     return;
8033   }
8034 
8035   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8036     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8037     NewVD->setInvalidDecl();
8038     return;
8039   }
8040 
8041   if (NewVD->isConstexpr() && !T->isDependentType() &&
8042       RequireLiteralType(NewVD->getLocation(), T,
8043                          diag::err_constexpr_var_non_literal)) {
8044     NewVD->setInvalidDecl();
8045     return;
8046   }
8047 }
8048 
8049 /// Perform semantic checking on a newly-created variable
8050 /// declaration.
8051 ///
8052 /// This routine performs all of the type-checking required for a
8053 /// variable declaration once it has been built. It is used both to
8054 /// check variables after they have been parsed and their declarators
8055 /// have been translated into a declaration, and to check variables
8056 /// that have been instantiated from a template.
8057 ///
8058 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8059 ///
8060 /// Returns true if the variable declaration is a redeclaration.
CheckVariableDeclaration(VarDecl * NewVD,LookupResult & Previous)8061 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8062   CheckVariableDeclarationType(NewVD);
8063 
8064   // If the decl is already known invalid, don't check it.
8065   if (NewVD->isInvalidDecl())
8066     return false;
8067 
8068   // If we did not find anything by this name, look for a non-visible
8069   // extern "C" declaration with the same name.
8070   if (Previous.empty() &&
8071       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8072     Previous.setShadowed();
8073 
8074   if (!Previous.empty()) {
8075     MergeVarDecl(NewVD, Previous);
8076     return true;
8077   }
8078   return false;
8079 }
8080 
8081 namespace {
8082 struct FindOverriddenMethod {
8083   Sema *S;
8084   CXXMethodDecl *Method;
8085 
8086   /// Member lookup function that determines whether a given C++
8087   /// method overrides a method in a base class, to be used with
8088   /// CXXRecordDecl::lookupInBases().
operator ()__anon87d11b5b0a11::FindOverriddenMethod8089   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8090     RecordDecl *BaseRecord =
8091         Specifier->getType()->castAs<RecordType>()->getDecl();
8092 
8093     DeclarationName Name = Method->getDeclName();
8094 
8095     // FIXME: Do we care about other names here too?
8096     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8097       // We really want to find the base class destructor here.
8098       QualType T = S->Context.getTypeDeclType(BaseRecord);
8099       CanQualType CT = S->Context.getCanonicalType(T);
8100 
8101       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
8102     }
8103 
8104     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8105          Path.Decls = Path.Decls.slice(1)) {
8106       NamedDecl *D = Path.Decls.front();
8107       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8108         if (MD->isVirtual() &&
8109             !S->IsOverload(
8110                 Method, MD, /*UseMemberUsingDeclRules=*/false,
8111                 /*ConsiderCudaAttrs=*/true,
8112                 // C++2a [class.virtual]p2 does not consider requires clauses
8113                 // when overriding.
8114                 /*ConsiderRequiresClauses=*/false))
8115           return true;
8116       }
8117     }
8118 
8119     return false;
8120   }
8121 };
8122 } // end anonymous namespace
8123 
8124 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8125 /// and if so, check that it's a valid override and remember it.
AddOverriddenMethods(CXXRecordDecl * DC,CXXMethodDecl * MD)8126 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8127   // Look for methods in base classes that this method might override.
8128   CXXBasePaths Paths;
8129   FindOverriddenMethod FOM;
8130   FOM.Method = MD;
8131   FOM.S = this;
8132   bool AddedAny = false;
8133   if (DC->lookupInBases(FOM, Paths)) {
8134     for (auto *I : Paths.found_decls()) {
8135       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
8136         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
8137         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
8138             !CheckOverridingFunctionAttributes(MD, OldMD) &&
8139             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
8140             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
8141           AddedAny = true;
8142         }
8143       }
8144     }
8145   }
8146 
8147   return AddedAny;
8148 }
8149 
8150 namespace {
8151   // Struct for holding all of the extra arguments needed by
8152   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8153   struct ActOnFDArgs {
8154     Scope *S;
8155     Declarator &D;
8156     MultiTemplateParamsArg TemplateParamLists;
8157     bool AddToScope;
8158   };
8159 } // end anonymous namespace
8160 
8161 namespace {
8162 
8163 // Callback to only accept typo corrections that have a non-zero edit distance.
8164 // Also only accept corrections that have the same parent decl.
8165 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8166  public:
DifferentNameValidatorCCC(ASTContext & Context,FunctionDecl * TypoFD,CXXRecordDecl * Parent)8167   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8168                             CXXRecordDecl *Parent)
8169       : Context(Context), OriginalFD(TypoFD),
8170         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8171 
ValidateCandidate(const TypoCorrection & candidate)8172   bool ValidateCandidate(const TypoCorrection &candidate) override {
8173     if (candidate.getEditDistance() == 0)
8174       return false;
8175 
8176     SmallVector<unsigned, 1> MismatchedParams;
8177     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8178                                           CDeclEnd = candidate.end();
8179          CDecl != CDeclEnd; ++CDecl) {
8180       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8181 
8182       if (FD && !FD->hasBody() &&
8183           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8184         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8185           CXXRecordDecl *Parent = MD->getParent();
8186           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8187             return true;
8188         } else if (!ExpectedParent) {
8189           return true;
8190         }
8191       }
8192     }
8193 
8194     return false;
8195   }
8196 
clone()8197   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8198     return std::make_unique<DifferentNameValidatorCCC>(*this);
8199   }
8200 
8201  private:
8202   ASTContext &Context;
8203   FunctionDecl *OriginalFD;
8204   CXXRecordDecl *ExpectedParent;
8205 };
8206 
8207 } // end anonymous namespace
8208 
MarkTypoCorrectedFunctionDefinition(const NamedDecl * F)8209 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8210   TypoCorrectedFunctionDefinitions.insert(F);
8211 }
8212 
8213 /// Generate diagnostics for an invalid function redeclaration.
8214 ///
8215 /// This routine handles generating the diagnostic messages for an invalid
8216 /// function redeclaration, including finding possible similar declarations
8217 /// or performing typo correction if there are no previous declarations with
8218 /// the same name.
8219 ///
8220 /// Returns a NamedDecl iff typo correction was performed and substituting in
8221 /// the new declaration name does not cause new errors.
DiagnoseInvalidRedeclaration(Sema & SemaRef,LookupResult & Previous,FunctionDecl * NewFD,ActOnFDArgs & ExtraArgs,bool IsLocalFriend,Scope * S)8222 static NamedDecl *DiagnoseInvalidRedeclaration(
8223     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8224     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8225   DeclarationName Name = NewFD->getDeclName();
8226   DeclContext *NewDC = NewFD->getDeclContext();
8227   SmallVector<unsigned, 1> MismatchedParams;
8228   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8229   TypoCorrection Correction;
8230   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8231   unsigned DiagMsg =
8232     IsLocalFriend ? diag::err_no_matching_local_friend :
8233     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8234     diag::err_member_decl_does_not_match;
8235   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8236                     IsLocalFriend ? Sema::LookupLocalFriendName
8237                                   : Sema::LookupOrdinaryName,
8238                     Sema::ForVisibleRedeclaration);
8239 
8240   NewFD->setInvalidDecl();
8241   if (IsLocalFriend)
8242     SemaRef.LookupName(Prev, S);
8243   else
8244     SemaRef.LookupQualifiedName(Prev, NewDC);
8245   assert(!Prev.isAmbiguous() &&
8246          "Cannot have an ambiguity in previous-declaration lookup");
8247   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8248   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8249                                 MD ? MD->getParent() : nullptr);
8250   if (!Prev.empty()) {
8251     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8252          Func != FuncEnd; ++Func) {
8253       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8254       if (FD &&
8255           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8256         // Add 1 to the index so that 0 can mean the mismatch didn't
8257         // involve a parameter
8258         unsigned ParamNum =
8259             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8260         NearMatches.push_back(std::make_pair(FD, ParamNum));
8261       }
8262     }
8263   // If the qualified name lookup yielded nothing, try typo correction
8264   } else if ((Correction = SemaRef.CorrectTypo(
8265                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8266                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8267                   IsLocalFriend ? nullptr : NewDC))) {
8268     // Set up everything for the call to ActOnFunctionDeclarator
8269     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8270                               ExtraArgs.D.getIdentifierLoc());
8271     Previous.clear();
8272     Previous.setLookupName(Correction.getCorrection());
8273     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8274                                     CDeclEnd = Correction.end();
8275          CDecl != CDeclEnd; ++CDecl) {
8276       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8277       if (FD && !FD->hasBody() &&
8278           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8279         Previous.addDecl(FD);
8280       }
8281     }
8282     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8283 
8284     NamedDecl *Result;
8285     // Retry building the function declaration with the new previous
8286     // declarations, and with errors suppressed.
8287     {
8288       // Trap errors.
8289       Sema::SFINAETrap Trap(SemaRef);
8290 
8291       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8292       // pieces need to verify the typo-corrected C++ declaration and hopefully
8293       // eliminate the need for the parameter pack ExtraArgs.
8294       Result = SemaRef.ActOnFunctionDeclarator(
8295           ExtraArgs.S, ExtraArgs.D,
8296           Correction.getCorrectionDecl()->getDeclContext(),
8297           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8298           ExtraArgs.AddToScope);
8299 
8300       if (Trap.hasErrorOccurred())
8301         Result = nullptr;
8302     }
8303 
8304     if (Result) {
8305       // Determine which correction we picked.
8306       Decl *Canonical = Result->getCanonicalDecl();
8307       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8308            I != E; ++I)
8309         if ((*I)->getCanonicalDecl() == Canonical)
8310           Correction.setCorrectionDecl(*I);
8311 
8312       // Let Sema know about the correction.
8313       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8314       SemaRef.diagnoseTypo(
8315           Correction,
8316           SemaRef.PDiag(IsLocalFriend
8317                           ? diag::err_no_matching_local_friend_suggest
8318                           : diag::err_member_decl_does_not_match_suggest)
8319             << Name << NewDC << IsDefinition);
8320       return Result;
8321     }
8322 
8323     // Pretend the typo correction never occurred
8324     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8325                               ExtraArgs.D.getIdentifierLoc());
8326     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8327     Previous.clear();
8328     Previous.setLookupName(Name);
8329   }
8330 
8331   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8332       << Name << NewDC << IsDefinition << NewFD->getLocation();
8333 
8334   bool NewFDisConst = false;
8335   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8336     NewFDisConst = NewMD->isConst();
8337 
8338   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8339        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8340        NearMatch != NearMatchEnd; ++NearMatch) {
8341     FunctionDecl *FD = NearMatch->first;
8342     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8343     bool FDisConst = MD && MD->isConst();
8344     bool IsMember = MD || !IsLocalFriend;
8345 
8346     // FIXME: These notes are poorly worded for the local friend case.
8347     if (unsigned Idx = NearMatch->second) {
8348       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8349       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8350       if (Loc.isInvalid()) Loc = FD->getLocation();
8351       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8352                                  : diag::note_local_decl_close_param_match)
8353         << Idx << FDParam->getType()
8354         << NewFD->getParamDecl(Idx - 1)->getType();
8355     } else if (FDisConst != NewFDisConst) {
8356       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8357           << NewFDisConst << FD->getSourceRange().getEnd();
8358     } else
8359       SemaRef.Diag(FD->getLocation(),
8360                    IsMember ? diag::note_member_def_close_match
8361                             : diag::note_local_decl_close_match);
8362   }
8363   return nullptr;
8364 }
8365 
getFunctionStorageClass(Sema & SemaRef,Declarator & D)8366 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8367   switch (D.getDeclSpec().getStorageClassSpec()) {
8368   default: llvm_unreachable("Unknown storage class!");
8369   case DeclSpec::SCS_auto:
8370   case DeclSpec::SCS_register:
8371   case DeclSpec::SCS_mutable:
8372     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8373                  diag::err_typecheck_sclass_func);
8374     D.getMutableDeclSpec().ClearStorageClassSpecs();
8375     D.setInvalidType();
8376     break;
8377   case DeclSpec::SCS_unspecified: break;
8378   case DeclSpec::SCS_extern:
8379     if (D.getDeclSpec().isExternInLinkageSpec())
8380       return SC_None;
8381     return SC_Extern;
8382   case DeclSpec::SCS_static: {
8383     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8384       // C99 6.7.1p5:
8385       //   The declaration of an identifier for a function that has
8386       //   block scope shall have no explicit storage-class specifier
8387       //   other than extern
8388       // See also (C++ [dcl.stc]p4).
8389       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8390                    diag::err_static_block_func);
8391       break;
8392     } else
8393       return SC_Static;
8394   }
8395   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8396   }
8397 
8398   // No explicit storage class has already been returned
8399   return SC_None;
8400 }
8401 
CreateNewFunctionDecl(Sema & SemaRef,Declarator & D,DeclContext * DC,QualType & R,TypeSourceInfo * TInfo,StorageClass SC,bool & IsVirtualOkay)8402 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8403                                            DeclContext *DC, QualType &R,
8404                                            TypeSourceInfo *TInfo,
8405                                            StorageClass SC,
8406                                            bool &IsVirtualOkay) {
8407   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8408   DeclarationName Name = NameInfo.getName();
8409 
8410   FunctionDecl *NewFD = nullptr;
8411   bool isInline = D.getDeclSpec().isInlineSpecified();
8412 
8413   if (!SemaRef.getLangOpts().CPlusPlus) {
8414     // Determine whether the function was written with a
8415     // prototype. This true when:
8416     //   - there is a prototype in the declarator, or
8417     //   - the type R of the function is some kind of typedef or other non-
8418     //     attributed reference to a type name (which eventually refers to a
8419     //     function type).
8420     bool HasPrototype =
8421       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8422       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8423 
8424     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8425                                  R, TInfo, SC, isInline, HasPrototype,
8426                                  CSK_unspecified,
8427                                  /*TrailingRequiresClause=*/nullptr);
8428     if (D.isInvalidType())
8429       NewFD->setInvalidDecl();
8430 
8431     return NewFD;
8432   }
8433 
8434   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8435 
8436   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8437   if (ConstexprKind == CSK_constinit) {
8438     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8439                  diag::err_constexpr_wrong_decl_kind)
8440         << ConstexprKind;
8441     ConstexprKind = CSK_unspecified;
8442     D.getMutableDeclSpec().ClearConstexprSpec();
8443   }
8444   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8445 
8446   // Check that the return type is not an abstract class type.
8447   // For record types, this is done by the AbstractClassUsageDiagnoser once
8448   // the class has been completely parsed.
8449   if (!DC->isRecord() &&
8450       SemaRef.RequireNonAbstractType(
8451           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8452           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8453     D.setInvalidType();
8454 
8455   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8456     // This is a C++ constructor declaration.
8457     assert(DC->isRecord() &&
8458            "Constructors can only be declared in a member context");
8459 
8460     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8461     return CXXConstructorDecl::Create(
8462         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8463         TInfo, ExplicitSpecifier, isInline,
8464         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8465         TrailingRequiresClause);
8466 
8467   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8468     // This is a C++ destructor declaration.
8469     if (DC->isRecord()) {
8470       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8471       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8472       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8473           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8474           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8475           TrailingRequiresClause);
8476 
8477       // If the destructor needs an implicit exception specification, set it
8478       // now. FIXME: It'd be nice to be able to create the right type to start
8479       // with, but the type needs to reference the destructor declaration.
8480       if (SemaRef.getLangOpts().CPlusPlus11)
8481         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8482 
8483       IsVirtualOkay = true;
8484       return NewDD;
8485 
8486     } else {
8487       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8488       D.setInvalidType();
8489 
8490       // Create a FunctionDecl to satisfy the function definition parsing
8491       // code path.
8492       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8493                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8494                                   isInline,
8495                                   /*hasPrototype=*/true, ConstexprKind,
8496                                   TrailingRequiresClause);
8497     }
8498 
8499   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8500     if (!DC->isRecord()) {
8501       SemaRef.Diag(D.getIdentifierLoc(),
8502            diag::err_conv_function_not_member);
8503       return nullptr;
8504     }
8505 
8506     SemaRef.CheckConversionDeclarator(D, R, SC);
8507     if (D.isInvalidType())
8508       return nullptr;
8509 
8510     IsVirtualOkay = true;
8511     return CXXConversionDecl::Create(
8512         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8513         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8514         TrailingRequiresClause);
8515 
8516   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8517     if (TrailingRequiresClause)
8518       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8519                    diag::err_trailing_requires_clause_on_deduction_guide)
8520           << TrailingRequiresClause->getSourceRange();
8521     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8522 
8523     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8524                                          ExplicitSpecifier, NameInfo, R, TInfo,
8525                                          D.getEndLoc());
8526   } else if (DC->isRecord()) {
8527     // If the name of the function is the same as the name of the record,
8528     // then this must be an invalid constructor that has a return type.
8529     // (The parser checks for a return type and makes the declarator a
8530     // constructor if it has no return type).
8531     if (Name.getAsIdentifierInfo() &&
8532         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8533       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8534         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8535         << SourceRange(D.getIdentifierLoc());
8536       return nullptr;
8537     }
8538 
8539     // This is a C++ method declaration.
8540     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8541         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8542         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8543         TrailingRequiresClause);
8544     IsVirtualOkay = !Ret->isStatic();
8545     return Ret;
8546   } else {
8547     bool isFriend =
8548         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8549     if (!isFriend && SemaRef.CurContext->isRecord())
8550       return nullptr;
8551 
8552     // Determine whether the function was written with a
8553     // prototype. This true when:
8554     //   - we're in C++ (where every function has a prototype),
8555     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8556                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8557                                 ConstexprKind, TrailingRequiresClause);
8558   }
8559 }
8560 
8561 enum OpenCLParamType {
8562   ValidKernelParam,
8563   PtrPtrKernelParam,
8564   PtrKernelParam,
8565   InvalidAddrSpacePtrKernelParam,
8566   InvalidKernelParam,
8567   RecordKernelParam
8568 };
8569 
isOpenCLSizeDependentType(ASTContext & C,QualType Ty)8570 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8571   // Size dependent types are just typedefs to normal integer types
8572   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8573   // integers other than by their names.
8574   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8575 
8576   // Remove typedefs one by one until we reach a typedef
8577   // for a size dependent type.
8578   QualType DesugaredTy = Ty;
8579   do {
8580     ArrayRef<StringRef> Names(SizeTypeNames);
8581     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8582     if (Names.end() != Match)
8583       return true;
8584 
8585     Ty = DesugaredTy;
8586     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8587   } while (DesugaredTy != Ty);
8588 
8589   return false;
8590 }
8591 
getOpenCLKernelParameterType(Sema & S,QualType PT)8592 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8593   if (PT->isPointerType()) {
8594     QualType PointeeType = PT->getPointeeType();
8595     if (PointeeType->isPointerType())
8596       return PtrPtrKernelParam;
8597     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8598         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8599         PointeeType.getAddressSpace() == LangAS::Default)
8600       return InvalidAddrSpacePtrKernelParam;
8601     return PtrKernelParam;
8602   }
8603 
8604   // OpenCL v1.2 s6.9.k:
8605   // Arguments to kernel functions in a program cannot be declared with the
8606   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8607   // uintptr_t or a struct and/or union that contain fields declared to be one
8608   // of these built-in scalar types.
8609   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8610     return InvalidKernelParam;
8611 
8612   if (PT->isImageType())
8613     return PtrKernelParam;
8614 
8615   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8616     return InvalidKernelParam;
8617 
8618   // OpenCL extension spec v1.2 s9.5:
8619   // This extension adds support for half scalar and vector types as built-in
8620   // types that can be used for arithmetic operations, conversions etc.
8621   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8622     return InvalidKernelParam;
8623 
8624   if (PT->isRecordType())
8625     return RecordKernelParam;
8626 
8627   // Look into an array argument to check if it has a forbidden type.
8628   if (PT->isArrayType()) {
8629     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8630     // Call ourself to check an underlying type of an array. Since the
8631     // getPointeeOrArrayElementType returns an innermost type which is not an
8632     // array, this recursive call only happens once.
8633     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8634   }
8635 
8636   return ValidKernelParam;
8637 }
8638 
checkIsValidOpenCLKernelParameter(Sema & S,Declarator & D,ParmVarDecl * Param,llvm::SmallPtrSetImpl<const Type * > & ValidTypes)8639 static void checkIsValidOpenCLKernelParameter(
8640   Sema &S,
8641   Declarator &D,
8642   ParmVarDecl *Param,
8643   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8644   QualType PT = Param->getType();
8645 
8646   // Cache the valid types we encounter to avoid rechecking structs that are
8647   // used again
8648   if (ValidTypes.count(PT.getTypePtr()))
8649     return;
8650 
8651   switch (getOpenCLKernelParameterType(S, PT)) {
8652   case PtrPtrKernelParam:
8653     // OpenCL v1.2 s6.9.a:
8654     // A kernel function argument cannot be declared as a
8655     // pointer to a pointer type.
8656     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8657     D.setInvalidType();
8658     return;
8659 
8660   case InvalidAddrSpacePtrKernelParam:
8661     // OpenCL v1.0 s6.5:
8662     // __kernel function arguments declared to be a pointer of a type can point
8663     // to one of the following address spaces only : __global, __local or
8664     // __constant.
8665     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8666     D.setInvalidType();
8667     return;
8668 
8669     // OpenCL v1.2 s6.9.k:
8670     // Arguments to kernel functions in a program cannot be declared with the
8671     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8672     // uintptr_t or a struct and/or union that contain fields declared to be
8673     // one of these built-in scalar types.
8674 
8675   case InvalidKernelParam:
8676     // OpenCL v1.2 s6.8 n:
8677     // A kernel function argument cannot be declared
8678     // of event_t type.
8679     // Do not diagnose half type since it is diagnosed as invalid argument
8680     // type for any function elsewhere.
8681     if (!PT->isHalfType()) {
8682       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8683 
8684       // Explain what typedefs are involved.
8685       const TypedefType *Typedef = nullptr;
8686       while ((Typedef = PT->getAs<TypedefType>())) {
8687         SourceLocation Loc = Typedef->getDecl()->getLocation();
8688         // SourceLocation may be invalid for a built-in type.
8689         if (Loc.isValid())
8690           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8691         PT = Typedef->desugar();
8692       }
8693     }
8694 
8695     D.setInvalidType();
8696     return;
8697 
8698   case PtrKernelParam:
8699   case ValidKernelParam:
8700     ValidTypes.insert(PT.getTypePtr());
8701     return;
8702 
8703   case RecordKernelParam:
8704     break;
8705   }
8706 
8707   // Track nested structs we will inspect
8708   SmallVector<const Decl *, 4> VisitStack;
8709 
8710   // Track where we are in the nested structs. Items will migrate from
8711   // VisitStack to HistoryStack as we do the DFS for bad field.
8712   SmallVector<const FieldDecl *, 4> HistoryStack;
8713   HistoryStack.push_back(nullptr);
8714 
8715   // At this point we already handled everything except of a RecordType or
8716   // an ArrayType of a RecordType.
8717   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8718   const RecordType *RecTy =
8719       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8720   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8721 
8722   VisitStack.push_back(RecTy->getDecl());
8723   assert(VisitStack.back() && "First decl null?");
8724 
8725   do {
8726     const Decl *Next = VisitStack.pop_back_val();
8727     if (!Next) {
8728       assert(!HistoryStack.empty());
8729       // Found a marker, we have gone up a level
8730       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8731         ValidTypes.insert(Hist->getType().getTypePtr());
8732 
8733       continue;
8734     }
8735 
8736     // Adds everything except the original parameter declaration (which is not a
8737     // field itself) to the history stack.
8738     const RecordDecl *RD;
8739     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8740       HistoryStack.push_back(Field);
8741 
8742       QualType FieldTy = Field->getType();
8743       // Other field types (known to be valid or invalid) are handled while we
8744       // walk around RecordDecl::fields().
8745       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8746              "Unexpected type.");
8747       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8748 
8749       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8750     } else {
8751       RD = cast<RecordDecl>(Next);
8752     }
8753 
8754     // Add a null marker so we know when we've gone back up a level
8755     VisitStack.push_back(nullptr);
8756 
8757     for (const auto *FD : RD->fields()) {
8758       QualType QT = FD->getType();
8759 
8760       if (ValidTypes.count(QT.getTypePtr()))
8761         continue;
8762 
8763       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8764       if (ParamType == ValidKernelParam)
8765         continue;
8766 
8767       if (ParamType == RecordKernelParam) {
8768         VisitStack.push_back(FD);
8769         continue;
8770       }
8771 
8772       // OpenCL v1.2 s6.9.p:
8773       // Arguments to kernel functions that are declared to be a struct or union
8774       // do not allow OpenCL objects to be passed as elements of the struct or
8775       // union.
8776       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8777           ParamType == InvalidAddrSpacePtrKernelParam) {
8778         S.Diag(Param->getLocation(),
8779                diag::err_record_with_pointers_kernel_param)
8780           << PT->isUnionType()
8781           << PT;
8782       } else {
8783         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8784       }
8785 
8786       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8787           << OrigRecDecl->getDeclName();
8788 
8789       // We have an error, now let's go back up through history and show where
8790       // the offending field came from
8791       for (ArrayRef<const FieldDecl *>::const_iterator
8792                I = HistoryStack.begin() + 1,
8793                E = HistoryStack.end();
8794            I != E; ++I) {
8795         const FieldDecl *OuterField = *I;
8796         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8797           << OuterField->getType();
8798       }
8799 
8800       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8801         << QT->isPointerType()
8802         << QT;
8803       D.setInvalidType();
8804       return;
8805     }
8806   } while (!VisitStack.empty());
8807 }
8808 
8809 /// Find the DeclContext in which a tag is implicitly declared if we see an
8810 /// elaborated type specifier in the specified context, and lookup finds
8811 /// nothing.
getTagInjectionContext(DeclContext * DC)8812 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8813   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8814     DC = DC->getParent();
8815   return DC;
8816 }
8817 
8818 /// Find the Scope in which a tag is implicitly declared if we see an
8819 /// elaborated type specifier in the specified context, and lookup finds
8820 /// nothing.
getTagInjectionScope(Scope * S,const LangOptions & LangOpts)8821 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8822   while (S->isClassScope() ||
8823          (LangOpts.CPlusPlus &&
8824           S->isFunctionPrototypeScope()) ||
8825          ((S->getFlags() & Scope::DeclScope) == 0) ||
8826          (S->getEntity() && S->getEntity()->isTransparentContext()))
8827     S = S->getParent();
8828   return S;
8829 }
8830 
8831 NamedDecl*
ActOnFunctionDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous,MultiTemplateParamsArg TemplateParamListsRef,bool & AddToScope)8832 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8833                               TypeSourceInfo *TInfo, LookupResult &Previous,
8834                               MultiTemplateParamsArg TemplateParamListsRef,
8835                               bool &AddToScope) {
8836   QualType R = TInfo->getType();
8837 
8838   assert(R->isFunctionType());
8839   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8840     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8841 
8842   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8843   for (TemplateParameterList *TPL : TemplateParamListsRef)
8844     TemplateParamLists.push_back(TPL);
8845   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8846     if (!TemplateParamLists.empty() &&
8847         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8848       TemplateParamLists.back() = Invented;
8849     else
8850       TemplateParamLists.push_back(Invented);
8851   }
8852 
8853   // TODO: consider using NameInfo for diagnostic.
8854   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8855   DeclarationName Name = NameInfo.getName();
8856   StorageClass SC = getFunctionStorageClass(*this, D);
8857 
8858   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8859     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8860          diag::err_invalid_thread)
8861       << DeclSpec::getSpecifierName(TSCS);
8862 
8863   if (D.isFirstDeclarationOfMember())
8864     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8865                            D.getIdentifierLoc());
8866 
8867   bool isFriend = false;
8868   FunctionTemplateDecl *FunctionTemplate = nullptr;
8869   bool isMemberSpecialization = false;
8870   bool isFunctionTemplateSpecialization = false;
8871 
8872   bool isDependentClassScopeExplicitSpecialization = false;
8873   bool HasExplicitTemplateArgs = false;
8874   TemplateArgumentListInfo TemplateArgs;
8875 
8876   bool isVirtualOkay = false;
8877 
8878   DeclContext *OriginalDC = DC;
8879   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8880 
8881   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8882                                               isVirtualOkay);
8883   if (!NewFD) return nullptr;
8884 
8885   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8886     NewFD->setTopLevelDeclInObjCContainer();
8887 
8888   // Set the lexical context. If this is a function-scope declaration, or has a
8889   // C++ scope specifier, or is the object of a friend declaration, the lexical
8890   // context will be different from the semantic context.
8891   NewFD->setLexicalDeclContext(CurContext);
8892 
8893   if (IsLocalExternDecl)
8894     NewFD->setLocalExternDecl();
8895 
8896   if (getLangOpts().CPlusPlus) {
8897     bool isInline = D.getDeclSpec().isInlineSpecified();
8898     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8899     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8900     isFriend = D.getDeclSpec().isFriendSpecified();
8901     if (isFriend && !isInline && D.isFunctionDefinition()) {
8902       // C++ [class.friend]p5
8903       //   A function can be defined in a friend declaration of a
8904       //   class . . . . Such a function is implicitly inline.
8905       NewFD->setImplicitlyInline();
8906     }
8907 
8908     // If this is a method defined in an __interface, and is not a constructor
8909     // or an overloaded operator, then set the pure flag (isVirtual will already
8910     // return true).
8911     if (const CXXRecordDecl *Parent =
8912           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8913       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8914         NewFD->setPure(true);
8915 
8916       // C++ [class.union]p2
8917       //   A union can have member functions, but not virtual functions.
8918       if (isVirtual && Parent->isUnion())
8919         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8920     }
8921 
8922     SetNestedNameSpecifier(*this, NewFD, D);
8923     isMemberSpecialization = false;
8924     isFunctionTemplateSpecialization = false;
8925     if (D.isInvalidType())
8926       NewFD->setInvalidDecl();
8927 
8928     // Match up the template parameter lists with the scope specifier, then
8929     // determine whether we have a template or a template specialization.
8930     bool Invalid = false;
8931     TemplateParameterList *TemplateParams =
8932         MatchTemplateParametersToScopeSpecifier(
8933             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8934             D.getCXXScopeSpec(),
8935             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8936                 ? D.getName().TemplateId
8937                 : nullptr,
8938             TemplateParamLists, isFriend, isMemberSpecialization,
8939             Invalid);
8940     if (TemplateParams) {
8941       if (TemplateParams->size() > 0) {
8942         // This is a function template
8943 
8944         // Check that we can declare a template here.
8945         if (CheckTemplateDeclScope(S, TemplateParams))
8946           NewFD->setInvalidDecl();
8947 
8948         // A destructor cannot be a template.
8949         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8950           Diag(NewFD->getLocation(), diag::err_destructor_template);
8951           NewFD->setInvalidDecl();
8952         }
8953 
8954         // If we're adding a template to a dependent context, we may need to
8955         // rebuilding some of the types used within the template parameter list,
8956         // now that we know what the current instantiation is.
8957         if (DC->isDependentContext()) {
8958           ContextRAII SavedContext(*this, DC);
8959           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8960             Invalid = true;
8961         }
8962 
8963         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8964                                                         NewFD->getLocation(),
8965                                                         Name, TemplateParams,
8966                                                         NewFD);
8967         FunctionTemplate->setLexicalDeclContext(CurContext);
8968         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8969 
8970         // For source fidelity, store the other template param lists.
8971         if (TemplateParamLists.size() > 1) {
8972           NewFD->setTemplateParameterListsInfo(Context,
8973               ArrayRef<TemplateParameterList *>(TemplateParamLists)
8974                   .drop_back(1));
8975         }
8976       } else {
8977         // This is a function template specialization.
8978         isFunctionTemplateSpecialization = true;
8979         // For source fidelity, store all the template param lists.
8980         if (TemplateParamLists.size() > 0)
8981           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8982 
8983         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8984         if (isFriend) {
8985           // We want to remove the "template<>", found here.
8986           SourceRange RemoveRange = TemplateParams->getSourceRange();
8987 
8988           // If we remove the template<> and the name is not a
8989           // template-id, we're actually silently creating a problem:
8990           // the friend declaration will refer to an untemplated decl,
8991           // and clearly the user wants a template specialization.  So
8992           // we need to insert '<>' after the name.
8993           SourceLocation InsertLoc;
8994           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8995             InsertLoc = D.getName().getSourceRange().getEnd();
8996             InsertLoc = getLocForEndOfToken(InsertLoc);
8997           }
8998 
8999           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9000             << Name << RemoveRange
9001             << FixItHint::CreateRemoval(RemoveRange)
9002             << FixItHint::CreateInsertion(InsertLoc, "<>");
9003         }
9004       }
9005     } else {
9006       // All template param lists were matched against the scope specifier:
9007       // this is NOT (an explicit specialization of) a template.
9008       if (TemplateParamLists.size() > 0)
9009         // For source fidelity, store all the template param lists.
9010         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9011     }
9012 
9013     if (Invalid) {
9014       NewFD->setInvalidDecl();
9015       if (FunctionTemplate)
9016         FunctionTemplate->setInvalidDecl();
9017     }
9018 
9019     // C++ [dcl.fct.spec]p5:
9020     //   The virtual specifier shall only be used in declarations of
9021     //   nonstatic class member functions that appear within a
9022     //   member-specification of a class declaration; see 10.3.
9023     //
9024     if (isVirtual && !NewFD->isInvalidDecl()) {
9025       if (!isVirtualOkay) {
9026         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9027              diag::err_virtual_non_function);
9028       } else if (!CurContext->isRecord()) {
9029         // 'virtual' was specified outside of the class.
9030         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9031              diag::err_virtual_out_of_class)
9032           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9033       } else if (NewFD->getDescribedFunctionTemplate()) {
9034         // C++ [temp.mem]p3:
9035         //  A member function template shall not be virtual.
9036         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9037              diag::err_virtual_member_function_template)
9038           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9039       } else {
9040         // Okay: Add virtual to the method.
9041         NewFD->setVirtualAsWritten(true);
9042       }
9043 
9044       if (getLangOpts().CPlusPlus14 &&
9045           NewFD->getReturnType()->isUndeducedType())
9046         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9047     }
9048 
9049     if (getLangOpts().CPlusPlus14 &&
9050         (NewFD->isDependentContext() ||
9051          (isFriend && CurContext->isDependentContext())) &&
9052         NewFD->getReturnType()->isUndeducedType()) {
9053       // If the function template is referenced directly (for instance, as a
9054       // member of the current instantiation), pretend it has a dependent type.
9055       // This is not really justified by the standard, but is the only sane
9056       // thing to do.
9057       // FIXME: For a friend function, we have not marked the function as being
9058       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9059       const FunctionProtoType *FPT =
9060           NewFD->getType()->castAs<FunctionProtoType>();
9061       QualType Result =
9062           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9063       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9064                                              FPT->getExtProtoInfo()));
9065     }
9066 
9067     // C++ [dcl.fct.spec]p3:
9068     //  The inline specifier shall not appear on a block scope function
9069     //  declaration.
9070     if (isInline && !NewFD->isInvalidDecl()) {
9071       if (CurContext->isFunctionOrMethod()) {
9072         // 'inline' is not allowed on block scope function declaration.
9073         Diag(D.getDeclSpec().getInlineSpecLoc(),
9074              diag::err_inline_declaration_block_scope) << Name
9075           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9076       }
9077     }
9078 
9079     // C++ [dcl.fct.spec]p6:
9080     //  The explicit specifier shall be used only in the declaration of a
9081     //  constructor or conversion function within its class definition;
9082     //  see 12.3.1 and 12.3.2.
9083     if (hasExplicit && !NewFD->isInvalidDecl() &&
9084         !isa<CXXDeductionGuideDecl>(NewFD)) {
9085       if (!CurContext->isRecord()) {
9086         // 'explicit' was specified outside of the class.
9087         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9088              diag::err_explicit_out_of_class)
9089             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9090       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9091                  !isa<CXXConversionDecl>(NewFD)) {
9092         // 'explicit' was specified on a function that wasn't a constructor
9093         // or conversion function.
9094         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9095              diag::err_explicit_non_ctor_or_conv_function)
9096             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9097       }
9098     }
9099 
9100     if (ConstexprSpecKind ConstexprKind =
9101             D.getDeclSpec().getConstexprSpecifier()) {
9102       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9103       // are implicitly inline.
9104       NewFD->setImplicitlyInline();
9105 
9106       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9107       // be either constructors or to return a literal type. Therefore,
9108       // destructors cannot be declared constexpr.
9109       if (isa<CXXDestructorDecl>(NewFD) &&
9110           (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) {
9111         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9112             << ConstexprKind;
9113         NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr);
9114       }
9115       // C++20 [dcl.constexpr]p2: An allocation function, or a
9116       // deallocation function shall not be declared with the consteval
9117       // specifier.
9118       if (ConstexprKind == CSK_consteval &&
9119           (NewFD->getOverloadedOperator() == OO_New ||
9120            NewFD->getOverloadedOperator() == OO_Array_New ||
9121            NewFD->getOverloadedOperator() == OO_Delete ||
9122            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9123         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9124              diag::err_invalid_consteval_decl_kind)
9125             << NewFD;
9126         NewFD->setConstexprKind(CSK_constexpr);
9127       }
9128     }
9129 
9130     // If __module_private__ was specified, mark the function accordingly.
9131     if (D.getDeclSpec().isModulePrivateSpecified()) {
9132       if (isFunctionTemplateSpecialization) {
9133         SourceLocation ModulePrivateLoc
9134           = D.getDeclSpec().getModulePrivateSpecLoc();
9135         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9136           << 0
9137           << FixItHint::CreateRemoval(ModulePrivateLoc);
9138       } else {
9139         NewFD->setModulePrivate();
9140         if (FunctionTemplate)
9141           FunctionTemplate->setModulePrivate();
9142       }
9143     }
9144 
9145     if (isFriend) {
9146       if (FunctionTemplate) {
9147         FunctionTemplate->setObjectOfFriendDecl();
9148         FunctionTemplate->setAccess(AS_public);
9149       }
9150       NewFD->setObjectOfFriendDecl();
9151       NewFD->setAccess(AS_public);
9152     }
9153 
9154     // If a function is defined as defaulted or deleted, mark it as such now.
9155     // We'll do the relevant checks on defaulted / deleted functions later.
9156     switch (D.getFunctionDefinitionKind()) {
9157       case FDK_Declaration:
9158       case FDK_Definition:
9159         break;
9160 
9161       case FDK_Defaulted:
9162         NewFD->setDefaulted();
9163         break;
9164 
9165       case FDK_Deleted:
9166         NewFD->setDeletedAsWritten();
9167         break;
9168     }
9169 
9170     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9171         D.isFunctionDefinition()) {
9172       // C++ [class.mfct]p2:
9173       //   A member function may be defined (8.4) in its class definition, in
9174       //   which case it is an inline member function (7.1.2)
9175       NewFD->setImplicitlyInline();
9176     }
9177 
9178     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9179         !CurContext->isRecord()) {
9180       // C++ [class.static]p1:
9181       //   A data or function member of a class may be declared static
9182       //   in a class definition, in which case it is a static member of
9183       //   the class.
9184 
9185       // Complain about the 'static' specifier if it's on an out-of-line
9186       // member function definition.
9187 
9188       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9189       // member function template declaration and class member template
9190       // declaration (MSVC versions before 2015), warn about this.
9191       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9192            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9193              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9194            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9195            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9196         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9197     }
9198 
9199     // C++11 [except.spec]p15:
9200     //   A deallocation function with no exception-specification is treated
9201     //   as if it were specified with noexcept(true).
9202     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9203     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9204          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9205         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9206       NewFD->setType(Context.getFunctionType(
9207           FPT->getReturnType(), FPT->getParamTypes(),
9208           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9209   }
9210 
9211   // Filter out previous declarations that don't match the scope.
9212   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9213                        D.getCXXScopeSpec().isNotEmpty() ||
9214                        isMemberSpecialization ||
9215                        isFunctionTemplateSpecialization);
9216 
9217   // Handle GNU asm-label extension (encoded as an attribute).
9218   if (Expr *E = (Expr*) D.getAsmLabel()) {
9219     // The parser guarantees this is a string.
9220     StringLiteral *SE = cast<StringLiteral>(E);
9221     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9222                                         /*IsLiteralLabel=*/true,
9223                                         SE->getStrTokenLoc(0)));
9224   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9225     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9226       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9227     if (I != ExtnameUndeclaredIdentifiers.end()) {
9228       if (isDeclExternC(NewFD)) {
9229         NewFD->addAttr(I->second);
9230         ExtnameUndeclaredIdentifiers.erase(I);
9231       } else
9232         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9233             << /*Variable*/0 << NewFD;
9234     }
9235   }
9236 
9237   // Copy the parameter declarations from the declarator D to the function
9238   // declaration NewFD, if they are available.  First scavenge them into Params.
9239   SmallVector<ParmVarDecl*, 16> Params;
9240   unsigned FTIIdx;
9241   if (D.isFunctionDeclarator(FTIIdx)) {
9242     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9243 
9244     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9245     // function that takes no arguments, not a function that takes a
9246     // single void argument.
9247     // We let through "const void" here because Sema::GetTypeForDeclarator
9248     // already checks for that case.
9249     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9250       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9251         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9252         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9253         Param->setDeclContext(NewFD);
9254         Params.push_back(Param);
9255 
9256         if (Param->isInvalidDecl())
9257           NewFD->setInvalidDecl();
9258       }
9259     }
9260 
9261     if (!getLangOpts().CPlusPlus) {
9262       // In C, find all the tag declarations from the prototype and move them
9263       // into the function DeclContext. Remove them from the surrounding tag
9264       // injection context of the function, which is typically but not always
9265       // the TU.
9266       DeclContext *PrototypeTagContext =
9267           getTagInjectionContext(NewFD->getLexicalDeclContext());
9268       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9269         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9270 
9271         // We don't want to reparent enumerators. Look at their parent enum
9272         // instead.
9273         if (!TD) {
9274           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9275             TD = cast<EnumDecl>(ECD->getDeclContext());
9276         }
9277         if (!TD)
9278           continue;
9279         DeclContext *TagDC = TD->getLexicalDeclContext();
9280         if (!TagDC->containsDecl(TD))
9281           continue;
9282         TagDC->removeDecl(TD);
9283         TD->setDeclContext(NewFD);
9284         NewFD->addDecl(TD);
9285 
9286         // Preserve the lexical DeclContext if it is not the surrounding tag
9287         // injection context of the FD. In this example, the semantic context of
9288         // E will be f and the lexical context will be S, while both the
9289         // semantic and lexical contexts of S will be f:
9290         //   void f(struct S { enum E { a } f; } s);
9291         if (TagDC != PrototypeTagContext)
9292           TD->setLexicalDeclContext(TagDC);
9293       }
9294     }
9295   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9296     // When we're declaring a function with a typedef, typeof, etc as in the
9297     // following example, we'll need to synthesize (unnamed)
9298     // parameters for use in the declaration.
9299     //
9300     // @code
9301     // typedef void fn(int);
9302     // fn f;
9303     // @endcode
9304 
9305     // Synthesize a parameter for each argument type.
9306     for (const auto &AI : FT->param_types()) {
9307       ParmVarDecl *Param =
9308           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9309       Param->setScopeInfo(0, Params.size());
9310       Params.push_back(Param);
9311     }
9312   } else {
9313     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9314            "Should not need args for typedef of non-prototype fn");
9315   }
9316 
9317   // Finally, we know we have the right number of parameters, install them.
9318   NewFD->setParams(Params);
9319 
9320   if (D.getDeclSpec().isNoreturnSpecified())
9321     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9322                                            D.getDeclSpec().getNoreturnSpecLoc(),
9323                                            AttributeCommonInfo::AS_Keyword));
9324 
9325   // Functions returning a variably modified type violate C99 6.7.5.2p2
9326   // because all functions have linkage.
9327   if (!NewFD->isInvalidDecl() &&
9328       NewFD->getReturnType()->isVariablyModifiedType()) {
9329     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9330     NewFD->setInvalidDecl();
9331   }
9332 
9333   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9334   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9335       !NewFD->hasAttr<SectionAttr>())
9336     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9337         Context, PragmaClangTextSection.SectionName,
9338         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9339 
9340   // Apply an implicit SectionAttr if #pragma code_seg is active.
9341   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9342       !NewFD->hasAttr<SectionAttr>()) {
9343     NewFD->addAttr(SectionAttr::CreateImplicit(
9344         Context, CodeSegStack.CurrentValue->getString(),
9345         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9346         SectionAttr::Declspec_allocate));
9347     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9348                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9349                          ASTContext::PSF_Read,
9350                      NewFD))
9351       NewFD->dropAttr<SectionAttr>();
9352   }
9353 
9354   // Apply an implicit CodeSegAttr from class declspec or
9355   // apply an implicit SectionAttr from #pragma code_seg if active.
9356   if (!NewFD->hasAttr<CodeSegAttr>()) {
9357     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9358                                                                  D.isFunctionDefinition())) {
9359       NewFD->addAttr(SAttr);
9360     }
9361   }
9362 
9363   // Handle attributes.
9364   ProcessDeclAttributes(S, NewFD, D);
9365 
9366   if (NewFD->hasAttr<PointerInterpretationCapsAttr>()) {
9367     // FIXME: This will assert on failure - it should print a nice error.
9368     //unsigned CapAS = Context.getTargetInfo() .AddressSpaceForCapabilities();
9369     const FunctionProtoType *FPT =
9370       NewFD->getType()->getAs<FunctionProtoType>();
9371     ArrayRef<QualType> OldParams = FPT->getParamTypes();
9372     llvm::SmallVector<QualType, 8> NewParams;
9373     for (QualType T : OldParams) {
9374       if (const PointerType *PT = T->getAs<PointerType>())
9375         NewParams.push_back(Context.getPointerType(PT->getPointeeType(),
9376                                                    PIK_Capability));
9377       else
9378         NewParams.push_back(T);
9379     }
9380     QualType RetTy = FPT->getReturnType();
9381     if (const PointerType *PT = RetTy->getAs<PointerType>())
9382       RetTy = Context.getPointerType(PT->getPointeeType(),
9383                                      PIK_Capability);
9384     NewFD->setType(Context.getFunctionType(RetTy, NewParams,
9385           FPT->getExtProtoInfo()));
9386   }
9387 
9388   QualType RetType = NewFD->getReturnType();
9389 
9390   if (CHERIMethodSuffixAttr *Attr = NewFD->getAttr<CHERIMethodSuffixAttr>()) {
9391     auto *TU = Context.getTranslationUnitDecl();
9392     // Lookup the type of cheri_object, or generate it if it isn't specified.
9393     QualType CHERIClassTy;
9394     IdentifierInfo &ClassII = Context.Idents.get("cheri_object");
9395     DeclarationName ClassDN(&ClassII);
9396     auto Defs = TU->lookup(ClassDN);
9397     for (NamedDecl *D : Defs)
9398       if (RecordDecl *RD = dyn_cast<RecordDecl>(D))
9399         CHERIClassTy = Context.getTypeDeclType(RD);
9400     if (CHERIClassTy == QualType())
9401       CHERIClassTy = Context.getCHERIClassType();
9402     // Construct a new function prototype that is the same as the original,
9403     // except that it has an extra struct cheri_object as the first argument.
9404     const FunctionProtoType *OFT =
9405       NewFD->getType()->getAs<FunctionProtoType>();
9406     const ArrayRef<QualType> Params = OFT->getParamTypes();
9407     SmallVector<QualType, 16> NewParams;
9408     NewParams.push_back(CHERIClassTy);
9409     NewParams.insert(NewParams.end(), Params.begin(), Params.end());
9410     FunctionProtoType::ExtProtoInfo EPI = OFT->getExtProtoInfo();
9411     EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_CHERICCall);
9412     QualType WrappedType = Context.getFunctionType(RetType, NewParams, EPI);
9413     // Construct the new function name, taking the old one and adding the
9414     // suffix.
9415     std::string Name = (NewFD->getName() + Attr->getSuffix()).str();
9416     IdentifierInfo &II = Context.Idents.get(Name);
9417     DeclarationName DN(&II);
9418     DeclarationNameInfo DNI(DN, SourceLocation());
9419     // construct the function decl and its associated parameter decls
9420     FunctionDecl *WrappedFD = FunctionDecl::Create(Context,
9421         NewFD->getDeclContext(), NewFD->getTypeSpecStartLoc(), DNI,
9422         WrappedType, TInfo, SC_Extern, false, true, CSK_unspecified, nullptr);
9423     SmallVector<ParmVarDecl*, 16> Parms;
9424     for (QualType Ty : NewParams) {
9425       Parms.push_back(ParmVarDecl::Create(Context, NewFD, SourceLocation(),
9426             SourceLocation(), nullptr, Ty, Context.getTrivialTypeSourceInfo(Ty,
9427               SourceLocation()), SC_None, nullptr));
9428     }
9429     WrappedFD->setParams(Parms);
9430     // Propagate the default class (the calling convention is copied
9431     // automatically).  This won't be used in the suffixed version, but is used
9432     // to look up the method number.
9433     if (CHERIMethodClassAttr *Cls = NewFD->getAttr<CHERIMethodClassAttr>())
9434       WrappedFD->addAttr(Cls->clone(Context));
9435     WrappedFD->addAttr(Attr->clone(Context));
9436     Attr->setSuffix(Context, "");
9437     // Make the new prototype visible.
9438     NewFD->getLexicalDeclContext()->addDecl(WrappedFD);
9439     S->AddDecl(WrappedFD);
9440     IdResolver.AddDecl(WrappedFD);
9441   }
9442 
9443   if (getLangOpts().OpenCL) {
9444     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9445     // type declaration will generate a compilation error.
9446     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9447     if (AddressSpace != LangAS::Default) {
9448       Diag(NewFD->getLocation(),
9449            diag::err_opencl_return_value_with_address_space);
9450       NewFD->setInvalidDecl();
9451     }
9452   }
9453 
9454   if (!getLangOpts().CPlusPlus) {
9455     // Perform semantic checking on the function declaration.
9456     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9457       CheckMain(NewFD, D.getDeclSpec());
9458 
9459     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9460       CheckMSVCRTEntryPoint(NewFD);
9461 
9462     if (!NewFD->isInvalidDecl())
9463       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9464                                                   isMemberSpecialization));
9465     else if (!Previous.empty())
9466       // Recover gracefully from an invalid redeclaration.
9467       D.setRedeclaration(true);
9468     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9469             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9470            "previous declaration set still overloaded");
9471 
9472     // Diagnose no-prototype function declarations with calling conventions that
9473     // don't support variadic calls. Only do this in C and do it after merging
9474     // possibly prototyped redeclarations.
9475     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9476     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9477       CallingConv CC = FT->getExtInfo().getCC();
9478       if (!supportsVariadicCall(CC)) {
9479         // Windows system headers sometimes accidentally use stdcall without
9480         // (void) parameters, so we relax this to a warning.
9481         int DiagID =
9482             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9483         Diag(NewFD->getLocation(), DiagID)
9484             << FunctionType::getNameForCallConv(CC);
9485       }
9486     }
9487 
9488    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9489        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9490      checkNonTrivialCUnion(NewFD->getReturnType(),
9491                            NewFD->getReturnTypeSourceRange().getBegin(),
9492                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9493   } else {
9494     // C++11 [replacement.functions]p3:
9495     //  The program's definitions shall not be specified as inline.
9496     //
9497     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9498     //
9499     // Suppress the diagnostic if the function is __attribute__((used)), since
9500     // that forces an external definition to be emitted.
9501     if (D.getDeclSpec().isInlineSpecified() &&
9502         NewFD->isReplaceableGlobalAllocationFunction() &&
9503         !NewFD->hasAttr<UsedAttr>())
9504       Diag(D.getDeclSpec().getInlineSpecLoc(),
9505            diag::ext_operator_new_delete_declared_inline)
9506         << NewFD->getDeclName();
9507 
9508     // If the declarator is a template-id, translate the parser's template
9509     // argument list into our AST format.
9510     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9511       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9512       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9513       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9514       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9515                                          TemplateId->NumArgs);
9516       translateTemplateArguments(TemplateArgsPtr,
9517                                  TemplateArgs);
9518 
9519       HasExplicitTemplateArgs = true;
9520 
9521       if (NewFD->isInvalidDecl()) {
9522         HasExplicitTemplateArgs = false;
9523       } else if (FunctionTemplate) {
9524         // Function template with explicit template arguments.
9525         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9526           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9527 
9528         HasExplicitTemplateArgs = false;
9529       } else {
9530         assert((isFunctionTemplateSpecialization ||
9531                 D.getDeclSpec().isFriendSpecified()) &&
9532                "should have a 'template<>' for this decl");
9533         // "friend void foo<>(int);" is an implicit specialization decl.
9534         isFunctionTemplateSpecialization = true;
9535       }
9536     } else if (isFriend && isFunctionTemplateSpecialization) {
9537       // This combination is only possible in a recovery case;  the user
9538       // wrote something like:
9539       //   template <> friend void foo(int);
9540       // which we're recovering from as if the user had written:
9541       //   friend void foo<>(int);
9542       // Go ahead and fake up a template id.
9543       HasExplicitTemplateArgs = true;
9544       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9545       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9546     }
9547 
9548     // We do not add HD attributes to specializations here because
9549     // they may have different constexpr-ness compared to their
9550     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9551     // may end up with different effective targets. Instead, a
9552     // specialization inherits its target attributes from its template
9553     // in the CheckFunctionTemplateSpecialization() call below.
9554     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9555       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9556 
9557     // If it's a friend (and only if it's a friend), it's possible
9558     // that either the specialized function type or the specialized
9559     // template is dependent, and therefore matching will fail.  In
9560     // this case, don't check the specialization yet.
9561     bool InstantiationDependent = false;
9562     if (isFunctionTemplateSpecialization && isFriend &&
9563         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9564          TemplateSpecializationType::anyDependentTemplateArguments(
9565             TemplateArgs,
9566             InstantiationDependent))) {
9567       assert(HasExplicitTemplateArgs &&
9568              "friend function specialization without template args");
9569       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9570                                                        Previous))
9571         NewFD->setInvalidDecl();
9572     } else if (isFunctionTemplateSpecialization) {
9573       if (CurContext->isDependentContext() && CurContext->isRecord()
9574           && !isFriend) {
9575         isDependentClassScopeExplicitSpecialization = true;
9576       } else if (!NewFD->isInvalidDecl() &&
9577                  CheckFunctionTemplateSpecialization(
9578                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9579                      Previous))
9580         NewFD->setInvalidDecl();
9581 
9582       // C++ [dcl.stc]p1:
9583       //   A storage-class-specifier shall not be specified in an explicit
9584       //   specialization (14.7.3)
9585       FunctionTemplateSpecializationInfo *Info =
9586           NewFD->getTemplateSpecializationInfo();
9587       if (Info && SC != SC_None) {
9588         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9589           Diag(NewFD->getLocation(),
9590                diag::err_explicit_specialization_inconsistent_storage_class)
9591             << SC
9592             << FixItHint::CreateRemoval(
9593                                       D.getDeclSpec().getStorageClassSpecLoc());
9594 
9595         else
9596           Diag(NewFD->getLocation(),
9597                diag::ext_explicit_specialization_storage_class)
9598             << FixItHint::CreateRemoval(
9599                                       D.getDeclSpec().getStorageClassSpecLoc());
9600       }
9601     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9602       if (CheckMemberSpecialization(NewFD, Previous))
9603           NewFD->setInvalidDecl();
9604     }
9605 
9606     // Perform semantic checking on the function declaration.
9607     if (!isDependentClassScopeExplicitSpecialization) {
9608       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9609         CheckMain(NewFD, D.getDeclSpec());
9610 
9611       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9612         CheckMSVCRTEntryPoint(NewFD);
9613 
9614       if (!NewFD->isInvalidDecl())
9615         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9616                                                     isMemberSpecialization));
9617       else if (!Previous.empty())
9618         // Recover gracefully from an invalid redeclaration.
9619         D.setRedeclaration(true);
9620     }
9621 
9622     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9623             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9624            "previous declaration set still overloaded");
9625 
9626     NamedDecl *PrincipalDecl = (FunctionTemplate
9627                                 ? cast<NamedDecl>(FunctionTemplate)
9628                                 : NewFD);
9629 
9630     if (isFriend && NewFD->getPreviousDecl()) {
9631       AccessSpecifier Access = AS_public;
9632       if (!NewFD->isInvalidDecl())
9633         Access = NewFD->getPreviousDecl()->getAccess();
9634 
9635       NewFD->setAccess(Access);
9636       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9637     }
9638 
9639     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9640         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9641       PrincipalDecl->setNonMemberOperator();
9642 
9643     // If we have a function template, check the template parameter
9644     // list. This will check and merge default template arguments.
9645     if (FunctionTemplate) {
9646       FunctionTemplateDecl *PrevTemplate =
9647                                      FunctionTemplate->getPreviousDecl();
9648       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9649                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9650                                     : nullptr,
9651                             D.getDeclSpec().isFriendSpecified()
9652                               ? (D.isFunctionDefinition()
9653                                    ? TPC_FriendFunctionTemplateDefinition
9654                                    : TPC_FriendFunctionTemplate)
9655                               : (D.getCXXScopeSpec().isSet() &&
9656                                  DC && DC->isRecord() &&
9657                                  DC->isDependentContext())
9658                                   ? TPC_ClassTemplateMember
9659                                   : TPC_FunctionTemplate);
9660     }
9661 
9662     if (NewFD->isInvalidDecl()) {
9663       // Ignore all the rest of this.
9664     } else if (!D.isRedeclaration()) {
9665       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9666                                        AddToScope };
9667       // Fake up an access specifier if it's supposed to be a class member.
9668       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9669         NewFD->setAccess(AS_public);
9670 
9671       // Qualified decls generally require a previous declaration.
9672       if (D.getCXXScopeSpec().isSet()) {
9673         // ...with the major exception of templated-scope or
9674         // dependent-scope friend declarations.
9675 
9676         // TODO: we currently also suppress this check in dependent
9677         // contexts because (1) the parameter depth will be off when
9678         // matching friend templates and (2) we might actually be
9679         // selecting a friend based on a dependent factor.  But there
9680         // are situations where these conditions don't apply and we
9681         // can actually do this check immediately.
9682         //
9683         // Unless the scope is dependent, it's always an error if qualified
9684         // redeclaration lookup found nothing at all. Diagnose that now;
9685         // nothing will diagnose that error later.
9686         if (isFriend &&
9687             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9688              (!Previous.empty() && CurContext->isDependentContext()))) {
9689           // ignore these
9690         } else {
9691           // The user tried to provide an out-of-line definition for a
9692           // function that is a member of a class or namespace, but there
9693           // was no such member function declared (C++ [class.mfct]p2,
9694           // C++ [namespace.memdef]p2). For example:
9695           //
9696           // class X {
9697           //   void f() const;
9698           // };
9699           //
9700           // void X::f() { } // ill-formed
9701           //
9702           // Complain about this problem, and attempt to suggest close
9703           // matches (e.g., those that differ only in cv-qualifiers and
9704           // whether the parameter types are references).
9705 
9706           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9707                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9708             AddToScope = ExtraArgs.AddToScope;
9709             return Result;
9710           }
9711         }
9712 
9713         // Unqualified local friend declarations are required to resolve
9714         // to something.
9715       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9716         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9717                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9718           AddToScope = ExtraArgs.AddToScope;
9719           return Result;
9720         }
9721       }
9722     } else if (!D.isFunctionDefinition() &&
9723                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9724                !isFriend && !isFunctionTemplateSpecialization &&
9725                !isMemberSpecialization) {
9726       // An out-of-line member function declaration must also be a
9727       // definition (C++ [class.mfct]p2).
9728       // Note that this is not the case for explicit specializations of
9729       // function templates or member functions of class templates, per
9730       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9731       // extension for compatibility with old SWIG code which likes to
9732       // generate them.
9733       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9734         << D.getCXXScopeSpec().getRange();
9735     }
9736   }
9737 
9738   ProcessPragmaWeak(S, NewFD);
9739   checkAttributesAfterMerging(*this, *NewFD);
9740 
9741   AddKnownFunctionAttributes(NewFD);
9742 
9743   if (NewFD->hasAttr<OverloadableAttr>() &&
9744       !NewFD->getType()->getAs<FunctionProtoType>()) {
9745     Diag(NewFD->getLocation(),
9746          diag::err_attribute_overloadable_no_prototype)
9747       << NewFD;
9748 
9749     // Turn this into a variadic function with no parameters.
9750     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9751     FunctionProtoType::ExtProtoInfo EPI(
9752         Context.getDefaultCallingConvention(true, false));
9753     EPI.Variadic = true;
9754     EPI.ExtInfo = FT->getExtInfo();
9755 
9756     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9757     NewFD->setType(R);
9758   }
9759 
9760   // If there's a #pragma GCC visibility in scope, and this isn't a class
9761   // member, set the visibility of this function.
9762   if (!DC->isRecord() && NewFD->isExternallyVisible())
9763     AddPushedVisibilityAttribute(NewFD);
9764 
9765   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9766   // marking the function.
9767   AddCFAuditedAttribute(NewFD);
9768 
9769   // If this is a function definition, check if we have to apply optnone due to
9770   // a pragma.
9771   if(D.isFunctionDefinition())
9772     AddRangeBasedOptnone(NewFD);
9773 
9774   // If this is the first declaration of an extern C variable, update
9775   // the map of such variables.
9776   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9777       isIncompleteDeclExternC(*this, NewFD))
9778     RegisterLocallyScopedExternCDecl(NewFD, S);
9779 
9780   // Set this FunctionDecl's range up to the right paren.
9781   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9782 
9783   if (D.isRedeclaration() && !Previous.empty()) {
9784     NamedDecl *Prev = Previous.getRepresentativeDecl();
9785     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9786                                    isMemberSpecialization ||
9787                                        isFunctionTemplateSpecialization,
9788                                    D.isFunctionDefinition());
9789   }
9790 
9791   if (getLangOpts().CUDA) {
9792     IdentifierInfo *II = NewFD->getIdentifier();
9793     if (II && II->isStr(getCudaConfigureFuncName()) &&
9794         !NewFD->isInvalidDecl() &&
9795         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9796       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9797         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9798             << getCudaConfigureFuncName();
9799       Context.setcudaConfigureCallDecl(NewFD);
9800     }
9801 
9802     // Variadic functions, other than a *declaration* of printf, are not allowed
9803     // in device-side CUDA code, unless someone passed
9804     // -fcuda-allow-variadic-functions.
9805     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9806         (NewFD->hasAttr<CUDADeviceAttr>() ||
9807          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9808         !(II && II->isStr("printf") && NewFD->isExternC() &&
9809           !D.isFunctionDefinition())) {
9810       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9811     }
9812   }
9813 
9814   MarkUnusedFileScopedDecl(NewFD);
9815 
9816 
9817 
9818   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9819     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9820     if ((getLangOpts().OpenCLVersion >= 120)
9821         && (SC == SC_Static)) {
9822       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9823       D.setInvalidType();
9824     }
9825 
9826     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9827     if (!NewFD->getReturnType()->isVoidType()) {
9828       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9829       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9830           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9831                                 : FixItHint());
9832       D.setInvalidType();
9833     }
9834 
9835     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9836     for (auto Param : NewFD->parameters())
9837       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9838 
9839     if (getLangOpts().OpenCLCPlusPlus) {
9840       if (DC->isRecord()) {
9841         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9842         D.setInvalidType();
9843       }
9844       if (FunctionTemplate) {
9845         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9846         D.setInvalidType();
9847       }
9848     }
9849   }
9850 
9851   if (getLangOpts().CPlusPlus) {
9852     if (FunctionTemplate) {
9853       if (NewFD->isInvalidDecl())
9854         FunctionTemplate->setInvalidDecl();
9855       return FunctionTemplate;
9856     }
9857 
9858     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9859       CompleteMemberSpecialization(NewFD, Previous);
9860   }
9861 
9862   for (const ParmVarDecl *Param : NewFD->parameters()) {
9863     QualType PT = Param->getType();
9864 
9865     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9866     // types.
9867     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9868       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9869         QualType ElemTy = PipeTy->getElementType();
9870           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9871             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9872             D.setInvalidType();
9873           }
9874       }
9875     }
9876   }
9877 
9878   // Here we have an function template explicit specialization at class scope.
9879   // The actual specialization will be postponed to template instatiation
9880   // time via the ClassScopeFunctionSpecializationDecl node.
9881   if (isDependentClassScopeExplicitSpecialization) {
9882     ClassScopeFunctionSpecializationDecl *NewSpec =
9883                          ClassScopeFunctionSpecializationDecl::Create(
9884                                 Context, CurContext, NewFD->getLocation(),
9885                                 cast<CXXMethodDecl>(NewFD),
9886                                 HasExplicitTemplateArgs, TemplateArgs);
9887     CurContext->addDecl(NewSpec);
9888     AddToScope = false;
9889   }
9890 
9891   // Diagnose availability attributes. Availability cannot be used on functions
9892   // that are run during load/unload.
9893   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9894     if (NewFD->hasAttr<ConstructorAttr>()) {
9895       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9896           << 1;
9897       NewFD->dropAttr<AvailabilityAttr>();
9898     }
9899     if (NewFD->hasAttr<DestructorAttr>()) {
9900       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9901           << 2;
9902       NewFD->dropAttr<AvailabilityAttr>();
9903     }
9904   }
9905 
9906   // Diagnose no_builtin attribute on function declaration that are not a
9907   // definition.
9908   // FIXME: We should really be doing this in
9909   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9910   // the FunctionDecl and at this point of the code
9911   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9912   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9913   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9914     switch (D.getFunctionDefinitionKind()) {
9915     case FDK_Defaulted:
9916     case FDK_Deleted:
9917       Diag(NBA->getLocation(),
9918            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9919           << NBA->getSpelling();
9920       break;
9921     case FDK_Declaration:
9922       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9923           << NBA->getSpelling();
9924       break;
9925     case FDK_Definition:
9926       break;
9927     }
9928 
9929   return NewFD;
9930 }
9931 
9932 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9933 /// when __declspec(code_seg) "is applied to a class, all member functions of
9934 /// the class and nested classes -- this includes compiler-generated special
9935 /// member functions -- are put in the specified segment."
9936 /// The actual behavior is a little more complicated. The Microsoft compiler
9937 /// won't check outer classes if there is an active value from #pragma code_seg.
9938 /// The CodeSeg is always applied from the direct parent but only from outer
9939 /// classes when the #pragma code_seg stack is empty. See:
9940 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9941 /// available since MS has removed the page.
getImplicitCodeSegAttrFromClass(Sema & S,const FunctionDecl * FD)9942 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9943   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9944   if (!Method)
9945     return nullptr;
9946   const CXXRecordDecl *Parent = Method->getParent();
9947   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9948     Attr *NewAttr = SAttr->clone(S.getASTContext());
9949     NewAttr->setImplicit(true);
9950     return NewAttr;
9951   }
9952 
9953   // The Microsoft compiler won't check outer classes for the CodeSeg
9954   // when the #pragma code_seg stack is active.
9955   if (S.CodeSegStack.CurrentValue)
9956    return nullptr;
9957 
9958   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9959     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9960       Attr *NewAttr = SAttr->clone(S.getASTContext());
9961       NewAttr->setImplicit(true);
9962       return NewAttr;
9963     }
9964   }
9965   return nullptr;
9966 }
9967 
9968 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9969 /// containing class. Otherwise it will return implicit SectionAttr if the
9970 /// function is a definition and there is an active value on CodeSegStack
9971 /// (from the current #pragma code-seg value).
9972 ///
9973 /// \param FD Function being declared.
9974 /// \param IsDefinition Whether it is a definition or just a declarartion.
9975 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9976 ///          nullptr if no attribute should be added.
getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl * FD,bool IsDefinition)9977 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9978                                                        bool IsDefinition) {
9979   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9980     return A;
9981   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9982       CodeSegStack.CurrentValue)
9983     return SectionAttr::CreateImplicit(
9984         getASTContext(), CodeSegStack.CurrentValue->getString(),
9985         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9986         SectionAttr::Declspec_allocate);
9987   return nullptr;
9988 }
9989 
9990 /// Determines if we can perform a correct type check for \p D as a
9991 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9992 /// best-effort check.
9993 ///
9994 /// \param NewD The new declaration.
9995 /// \param OldD The old declaration.
9996 /// \param NewT The portion of the type of the new declaration to check.
9997 /// \param OldT The portion of the type of the old declaration to check.
canFullyTypeCheckRedeclaration(ValueDecl * NewD,ValueDecl * OldD,QualType NewT,QualType OldT)9998 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9999                                           QualType NewT, QualType OldT) {
10000   if (!NewD->getLexicalDeclContext()->isDependentContext())
10001     return true;
10002 
10003   // For dependently-typed local extern declarations and friends, we can't
10004   // perform a correct type check in general until instantiation:
10005   //
10006   //   int f();
10007   //   template<typename T> void g() { T f(); }
10008   //
10009   // (valid if g() is only instantiated with T = int).
10010   if (NewT->isDependentType() &&
10011       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10012     return false;
10013 
10014   // Similarly, if the previous declaration was a dependent local extern
10015   // declaration, we don't really know its type yet.
10016   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10017     return false;
10018 
10019   return true;
10020 }
10021 
10022 /// Checks if the new declaration declared in dependent context must be
10023 /// put in the same redeclaration chain as the specified declaration.
10024 ///
10025 /// \param D Declaration that is checked.
10026 /// \param PrevDecl Previous declaration found with proper lookup method for the
10027 ///                 same declaration name.
10028 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10029 ///          belongs to.
10030 ///
shouldLinkDependentDeclWithPrevious(Decl * D,Decl * PrevDecl)10031 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10032   if (!D->getLexicalDeclContext()->isDependentContext())
10033     return true;
10034 
10035   // Don't chain dependent friend function definitions until instantiation, to
10036   // permit cases like
10037   //
10038   //   void func();
10039   //   template<typename T> class C1 { friend void func() {} };
10040   //   template<typename T> class C2 { friend void func() {} };
10041   //
10042   // ... which is valid if only one of C1 and C2 is ever instantiated.
10043   //
10044   // FIXME: This need only apply to function definitions. For now, we proxy
10045   // this by checking for a file-scope function. We do not want this to apply
10046   // to friend declarations nominating member functions, because that gets in
10047   // the way of access checks.
10048   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10049     return false;
10050 
10051   auto *VD = dyn_cast<ValueDecl>(D);
10052   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10053   return !VD || !PrevVD ||
10054          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10055                                         PrevVD->getType());
10056 }
10057 
10058 /// Check the target attribute of the function for MultiVersion
10059 /// validity.
10060 ///
10061 /// Returns true if there was an error, false otherwise.
CheckMultiVersionValue(Sema & S,const FunctionDecl * FD)10062 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10063   const auto *TA = FD->getAttr<TargetAttr>();
10064   assert(TA && "MultiVersion Candidate requires a target attribute");
10065   ParsedTargetAttr ParseInfo = TA->parse();
10066   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10067   enum ErrType { Feature = 0, Architecture = 1 };
10068 
10069   if (!ParseInfo.Architecture.empty() &&
10070       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10071     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10072         << Architecture << ParseInfo.Architecture;
10073     return true;
10074   }
10075 
10076   for (const auto &Feat : ParseInfo.Features) {
10077     auto BareFeat = StringRef{Feat}.substr(1);
10078     if (Feat[0] == '-') {
10079       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10080           << Feature << ("no-" + BareFeat).str();
10081       return true;
10082     }
10083 
10084     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10085         !TargetInfo.isValidFeatureName(BareFeat)) {
10086       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10087           << Feature << BareFeat;
10088       return true;
10089     }
10090   }
10091   return false;
10092 }
10093 
10094 // Provide a white-list of attributes that are allowed to be combined with
10095 // multiversion functions.
AttrCompatibleWithMultiVersion(attr::Kind Kind,MultiVersionKind MVType)10096 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10097                                            MultiVersionKind MVType) {
10098   switch (Kind) {
10099   default:
10100     return false;
10101   case attr::Used:
10102     return MVType == MultiVersionKind::Target;
10103   }
10104 }
10105 
HasNonMultiVersionAttributes(const FunctionDecl * FD,MultiVersionKind MVType)10106 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
10107                                          MultiVersionKind MVType) {
10108   for (const Attr *A : FD->attrs()) {
10109     switch (A->getKind()) {
10110     case attr::CPUDispatch:
10111     case attr::CPUSpecific:
10112       if (MVType != MultiVersionKind::CPUDispatch &&
10113           MVType != MultiVersionKind::CPUSpecific)
10114         return true;
10115       break;
10116     case attr::Target:
10117       if (MVType != MultiVersionKind::Target)
10118         return true;
10119       break;
10120     default:
10121       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10122         return true;
10123       break;
10124     }
10125   }
10126   return false;
10127 }
10128 
areMultiversionVariantFunctionsCompatible(const FunctionDecl * OldFD,const FunctionDecl * NewFD,const PartialDiagnostic & NoProtoDiagID,const PartialDiagnosticAt & NoteCausedDiagIDAt,const PartialDiagnosticAt & NoSupportDiagIDAt,const PartialDiagnosticAt & DiffDiagIDAt,bool TemplatesSupported,bool ConstexprSupported,bool CLinkageMayDiffer)10129 bool Sema::areMultiversionVariantFunctionsCompatible(
10130     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10131     const PartialDiagnostic &NoProtoDiagID,
10132     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10133     const PartialDiagnosticAt &NoSupportDiagIDAt,
10134     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10135     bool ConstexprSupported, bool CLinkageMayDiffer) {
10136   enum DoesntSupport {
10137     FuncTemplates = 0,
10138     VirtFuncs = 1,
10139     DeducedReturn = 2,
10140     Constructors = 3,
10141     Destructors = 4,
10142     DeletedFuncs = 5,
10143     DefaultedFuncs = 6,
10144     ConstexprFuncs = 7,
10145     ConstevalFuncs = 8,
10146   };
10147   enum Different {
10148     CallingConv = 0,
10149     ReturnType = 1,
10150     ConstexprSpec = 2,
10151     InlineSpec = 3,
10152     StorageClass = 4,
10153     Linkage = 5,
10154   };
10155 
10156   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10157       !OldFD->getType()->getAs<FunctionProtoType>()) {
10158     Diag(OldFD->getLocation(), NoProtoDiagID);
10159     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10160     return true;
10161   }
10162 
10163   if (NoProtoDiagID.getDiagID() != 0 &&
10164       !NewFD->getType()->getAs<FunctionProtoType>())
10165     return Diag(NewFD->getLocation(), NoProtoDiagID);
10166 
10167   if (!TemplatesSupported &&
10168       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10169     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10170            << FuncTemplates;
10171 
10172   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10173     if (NewCXXFD->isVirtual())
10174       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10175              << VirtFuncs;
10176 
10177     if (isa<CXXConstructorDecl>(NewCXXFD))
10178       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10179              << Constructors;
10180 
10181     if (isa<CXXDestructorDecl>(NewCXXFD))
10182       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10183              << Destructors;
10184   }
10185 
10186   if (NewFD->isDeleted())
10187     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10188            << DeletedFuncs;
10189 
10190   if (NewFD->isDefaulted())
10191     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10192            << DefaultedFuncs;
10193 
10194   if (!ConstexprSupported && NewFD->isConstexpr())
10195     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10196            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10197 
10198   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10199   const auto *NewType = cast<FunctionType>(NewQType);
10200   QualType NewReturnType = NewType->getReturnType();
10201 
10202   if (NewReturnType->isUndeducedType())
10203     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10204            << DeducedReturn;
10205 
10206   // Ensure the return type is identical.
10207   if (OldFD) {
10208     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10209     const auto *OldType = cast<FunctionType>(OldQType);
10210     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10211     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10212 
10213     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10214       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10215 
10216     QualType OldReturnType = OldType->getReturnType();
10217 
10218     if (OldReturnType != NewReturnType)
10219       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10220 
10221     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10222       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10223 
10224     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10225       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10226 
10227     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10228       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10229 
10230     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10231       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10232 
10233     if (CheckEquivalentExceptionSpec(
10234             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10235             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10236       return true;
10237   }
10238   return false;
10239 }
10240 
CheckMultiVersionAdditionalRules(Sema & S,const FunctionDecl * OldFD,const FunctionDecl * NewFD,bool CausesMV,MultiVersionKind MVType)10241 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10242                                              const FunctionDecl *NewFD,
10243                                              bool CausesMV,
10244                                              MultiVersionKind MVType) {
10245   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10246     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10247     if (OldFD)
10248       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10249     return true;
10250   }
10251 
10252   bool IsCPUSpecificCPUDispatchMVType =
10253       MVType == MultiVersionKind::CPUDispatch ||
10254       MVType == MultiVersionKind::CPUSpecific;
10255 
10256   // For now, disallow all other attributes.  These should be opt-in, but
10257   // an analysis of all of them is a future FIXME.
10258   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
10259     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
10260         << IsCPUSpecificCPUDispatchMVType;
10261     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10262     return true;
10263   }
10264 
10265   if (HasNonMultiVersionAttributes(NewFD, MVType))
10266     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
10267            << IsCPUSpecificCPUDispatchMVType;
10268 
10269   // Only allow transition to MultiVersion if it hasn't been used.
10270   if (OldFD && CausesMV && OldFD->isUsed(false))
10271     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10272 
10273   return S.areMultiversionVariantFunctionsCompatible(
10274       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10275       PartialDiagnosticAt(NewFD->getLocation(),
10276                           S.PDiag(diag::note_multiversioning_caused_here)),
10277       PartialDiagnosticAt(NewFD->getLocation(),
10278                           S.PDiag(diag::err_multiversion_doesnt_support)
10279                               << IsCPUSpecificCPUDispatchMVType),
10280       PartialDiagnosticAt(NewFD->getLocation(),
10281                           S.PDiag(diag::err_multiversion_diff)),
10282       /*TemplatesSupported=*/false,
10283       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10284       /*CLinkageMayDiffer=*/false);
10285 }
10286 
10287 /// Check the validity of a multiversion function declaration that is the
10288 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10289 ///
10290 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10291 ///
10292 /// Returns true if there was an error, false otherwise.
CheckMultiVersionFirstFunction(Sema & S,FunctionDecl * FD,MultiVersionKind MVType,const TargetAttr * TA)10293 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10294                                            MultiVersionKind MVType,
10295                                            const TargetAttr *TA) {
10296   assert(MVType != MultiVersionKind::None &&
10297          "Function lacks multiversion attribute");
10298 
10299   // Target only causes MV if it is default, otherwise this is a normal
10300   // function.
10301   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10302     return false;
10303 
10304   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10305     FD->setInvalidDecl();
10306     return true;
10307   }
10308 
10309   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10310     FD->setInvalidDecl();
10311     return true;
10312   }
10313 
10314   FD->setIsMultiVersion();
10315   return false;
10316 }
10317 
PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl * FD)10318 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10319   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10320     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10321       return true;
10322   }
10323 
10324   return false;
10325 }
10326 
CheckTargetCausesMultiVersioning(Sema & S,FunctionDecl * OldFD,FunctionDecl * NewFD,const TargetAttr * NewTA,bool & Redeclaration,NamedDecl * & OldDecl,bool & MergeTypeWithPrevious,LookupResult & Previous)10327 static bool CheckTargetCausesMultiVersioning(
10328     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10329     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10330     LookupResult &Previous) {
10331   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10332   ParsedTargetAttr NewParsed = NewTA->parse();
10333   // Sort order doesn't matter, it just needs to be consistent.
10334   llvm::sort(NewParsed.Features);
10335 
10336   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10337   // to change, this is a simple redeclaration.
10338   if (!NewTA->isDefaultVersion() &&
10339       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10340     return false;
10341 
10342   // Otherwise, this decl causes MultiVersioning.
10343   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10344     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10345     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10346     NewFD->setInvalidDecl();
10347     return true;
10348   }
10349 
10350   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10351                                        MultiVersionKind::Target)) {
10352     NewFD->setInvalidDecl();
10353     return true;
10354   }
10355 
10356   if (CheckMultiVersionValue(S, NewFD)) {
10357     NewFD->setInvalidDecl();
10358     return true;
10359   }
10360 
10361   // If this is 'default', permit the forward declaration.
10362   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10363     Redeclaration = true;
10364     OldDecl = OldFD;
10365     OldFD->setIsMultiVersion();
10366     NewFD->setIsMultiVersion();
10367     return false;
10368   }
10369 
10370   if (CheckMultiVersionValue(S, OldFD)) {
10371     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10372     NewFD->setInvalidDecl();
10373     return true;
10374   }
10375 
10376   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10377 
10378   if (OldParsed == NewParsed) {
10379     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10380     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10381     NewFD->setInvalidDecl();
10382     return true;
10383   }
10384 
10385   for (const auto *FD : OldFD->redecls()) {
10386     const auto *CurTA = FD->getAttr<TargetAttr>();
10387     // We allow forward declarations before ANY multiversioning attributes, but
10388     // nothing after the fact.
10389     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10390         (!CurTA || CurTA->isInherited())) {
10391       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10392           << 0;
10393       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10394       NewFD->setInvalidDecl();
10395       return true;
10396     }
10397   }
10398 
10399   OldFD->setIsMultiVersion();
10400   NewFD->setIsMultiVersion();
10401   Redeclaration = false;
10402   MergeTypeWithPrevious = false;
10403   OldDecl = nullptr;
10404   Previous.clear();
10405   return false;
10406 }
10407 
10408 /// Check the validity of a new function declaration being added to an existing
10409 /// multiversioned declaration collection.
CheckMultiVersionAdditionalDecl(Sema & S,FunctionDecl * OldFD,FunctionDecl * NewFD,MultiVersionKind NewMVType,const TargetAttr * NewTA,const CPUDispatchAttr * NewCPUDisp,const CPUSpecificAttr * NewCPUSpec,bool & Redeclaration,NamedDecl * & OldDecl,bool & MergeTypeWithPrevious,LookupResult & Previous)10410 static bool CheckMultiVersionAdditionalDecl(
10411     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10412     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10413     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10414     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10415     LookupResult &Previous) {
10416 
10417   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10418   // Disallow mixing of multiversioning types.
10419   if ((OldMVType == MultiVersionKind::Target &&
10420        NewMVType != MultiVersionKind::Target) ||
10421       (NewMVType == MultiVersionKind::Target &&
10422        OldMVType != MultiVersionKind::Target)) {
10423     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10424     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10425     NewFD->setInvalidDecl();
10426     return true;
10427   }
10428 
10429   ParsedTargetAttr NewParsed;
10430   if (NewTA) {
10431     NewParsed = NewTA->parse();
10432     llvm::sort(NewParsed.Features);
10433   }
10434 
10435   bool UseMemberUsingDeclRules =
10436       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10437 
10438   // Next, check ALL non-overloads to see if this is a redeclaration of a
10439   // previous member of the MultiVersion set.
10440   for (NamedDecl *ND : Previous) {
10441     FunctionDecl *CurFD = ND->getAsFunction();
10442     if (!CurFD)
10443       continue;
10444     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10445       continue;
10446 
10447     if (NewMVType == MultiVersionKind::Target) {
10448       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10449       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10450         NewFD->setIsMultiVersion();
10451         Redeclaration = true;
10452         OldDecl = ND;
10453         return false;
10454       }
10455 
10456       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10457       if (CurParsed == NewParsed) {
10458         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10459         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10460         NewFD->setInvalidDecl();
10461         return true;
10462       }
10463     } else {
10464       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10465       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10466       // Handle CPUDispatch/CPUSpecific versions.
10467       // Only 1 CPUDispatch function is allowed, this will make it go through
10468       // the redeclaration errors.
10469       if (NewMVType == MultiVersionKind::CPUDispatch &&
10470           CurFD->hasAttr<CPUDispatchAttr>()) {
10471         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10472             std::equal(
10473                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10474                 NewCPUDisp->cpus_begin(),
10475                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10476                   return Cur->getName() == New->getName();
10477                 })) {
10478           NewFD->setIsMultiVersion();
10479           Redeclaration = true;
10480           OldDecl = ND;
10481           return false;
10482         }
10483 
10484         // If the declarations don't match, this is an error condition.
10485         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10486         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10487         NewFD->setInvalidDecl();
10488         return true;
10489       }
10490       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10491 
10492         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10493             std::equal(
10494                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10495                 NewCPUSpec->cpus_begin(),
10496                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10497                   return Cur->getName() == New->getName();
10498                 })) {
10499           NewFD->setIsMultiVersion();
10500           Redeclaration = true;
10501           OldDecl = ND;
10502           return false;
10503         }
10504 
10505         // Only 1 version of CPUSpecific is allowed for each CPU.
10506         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10507           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10508             if (CurII == NewII) {
10509               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10510                   << NewII;
10511               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10512               NewFD->setInvalidDecl();
10513               return true;
10514             }
10515           }
10516         }
10517       }
10518       // If the two decls aren't the same MVType, there is no possible error
10519       // condition.
10520     }
10521   }
10522 
10523   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10524   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10525   // handled in the attribute adding step.
10526   if (NewMVType == MultiVersionKind::Target &&
10527       CheckMultiVersionValue(S, NewFD)) {
10528     NewFD->setInvalidDecl();
10529     return true;
10530   }
10531 
10532   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10533                                        !OldFD->isMultiVersion(), NewMVType)) {
10534     NewFD->setInvalidDecl();
10535     return true;
10536   }
10537 
10538   // Permit forward declarations in the case where these two are compatible.
10539   if (!OldFD->isMultiVersion()) {
10540     OldFD->setIsMultiVersion();
10541     NewFD->setIsMultiVersion();
10542     Redeclaration = true;
10543     OldDecl = OldFD;
10544     return false;
10545   }
10546 
10547   NewFD->setIsMultiVersion();
10548   Redeclaration = false;
10549   MergeTypeWithPrevious = false;
10550   OldDecl = nullptr;
10551   Previous.clear();
10552   return false;
10553 }
10554 
10555 
10556 /// Check the validity of a mulitversion function declaration.
10557 /// Also sets the multiversion'ness' of the function itself.
10558 ///
10559 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10560 ///
10561 /// Returns true if there was an error, false otherwise.
CheckMultiVersionFunction(Sema & S,FunctionDecl * NewFD,bool & Redeclaration,NamedDecl * & OldDecl,bool & MergeTypeWithPrevious,LookupResult & Previous)10562 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10563                                       bool &Redeclaration, NamedDecl *&OldDecl,
10564                                       bool &MergeTypeWithPrevious,
10565                                       LookupResult &Previous) {
10566   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10567   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10568   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10569 
10570   // Mixing Multiversioning types is prohibited.
10571   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10572       (NewCPUDisp && NewCPUSpec)) {
10573     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10574     NewFD->setInvalidDecl();
10575     return true;
10576   }
10577 
10578   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10579 
10580   // Main isn't allowed to become a multiversion function, however it IS
10581   // permitted to have 'main' be marked with the 'target' optimization hint.
10582   if (NewFD->isMain()) {
10583     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10584         MVType == MultiVersionKind::CPUDispatch ||
10585         MVType == MultiVersionKind::CPUSpecific) {
10586       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10587       NewFD->setInvalidDecl();
10588       return true;
10589     }
10590     return false;
10591   }
10592 
10593   if (!OldDecl || !OldDecl->getAsFunction() ||
10594       OldDecl->getDeclContext()->getRedeclContext() !=
10595           NewFD->getDeclContext()->getRedeclContext()) {
10596     // If there's no previous declaration, AND this isn't attempting to cause
10597     // multiversioning, this isn't an error condition.
10598     if (MVType == MultiVersionKind::None)
10599       return false;
10600     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10601   }
10602 
10603   FunctionDecl *OldFD = OldDecl->getAsFunction();
10604 
10605   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10606     return false;
10607 
10608   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10609     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10610         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10611     NewFD->setInvalidDecl();
10612     return true;
10613   }
10614 
10615   // Handle the target potentially causes multiversioning case.
10616   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10617     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10618                                             Redeclaration, OldDecl,
10619                                             MergeTypeWithPrevious, Previous);
10620 
10621   // At this point, we have a multiversion function decl (in OldFD) AND an
10622   // appropriate attribute in the current function decl.  Resolve that these are
10623   // still compatible with previous declarations.
10624   return CheckMultiVersionAdditionalDecl(
10625       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10626       OldDecl, MergeTypeWithPrevious, Previous);
10627 }
10628 
10629 /// Perform semantic checking of a new function declaration.
10630 ///
10631 /// Performs semantic analysis of the new function declaration
10632 /// NewFD. This routine performs all semantic checking that does not
10633 /// require the actual declarator involved in the declaration, and is
10634 /// used both for the declaration of functions as they are parsed
10635 /// (called via ActOnDeclarator) and for the declaration of functions
10636 /// that have been instantiated via C++ template instantiation (called
10637 /// via InstantiateDecl).
10638 ///
10639 /// \param IsMemberSpecialization whether this new function declaration is
10640 /// a member specialization (that replaces any definition provided by the
10641 /// previous declaration).
10642 ///
10643 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10644 ///
10645 /// \returns true if the function declaration is a redeclaration.
CheckFunctionDeclaration(Scope * S,FunctionDecl * NewFD,LookupResult & Previous,bool IsMemberSpecialization)10646 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10647                                     LookupResult &Previous,
10648                                     bool IsMemberSpecialization) {
10649   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10650          "Variably modified return types are not handled here");
10651 
10652   // Determine whether the type of this function should be merged with
10653   // a previous visible declaration. This never happens for functions in C++,
10654   // and always happens in C if the previous declaration was visible.
10655   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10656                                !Previous.isShadowed();
10657 
10658   bool Redeclaration = false;
10659   NamedDecl *OldDecl = nullptr;
10660   bool MayNeedOverloadableChecks = false;
10661 
10662   // Merge or overload the declaration with an existing declaration of
10663   // the same name, if appropriate.
10664   if (!Previous.empty()) {
10665     // Determine whether NewFD is an overload of PrevDecl or
10666     // a declaration that requires merging. If it's an overload,
10667     // there's no more work to do here; we'll just add the new
10668     // function to the scope.
10669     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10670       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10671       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10672         Redeclaration = true;
10673         OldDecl = Candidate;
10674       }
10675     } else {
10676       MayNeedOverloadableChecks = true;
10677       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10678                             /*NewIsUsingDecl*/ false)) {
10679       case Ovl_Match:
10680         Redeclaration = true;
10681         break;
10682 
10683       case Ovl_NonFunction:
10684         Redeclaration = true;
10685         break;
10686 
10687       case Ovl_Overload:
10688         Redeclaration = false;
10689         break;
10690       }
10691     }
10692   }
10693 
10694   // Check for a previous extern "C" declaration with this name.
10695   if (!Redeclaration &&
10696       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10697     if (!Previous.empty()) {
10698       // This is an extern "C" declaration with the same name as a previous
10699       // declaration, and thus redeclares that entity...
10700       Redeclaration = true;
10701       OldDecl = Previous.getFoundDecl();
10702       MergeTypeWithPrevious = false;
10703 
10704       // ... except in the presence of __attribute__((overloadable)).
10705       if (OldDecl->hasAttr<OverloadableAttr>() ||
10706           NewFD->hasAttr<OverloadableAttr>()) {
10707         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10708           MayNeedOverloadableChecks = true;
10709           Redeclaration = false;
10710           OldDecl = nullptr;
10711         }
10712       }
10713     }
10714   }
10715 
10716   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10717                                 MergeTypeWithPrevious, Previous))
10718     return Redeclaration;
10719 
10720   // C++11 [dcl.constexpr]p8:
10721   //   A constexpr specifier for a non-static member function that is not
10722   //   a constructor declares that member function to be const.
10723   //
10724   // This needs to be delayed until we know whether this is an out-of-line
10725   // definition of a static member function.
10726   //
10727   // This rule is not present in C++1y, so we produce a backwards
10728   // compatibility warning whenever it happens in C++11.
10729   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10730   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10731       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10732       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10733     CXXMethodDecl *OldMD = nullptr;
10734     if (OldDecl)
10735       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10736     if (!OldMD || !OldMD->isStatic()) {
10737       const FunctionProtoType *FPT =
10738         MD->getType()->castAs<FunctionProtoType>();
10739       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10740       EPI.TypeQuals.addConst();
10741       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10742                                           FPT->getParamTypes(), EPI));
10743 
10744       // Warn that we did this, if we're not performing template instantiation.
10745       // In that case, we'll have warned already when the template was defined.
10746       if (!inTemplateInstantiation()) {
10747         SourceLocation AddConstLoc;
10748         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10749                 .IgnoreParens().getAs<FunctionTypeLoc>())
10750           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10751 
10752         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10753           << FixItHint::CreateInsertion(AddConstLoc, " const");
10754       }
10755     }
10756   }
10757 
10758   if (Redeclaration) {
10759     // NewFD and OldDecl represent declarations that need to be
10760     // merged.
10761     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10762       NewFD->setInvalidDecl();
10763       return Redeclaration;
10764     }
10765 
10766     Previous.clear();
10767     Previous.addDecl(OldDecl);
10768 
10769     if (FunctionTemplateDecl *OldTemplateDecl =
10770             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10771       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10772       FunctionTemplateDecl *NewTemplateDecl
10773         = NewFD->getDescribedFunctionTemplate();
10774       assert(NewTemplateDecl && "Template/non-template mismatch");
10775 
10776       // The call to MergeFunctionDecl above may have created some state in
10777       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10778       // can add it as a redeclaration.
10779       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10780 
10781       NewFD->setPreviousDeclaration(OldFD);
10782       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10783       if (NewFD->isCXXClassMember()) {
10784         NewFD->setAccess(OldTemplateDecl->getAccess());
10785         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10786       }
10787 
10788       // If this is an explicit specialization of a member that is a function
10789       // template, mark it as a member specialization.
10790       if (IsMemberSpecialization &&
10791           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10792         NewTemplateDecl->setMemberSpecialization();
10793         assert(OldTemplateDecl->isMemberSpecialization());
10794         // Explicit specializations of a member template do not inherit deleted
10795         // status from the parent member template that they are specializing.
10796         if (OldFD->isDeleted()) {
10797           // FIXME: This assert will not hold in the presence of modules.
10798           assert(OldFD->getCanonicalDecl() == OldFD);
10799           // FIXME: We need an update record for this AST mutation.
10800           OldFD->setDeletedAsWritten(false);
10801         }
10802       }
10803 
10804     } else {
10805       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10806         auto *OldFD = cast<FunctionDecl>(OldDecl);
10807         // This needs to happen first so that 'inline' propagates.
10808         NewFD->setPreviousDeclaration(OldFD);
10809         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10810         if (NewFD->isCXXClassMember())
10811           NewFD->setAccess(OldFD->getAccess());
10812       }
10813     }
10814   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10815              !NewFD->getAttr<OverloadableAttr>()) {
10816     assert((Previous.empty() ||
10817             llvm::any_of(Previous,
10818                          [](const NamedDecl *ND) {
10819                            return ND->hasAttr<OverloadableAttr>();
10820                          })) &&
10821            "Non-redecls shouldn't happen without overloadable present");
10822 
10823     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10824       const auto *FD = dyn_cast<FunctionDecl>(ND);
10825       return FD && !FD->hasAttr<OverloadableAttr>();
10826     });
10827 
10828     if (OtherUnmarkedIter != Previous.end()) {
10829       Diag(NewFD->getLocation(),
10830            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10831       Diag((*OtherUnmarkedIter)->getLocation(),
10832            diag::note_attribute_overloadable_prev_overload)
10833           << false;
10834 
10835       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10836     }
10837   }
10838 
10839   // Semantic checking for this function declaration (in isolation).
10840 
10841   if (getLangOpts().CPlusPlus) {
10842     // C++-specific checks.
10843     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10844       CheckConstructor(Constructor);
10845     } else if (CXXDestructorDecl *Destructor =
10846                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10847       CXXRecordDecl *Record = Destructor->getParent();
10848       QualType ClassType = Context.getTypeDeclType(Record);
10849 
10850       // FIXME: Shouldn't we be able to perform this check even when the class
10851       // type is dependent? Both gcc and edg can handle that.
10852       if (!ClassType->isDependentType()) {
10853         DeclarationName Name
10854           = Context.DeclarationNames.getCXXDestructorName(
10855                                         Context.getCanonicalType(ClassType));
10856         if (NewFD->getDeclName() != Name) {
10857           Diag(NewFD->getLocation(), diag::err_destructor_name);
10858           NewFD->setInvalidDecl();
10859           return Redeclaration;
10860         }
10861       }
10862     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10863       if (auto *TD = Guide->getDescribedFunctionTemplate())
10864         CheckDeductionGuideTemplate(TD);
10865 
10866       // A deduction guide is not on the list of entities that can be
10867       // explicitly specialized.
10868       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10869         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10870             << /*explicit specialization*/ 1;
10871     }
10872 
10873     // Find any virtual functions that this function overrides.
10874     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10875       if (!Method->isFunctionTemplateSpecialization() &&
10876           !Method->getDescribedFunctionTemplate() &&
10877           Method->isCanonicalDecl()) {
10878         AddOverriddenMethods(Method->getParent(), Method);
10879       }
10880       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10881         // C++2a [class.virtual]p6
10882         // A virtual method shall not have a requires-clause.
10883         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10884              diag::err_constrained_virtual_method);
10885 
10886       if (Method->isStatic())
10887         checkThisInStaticMemberFunctionType(Method);
10888     }
10889 
10890     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10891       ActOnConversionDeclarator(Conversion);
10892 
10893     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10894     if (NewFD->isOverloadedOperator() &&
10895         CheckOverloadedOperatorDeclaration(NewFD)) {
10896       NewFD->setInvalidDecl();
10897       return Redeclaration;
10898     }
10899 
10900     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10901     if (NewFD->getLiteralIdentifier() &&
10902         CheckLiteralOperatorDeclaration(NewFD)) {
10903       NewFD->setInvalidDecl();
10904       return Redeclaration;
10905     }
10906 
10907     // In C++, check default arguments now that we have merged decls. Unless
10908     // the lexical context is the class, because in this case this is done
10909     // during delayed parsing anyway.
10910     if (!CurContext->isRecord())
10911       CheckCXXDefaultArguments(NewFD);
10912 
10913     // If this function declares a builtin function, check the type of this
10914     // declaration against the expected type for the builtin.
10915     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10916       ASTContext::GetBuiltinTypeError Error;
10917       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10918       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10919       // If the type of the builtin differs only in its exception
10920       // specification, that's OK.
10921       // FIXME: If the types do differ in this way, it would be better to
10922       // retain the 'noexcept' form of the type.
10923       if (!T.isNull() &&
10924           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10925                                                             NewFD->getType()))
10926         // The type of this function differs from the type of the builtin,
10927         // so forget about the builtin entirely.
10928         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10929     }
10930 
10931     // If this function is declared as being extern "C", then check to see if
10932     // the function returns a UDT (class, struct, or union type) that is not C
10933     // compatible, and if it does, warn the user.
10934     // But, issue any diagnostic on the first declaration only.
10935     if (Previous.empty() && NewFD->isExternC()) {
10936       QualType R = NewFD->getReturnType();
10937       if (R->isIncompleteType() && !R->isVoidType())
10938         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10939             << NewFD << R;
10940       else if (!R.isPODType(Context) && !R->isVoidType() &&
10941                !R->isObjCObjectPointerType())
10942         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10943     }
10944 
10945     // C++1z [dcl.fct]p6:
10946     //   [...] whether the function has a non-throwing exception-specification
10947     //   [is] part of the function type
10948     //
10949     // This results in an ABI break between C++14 and C++17 for functions whose
10950     // declared type includes an exception-specification in a parameter or
10951     // return type. (Exception specifications on the function itself are OK in
10952     // most cases, and exception specifications are not permitted in most other
10953     // contexts where they could make it into a mangling.)
10954     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10955       auto HasNoexcept = [&](QualType T) -> bool {
10956         // Strip off declarator chunks that could be between us and a function
10957         // type. We don't need to look far, exception specifications are very
10958         // restricted prior to C++17.
10959         if (auto *RT = T->getAs<ReferenceType>())
10960           T = RT->getPointeeType();
10961         else if (T->isAnyPointerType())
10962           T = T->getPointeeType();
10963         else if (auto *MPT = T->getAs<MemberPointerType>())
10964           T = MPT->getPointeeType();
10965         if (auto *FPT = T->getAs<FunctionProtoType>())
10966           if (FPT->isNothrow())
10967             return true;
10968         return false;
10969       };
10970 
10971       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10972       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10973       for (QualType T : FPT->param_types())
10974         AnyNoexcept |= HasNoexcept(T);
10975       if (AnyNoexcept)
10976         Diag(NewFD->getLocation(),
10977              diag::warn_cxx17_compat_exception_spec_in_signature)
10978             << NewFD;
10979     }
10980 
10981     if (!Redeclaration && LangOpts.CUDA)
10982       checkCUDATargetOverload(NewFD, Previous);
10983   }
10984   return Redeclaration;
10985 }
10986 
CheckMain(FunctionDecl * FD,const DeclSpec & DS)10987 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10988   // C++11 [basic.start.main]p3:
10989   //   A program that [...] declares main to be inline, static or
10990   //   constexpr is ill-formed.
10991   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10992   //   appear in a declaration of main.
10993   // static main is not an error under C99, but we should warn about it.
10994   // We accept _Noreturn main as an extension.
10995   if (FD->getStorageClass() == SC_Static)
10996     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10997          ? diag::err_static_main : diag::warn_static_main)
10998       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10999   if (FD->isInlineSpecified())
11000     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11001       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11002   if (DS.isNoreturnSpecified()) {
11003     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11004     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11005     Diag(NoreturnLoc, diag::ext_noreturn_main);
11006     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11007       << FixItHint::CreateRemoval(NoreturnRange);
11008   }
11009   if (FD->isConstexpr()) {
11010     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11011         << FD->isConsteval()
11012         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11013     FD->setConstexprKind(CSK_unspecified);
11014   }
11015 
11016   if (getLangOpts().OpenCL) {
11017     Diag(FD->getLocation(), diag::err_opencl_no_main)
11018         << FD->hasAttr<OpenCLKernelAttr>();
11019     FD->setInvalidDecl();
11020     return;
11021   }
11022 
11023   QualType T = FD->getType();
11024   assert(T->isFunctionType() && "function decl is not of function type");
11025   const FunctionType* FT = T->castAs<FunctionType>();
11026 
11027   // Set default calling convention for main()
11028   if (FT->getCallConv() != CC_C) {
11029     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11030     FD->setType(QualType(FT, 0));
11031     T = Context.getCanonicalType(FD->getType());
11032   }
11033 
11034   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11035     // In C with GNU extensions we allow main() to have non-integer return
11036     // type, but we should warn about the extension, and we disable the
11037     // implicit-return-zero rule.
11038 
11039     // GCC in C mode accepts qualified 'int'.
11040     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11041       FD->setHasImplicitReturnZero(true);
11042     else {
11043       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11044       SourceRange RTRange = FD->getReturnTypeSourceRange();
11045       if (RTRange.isValid())
11046         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11047             << FixItHint::CreateReplacement(RTRange, "int");
11048     }
11049   } else {
11050     // In C and C++, main magically returns 0 if you fall off the end;
11051     // set the flag which tells us that.
11052     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11053 
11054     // All the standards say that main() should return 'int'.
11055     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11056       FD->setHasImplicitReturnZero(true);
11057     else {
11058       // Otherwise, this is just a flat-out error.
11059       SourceRange RTRange = FD->getReturnTypeSourceRange();
11060       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11061           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11062                                 : FixItHint());
11063       FD->setInvalidDecl(true);
11064     }
11065   }
11066 
11067   // Treat protoless main() as nullary.
11068   if (isa<FunctionNoProtoType>(FT)) return;
11069 
11070   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11071   unsigned nparams = FTP->getNumParams();
11072   assert(FD->getNumParams() == nparams);
11073 
11074   bool HasExtraParameters = (nparams > 3);
11075 
11076   if (FTP->isVariadic()) {
11077     Diag(FD->getLocation(), diag::ext_variadic_main);
11078     // FIXME: if we had information about the location of the ellipsis, we
11079     // could add a FixIt hint to remove it as a parameter.
11080   }
11081 
11082   // Darwin passes an undocumented fourth argument of type char**.  If
11083   // other platforms start sprouting these, the logic below will start
11084   // getting shifty.
11085   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11086     HasExtraParameters = false;
11087 
11088   if (HasExtraParameters) {
11089     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11090     FD->setInvalidDecl(true);
11091     nparams = 3;
11092   }
11093 
11094   // FIXME: a lot of the following diagnostics would be improved
11095   // if we had some location information about types.
11096 
11097   QualType CharPP =
11098     Context.getPointerType(Context.getPointerType(Context.CharTy));
11099   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11100 
11101   for (unsigned i = 0; i < nparams; ++i) {
11102     QualType AT = FTP->getParamType(i);
11103 
11104     bool mismatch = true;
11105 
11106     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11107       mismatch = false;
11108     else if (Expected[i] == CharPP) {
11109       // As an extension, the following forms are okay:
11110       //   char const **
11111       //   char const * const *
11112       //   char * const *
11113 
11114       QualifierCollector qs;
11115       const PointerType* PT;
11116       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11117           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11118           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11119                               Context.CharTy)) {
11120         qs.removeConst();
11121         mismatch = !qs.empty();
11122       }
11123     }
11124 
11125     if (mismatch) {
11126       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11127       // TODO: suggest replacing given type with expected type
11128       FD->setInvalidDecl(true);
11129     }
11130   }
11131 
11132   if (nparams == 1 && !FD->isInvalidDecl()) {
11133     Diag(FD->getLocation(), diag::warn_main_one_arg);
11134   }
11135 
11136   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11137     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11138     FD->setInvalidDecl();
11139   }
11140 }
11141 
CheckMSVCRTEntryPoint(FunctionDecl * FD)11142 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11143   QualType T = FD->getType();
11144   assert(T->isFunctionType() && "function decl is not of function type");
11145   const FunctionType *FT = T->castAs<FunctionType>();
11146 
11147   // Set an implicit return of 'zero' if the function can return some integral,
11148   // enumeration, pointer or nullptr type.
11149   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11150       FT->getReturnType()->isAnyPointerType() ||
11151       FT->getReturnType()->isNullPtrType())
11152     // DllMain is exempt because a return value of zero means it failed.
11153     if (FD->getName() != "DllMain")
11154       FD->setHasImplicitReturnZero(true);
11155 
11156   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11157     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11158     FD->setInvalidDecl();
11159   }
11160 }
11161 
CheckForConstantInitializer(Expr * Init,QualType DclT)11162 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11163   // FIXME: Need strict checking.  In C89, we need to check for
11164   // any assignment, increment, decrement, function-calls, or
11165   // commas outside of a sizeof.  In C99, it's the same list,
11166   // except that the aforementioned are allowed in unevaluated
11167   // expressions.  Everything else falls under the
11168   // "may accept other forms of constant expressions" exception.
11169   // (We never end up here for C++, so the constant expression
11170   // rules there don't matter.)
11171   const Expr *Culprit;
11172   if (Init->isConstantInitializer(Context, false, &Culprit))
11173     return false;
11174   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11175     << Culprit->getSourceRange();
11176   return true;
11177 }
11178 
11179 namespace {
11180   // Visits an initialization expression to see if OrigDecl is evaluated in
11181   // its own initialization and throws a warning if it does.
11182   class SelfReferenceChecker
11183       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11184     Sema &S;
11185     Decl *OrigDecl;
11186     bool isRecordType;
11187     bool isPODType;
11188     bool isReferenceType;
11189 
11190     bool isInitList;
11191     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11192 
11193   public:
11194     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11195 
SelfReferenceChecker(Sema & S,Decl * OrigDecl)11196     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11197                                                     S(S), OrigDecl(OrigDecl) {
11198       isPODType = false;
11199       isRecordType = false;
11200       isReferenceType = false;
11201       isInitList = false;
11202       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11203         isPODType = VD->getType().isPODType(S.Context);
11204         isRecordType = VD->getType()->isRecordType();
11205         isReferenceType = VD->getType()->isReferenceType();
11206       }
11207     }
11208 
11209     // For most expressions, just call the visitor.  For initializer lists,
11210     // track the index of the field being initialized since fields are
11211     // initialized in order allowing use of previously initialized fields.
CheckExpr(Expr * E)11212     void CheckExpr(Expr *E) {
11213       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11214       if (!InitList) {
11215         Visit(E);
11216         return;
11217       }
11218 
11219       // Track and increment the index here.
11220       isInitList = true;
11221       InitFieldIndex.push_back(0);
11222       for (auto Child : InitList->children()) {
11223         CheckExpr(cast<Expr>(Child));
11224         ++InitFieldIndex.back();
11225       }
11226       InitFieldIndex.pop_back();
11227     }
11228 
11229     // Returns true if MemberExpr is checked and no further checking is needed.
11230     // Returns false if additional checking is required.
CheckInitListMemberExpr(MemberExpr * E,bool CheckReference)11231     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11232       llvm::SmallVector<FieldDecl*, 4> Fields;
11233       Expr *Base = E;
11234       bool ReferenceField = false;
11235 
11236       // Get the field members used.
11237       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11238         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11239         if (!FD)
11240           return false;
11241         Fields.push_back(FD);
11242         if (FD->getType()->isReferenceType())
11243           ReferenceField = true;
11244         Base = ME->getBase()->IgnoreParenImpCasts();
11245       }
11246 
11247       // Keep checking only if the base Decl is the same.
11248       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11249       if (!DRE || DRE->getDecl() != OrigDecl)
11250         return false;
11251 
11252       // A reference field can be bound to an unininitialized field.
11253       if (CheckReference && !ReferenceField)
11254         return true;
11255 
11256       // Convert FieldDecls to their index number.
11257       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11258       for (const FieldDecl *I : llvm::reverse(Fields))
11259         UsedFieldIndex.push_back(I->getFieldIndex());
11260 
11261       // See if a warning is needed by checking the first difference in index
11262       // numbers.  If field being used has index less than the field being
11263       // initialized, then the use is safe.
11264       for (auto UsedIter = UsedFieldIndex.begin(),
11265                 UsedEnd = UsedFieldIndex.end(),
11266                 OrigIter = InitFieldIndex.begin(),
11267                 OrigEnd = InitFieldIndex.end();
11268            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11269         if (*UsedIter < *OrigIter)
11270           return true;
11271         if (*UsedIter > *OrigIter)
11272           break;
11273       }
11274 
11275       // TODO: Add a different warning which will print the field names.
11276       HandleDeclRefExpr(DRE);
11277       return true;
11278     }
11279 
11280     // For most expressions, the cast is directly above the DeclRefExpr.
11281     // For conditional operators, the cast can be outside the conditional
11282     // operator if both expressions are DeclRefExpr's.
HandleValue(Expr * E)11283     void HandleValue(Expr *E) {
11284       E = E->IgnoreParens();
11285       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11286         HandleDeclRefExpr(DRE);
11287         return;
11288       }
11289 
11290       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11291         Visit(CO->getCond());
11292         HandleValue(CO->getTrueExpr());
11293         HandleValue(CO->getFalseExpr());
11294         return;
11295       }
11296 
11297       if (BinaryConditionalOperator *BCO =
11298               dyn_cast<BinaryConditionalOperator>(E)) {
11299         Visit(BCO->getCond());
11300         HandleValue(BCO->getFalseExpr());
11301         return;
11302       }
11303 
11304       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11305         HandleValue(OVE->getSourceExpr());
11306         return;
11307       }
11308 
11309       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11310         if (BO->getOpcode() == BO_Comma) {
11311           Visit(BO->getLHS());
11312           HandleValue(BO->getRHS());
11313           return;
11314         }
11315       }
11316 
11317       if (isa<MemberExpr>(E)) {
11318         if (isInitList) {
11319           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11320                                       false /*CheckReference*/))
11321             return;
11322         }
11323 
11324         Expr *Base = E->IgnoreParenImpCasts();
11325         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11326           // Check for static member variables and don't warn on them.
11327           if (!isa<FieldDecl>(ME->getMemberDecl()))
11328             return;
11329           Base = ME->getBase()->IgnoreParenImpCasts();
11330         }
11331         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11332           HandleDeclRefExpr(DRE);
11333         return;
11334       }
11335 
11336       Visit(E);
11337     }
11338 
11339     // Reference types not handled in HandleValue are handled here since all
11340     // uses of references are bad, not just r-value uses.
VisitDeclRefExpr(DeclRefExpr * E)11341     void VisitDeclRefExpr(DeclRefExpr *E) {
11342       if (isReferenceType)
11343         HandleDeclRefExpr(E);
11344     }
11345 
VisitImplicitCastExpr(ImplicitCastExpr * E)11346     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11347       if (E->getCastKind() == CK_LValueToRValue) {
11348         HandleValue(E->getSubExpr());
11349         return;
11350       }
11351 
11352       Inherited::VisitImplicitCastExpr(E);
11353     }
11354 
VisitMemberExpr(MemberExpr * E)11355     void VisitMemberExpr(MemberExpr *E) {
11356       if (isInitList) {
11357         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11358           return;
11359       }
11360 
11361       // Don't warn on arrays since they can be treated as pointers.
11362       if (E->getType()->canDecayToPointerType()) return;
11363 
11364       // Warn when a non-static method call is followed by non-static member
11365       // field accesses, which is followed by a DeclRefExpr.
11366       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11367       bool Warn = (MD && !MD->isStatic());
11368       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11369       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11370         if (!isa<FieldDecl>(ME->getMemberDecl()))
11371           Warn = false;
11372         Base = ME->getBase()->IgnoreParenImpCasts();
11373       }
11374 
11375       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11376         if (Warn)
11377           HandleDeclRefExpr(DRE);
11378         return;
11379       }
11380 
11381       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11382       // Visit that expression.
11383       Visit(Base);
11384     }
11385 
VisitCXXOperatorCallExpr(CXXOperatorCallExpr * E)11386     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11387       Expr *Callee = E->getCallee();
11388 
11389       if (isa<UnresolvedLookupExpr>(Callee))
11390         return Inherited::VisitCXXOperatorCallExpr(E);
11391 
11392       Visit(Callee);
11393       for (auto Arg: E->arguments())
11394         HandleValue(Arg->IgnoreParenImpCasts());
11395     }
11396 
VisitUnaryOperator(UnaryOperator * E)11397     void VisitUnaryOperator(UnaryOperator *E) {
11398       // For POD record types, addresses of its own members are well-defined.
11399       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11400           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11401         if (!isPODType)
11402           HandleValue(E->getSubExpr());
11403         return;
11404       }
11405 
11406       if (E->isIncrementDecrementOp()) {
11407         HandleValue(E->getSubExpr());
11408         return;
11409       }
11410 
11411       Inherited::VisitUnaryOperator(E);
11412     }
11413 
VisitObjCMessageExpr(ObjCMessageExpr * E)11414     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11415 
VisitCXXConstructExpr(CXXConstructExpr * E)11416     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11417       if (E->getConstructor()->isCopyConstructor()) {
11418         Expr *ArgExpr = E->getArg(0);
11419         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11420           if (ILE->getNumInits() == 1)
11421             ArgExpr = ILE->getInit(0);
11422         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11423           if (ICE->getCastKind() == CK_NoOp)
11424             ArgExpr = ICE->getSubExpr();
11425         HandleValue(ArgExpr);
11426         return;
11427       }
11428       Inherited::VisitCXXConstructExpr(E);
11429     }
11430 
VisitCallExpr(CallExpr * E)11431     void VisitCallExpr(CallExpr *E) {
11432       // Treat std::move as a use.
11433       if (E->isCallToStdMove()) {
11434         HandleValue(E->getArg(0));
11435         return;
11436       }
11437 
11438       Inherited::VisitCallExpr(E);
11439     }
11440 
VisitBinaryOperator(BinaryOperator * E)11441     void VisitBinaryOperator(BinaryOperator *E) {
11442       if (E->isCompoundAssignmentOp()) {
11443         HandleValue(E->getLHS());
11444         Visit(E->getRHS());
11445         return;
11446       }
11447 
11448       Inherited::VisitBinaryOperator(E);
11449     }
11450 
11451     // A custom visitor for BinaryConditionalOperator is needed because the
11452     // regular visitor would check the condition and true expression separately
11453     // but both point to the same place giving duplicate diagnostics.
VisitBinaryConditionalOperator(BinaryConditionalOperator * E)11454     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11455       Visit(E->getCond());
11456       Visit(E->getFalseExpr());
11457     }
11458 
HandleDeclRefExpr(DeclRefExpr * DRE)11459     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11460       Decl* ReferenceDecl = DRE->getDecl();
11461       if (OrigDecl != ReferenceDecl) return;
11462       unsigned diag;
11463       if (isReferenceType) {
11464         diag = diag::warn_uninit_self_reference_in_reference_init;
11465       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11466         diag = diag::warn_static_self_reference_in_init;
11467       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11468                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11469                  DRE->getDecl()->getType()->isRecordType()) {
11470         diag = diag::warn_uninit_self_reference_in_init;
11471       } else {
11472         // Local variables will be handled by the CFG analysis.
11473         return;
11474       }
11475 
11476       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11477                             S.PDiag(diag)
11478                                 << DRE->getDecl() << OrigDecl->getLocation()
11479                                 << DRE->getSourceRange());
11480     }
11481   };
11482 
11483   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
CheckSelfReference(Sema & S,Decl * OrigDecl,Expr * E,bool DirectInit)11484   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11485                                  bool DirectInit) {
11486     // Parameters arguments are occassionially constructed with itself,
11487     // for instance, in recursive functions.  Skip them.
11488     if (isa<ParmVarDecl>(OrigDecl))
11489       return;
11490 
11491     E = E->IgnoreParens();
11492 
11493     // Skip checking T a = a where T is not a record or reference type.
11494     // Doing so is a way to silence uninitialized warnings.
11495     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11496       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11497         if (ICE->getCastKind() == CK_LValueToRValue)
11498           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11499             if (DRE->getDecl() == OrigDecl)
11500               return;
11501 
11502     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11503   }
11504 } // end anonymous namespace
11505 
11506 namespace {
11507   // Simple wrapper to add the name of a variable or (if no variable is
11508   // available) a DeclarationName into a diagnostic.
11509   struct VarDeclOrName {
11510     VarDecl *VDecl;
11511     DeclarationName Name;
11512 
11513     friend const Sema::SemaDiagnosticBuilder &
operator <<(const Sema::SemaDiagnosticBuilder & Diag,VarDeclOrName VN)11514     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11515       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11516     }
11517   };
11518 } // end anonymous namespace
11519 
deduceVarTypeFromInitializer(VarDecl * VDecl,DeclarationName Name,QualType Type,TypeSourceInfo * TSI,SourceRange Range,bool DirectInit,Expr * Init)11520 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11521                                             DeclarationName Name, QualType Type,
11522                                             TypeSourceInfo *TSI,
11523                                             SourceRange Range, bool DirectInit,
11524                                             Expr *Init) {
11525   bool IsInitCapture = !VDecl;
11526   assert((!VDecl || !VDecl->isInitCapture()) &&
11527          "init captures are expected to be deduced prior to initialization");
11528 
11529   VarDeclOrName VN{VDecl, Name};
11530 
11531   DeducedType *Deduced = Type->getContainedDeducedType();
11532   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11533 
11534   // C++11 [dcl.spec.auto]p3
11535   if (!Init) {
11536     assert(VDecl && "no init for init capture deduction?");
11537 
11538     // Except for class argument deduction, and then for an initializing
11539     // declaration only, i.e. no static at class scope or extern.
11540     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11541         VDecl->hasExternalStorage() ||
11542         VDecl->isStaticDataMember()) {
11543       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11544         << VDecl->getDeclName() << Type;
11545       return QualType();
11546     }
11547   }
11548 
11549   ArrayRef<Expr*> DeduceInits;
11550   if (Init)
11551     DeduceInits = Init;
11552 
11553   if (DirectInit) {
11554     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11555       DeduceInits = PL->exprs();
11556   }
11557 
11558   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11559     assert(VDecl && "non-auto type for init capture deduction?");
11560     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11561     InitializationKind Kind = InitializationKind::CreateForInit(
11562         VDecl->getLocation(), DirectInit, Init);
11563     // FIXME: Initialization should not be taking a mutable list of inits.
11564     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11565     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11566                                                        InitsCopy);
11567   }
11568 
11569   if (DirectInit) {
11570     if (auto *IL = dyn_cast<InitListExpr>(Init))
11571       DeduceInits = IL->inits();
11572   }
11573 
11574   // Deduction only works if we have exactly one source expression.
11575   if (DeduceInits.empty()) {
11576     // It isn't possible to write this directly, but it is possible to
11577     // end up in this situation with "auto x(some_pack...);"
11578     Diag(Init->getBeginLoc(), IsInitCapture
11579                                   ? diag::err_init_capture_no_expression
11580                                   : diag::err_auto_var_init_no_expression)
11581         << VN << Type << Range;
11582     return QualType();
11583   }
11584 
11585   if (DeduceInits.size() > 1) {
11586     Diag(DeduceInits[1]->getBeginLoc(),
11587          IsInitCapture ? diag::err_init_capture_multiple_expressions
11588                        : diag::err_auto_var_init_multiple_expressions)
11589         << VN << Type << Range;
11590     return QualType();
11591   }
11592 
11593   Expr *DeduceInit = DeduceInits[0];
11594   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11595     Diag(Init->getBeginLoc(), IsInitCapture
11596                                   ? diag::err_init_capture_paren_braces
11597                                   : diag::err_auto_var_init_paren_braces)
11598         << isa<InitListExpr>(Init) << VN << Type << Range;
11599     return QualType();
11600   }
11601 
11602   // Expressions default to 'id' when we're in a debugger.
11603   bool DefaultedAnyToId = false;
11604   if (getLangOpts().DebuggerCastResultToId &&
11605       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11606     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11607     if (Result.isInvalid()) {
11608       return QualType();
11609     }
11610     Init = Result.get();
11611     DefaultedAnyToId = true;
11612   }
11613 
11614   // C++ [dcl.decomp]p1:
11615   //   If the assignment-expression [...] has array type A and no ref-qualifier
11616   //   is present, e has type cv A
11617   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11618       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11619       DeduceInit->getType()->isConstantArrayType())
11620     return Context.getQualifiedType(DeduceInit->getType(),
11621                                     Type.getQualifiers());
11622 
11623   QualType DeducedType;
11624   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11625     if (!IsInitCapture)
11626       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11627     else if (isa<InitListExpr>(Init))
11628       Diag(Range.getBegin(),
11629            diag::err_init_capture_deduction_failure_from_init_list)
11630           << VN
11631           << (DeduceInit->getType().isNull() ? TSI->getType()
11632                                              : DeduceInit->getType())
11633           << DeduceInit->getSourceRange();
11634     else
11635       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11636           << VN << TSI->getType()
11637           << (DeduceInit->getType().isNull() ? TSI->getType()
11638                                              : DeduceInit->getType())
11639           << DeduceInit->getSourceRange();
11640   }
11641 
11642   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11643   // 'id' instead of a specific object type prevents most of our usual
11644   // checks.
11645   // We only want to warn outside of template instantiations, though:
11646   // inside a template, the 'id' could have come from a parameter.
11647   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11648       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11649     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11650     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11651   }
11652 
11653   return DeducedType;
11654 }
11655 
DeduceVariableDeclarationType(VarDecl * VDecl,bool DirectInit,Expr * Init)11656 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11657                                          Expr *Init) {
11658   assert(!Init || !Init->containsErrors());
11659   QualType DeducedType = deduceVarTypeFromInitializer(
11660       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11661       VDecl->getSourceRange(), DirectInit, Init);
11662   if (DeducedType.isNull()) {
11663     VDecl->setInvalidDecl();
11664     return true;
11665   }
11666 
11667   VDecl->setType(DeducedType);
11668   assert(VDecl->isLinkageValid());
11669 
11670   // In ARC, infer lifetime.
11671   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11672     VDecl->setInvalidDecl();
11673 
11674   if (getLangOpts().OpenCL)
11675     deduceOpenCLAddressSpace(VDecl);
11676 
11677   // If this is a redeclaration, check that the type we just deduced matches
11678   // the previously declared type.
11679   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11680     // We never need to merge the type, because we cannot form an incomplete
11681     // array of auto, nor deduce such a type.
11682     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11683   }
11684 
11685   // Check the deduced type is valid for a variable declaration.
11686   CheckVariableDeclarationType(VDecl);
11687   return VDecl->isInvalidDecl();
11688 }
11689 
checkNonTrivialCUnionInInitializer(const Expr * Init,SourceLocation Loc)11690 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11691                                               SourceLocation Loc) {
11692   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11693     Init = EWC->getSubExpr();
11694 
11695   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11696     Init = CE->getSubExpr();
11697 
11698   QualType InitType = Init->getType();
11699   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11700           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11701          "shouldn't be called if type doesn't have a non-trivial C struct");
11702   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11703     for (auto I : ILE->inits()) {
11704       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11705           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11706         continue;
11707       SourceLocation SL = I->getExprLoc();
11708       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11709     }
11710     return;
11711   }
11712 
11713   if (isa<ImplicitValueInitExpr>(Init)) {
11714     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11715       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11716                             NTCUK_Init);
11717   } else {
11718     // Assume all other explicit initializers involving copying some existing
11719     // object.
11720     // TODO: ignore any explicit initializers where we can guarantee
11721     // copy-elision.
11722     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11723       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11724   }
11725 }
11726 
11727 namespace {
11728 
shouldIgnoreForRecordTriviality(const FieldDecl * FD)11729 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11730   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11731   // in the source code or implicitly by the compiler if it is in a union
11732   // defined in a system header and has non-trivial ObjC ownership
11733   // qualifications. We don't want those fields to participate in determining
11734   // whether the containing union is non-trivial.
11735   return FD->hasAttr<UnavailableAttr>();
11736 }
11737 
11738 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11739     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11740                                     void> {
11741   using Super =
11742       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11743                                     void>;
11744 
DiagNonTrivalCUnionDefaultInitializeVisitor__anon87d11b5b1411::DiagNonTrivalCUnionDefaultInitializeVisitor11745   DiagNonTrivalCUnionDefaultInitializeVisitor(
11746       QualType OrigTy, SourceLocation OrigLoc,
11747       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11748       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11749 
visitWithKind__anon87d11b5b1411::DiagNonTrivalCUnionDefaultInitializeVisitor11750   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11751                      const FieldDecl *FD, bool InNonTrivialUnion) {
11752     if (const auto *AT = S.Context.getAsArrayType(QT))
11753       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11754                                      InNonTrivialUnion);
11755     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11756   }
11757 
visitARCStrong__anon87d11b5b1411::DiagNonTrivalCUnionDefaultInitializeVisitor11758   void visitARCStrong(QualType QT, const FieldDecl *FD,
11759                       bool InNonTrivialUnion) {
11760     if (InNonTrivialUnion)
11761       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11762           << 1 << 0 << QT << FD->getName();
11763   }
11764 
visitARCWeak__anon87d11b5b1411::DiagNonTrivalCUnionDefaultInitializeVisitor11765   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11766     if (InNonTrivialUnion)
11767       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11768           << 1 << 0 << QT << FD->getName();
11769   }
11770 
visitStruct__anon87d11b5b1411::DiagNonTrivalCUnionDefaultInitializeVisitor11771   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11772     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11773     if (RD->isUnion()) {
11774       if (OrigLoc.isValid()) {
11775         bool IsUnion = false;
11776         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11777           IsUnion = OrigRD->isUnion();
11778         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11779             << 0 << OrigTy << IsUnion << UseContext;
11780         // Reset OrigLoc so that this diagnostic is emitted only once.
11781         OrigLoc = SourceLocation();
11782       }
11783       InNonTrivialUnion = true;
11784     }
11785 
11786     if (InNonTrivialUnion)
11787       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11788           << 0 << 0 << QT.getUnqualifiedType() << "";
11789 
11790     for (const FieldDecl *FD : RD->fields())
11791       if (!shouldIgnoreForRecordTriviality(FD))
11792         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11793   }
11794 
visitTrivial__anon87d11b5b1411::DiagNonTrivalCUnionDefaultInitializeVisitor11795   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11796 
11797   // The non-trivial C union type or the struct/union type that contains a
11798   // non-trivial C union.
11799   QualType OrigTy;
11800   SourceLocation OrigLoc;
11801   Sema::NonTrivialCUnionContext UseContext;
11802   Sema &S;
11803 };
11804 
11805 struct DiagNonTrivalCUnionDestructedTypeVisitor
11806     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11807   using Super =
11808       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11809 
DiagNonTrivalCUnionDestructedTypeVisitor__anon87d11b5b1411::DiagNonTrivalCUnionDestructedTypeVisitor11810   DiagNonTrivalCUnionDestructedTypeVisitor(
11811       QualType OrigTy, SourceLocation OrigLoc,
11812       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11813       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11814 
visitWithKind__anon87d11b5b1411::DiagNonTrivalCUnionDestructedTypeVisitor11815   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11816                      const FieldDecl *FD, bool InNonTrivialUnion) {
11817     if (const auto *AT = S.Context.getAsArrayType(QT))
11818       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11819                                      InNonTrivialUnion);
11820     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11821   }
11822 
visitARCStrong__anon87d11b5b1411::DiagNonTrivalCUnionDestructedTypeVisitor11823   void visitARCStrong(QualType QT, const FieldDecl *FD,
11824                       bool InNonTrivialUnion) {
11825     if (InNonTrivialUnion)
11826       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11827           << 1 << 1 << QT << FD->getName();
11828   }
11829 
visitARCWeak__anon87d11b5b1411::DiagNonTrivalCUnionDestructedTypeVisitor11830   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11831     if (InNonTrivialUnion)
11832       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11833           << 1 << 1 << QT << FD->getName();
11834   }
11835 
visitStruct__anon87d11b5b1411::DiagNonTrivalCUnionDestructedTypeVisitor11836   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11837     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11838     if (RD->isUnion()) {
11839       if (OrigLoc.isValid()) {
11840         bool IsUnion = false;
11841         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11842           IsUnion = OrigRD->isUnion();
11843         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11844             << 1 << OrigTy << IsUnion << UseContext;
11845         // Reset OrigLoc so that this diagnostic is emitted only once.
11846         OrigLoc = SourceLocation();
11847       }
11848       InNonTrivialUnion = true;
11849     }
11850 
11851     if (InNonTrivialUnion)
11852       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11853           << 0 << 1 << QT.getUnqualifiedType() << "";
11854 
11855     for (const FieldDecl *FD : RD->fields())
11856       if (!shouldIgnoreForRecordTriviality(FD))
11857         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11858   }
11859 
visitTrivial__anon87d11b5b1411::DiagNonTrivalCUnionDestructedTypeVisitor11860   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
visitCXXDestructor__anon87d11b5b1411::DiagNonTrivalCUnionDestructedTypeVisitor11861   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11862                           bool InNonTrivialUnion) {}
11863 
11864   // The non-trivial C union type or the struct/union type that contains a
11865   // non-trivial C union.
11866   QualType OrigTy;
11867   SourceLocation OrigLoc;
11868   Sema::NonTrivialCUnionContext UseContext;
11869   Sema &S;
11870 };
11871 
11872 struct DiagNonTrivalCUnionCopyVisitor
11873     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11874   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11875 
DiagNonTrivalCUnionCopyVisitor__anon87d11b5b1411::DiagNonTrivalCUnionCopyVisitor11876   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11877                                  Sema::NonTrivialCUnionContext UseContext,
11878                                  Sema &S)
11879       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11880 
visitWithKind__anon87d11b5b1411::DiagNonTrivalCUnionCopyVisitor11881   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11882                      const FieldDecl *FD, bool InNonTrivialUnion) {
11883     if (const auto *AT = S.Context.getAsArrayType(QT))
11884       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11885                                      InNonTrivialUnion);
11886     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11887   }
11888 
visitARCStrong__anon87d11b5b1411::DiagNonTrivalCUnionCopyVisitor11889   void visitARCStrong(QualType QT, const FieldDecl *FD,
11890                       bool InNonTrivialUnion) {
11891     if (InNonTrivialUnion)
11892       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11893           << 1 << 2 << QT << FD->getName();
11894   }
11895 
visitARCWeak__anon87d11b5b1411::DiagNonTrivalCUnionCopyVisitor11896   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11897     if (InNonTrivialUnion)
11898       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11899           << 1 << 2 << QT << FD->getName();
11900   }
11901 
visitStruct__anon87d11b5b1411::DiagNonTrivalCUnionCopyVisitor11902   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11903     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11904     if (RD->isUnion()) {
11905       if (OrigLoc.isValid()) {
11906         bool IsUnion = false;
11907         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11908           IsUnion = OrigRD->isUnion();
11909         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11910             << 2 << OrigTy << IsUnion << UseContext;
11911         // Reset OrigLoc so that this diagnostic is emitted only once.
11912         OrigLoc = SourceLocation();
11913       }
11914       InNonTrivialUnion = true;
11915     }
11916 
11917     if (InNonTrivialUnion)
11918       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11919           << 0 << 2 << QT.getUnqualifiedType() << "";
11920 
11921     for (const FieldDecl *FD : RD->fields())
11922       if (!shouldIgnoreForRecordTriviality(FD))
11923         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11924   }
11925 
preVisit__anon87d11b5b1411::DiagNonTrivalCUnionCopyVisitor11926   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11927                 const FieldDecl *FD, bool InNonTrivialUnion) {}
visitTrivial__anon87d11b5b1411::DiagNonTrivalCUnionCopyVisitor11928   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
visitVolatileTrivial__anon87d11b5b1411::DiagNonTrivalCUnionCopyVisitor11929   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11930                             bool InNonTrivialUnion) {}
11931 
11932   // The non-trivial C union type or the struct/union type that contains a
11933   // non-trivial C union.
11934   QualType OrigTy;
11935   SourceLocation OrigLoc;
11936   Sema::NonTrivialCUnionContext UseContext;
11937   Sema &S;
11938 };
11939 
11940 } // namespace
11941 
checkNonTrivialCUnion(QualType QT,SourceLocation Loc,NonTrivialCUnionContext UseContext,unsigned NonTrivialKind)11942 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11943                                  NonTrivialCUnionContext UseContext,
11944                                  unsigned NonTrivialKind) {
11945   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11946           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11947           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11948          "shouldn't be called if type doesn't have a non-trivial C union");
11949 
11950   if ((NonTrivialKind & NTCUK_Init) &&
11951       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11952     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11953         .visit(QT, nullptr, false);
11954   if ((NonTrivialKind & NTCUK_Destruct) &&
11955       QT.hasNonTrivialToPrimitiveDestructCUnion())
11956     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11957         .visit(QT, nullptr, false);
11958   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11959     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11960         .visit(QT, nullptr, false);
11961 }
11962 
11963 /// AddInitializerToDecl - Adds the initializer Init to the
11964 /// declaration dcl. If DirectInit is true, this is C++ direct
11965 /// initialization rather than copy initialization.
AddInitializerToDecl(Decl * RealDecl,Expr * Init,bool DirectInit)11966 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11967   // If there is no declaration, there was an error parsing it.  Just ignore
11968   // the initializer.
11969   if (!RealDecl || RealDecl->isInvalidDecl()) {
11970     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11971     return;
11972   }
11973 
11974   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11975     // Pure-specifiers are handled in ActOnPureSpecifier.
11976     Diag(Method->getLocation(), diag::err_member_function_initialization)
11977       << Method->getDeclName() << Init->getSourceRange();
11978     Method->setInvalidDecl();
11979     return;
11980   }
11981 
11982   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11983   if (!VDecl) {
11984     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11985     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11986     RealDecl->setInvalidDecl();
11987     return;
11988   }
11989 
11990   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11991   if (VDecl->getType()->isUndeducedType()) {
11992     // Attempt typo correction early so that the type of the init expression can
11993     // be deduced based on the chosen correction if the original init contains a
11994     // TypoExpr.
11995     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11996     if (!Res.isUsable()) {
11997       // There are unresolved typos in Init, just drop them.
11998       // FIXME: improve the recovery strategy to preserve the Init.
11999       RealDecl->setInvalidDecl();
12000       return;
12001     }
12002     if (Res.get()->containsErrors()) {
12003       // Invalidate the decl as we don't know the type for recovery-expr yet.
12004       RealDecl->setInvalidDecl();
12005       VDecl->setInit(Res.get());
12006       return;
12007     }
12008     Init = Res.get();
12009 
12010     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12011       return;
12012   }
12013 
12014   // dllimport cannot be used on variable definitions.
12015   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12016     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12017     VDecl->setInvalidDecl();
12018     return;
12019   }
12020 
12021   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12022     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12023     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12024     VDecl->setInvalidDecl();
12025     return;
12026   }
12027 
12028   if (!VDecl->getType()->isDependentType()) {
12029     // A definition must end up with a complete type, which means it must be
12030     // complete with the restriction that an array type might be completed by
12031     // the initializer; note that later code assumes this restriction.
12032     QualType BaseDeclType = VDecl->getType();
12033     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12034       BaseDeclType = Array->getElementType();
12035     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12036                             diag::err_typecheck_decl_incomplete_type)) {
12037       RealDecl->setInvalidDecl();
12038       return;
12039     }
12040 
12041     // The variable can not have an abstract class type.
12042     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12043                                diag::err_abstract_type_in_decl,
12044                                AbstractVariableType))
12045       VDecl->setInvalidDecl();
12046   }
12047 
12048   // If adding the initializer will turn this declaration into a definition,
12049   // and we already have a definition for this variable, diagnose or otherwise
12050   // handle the situation.
12051   VarDecl *Def;
12052   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12053       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12054       !VDecl->isThisDeclarationADemotedDefinition() &&
12055       checkVarDeclRedefinition(Def, VDecl))
12056     return;
12057 
12058   if (getLangOpts().CPlusPlus) {
12059     // C++ [class.static.data]p4
12060     //   If a static data member is of const integral or const
12061     //   enumeration type, its declaration in the class definition can
12062     //   specify a constant-initializer which shall be an integral
12063     //   constant expression (5.19). In that case, the member can appear
12064     //   in integral constant expressions. The member shall still be
12065     //   defined in a namespace scope if it is used in the program and the
12066     //   namespace scope definition shall not contain an initializer.
12067     //
12068     // We already performed a redefinition check above, but for static
12069     // data members we also need to check whether there was an in-class
12070     // declaration with an initializer.
12071     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12072       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12073           << VDecl->getDeclName();
12074       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12075            diag::note_previous_initializer)
12076           << 0;
12077       return;
12078     }
12079 
12080     if (VDecl->hasLocalStorage())
12081       setFunctionHasBranchProtectedScope();
12082 
12083     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12084       VDecl->setInvalidDecl();
12085       return;
12086     }
12087   }
12088 
12089   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12090   // a kernel function cannot be initialized."
12091   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12092     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12093     VDecl->setInvalidDecl();
12094     return;
12095   }
12096 
12097   // The LoaderUninitialized attribute acts as a definition (of undef).
12098   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12099     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12100     VDecl->setInvalidDecl();
12101     return;
12102   }
12103 
12104   // Get the decls type and save a reference for later, since
12105   // CheckInitializerTypes may change it.
12106   QualType DclT = VDecl->getType(), SavT = DclT;
12107 
12108   // Expressions default to 'id' when we're in a debugger
12109   // and we are assigning it to a variable of Objective-C pointer type.
12110   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12111       Init->getType() == Context.UnknownAnyTy) {
12112     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12113     if (Result.isInvalid()) {
12114       VDecl->setInvalidDecl();
12115       return;
12116     }
12117     Init = Result.get();
12118   }
12119 
12120   // Perform the initialization.
12121   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12122   if (!VDecl->isInvalidDecl()) {
12123     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12124     InitializationKind Kind = InitializationKind::CreateForInit(
12125         VDecl->getLocation(), DirectInit, Init);
12126 
12127     MultiExprArg Args = Init;
12128     if (CXXDirectInit)
12129       Args = MultiExprArg(CXXDirectInit->getExprs(),
12130                           CXXDirectInit->getNumExprs());
12131 
12132     // Try to correct any TypoExprs in the initialization arguments.
12133     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12134       ExprResult Res = CorrectDelayedTyposInExpr(
12135           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/false,
12136           [this, Entity, Kind](Expr *E) {
12137             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12138             return Init.Failed() ? ExprError() : E;
12139           });
12140       if (Res.isInvalid()) {
12141         VDecl->setInvalidDecl();
12142       } else if (Res.get() != Args[Idx]) {
12143         Args[Idx] = Res.get();
12144       }
12145     }
12146     if (VDecl->isInvalidDecl())
12147       return;
12148 
12149     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12150                                    /*TopLevelOfInitList=*/false,
12151                                    /*TreatUnavailableAsInvalid=*/false);
12152     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12153     if (Result.isInvalid()) {
12154       // If the provied initializer fails to initialize the var decl,
12155       // we attach a recovery expr for better recovery.
12156       auto RecoveryExpr =
12157           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12158       if (RecoveryExpr.get())
12159         VDecl->setInit(RecoveryExpr.get());
12160       return;
12161     }
12162 
12163     Init = Result.getAs<Expr>();
12164   }
12165 
12166   // Check for self-references within variable initializers.
12167   // Variables declared within a function/method body (except for references)
12168   // are handled by a dataflow analysis.
12169   // This is undefined behavior in C++, but valid in C.
12170   if (getLangOpts().CPlusPlus) {
12171     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12172         VDecl->getType()->isReferenceType()) {
12173       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12174     }
12175   }
12176 
12177   // If the type changed, it means we had an incomplete type that was
12178   // completed by the initializer. For example:
12179   //   int ary[] = { 1, 3, 5 };
12180   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12181   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12182     VDecl->setType(DclT);
12183 
12184   if (!VDecl->isInvalidDecl()) {
12185     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12186 
12187     if (VDecl->hasAttr<BlocksAttr>())
12188       checkRetainCycles(VDecl, Init);
12189 
12190     // It is safe to assign a weak reference into a strong variable.
12191     // Although this code can still have problems:
12192     //   id x = self.weakProp;
12193     //   id y = self.weakProp;
12194     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12195     // paths through the function. This should be revisited if
12196     // -Wrepeated-use-of-weak is made flow-sensitive.
12197     if (FunctionScopeInfo *FSI = getCurFunction())
12198       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12199            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12200           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12201                            Init->getBeginLoc()))
12202         FSI->markSafeWeakUse(Init);
12203   }
12204 
12205   // The initialization is usually a full-expression.
12206   //
12207   // FIXME: If this is a braced initialization of an aggregate, it is not
12208   // an expression, and each individual field initializer is a separate
12209   // full-expression. For instance, in:
12210   //
12211   //   struct Temp { ~Temp(); };
12212   //   struct S { S(Temp); };
12213   //   struct T { S a, b; } t = { Temp(), Temp() }
12214   //
12215   // we should destroy the first Temp before constructing the second.
12216   ExprResult Result =
12217       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12218                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12219   if (Result.isInvalid()) {
12220     VDecl->setInvalidDecl();
12221     return;
12222   }
12223   Init = Result.get();
12224 
12225   // Attach the initializer to the decl.
12226   VDecl->setInit(Init);
12227 
12228   if (VDecl->isLocalVarDecl()) {
12229     // Don't check the initializer if the declaration is malformed.
12230     if (VDecl->isInvalidDecl()) {
12231       // do nothing
12232 
12233     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12234     // This is true even in C++ for OpenCL.
12235     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12236       CheckForConstantInitializer(Init, DclT);
12237 
12238     // Otherwise, C++ does not restrict the initializer.
12239     } else if (getLangOpts().CPlusPlus) {
12240       // do nothing
12241 
12242     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12243     // static storage duration shall be constant expressions or string literals.
12244     } else if (VDecl->getStorageClass() == SC_Static) {
12245       CheckForConstantInitializer(Init, DclT);
12246 
12247     // C89 is stricter than C99 for aggregate initializers.
12248     // C89 6.5.7p3: All the expressions [...] in an initializer list
12249     // for an object that has aggregate or union type shall be
12250     // constant expressions.
12251     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12252                isa<InitListExpr>(Init)) {
12253       const Expr *Culprit;
12254       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12255         Diag(Culprit->getExprLoc(),
12256              diag::ext_aggregate_init_not_constant)
12257           << Culprit->getSourceRange();
12258       }
12259     }
12260 
12261     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12262       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12263         if (VDecl->hasLocalStorage())
12264           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12265   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12266              VDecl->getLexicalDeclContext()->isRecord()) {
12267     // This is an in-class initialization for a static data member, e.g.,
12268     //
12269     // struct S {
12270     //   static const int value = 17;
12271     // };
12272 
12273     // C++ [class.mem]p4:
12274     //   A member-declarator can contain a constant-initializer only
12275     //   if it declares a static member (9.4) of const integral or
12276     //   const enumeration type, see 9.4.2.
12277     //
12278     // C++11 [class.static.data]p3:
12279     //   If a non-volatile non-inline const static data member is of integral
12280     //   or enumeration type, its declaration in the class definition can
12281     //   specify a brace-or-equal-initializer in which every initializer-clause
12282     //   that is an assignment-expression is a constant expression. A static
12283     //   data member of literal type can be declared in the class definition
12284     //   with the constexpr specifier; if so, its declaration shall specify a
12285     //   brace-or-equal-initializer in which every initializer-clause that is
12286     //   an assignment-expression is a constant expression.
12287 
12288     // Do nothing on dependent types.
12289     if (DclT->isDependentType()) {
12290 
12291     // Allow any 'static constexpr' members, whether or not they are of literal
12292     // type. We separately check that every constexpr variable is of literal
12293     // type.
12294     } else if (VDecl->isConstexpr()) {
12295 
12296     // Require constness.
12297     } else if (!DclT.isConstQualified()) {
12298       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12299         << Init->getSourceRange();
12300       VDecl->setInvalidDecl();
12301 
12302     // We allow integer constant expressions in all cases.
12303     } else if (DclT->isIntegralOrEnumerationType()) {
12304       // Check whether the expression is a constant expression.
12305       SourceLocation Loc;
12306       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12307         // In C++11, a non-constexpr const static data member with an
12308         // in-class initializer cannot be volatile.
12309         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12310       else if (Init->isValueDependent())
12311         ; // Nothing to check.
12312       else if (Init->isIntegerConstantExpr(Context, &Loc))
12313         ; // Ok, it's an ICE!
12314       else if (Init->getType()->isScopedEnumeralType() &&
12315                Init->isCXX11ConstantExpr(Context))
12316         ; // Ok, it is a scoped-enum constant expression.
12317       else if (Init->isEvaluatable(Context)) {
12318         // If we can constant fold the initializer through heroics, accept it,
12319         // but report this as a use of an extension for -pedantic.
12320         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12321           << Init->getSourceRange();
12322       } else {
12323         // Otherwise, this is some crazy unknown case.  Report the issue at the
12324         // location provided by the isIntegerConstantExpr failed check.
12325         Diag(Loc, diag::err_in_class_initializer_non_constant)
12326           << Init->getSourceRange();
12327         VDecl->setInvalidDecl();
12328       }
12329 
12330     // We allow foldable floating-point constants as an extension.
12331     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12332       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12333       // it anyway and provide a fixit to add the 'constexpr'.
12334       if (getLangOpts().CPlusPlus11) {
12335         Diag(VDecl->getLocation(),
12336              diag::ext_in_class_initializer_float_type_cxx11)
12337             << DclT << Init->getSourceRange();
12338         Diag(VDecl->getBeginLoc(),
12339              diag::note_in_class_initializer_float_type_cxx11)
12340             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12341       } else {
12342         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12343           << DclT << Init->getSourceRange();
12344 
12345         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12346           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12347             << Init->getSourceRange();
12348           VDecl->setInvalidDecl();
12349         }
12350       }
12351 
12352     // Suggest adding 'constexpr' in C++11 for literal types.
12353     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12354       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12355           << DclT << Init->getSourceRange()
12356           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12357       VDecl->setConstexpr(true);
12358 
12359     } else {
12360       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12361         << DclT << Init->getSourceRange();
12362       VDecl->setInvalidDecl();
12363     }
12364   } else if (VDecl->isFileVarDecl()) {
12365     // In C, extern is typically used to avoid tentative definitions when
12366     // declaring variables in headers, but adding an intializer makes it a
12367     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12368     // In C++, extern is often used to give implictly static const variables
12369     // external linkage, so don't warn in that case. If selectany is present,
12370     // this might be header code intended for C and C++ inclusion, so apply the
12371     // C++ rules.
12372     if (VDecl->getStorageClass() == SC_Extern &&
12373         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12374          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12375         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12376         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12377       Diag(VDecl->getLocation(), diag::warn_extern_init);
12378 
12379     // In Microsoft C++ mode, a const variable defined in namespace scope has
12380     // external linkage by default if the variable is declared with
12381     // __declspec(dllexport).
12382     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12383         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12384         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12385       VDecl->setStorageClass(SC_Extern);
12386 
12387     // C99 6.7.8p4. All file scoped initializers need to be constant.
12388     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12389       CheckForConstantInitializer(Init, DclT);
12390   }
12391 
12392   QualType InitType = Init->getType();
12393   if (!InitType.isNull() &&
12394       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12395        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12396     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12397 
12398   // We will represent direct-initialization similarly to copy-initialization:
12399   //    int x(1);  -as-> int x = 1;
12400   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12401   //
12402   // Clients that want to distinguish between the two forms, can check for
12403   // direct initializer using VarDecl::getInitStyle().
12404   // A major benefit is that clients that don't particularly care about which
12405   // exactly form was it (like the CodeGen) can handle both cases without
12406   // special case code.
12407 
12408   // C++ 8.5p11:
12409   // The form of initialization (using parentheses or '=') is generally
12410   // insignificant, but does matter when the entity being initialized has a
12411   // class type.
12412   if (CXXDirectInit) {
12413     assert(DirectInit && "Call-style initializer must be direct init.");
12414     VDecl->setInitStyle(VarDecl::CallInit);
12415   } else if (DirectInit) {
12416     // This must be list-initialization. No other way is direct-initialization.
12417     VDecl->setInitStyle(VarDecl::ListInit);
12418   }
12419 
12420   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12421     DeclsToCheckForDeferredDiags.push_back(VDecl);
12422   CheckCompleteVariableDeclaration(VDecl);
12423 }
12424 
12425 /// ActOnInitializerError - Given that there was an error parsing an
12426 /// initializer for the given declaration, try to return to some form
12427 /// of sanity.
ActOnInitializerError(Decl * D)12428 void Sema::ActOnInitializerError(Decl *D) {
12429   // Our main concern here is re-establishing invariants like "a
12430   // variable's type is either dependent or complete".
12431   if (!D || D->isInvalidDecl()) return;
12432 
12433   VarDecl *VD = dyn_cast<VarDecl>(D);
12434   if (!VD) return;
12435 
12436   // Bindings are not usable if we can't make sense of the initializer.
12437   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12438     for (auto *BD : DD->bindings())
12439       BD->setInvalidDecl();
12440 
12441   // Auto types are meaningless if we can't make sense of the initializer.
12442   if (VD->getType()->isUndeducedType()) {
12443     D->setInvalidDecl();
12444     return;
12445   }
12446 
12447   QualType Ty = VD->getType();
12448   if (Ty->isDependentType()) return;
12449 
12450   // Require a complete type.
12451   if (RequireCompleteType(VD->getLocation(),
12452                           Context.getBaseElementType(Ty),
12453                           diag::err_typecheck_decl_incomplete_type)) {
12454     VD->setInvalidDecl();
12455     return;
12456   }
12457 
12458   // Require a non-abstract type.
12459   if (RequireNonAbstractType(VD->getLocation(), Ty,
12460                              diag::err_abstract_type_in_decl,
12461                              AbstractVariableType)) {
12462     VD->setInvalidDecl();
12463     return;
12464   }
12465 
12466   // Don't bother complaining about constructors or destructors,
12467   // though.
12468 }
12469 
ActOnUninitializedDecl(Decl * RealDecl)12470 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12471   // If there is no declaration, there was an error parsing it. Just ignore it.
12472   if (!RealDecl)
12473     return;
12474 
12475   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12476     QualType Type = Var->getType();
12477 
12478     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12479     if (isa<DecompositionDecl>(RealDecl)) {
12480       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12481       Var->setInvalidDecl();
12482       return;
12483     }
12484 
12485     if (Type->isUndeducedType() &&
12486         DeduceVariableDeclarationType(Var, false, nullptr))
12487       return;
12488 
12489     // C++11 [class.static.data]p3: A static data member can be declared with
12490     // the constexpr specifier; if so, its declaration shall specify
12491     // a brace-or-equal-initializer.
12492     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12493     // the definition of a variable [...] or the declaration of a static data
12494     // member.
12495     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12496         !Var->isThisDeclarationADemotedDefinition()) {
12497       if (Var->isStaticDataMember()) {
12498         // C++1z removes the relevant rule; the in-class declaration is always
12499         // a definition there.
12500         if (!getLangOpts().CPlusPlus17 &&
12501             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12502           Diag(Var->getLocation(),
12503                diag::err_constexpr_static_mem_var_requires_init)
12504             << Var->getDeclName();
12505           Var->setInvalidDecl();
12506           return;
12507         }
12508       } else {
12509         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12510         Var->setInvalidDecl();
12511         return;
12512       }
12513     }
12514 
12515     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12516     // be initialized.
12517     if (!Var->isInvalidDecl() &&
12518         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12519         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12520       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12521       Var->setInvalidDecl();
12522       return;
12523     }
12524 
12525     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12526       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12527         if (!RD->hasTrivialDefaultConstructor()) {
12528           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12529           Var->setInvalidDecl();
12530           return;
12531         }
12532       }
12533       if (Var->getStorageClass() == SC_Extern) {
12534         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12535             << Var;
12536         Var->setInvalidDecl();
12537         return;
12538       }
12539     }
12540 
12541     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12542     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12543         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12544       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12545                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12546 
12547 
12548     switch (DefKind) {
12549     case VarDecl::Definition:
12550       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12551         break;
12552 
12553       // We have an out-of-line definition of a static data member
12554       // that has an in-class initializer, so we type-check this like
12555       // a declaration.
12556       //
12557       LLVM_FALLTHROUGH;
12558 
12559     case VarDecl::DeclarationOnly:
12560       // It's only a declaration.
12561 
12562       // Block scope. C99 6.7p7: If an identifier for an object is
12563       // declared with no linkage (C99 6.2.2p6), the type for the
12564       // object shall be complete.
12565       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12566           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12567           RequireCompleteType(Var->getLocation(), Type,
12568                               diag::err_typecheck_decl_incomplete_type))
12569         Var->setInvalidDecl();
12570 
12571       // Make sure that the type is not abstract.
12572       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12573           RequireNonAbstractType(Var->getLocation(), Type,
12574                                  diag::err_abstract_type_in_decl,
12575                                  AbstractVariableType))
12576         Var->setInvalidDecl();
12577       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12578           Var->getStorageClass() == SC_PrivateExtern) {
12579         Diag(Var->getLocation(), diag::warn_private_extern);
12580         Diag(Var->getLocation(), diag::note_private_extern);
12581       }
12582 
12583       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12584           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12585         ExternalDeclarations.push_back(Var);
12586 
12587       return;
12588 
12589     case VarDecl::TentativeDefinition:
12590       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12591       // object that has file scope without an initializer, and without a
12592       // storage-class specifier or with the storage-class specifier "static",
12593       // constitutes a tentative definition. Note: A tentative definition with
12594       // external linkage is valid (C99 6.2.2p5).
12595       if (!Var->isInvalidDecl()) {
12596         if (const IncompleteArrayType *ArrayT
12597                                     = Context.getAsIncompleteArrayType(Type)) {
12598           if (RequireCompleteSizedType(
12599                   Var->getLocation(), ArrayT->getElementType(),
12600                   diag::err_array_incomplete_or_sizeless_type))
12601             Var->setInvalidDecl();
12602         } else if (Var->getStorageClass() == SC_Static) {
12603           // C99 6.9.2p3: If the declaration of an identifier for an object is
12604           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12605           // declared type shall not be an incomplete type.
12606           // NOTE: code such as the following
12607           //     static struct s;
12608           //     struct s { int a; };
12609           // is accepted by gcc. Hence here we issue a warning instead of
12610           // an error and we do not invalidate the static declaration.
12611           // NOTE: to avoid multiple warnings, only check the first declaration.
12612           if (Var->isFirstDecl())
12613             RequireCompleteType(Var->getLocation(), Type,
12614                                 diag::ext_typecheck_decl_incomplete_type);
12615         }
12616       }
12617 
12618       // Record the tentative definition; we're done.
12619       if (!Var->isInvalidDecl())
12620         TentativeDefinitions.push_back(Var);
12621       return;
12622     }
12623 
12624     // Provide a specific diagnostic for uninitialized variable
12625     // definitions with incomplete array type.
12626     if (Type->isIncompleteArrayType()) {
12627       Diag(Var->getLocation(),
12628            diag::err_typecheck_incomplete_array_needs_initializer);
12629       Var->setInvalidDecl();
12630       return;
12631     }
12632 
12633     // Provide a specific diagnostic for uninitialized variable
12634     // definitions with reference type.
12635     if (Type->isReferenceType()) {
12636       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12637         << Var->getDeclName()
12638         << SourceRange(Var->getLocation(), Var->getLocation());
12639       Var->setInvalidDecl();
12640       return;
12641     }
12642 
12643     // Do not attempt to type-check the default initializer for a
12644     // variable with dependent type.
12645     if (Type->isDependentType())
12646       return;
12647 
12648     if (Var->isInvalidDecl())
12649       return;
12650 
12651     if (!Var->hasAttr<AliasAttr>()) {
12652       if (RequireCompleteType(Var->getLocation(),
12653                               Context.getBaseElementType(Type),
12654                               diag::err_typecheck_decl_incomplete_type)) {
12655         Var->setInvalidDecl();
12656         return;
12657       }
12658     } else {
12659       return;
12660     }
12661 
12662     // The variable can not have an abstract class type.
12663     if (RequireNonAbstractType(Var->getLocation(), Type,
12664                                diag::err_abstract_type_in_decl,
12665                                AbstractVariableType)) {
12666       Var->setInvalidDecl();
12667       return;
12668     }
12669 
12670     // Check for jumps past the implicit initializer.  C++0x
12671     // clarifies that this applies to a "variable with automatic
12672     // storage duration", not a "local variable".
12673     // C++11 [stmt.dcl]p3
12674     //   A program that jumps from a point where a variable with automatic
12675     //   storage duration is not in scope to a point where it is in scope is
12676     //   ill-formed unless the variable has scalar type, class type with a
12677     //   trivial default constructor and a trivial destructor, a cv-qualified
12678     //   version of one of these types, or an array of one of the preceding
12679     //   types and is declared without an initializer.
12680     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12681       if (const RecordType *Record
12682             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12683         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12684         // Mark the function (if we're in one) for further checking even if the
12685         // looser rules of C++11 do not require such checks, so that we can
12686         // diagnose incompatibilities with C++98.
12687         if (!CXXRecord->isPOD())
12688           setFunctionHasBranchProtectedScope();
12689       }
12690     }
12691     // In OpenCL, we can't initialize objects in the __local address space,
12692     // even implicitly, so don't synthesize an implicit initializer.
12693     if (getLangOpts().OpenCL &&
12694         Var->getType().getAddressSpace() == LangAS::opencl_local)
12695       return;
12696     // C++03 [dcl.init]p9:
12697     //   If no initializer is specified for an object, and the
12698     //   object is of (possibly cv-qualified) non-POD class type (or
12699     //   array thereof), the object shall be default-initialized; if
12700     //   the object is of const-qualified type, the underlying class
12701     //   type shall have a user-declared default
12702     //   constructor. Otherwise, if no initializer is specified for
12703     //   a non- static object, the object and its subobjects, if
12704     //   any, have an indeterminate initial value); if the object
12705     //   or any of its subobjects are of const-qualified type, the
12706     //   program is ill-formed.
12707     // C++0x [dcl.init]p11:
12708     //   If no initializer is specified for an object, the object is
12709     //   default-initialized; [...].
12710     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12711     InitializationKind Kind
12712       = InitializationKind::CreateDefault(Var->getLocation());
12713 
12714     InitializationSequence InitSeq(*this, Entity, Kind, None);
12715     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12716 
12717     if (Init.get()) {
12718       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12719       // This is important for template substitution.
12720       Var->setInitStyle(VarDecl::CallInit);
12721     } else if (Init.isInvalid()) {
12722       // If default-init fails, attach a recovery-expr initializer to track
12723       // that initialization was attempted and failed.
12724       auto RecoveryExpr =
12725           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12726       if (RecoveryExpr.get())
12727         Var->setInit(RecoveryExpr.get());
12728     }
12729 
12730     CheckCompleteVariableDeclaration(Var);
12731   }
12732 }
12733 
ActOnCXXForRangeDecl(Decl * D)12734 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12735   // If there is no declaration, there was an error parsing it. Ignore it.
12736   if (!D)
12737     return;
12738 
12739   VarDecl *VD = dyn_cast<VarDecl>(D);
12740   if (!VD) {
12741     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12742     D->setInvalidDecl();
12743     return;
12744   }
12745 
12746   VD->setCXXForRangeDecl(true);
12747 
12748   // for-range-declaration cannot be given a storage class specifier.
12749   int Error = -1;
12750   switch (VD->getStorageClass()) {
12751   case SC_None:
12752     break;
12753   case SC_Extern:
12754     Error = 0;
12755     break;
12756   case SC_Static:
12757     Error = 1;
12758     break;
12759   case SC_PrivateExtern:
12760     Error = 2;
12761     break;
12762   case SC_Auto:
12763     Error = 3;
12764     break;
12765   case SC_Register:
12766     Error = 4;
12767     break;
12768   }
12769   if (Error != -1) {
12770     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12771       << VD->getDeclName() << Error;
12772     D->setInvalidDecl();
12773   }
12774 }
12775 
12776 StmtResult
ActOnCXXForRangeIdentifier(Scope * S,SourceLocation IdentLoc,IdentifierInfo * Ident,ParsedAttributes & Attrs,SourceLocation AttrEnd)12777 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12778                                  IdentifierInfo *Ident,
12779                                  ParsedAttributes &Attrs,
12780                                  SourceLocation AttrEnd) {
12781   // C++1y [stmt.iter]p1:
12782   //   A range-based for statement of the form
12783   //      for ( for-range-identifier : for-range-initializer ) statement
12784   //   is equivalent to
12785   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12786   DeclSpec DS(Attrs.getPool().getFactory());
12787 
12788   const char *PrevSpec;
12789   unsigned DiagID;
12790   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12791                      getPrintingPolicy());
12792 
12793   Declarator D(DS, DeclaratorContext::ForContext);
12794   D.SetIdentifier(Ident, IdentLoc);
12795   D.takeAttributes(Attrs, AttrEnd);
12796 
12797   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12798                 IdentLoc);
12799   Decl *Var = ActOnDeclarator(S, D);
12800   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12801   FinalizeDeclaration(Var);
12802   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12803                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12804 }
12805 
CheckCompleteVariableDeclaration(VarDecl * var)12806 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12807   if (var->isInvalidDecl()) return;
12808 
12809   if (getLangOpts().OpenCL) {
12810     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12811     // initialiser
12812     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12813         !var->hasInit()) {
12814       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12815           << 1 /*Init*/;
12816       var->setInvalidDecl();
12817       return;
12818     }
12819   }
12820 
12821   // In Objective-C, don't allow jumps past the implicit initialization of a
12822   // local retaining variable.
12823   if (getLangOpts().ObjC &&
12824       var->hasLocalStorage()) {
12825     switch (var->getType().getObjCLifetime()) {
12826     case Qualifiers::OCL_None:
12827     case Qualifiers::OCL_ExplicitNone:
12828     case Qualifiers::OCL_Autoreleasing:
12829       break;
12830 
12831     case Qualifiers::OCL_Weak:
12832     case Qualifiers::OCL_Strong:
12833       setFunctionHasBranchProtectedScope();
12834       break;
12835     }
12836   }
12837 
12838   if (var->hasLocalStorage() &&
12839       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12840     setFunctionHasBranchProtectedScope();
12841 
12842   // Warn about externally-visible variables being defined without a
12843   // prior declaration.  We only want to do this for global
12844   // declarations, but we also specifically need to avoid doing it for
12845   // class members because the linkage of an anonymous class can
12846   // change if it's later given a typedef name.
12847   if (var->isThisDeclarationADefinition() &&
12848       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12849       var->isExternallyVisible() && var->hasLinkage() &&
12850       !var->isInline() && !var->getDescribedVarTemplate() &&
12851       !isa<VarTemplatePartialSpecializationDecl>(var) &&
12852       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12853       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12854                                   var->getLocation())) {
12855     // Find a previous declaration that's not a definition.
12856     VarDecl *prev = var->getPreviousDecl();
12857     while (prev && prev->isThisDeclarationADefinition())
12858       prev = prev->getPreviousDecl();
12859 
12860     if (!prev) {
12861       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12862       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12863           << /* variable */ 0;
12864     }
12865   }
12866 
12867   // Cache the result of checking for constant initialization.
12868   Optional<bool> CacheHasConstInit;
12869   const Expr *CacheCulprit = nullptr;
12870   auto checkConstInit = [&]() mutable {
12871     if (!CacheHasConstInit)
12872       CacheHasConstInit = var->getInit()->isConstantInitializer(
12873             Context, var->getType()->isReferenceType(), &CacheCulprit);
12874     return *CacheHasConstInit;
12875   };
12876 
12877   if (var->getTLSKind() == VarDecl::TLS_Static) {
12878     if (var->getType().isDestructedType()) {
12879       // GNU C++98 edits for __thread, [basic.start.term]p3:
12880       //   The type of an object with thread storage duration shall not
12881       //   have a non-trivial destructor.
12882       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12883       if (getLangOpts().CPlusPlus11)
12884         Diag(var->getLocation(), diag::note_use_thread_local);
12885     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12886       if (!checkConstInit()) {
12887         // GNU C++98 edits for __thread, [basic.start.init]p4:
12888         //   An object of thread storage duration shall not require dynamic
12889         //   initialization.
12890         // FIXME: Need strict checking here.
12891         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12892           << CacheCulprit->getSourceRange();
12893         if (getLangOpts().CPlusPlus11)
12894           Diag(var->getLocation(), diag::note_use_thread_local);
12895       }
12896     }
12897   }
12898 
12899   // Apply section attributes and pragmas to global variables.
12900   bool GlobalStorage = var->hasGlobalStorage();
12901   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12902       !inTemplateInstantiation()) {
12903     PragmaStack<StringLiteral *> *Stack = nullptr;
12904     int SectionFlags = ASTContext::PSF_Read;
12905     if (var->getType().isConstQualified())
12906       Stack = &ConstSegStack;
12907     else if (!var->getInit()) {
12908       Stack = &BSSSegStack;
12909       SectionFlags |= ASTContext::PSF_Write;
12910     } else {
12911       Stack = &DataSegStack;
12912       SectionFlags |= ASTContext::PSF_Write;
12913     }
12914     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
12915       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
12916         SectionFlags |= ASTContext::PSF_Implicit;
12917       UnifySection(SA->getName(), SectionFlags, var);
12918     } else if (Stack->CurrentValue) {
12919       SectionFlags |= ASTContext::PSF_Implicit;
12920       auto SectionName = Stack->CurrentValue->getString();
12921       var->addAttr(SectionAttr::CreateImplicit(
12922           Context, SectionName, Stack->CurrentPragmaLocation,
12923           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
12924       if (UnifySection(SectionName, SectionFlags, var))
12925         var->dropAttr<SectionAttr>();
12926     }
12927 
12928     // Apply the init_seg attribute if this has an initializer.  If the
12929     // initializer turns out to not be dynamic, we'll end up ignoring this
12930     // attribute.
12931     if (CurInitSeg && var->getInit())
12932       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12933                                                CurInitSegLoc,
12934                                                AttributeCommonInfo::AS_Pragma));
12935   }
12936 
12937   // All the following checks are C++ only.
12938   if (!getLangOpts().CPlusPlus) {
12939       // If this variable must be emitted, add it as an initializer for the
12940       // current module.
12941      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12942        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12943      return;
12944   }
12945 
12946   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12947     CheckCompleteDecompositionDeclaration(DD);
12948 
12949   QualType type = var->getType();
12950   if (type->isDependentType()) return;
12951 
12952   if (var->hasAttr<BlocksAttr>())
12953     getCurFunction()->addByrefBlockVar(var);
12954 
12955   Expr *Init = var->getInit();
12956   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12957   QualType baseType = Context.getBaseElementType(type);
12958 
12959   if (Init && !Init->isValueDependent()) {
12960     if (var->isConstexpr()) {
12961       SmallVector<PartialDiagnosticAt, 8> Notes;
12962       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12963         SourceLocation DiagLoc = var->getLocation();
12964         // If the note doesn't add any useful information other than a source
12965         // location, fold it into the primary diagnostic.
12966         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12967               diag::note_invalid_subexpr_in_const_expr) {
12968           DiagLoc = Notes[0].first;
12969           Notes.clear();
12970         }
12971         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12972           << var << Init->getSourceRange();
12973         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12974           Diag(Notes[I].first, Notes[I].second);
12975       }
12976     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12977       // Check whether the initializer of a const variable of integral or
12978       // enumeration type is an ICE now, since we can't tell whether it was
12979       // initialized by a constant expression if we check later.
12980       var->checkInitIsICE();
12981     }
12982 
12983     // Don't emit further diagnostics about constexpr globals since they
12984     // were just diagnosed.
12985     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12986       // FIXME: Need strict checking in C++03 here.
12987       bool DiagErr = getLangOpts().CPlusPlus11
12988           ? !var->checkInitIsICE() : !checkConstInit();
12989       if (DiagErr) {
12990         auto *Attr = var->getAttr<ConstInitAttr>();
12991         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12992           << Init->getSourceRange();
12993         Diag(Attr->getLocation(),
12994              diag::note_declared_required_constant_init_here)
12995             << Attr->getRange() << Attr->isConstinit();
12996         if (getLangOpts().CPlusPlus11) {
12997           APValue Value;
12998           SmallVector<PartialDiagnosticAt, 8> Notes;
12999           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
13000           for (auto &it : Notes)
13001             Diag(it.first, it.second);
13002         } else {
13003           Diag(CacheCulprit->getExprLoc(),
13004                diag::note_invalid_subexpr_in_const_expr)
13005               << CacheCulprit->getSourceRange();
13006         }
13007       }
13008     }
13009     else if (!var->isConstexpr() && IsGlobal &&
13010              !getDiagnostics().isIgnored(diag::warn_global_constructor,
13011                                     var->getLocation())) {
13012       // Warn about globals which don't have a constant initializer.  Don't
13013       // warn about globals with a non-trivial destructor because we already
13014       // warned about them.
13015       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13016       if (!(RD && !RD->hasTrivialDestructor())) {
13017         if (!checkConstInit())
13018           Diag(var->getLocation(), diag::warn_global_constructor)
13019             << Init->getSourceRange();
13020       }
13021     }
13022   }
13023 
13024   // Require the destructor.
13025   if (const RecordType *recordType = baseType->getAs<RecordType>())
13026     FinalizeVarWithDestructor(var, recordType);
13027 
13028   // If this variable must be emitted, add it as an initializer for the current
13029   // module.
13030   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13031     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13032 }
13033 
13034 /// Determines if a variable's alignment is dependent.
hasDependentAlignment(VarDecl * VD)13035 static bool hasDependentAlignment(VarDecl *VD) {
13036   if (VD->getType()->isDependentType())
13037     return true;
13038   for (auto *I : VD->specific_attrs<AlignedAttr>())
13039     if (I->isAlignmentDependent())
13040       return true;
13041   return false;
13042 }
13043 
13044 /// Check if VD needs to be dllexport/dllimport due to being in a
13045 /// dllexport/import function.
CheckStaticLocalForDllExport(VarDecl * VD)13046 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13047   assert(VD->isStaticLocal());
13048 
13049   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13050 
13051   // Find outermost function when VD is in lambda function.
13052   while (FD && !getDLLAttr(FD) &&
13053          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13054          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13055     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13056   }
13057 
13058   if (!FD)
13059     return;
13060 
13061   // Static locals inherit dll attributes from their function.
13062   if (Attr *A = getDLLAttr(FD)) {
13063     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13064     NewAttr->setInherited(true);
13065     VD->addAttr(NewAttr);
13066   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13067     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13068     NewAttr->setInherited(true);
13069     VD->addAttr(NewAttr);
13070 
13071     // Export this function to enforce exporting this static variable even
13072     // if it is not used in this compilation unit.
13073     if (!FD->hasAttr<DLLExportAttr>())
13074       FD->addAttr(NewAttr);
13075 
13076   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13077     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13078     NewAttr->setInherited(true);
13079     VD->addAttr(NewAttr);
13080   }
13081 }
13082 
13083 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13084 /// any semantic actions necessary after any initializer has been attached.
FinalizeDeclaration(Decl * ThisDecl)13085 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13086   // Note that we are no longer parsing the initializer for this declaration.
13087   ParsingInitForAutoVars.erase(ThisDecl);
13088 
13089   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13090   if (!VD)
13091     return;
13092 
13093   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13094   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13095       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13096     if (PragmaClangBSSSection.Valid)
13097       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13098           Context, PragmaClangBSSSection.SectionName,
13099           PragmaClangBSSSection.PragmaLocation,
13100           AttributeCommonInfo::AS_Pragma));
13101     if (PragmaClangDataSection.Valid)
13102       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13103           Context, PragmaClangDataSection.SectionName,
13104           PragmaClangDataSection.PragmaLocation,
13105           AttributeCommonInfo::AS_Pragma));
13106     if (PragmaClangRodataSection.Valid)
13107       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13108           Context, PragmaClangRodataSection.SectionName,
13109           PragmaClangRodataSection.PragmaLocation,
13110           AttributeCommonInfo::AS_Pragma));
13111     if (PragmaClangRelroSection.Valid)
13112       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13113           Context, PragmaClangRelroSection.SectionName,
13114           PragmaClangRelroSection.PragmaLocation,
13115           AttributeCommonInfo::AS_Pragma));
13116   }
13117 
13118   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13119     for (auto *BD : DD->bindings()) {
13120       FinalizeDeclaration(BD);
13121     }
13122   }
13123 
13124   checkAttributesAfterMerging(*this, *VD);
13125 
13126   // Perform TLS alignment check here after attributes attached to the variable
13127   // which may affect the alignment have been processed. Only perform the check
13128   // if the target has a maximum TLS alignment (zero means no constraints).
13129   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13130     // Protect the check so that it's not performed on dependent types and
13131     // dependent alignments (we can't determine the alignment in that case).
13132     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13133         !VD->isInvalidDecl()) {
13134       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13135       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13136         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13137           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13138           << (unsigned)MaxAlignChars.getQuantity();
13139       }
13140     }
13141   }
13142 
13143   if (VD->isStaticLocal()) {
13144     CheckStaticLocalForDllExport(VD);
13145 
13146     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
13147       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
13148       // function, only __shared__ variables or variables without any device
13149       // memory qualifiers may be declared with static storage class.
13150       // Note: It is unclear how a function-scope non-const static variable
13151       // without device memory qualifier is implemented, therefore only static
13152       // const variable without device memory qualifier is allowed.
13153       [&]() {
13154         if (!getLangOpts().CUDA)
13155           return;
13156         if (VD->hasAttr<CUDASharedAttr>())
13157           return;
13158         if (VD->getType().isConstQualified() &&
13159             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
13160           return;
13161         if (CUDADiagIfDeviceCode(VD->getLocation(),
13162                                  diag::err_device_static_local_var)
13163             << CurrentCUDATarget())
13164           VD->setInvalidDecl();
13165       }();
13166     }
13167   }
13168 
13169   // Perform check for initializers of device-side global variables.
13170   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13171   // 7.5). We must also apply the same checks to all __shared__
13172   // variables whether they are local or not. CUDA also allows
13173   // constant initializers for __constant__ and __device__ variables.
13174   if (getLangOpts().CUDA)
13175     checkAllowedCUDAInitializer(VD);
13176 
13177   // Grab the dllimport or dllexport attribute off of the VarDecl.
13178   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13179 
13180   // Imported static data members cannot be defined out-of-line.
13181   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13182     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13183         VD->isThisDeclarationADefinition()) {
13184       // We allow definitions of dllimport class template static data members
13185       // with a warning.
13186       CXXRecordDecl *Context =
13187         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13188       bool IsClassTemplateMember =
13189           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13190           Context->getDescribedClassTemplate();
13191 
13192       Diag(VD->getLocation(),
13193            IsClassTemplateMember
13194                ? diag::warn_attribute_dllimport_static_field_definition
13195                : diag::err_attribute_dllimport_static_field_definition);
13196       Diag(IA->getLocation(), diag::note_attribute);
13197       if (!IsClassTemplateMember)
13198         VD->setInvalidDecl();
13199     }
13200   }
13201 
13202   // dllimport/dllexport variables cannot be thread local, their TLS index
13203   // isn't exported with the variable.
13204   if (DLLAttr && VD->getTLSKind()) {
13205     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13206     if (F && getDLLAttr(F)) {
13207       assert(VD->isStaticLocal());
13208       // But if this is a static local in a dlimport/dllexport function, the
13209       // function will never be inlined, which means the var would never be
13210       // imported, so having it marked import/export is safe.
13211     } else {
13212       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13213                                                                     << DLLAttr;
13214       VD->setInvalidDecl();
13215     }
13216   }
13217 
13218   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13219     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13220       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
13221       VD->dropAttr<UsedAttr>();
13222     }
13223   }
13224 
13225   const DeclContext *DC = VD->getDeclContext();
13226   // If there's a #pragma GCC visibility in scope, and this isn't a class
13227   // member, set the visibility of this variable.
13228   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13229     AddPushedVisibilityAttribute(VD);
13230 
13231   // FIXME: Warn on unused var template partial specializations.
13232   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13233     MarkUnusedFileScopedDecl(VD);
13234 
13235   // Now we have parsed the initializer and can update the table of magic
13236   // tag values.
13237   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13238       !VD->getType()->isIntegralOrEnumerationType())
13239     return;
13240 
13241   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13242     const Expr *MagicValueExpr = VD->getInit();
13243     if (!MagicValueExpr) {
13244       continue;
13245     }
13246     llvm::APSInt MagicValueInt;
13247     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
13248       Diag(I->getRange().getBegin(),
13249            diag::err_type_tag_for_datatype_not_ice)
13250         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13251       continue;
13252     }
13253     if (MagicValueInt.getActiveBits() > 64) {
13254       Diag(I->getRange().getBegin(),
13255            diag::err_type_tag_for_datatype_too_large)
13256         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13257       continue;
13258     }
13259     uint64_t MagicValue = MagicValueInt.getZExtValue();
13260     RegisterTypeTagForDatatype(I->getArgumentKind(),
13261                                MagicValue,
13262                                I->getMatchingCType(),
13263                                I->getLayoutCompatible(),
13264                                I->getMustBeNull());
13265   }
13266 }
13267 
hasDeducedAuto(DeclaratorDecl * DD)13268 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13269   auto *VD = dyn_cast<VarDecl>(DD);
13270   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13271 }
13272 
FinalizeDeclaratorGroup(Scope * S,const DeclSpec & DS,ArrayRef<Decl * > Group)13273 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13274                                                    ArrayRef<Decl *> Group) {
13275   SmallVector<Decl*, 8> Decls;
13276 
13277   if (DS.isTypeSpecOwned())
13278     Decls.push_back(DS.getRepAsDecl());
13279 
13280   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13281   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13282   bool DiagnosedMultipleDecomps = false;
13283   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13284   bool DiagnosedNonDeducedAuto = false;
13285 
13286   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13287     if (Decl *D = Group[i]) {
13288       // For declarators, there are some additional syntactic-ish checks we need
13289       // to perform.
13290       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13291         if (!FirstDeclaratorInGroup)
13292           FirstDeclaratorInGroup = DD;
13293         if (!FirstDecompDeclaratorInGroup)
13294           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13295         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13296             !hasDeducedAuto(DD))
13297           FirstNonDeducedAutoInGroup = DD;
13298 
13299         if (FirstDeclaratorInGroup != DD) {
13300           // A decomposition declaration cannot be combined with any other
13301           // declaration in the same group.
13302           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13303             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13304                  diag::err_decomp_decl_not_alone)
13305                 << FirstDeclaratorInGroup->getSourceRange()
13306                 << DD->getSourceRange();
13307             DiagnosedMultipleDecomps = true;
13308           }
13309 
13310           // A declarator that uses 'auto' in any way other than to declare a
13311           // variable with a deduced type cannot be combined with any other
13312           // declarator in the same group.
13313           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13314             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13315                  diag::err_auto_non_deduced_not_alone)
13316                 << FirstNonDeducedAutoInGroup->getType()
13317                        ->hasAutoForTrailingReturnType()
13318                 << FirstDeclaratorInGroup->getSourceRange()
13319                 << DD->getSourceRange();
13320             DiagnosedNonDeducedAuto = true;
13321           }
13322         }
13323       }
13324 
13325       Decls.push_back(D);
13326     }
13327   }
13328 
13329   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13330     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13331       handleTagNumbering(Tag, S);
13332       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13333           getLangOpts().CPlusPlus)
13334         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13335     }
13336   }
13337 
13338   return BuildDeclaratorGroup(Decls);
13339 }
13340 
13341 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13342 /// group, performing any necessary semantic checking.
13343 Sema::DeclGroupPtrTy
BuildDeclaratorGroup(MutableArrayRef<Decl * > Group)13344 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13345   // C++14 [dcl.spec.auto]p7: (DR1347)
13346   //   If the type that replaces the placeholder type is not the same in each
13347   //   deduction, the program is ill-formed.
13348   if (Group.size() > 1) {
13349     QualType Deduced;
13350     VarDecl *DeducedDecl = nullptr;
13351     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13352       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13353       if (!D || D->isInvalidDecl())
13354         break;
13355       DeducedType *DT = D->getType()->getContainedDeducedType();
13356       if (!DT || DT->getDeducedType().isNull())
13357         continue;
13358       if (Deduced.isNull()) {
13359         Deduced = DT->getDeducedType();
13360         DeducedDecl = D;
13361       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13362         auto *AT = dyn_cast<AutoType>(DT);
13363         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13364                         diag::err_auto_different_deductions)
13365                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13366                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13367                    << D->getDeclName();
13368         if (DeducedDecl->hasInit())
13369           Dia << DeducedDecl->getInit()->getSourceRange();
13370         if (D->getInit())
13371           Dia << D->getInit()->getSourceRange();
13372         D->setInvalidDecl();
13373         break;
13374       }
13375     }
13376   }
13377 
13378   ActOnDocumentableDecls(Group);
13379 
13380   return DeclGroupPtrTy::make(
13381       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13382 }
13383 
ActOnDocumentableDecl(Decl * D)13384 void Sema::ActOnDocumentableDecl(Decl *D) {
13385   ActOnDocumentableDecls(D);
13386 }
13387 
ActOnDocumentableDecls(ArrayRef<Decl * > Group)13388 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13389   // Don't parse the comment if Doxygen diagnostics are ignored.
13390   if (Group.empty() || !Group[0])
13391     return;
13392 
13393   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13394                       Group[0]->getLocation()) &&
13395       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13396                       Group[0]->getLocation()))
13397     return;
13398 
13399   if (Group.size() >= 2) {
13400     // This is a decl group.  Normally it will contain only declarations
13401     // produced from declarator list.  But in case we have any definitions or
13402     // additional declaration references:
13403     //   'typedef struct S {} S;'
13404     //   'typedef struct S *S;'
13405     //   'struct S *pS;'
13406     // FinalizeDeclaratorGroup adds these as separate declarations.
13407     Decl *MaybeTagDecl = Group[0];
13408     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13409       Group = Group.slice(1);
13410     }
13411   }
13412 
13413   // FIMXE: We assume every Decl in the group is in the same file.
13414   // This is false when preprocessor constructs the group from decls in
13415   // different files (e. g. macros or #include).
13416   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13417 }
13418 
13419 /// Common checks for a parameter-declaration that should apply to both function
13420 /// parameters and non-type template parameters.
CheckFunctionOrTemplateParamDeclarator(Scope * S,Declarator & D)13421 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13422   // Check that there are no default arguments inside the type of this
13423   // parameter.
13424   if (getLangOpts().CPlusPlus)
13425     CheckExtraCXXDefaultArguments(D);
13426 
13427   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13428   if (D.getCXXScopeSpec().isSet()) {
13429     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13430       << D.getCXXScopeSpec().getRange();
13431   }
13432 
13433   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13434   // simple identifier except [...irrelevant cases...].
13435   switch (D.getName().getKind()) {
13436   case UnqualifiedIdKind::IK_Identifier:
13437     break;
13438 
13439   case UnqualifiedIdKind::IK_OperatorFunctionId:
13440   case UnqualifiedIdKind::IK_ConversionFunctionId:
13441   case UnqualifiedIdKind::IK_LiteralOperatorId:
13442   case UnqualifiedIdKind::IK_ConstructorName:
13443   case UnqualifiedIdKind::IK_DestructorName:
13444   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13445   case UnqualifiedIdKind::IK_DeductionGuideName:
13446     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13447       << GetNameForDeclarator(D).getName();
13448     break;
13449 
13450   case UnqualifiedIdKind::IK_TemplateId:
13451   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13452     // GetNameForDeclarator would not produce a useful name in this case.
13453     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13454     break;
13455   }
13456 }
13457 
13458 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13459 /// to introduce parameters into function prototype scope.
ActOnParamDeclarator(Scope * S,Declarator & D)13460 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13461   const DeclSpec &DS = D.getDeclSpec();
13462 
13463   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13464 
13465   // C++03 [dcl.stc]p2 also permits 'auto'.
13466   StorageClass SC = SC_None;
13467   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13468     SC = SC_Register;
13469     // In C++11, the 'register' storage class specifier is deprecated.
13470     // In C++17, it is not allowed, but we tolerate it as an extension.
13471     if (getLangOpts().CPlusPlus11) {
13472       Diag(DS.getStorageClassSpecLoc(),
13473            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13474                                      : diag::warn_deprecated_register)
13475         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13476     }
13477   } else if (getLangOpts().CPlusPlus &&
13478              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13479     SC = SC_Auto;
13480   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13481     Diag(DS.getStorageClassSpecLoc(),
13482          diag::err_invalid_storage_class_in_func_decl);
13483     D.getMutableDeclSpec().ClearStorageClassSpecs();
13484   }
13485 
13486   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13487     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13488       << DeclSpec::getSpecifierName(TSCS);
13489   if (DS.isInlineSpecified())
13490     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13491         << getLangOpts().CPlusPlus17;
13492   if (DS.hasConstexprSpecifier())
13493     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13494         << 0 << D.getDeclSpec().getConstexprSpecifier();
13495 
13496   DiagnoseFunctionSpecifiers(DS);
13497 
13498   CheckFunctionOrTemplateParamDeclarator(S, D);
13499 
13500   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13501   QualType parmDeclType = TInfo->getType();
13502 
13503   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13504   IdentifierInfo *II = D.getIdentifier();
13505   if (II) {
13506     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13507                    ForVisibleRedeclaration);
13508     LookupName(R, S);
13509     if (R.isSingleResult()) {
13510       NamedDecl *PrevDecl = R.getFoundDecl();
13511       if (PrevDecl->isTemplateParameter()) {
13512         // Maybe we will complain about the shadowed template parameter.
13513         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13514         // Just pretend that we didn't see the previous declaration.
13515         PrevDecl = nullptr;
13516       } else if (S->isDeclScope(PrevDecl)) {
13517         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13518         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13519 
13520         // Recover by removing the name
13521         II = nullptr;
13522         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13523         D.setInvalidType(true);
13524       }
13525     }
13526   }
13527 
13528   // Temporarily put parameter variables in the translation unit, not
13529   // the enclosing context.  This prevents them from accidentally
13530   // looking like class members in C++.
13531   ParmVarDecl *New =
13532       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13533                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13534 
13535   if (D.isInvalidType())
13536     New->setInvalidDecl();
13537 
13538   assert(S->isFunctionPrototypeScope());
13539   assert(S->getFunctionPrototypeDepth() >= 1);
13540   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13541                     S->getNextFunctionPrototypeIndex());
13542 
13543   // Add the parameter declaration into this scope.
13544   S->AddDecl(New);
13545   if (II)
13546     IdResolver.AddDecl(New);
13547 
13548   ProcessDeclAttributes(S, New, D);
13549 
13550   if (D.getDeclSpec().isModulePrivateSpecified())
13551     Diag(New->getLocation(), diag::err_module_private_local)
13552       << 1 << New->getDeclName()
13553       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13554       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13555 
13556   if (New->hasAttr<BlocksAttr>()) {
13557     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13558   }
13559 
13560   if (getLangOpts().OpenCL)
13561     deduceOpenCLAddressSpace(New);
13562 
13563   return New;
13564 }
13565 
13566 /// Synthesizes a variable for a parameter arising from a
13567 /// typedef.
BuildParmVarDeclForTypedef(DeclContext * DC,SourceLocation Loc,QualType T)13568 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13569                                               SourceLocation Loc,
13570                                               QualType T) {
13571   /* FIXME: setting StartLoc == Loc.
13572      Would it be worth to modify callers so as to provide proper source
13573      location for the unnamed parameters, embedding the parameter's type? */
13574   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13575                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13576                                            SC_None, nullptr);
13577   Param->setImplicit();
13578   return Param;
13579 }
13580 
DiagnoseUnusedParameters(ArrayRef<ParmVarDecl * > Parameters)13581 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13582   // Don't diagnose unused-parameter errors in template instantiations; we
13583   // will already have done so in the template itself.
13584   if (inTemplateInstantiation())
13585     return;
13586 
13587   for (const ParmVarDecl *Parameter : Parameters) {
13588     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13589         !Parameter->hasAttr<UnusedAttr>()) {
13590       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13591         << Parameter->getDeclName();
13592     }
13593   }
13594 }
13595 
DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl * > Parameters,QualType ReturnTy,NamedDecl * D)13596 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13597     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13598   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13599     return;
13600 
13601   // Warn if the return value is pass-by-value and larger than the specified
13602   // threshold.
13603   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13604     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13605     if (Size > LangOpts.NumLargeByValueCopy)
13606       Diag(D->getLocation(), diag::warn_return_value_size)
13607           << D->getDeclName() << Size;
13608   }
13609 
13610   // Warn if any parameter is pass-by-value and larger than the specified
13611   // threshold.
13612   for (const ParmVarDecl *Parameter : Parameters) {
13613     QualType T = Parameter->getType();
13614     if (T->isDependentType() || !T.isPODType(Context))
13615       continue;
13616     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13617     if (Size > LangOpts.NumLargeByValueCopy)
13618       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13619           << Parameter->getDeclName() << Size;
13620   }
13621 }
13622 
CheckParameter(DeclContext * DC,SourceLocation StartLoc,SourceLocation NameLoc,IdentifierInfo * Name,QualType T,TypeSourceInfo * TSInfo,StorageClass SC)13623 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13624                                   SourceLocation NameLoc, IdentifierInfo *Name,
13625                                   QualType T, TypeSourceInfo *TSInfo,
13626                                   StorageClass SC) {
13627   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13628   if (getLangOpts().ObjCAutoRefCount &&
13629       T.getObjCLifetime() == Qualifiers::OCL_None &&
13630       T->isObjCLifetimeType()) {
13631 
13632     Qualifiers::ObjCLifetime lifetime;
13633 
13634     // Special cases for arrays:
13635     //   - if it's const, use __unsafe_unretained
13636     //   - otherwise, it's an error
13637     if (T->isArrayType()) {
13638       if (!T.isConstQualified()) {
13639         if (DelayedDiagnostics.shouldDelayDiagnostics())
13640           DelayedDiagnostics.add(
13641               sema::DelayedDiagnostic::makeForbiddenType(
13642               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13643         else
13644           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13645               << TSInfo->getTypeLoc().getSourceRange();
13646       }
13647       lifetime = Qualifiers::OCL_ExplicitNone;
13648     } else {
13649       lifetime = T->getObjCARCImplicitLifetime();
13650     }
13651     T = Context.getLifetimeQualifiedType(T, lifetime);
13652   }
13653 
13654   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13655                                          Context.getAdjustedParameterType(T),
13656                                          TSInfo, SC, nullptr);
13657 
13658   // Make a note if we created a new pack in the scope of a lambda, so that
13659   // we know that references to that pack must also be expanded within the
13660   // lambda scope.
13661   if (New->isParameterPack())
13662     if (auto *LSI = getEnclosingLambda())
13663       LSI->LocalPacks.push_back(New);
13664 
13665   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13666       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13667     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13668                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13669 
13670   // Parameters can not be abstract class types.
13671   // For record types, this is done by the AbstractClassUsageDiagnoser once
13672   // the class has been completely parsed.
13673   if (!CurContext->isRecord() &&
13674       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13675                              AbstractParamType))
13676     New->setInvalidDecl();
13677 
13678   // Parameter declarators cannot be interface types. All ObjC objects are
13679   // passed by reference.
13680   if (T->isObjCObjectType()) {
13681     SourceLocation TypeEndLoc =
13682         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13683     Diag(NameLoc,
13684          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13685       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13686     T = Context.getObjCObjectPointerType(T);
13687     New->setType(T);
13688   }
13689 
13690   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13691   // duration shall not be qualified by an address-space qualifier."
13692   // Since all parameters have automatic store duration, they can not have
13693   // an address space.
13694   if (T.getAddressSpace() != LangAS::Default &&
13695       // OpenCL allows function arguments declared to be an array of a type
13696       // to be qualified with an address space.
13697       !(getLangOpts().OpenCL &&
13698         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13699     Diag(NameLoc, diag::err_arg_with_address_space);
13700     New->setInvalidDecl();
13701   }
13702 
13703   return New;
13704 }
13705 
ActOnFinishKNRParamDeclarations(Scope * S,Declarator & D,SourceLocation LocAfterDecls)13706 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13707                                            SourceLocation LocAfterDecls) {
13708   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13709 
13710   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13711   // for a K&R function.
13712   if (!FTI.hasPrototype) {
13713     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13714       --i;
13715       if (FTI.Params[i].Param == nullptr) {
13716         SmallString<256> Code;
13717         llvm::raw_svector_ostream(Code)
13718             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13719         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13720             << FTI.Params[i].Ident
13721             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13722 
13723         // Implicitly declare the argument as type 'int' for lack of a better
13724         // type.
13725         AttributeFactory attrs;
13726         DeclSpec DS(attrs);
13727         const char* PrevSpec; // unused
13728         unsigned DiagID; // unused
13729         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13730                            DiagID, Context.getPrintingPolicy());
13731         // Use the identifier location for the type source range.
13732         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13733         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13734         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13735         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13736         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13737       }
13738     }
13739   }
13740 }
13741 
13742 Decl *
ActOnStartOfFunctionDef(Scope * FnBodyScope,Declarator & D,MultiTemplateParamsArg TemplateParameterLists,SkipBodyInfo * SkipBody)13743 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13744                               MultiTemplateParamsArg TemplateParameterLists,
13745                               SkipBodyInfo *SkipBody) {
13746   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13747   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13748   Scope *ParentScope = FnBodyScope->getParent();
13749 
13750   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13751   // we define a non-templated function definition, we will create a declaration
13752   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13753   // The base function declaration will have the equivalent of an `omp declare
13754   // variant` annotation which specifies the mangled definition as a
13755   // specialization function under the OpenMP context defined as part of the
13756   // `omp begin declare variant`.
13757   FunctionDecl *BaseFD = nullptr;
13758   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope() &&
13759       TemplateParameterLists.empty())
13760     BaseFD = ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13761         ParentScope, D);
13762 
13763   D.setFunctionDefinitionKind(FDK_Definition);
13764   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13765   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13766 
13767   if (BaseFD)
13768     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
13769         cast<FunctionDecl>(Dcl), BaseFD);
13770 
13771   return Dcl;
13772 }
13773 
ActOnFinishInlineFunctionDef(FunctionDecl * D)13774 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13775   Consumer.HandleInlineFunctionDefinition(D);
13776 }
13777 
13778 static bool
ShouldWarnAboutMissingPrototype(const FunctionDecl * FD,const FunctionDecl * & PossiblePrototype)13779 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13780                                 const FunctionDecl *&PossiblePrototype) {
13781   // Don't warn about invalid declarations.
13782   if (FD->isInvalidDecl())
13783     return false;
13784 
13785   // Or declarations that aren't global.
13786   if (!FD->isGlobal())
13787     return false;
13788 
13789   // Don't warn about C++ member functions.
13790   if (isa<CXXMethodDecl>(FD))
13791     return false;
13792 
13793   // Don't warn about 'main'.
13794   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13795     if (IdentifierInfo *II = FD->getIdentifier())
13796       if (II->isStr("main"))
13797         return false;
13798 
13799   // Don't warn about inline functions.
13800   if (FD->isInlined())
13801     return false;
13802 
13803   // Don't warn about function templates.
13804   if (FD->getDescribedFunctionTemplate())
13805     return false;
13806 
13807   // Don't warn about function template specializations.
13808   if (FD->isFunctionTemplateSpecialization())
13809     return false;
13810 
13811   // Don't warn for OpenCL kernels.
13812   if (FD->hasAttr<OpenCLKernelAttr>())
13813     return false;
13814 
13815   // Don't warn on explicitly deleted functions.
13816   if (FD->isDeleted())
13817     return false;
13818 
13819   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13820        Prev; Prev = Prev->getPreviousDecl()) {
13821     // Ignore any declarations that occur in function or method
13822     // scope, because they aren't visible from the header.
13823     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13824       continue;
13825 
13826     PossiblePrototype = Prev;
13827     return Prev->getType()->isFunctionNoProtoType();
13828   }
13829 
13830   return true;
13831 }
13832 
13833 void
CheckForFunctionRedefinition(FunctionDecl * FD,const FunctionDecl * EffectiveDefinition,SkipBodyInfo * SkipBody)13834 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13835                                    const FunctionDecl *EffectiveDefinition,
13836                                    SkipBodyInfo *SkipBody) {
13837   const FunctionDecl *Definition = EffectiveDefinition;
13838   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13839     // If this is a friend function defined in a class template, it does not
13840     // have a body until it is used, nevertheless it is a definition, see
13841     // [temp.inst]p2:
13842     //
13843     // ... for the purpose of determining whether an instantiated redeclaration
13844     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13845     // corresponds to a definition in the template is considered to be a
13846     // definition.
13847     //
13848     // The following code must produce redefinition error:
13849     //
13850     //     template<typename T> struct C20 { friend void func_20() {} };
13851     //     C20<int> c20i;
13852     //     void func_20() {}
13853     //
13854     for (auto I : FD->redecls()) {
13855       if (I != FD && !I->isInvalidDecl() &&
13856           I->getFriendObjectKind() != Decl::FOK_None) {
13857         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13858           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13859             // A merged copy of the same function, instantiated as a member of
13860             // the same class, is OK.
13861             if (declaresSameEntity(OrigFD, Original) &&
13862                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13863                                    cast<Decl>(FD->getLexicalDeclContext())))
13864               continue;
13865           }
13866 
13867           if (Original->isThisDeclarationADefinition()) {
13868             Definition = I;
13869             break;
13870           }
13871         }
13872       }
13873     }
13874   }
13875 
13876   if (!Definition)
13877     // Similar to friend functions a friend function template may be a
13878     // definition and do not have a body if it is instantiated in a class
13879     // template.
13880     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13881       for (auto I : FTD->redecls()) {
13882         auto D = cast<FunctionTemplateDecl>(I);
13883         if (D != FTD) {
13884           assert(!D->isThisDeclarationADefinition() &&
13885                  "More than one definition in redeclaration chain");
13886           if (D->getFriendObjectKind() != Decl::FOK_None)
13887             if (FunctionTemplateDecl *FT =
13888                                        D->getInstantiatedFromMemberTemplate()) {
13889               if (FT->isThisDeclarationADefinition()) {
13890                 Definition = D->getTemplatedDecl();
13891                 break;
13892               }
13893             }
13894         }
13895       }
13896     }
13897 
13898   if (!Definition)
13899     return;
13900 
13901   if (canRedefineFunction(Definition, getLangOpts()))
13902     return;
13903 
13904   // Don't emit an error when this is redefinition of a typo-corrected
13905   // definition.
13906   if (TypoCorrectedFunctionDefinitions.count(Definition))
13907     return;
13908 
13909   // If we don't have a visible definition of the function, and it's inline or
13910   // a template, skip the new definition.
13911   if (SkipBody && !hasVisibleDefinition(Definition) &&
13912       (Definition->getFormalLinkage() == InternalLinkage ||
13913        Definition->isInlined() ||
13914        Definition->getDescribedFunctionTemplate() ||
13915        Definition->getNumTemplateParameterLists())) {
13916     SkipBody->ShouldSkip = true;
13917     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13918     if (auto *TD = Definition->getDescribedFunctionTemplate())
13919       makeMergedDefinitionVisible(TD);
13920     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13921     return;
13922   }
13923 
13924   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13925       Definition->getStorageClass() == SC_Extern)
13926     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13927         << FD->getDeclName() << getLangOpts().CPlusPlus;
13928   else
13929     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13930 
13931   Diag(Definition->getLocation(), diag::note_previous_definition);
13932   FD->setInvalidDecl();
13933 }
13934 
RebuildLambdaScopeInfo(CXXMethodDecl * CallOperator,Sema & S)13935 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13936                                    Sema &S) {
13937   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13938 
13939   LambdaScopeInfo *LSI = S.PushLambdaScope();
13940   LSI->CallOperator = CallOperator;
13941   LSI->Lambda = LambdaClass;
13942   LSI->ReturnType = CallOperator->getReturnType();
13943   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13944 
13945   if (LCD == LCD_None)
13946     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13947   else if (LCD == LCD_ByCopy)
13948     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13949   else if (LCD == LCD_ByRef)
13950     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13951   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13952 
13953   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13954   LSI->Mutable = !CallOperator->isConst();
13955 
13956   // Add the captures to the LSI so they can be noted as already
13957   // captured within tryCaptureVar.
13958   auto I = LambdaClass->field_begin();
13959   for (const auto &C : LambdaClass->captures()) {
13960     if (C.capturesVariable()) {
13961       VarDecl *VD = C.getCapturedVar();
13962       if (VD->isInitCapture())
13963         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13964       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13965       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13966           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13967           /*EllipsisLoc*/C.isPackExpansion()
13968                          ? C.getEllipsisLoc() : SourceLocation(),
13969           I->getType(), /*Invalid*/false);
13970 
13971     } else if (C.capturesThis()) {
13972       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13973                           C.getCaptureKind() == LCK_StarThis);
13974     } else {
13975       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13976                              I->getType());
13977     }
13978     ++I;
13979   }
13980 }
13981 
ActOnStartOfFunctionDef(Scope * FnBodyScope,Decl * D,SkipBodyInfo * SkipBody)13982 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13983                                     SkipBodyInfo *SkipBody) {
13984   if (!D) {
13985     // Parsing the function declaration failed in some way. Push on a fake scope
13986     // anyway so we can try to parse the function body.
13987     PushFunctionScope();
13988     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13989     return D;
13990   }
13991 
13992   FunctionDecl *FD = nullptr;
13993 
13994   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13995     FD = FunTmpl->getTemplatedDecl();
13996   else
13997     FD = cast<FunctionDecl>(D);
13998 
13999   // Do not push if it is a lambda because one is already pushed when building
14000   // the lambda in ActOnStartOfLambdaDefinition().
14001   if (!isLambdaCallOperator(FD))
14002     PushExpressionEvaluationContext(
14003         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14004                           : ExprEvalContexts.back().Context);
14005 
14006   // Check for defining attributes before the check for redefinition.
14007   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14008     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14009     FD->dropAttr<AliasAttr>();
14010     FD->setInvalidDecl();
14011   }
14012   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14013     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14014     FD->dropAttr<IFuncAttr>();
14015     FD->setInvalidDecl();
14016   }
14017 
14018   // See if this is a redefinition. If 'will have body' is already set, then
14019   // these checks were already performed when it was set.
14020   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
14021     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14022 
14023     // If we're skipping the body, we're done. Don't enter the scope.
14024     if (SkipBody && SkipBody->ShouldSkip)
14025       return D;
14026   }
14027 
14028   // Mark this function as "will have a body eventually".  This lets users to
14029   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14030   // this function.
14031   FD->setWillHaveBody();
14032 
14033   // If we are instantiating a generic lambda call operator, push
14034   // a LambdaScopeInfo onto the function stack.  But use the information
14035   // that's already been calculated (ActOnLambdaExpr) to prime the current
14036   // LambdaScopeInfo.
14037   // When the template operator is being specialized, the LambdaScopeInfo,
14038   // has to be properly restored so that tryCaptureVariable doesn't try
14039   // and capture any new variables. In addition when calculating potential
14040   // captures during transformation of nested lambdas, it is necessary to
14041   // have the LSI properly restored.
14042   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14043     assert(inTemplateInstantiation() &&
14044            "There should be an active template instantiation on the stack "
14045            "when instantiating a generic lambda!");
14046     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14047   } else {
14048     // Enter a new function scope
14049     PushFunctionScope();
14050   }
14051 
14052   // Builtin functions cannot be defined.
14053   if (unsigned BuiltinID = FD->getBuiltinID()) {
14054     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14055         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14056       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14057       FD->setInvalidDecl();
14058     }
14059   }
14060 
14061   // The return type of a function definition must be complete
14062   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14063   QualType ResultType = FD->getReturnType();
14064   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14065       !FD->isInvalidDecl() &&
14066       RequireCompleteType(FD->getLocation(), ResultType,
14067                           diag::err_func_def_incomplete_result))
14068     FD->setInvalidDecl();
14069 
14070   if (FnBodyScope)
14071     PushDeclContext(FnBodyScope, FD);
14072 
14073   // Check the validity of our function parameters
14074   CheckParmsForFunctionDef(FD->parameters(),
14075                            /*CheckParameterNames=*/true);
14076 
14077   // Add non-parameter declarations already in the function to the current
14078   // scope.
14079   if (FnBodyScope) {
14080     for (Decl *NPD : FD->decls()) {
14081       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14082       if (!NonParmDecl)
14083         continue;
14084       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14085              "parameters should not be in newly created FD yet");
14086 
14087       // If the decl has a name, make it accessible in the current scope.
14088       if (NonParmDecl->getDeclName())
14089         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14090 
14091       // Similarly, dive into enums and fish their constants out, making them
14092       // accessible in this scope.
14093       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14094         for (auto *EI : ED->enumerators())
14095           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14096       }
14097     }
14098   }
14099 
14100   // Introduce our parameters into the function scope
14101   for (auto Param : FD->parameters()) {
14102     Param->setOwningFunction(FD);
14103 
14104     // If this has an identifier, add it to the scope stack.
14105     if (Param->getIdentifier() && FnBodyScope) {
14106       CheckShadow(FnBodyScope, Param);
14107 
14108       PushOnScopeChains(Param, FnBodyScope);
14109     }
14110   }
14111 
14112   // Ensure that the function's exception specification is instantiated.
14113   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14114     ResolveExceptionSpec(D->getLocation(), FPT);
14115 
14116   // dllimport cannot be applied to non-inline function definitions.
14117   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14118       !FD->isTemplateInstantiation()) {
14119     assert(!FD->hasAttr<DLLExportAttr>());
14120     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14121     FD->setInvalidDecl();
14122     return D;
14123   }
14124   // We want to attach documentation to original Decl (which might be
14125   // a function template).
14126   ActOnDocumentableDecl(D);
14127   if (getCurLexicalContext()->isObjCContainer() &&
14128       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14129       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14130     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14131 
14132   return D;
14133 }
14134 
14135 /// Given the set of return statements within a function body,
14136 /// compute the variables that are subject to the named return value
14137 /// optimization.
14138 ///
14139 /// Each of the variables that is subject to the named return value
14140 /// optimization will be marked as NRVO variables in the AST, and any
14141 /// return statement that has a marked NRVO variable as its NRVO candidate can
14142 /// use the named return value optimization.
14143 ///
14144 /// This function applies a very simplistic algorithm for NRVO: if every return
14145 /// statement in the scope of a variable has the same NRVO candidate, that
14146 /// candidate is an NRVO variable.
computeNRVO(Stmt * Body,FunctionScopeInfo * Scope)14147 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14148   ReturnStmt **Returns = Scope->Returns.data();
14149 
14150   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14151     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14152       if (!NRVOCandidate->isNRVOVariable())
14153         Returns[I]->setNRVOCandidate(nullptr);
14154     }
14155   }
14156 }
14157 
canDelayFunctionBody(const Declarator & D)14158 bool Sema::canDelayFunctionBody(const Declarator &D) {
14159   // We can't delay parsing the body of a constexpr function template (yet).
14160   if (D.getDeclSpec().hasConstexprSpecifier())
14161     return false;
14162 
14163   // We can't delay parsing the body of a function template with a deduced
14164   // return type (yet).
14165   if (D.getDeclSpec().hasAutoTypeSpec()) {
14166     // If the placeholder introduces a non-deduced trailing return type,
14167     // we can still delay parsing it.
14168     if (D.getNumTypeObjects()) {
14169       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14170       if (Outer.Kind == DeclaratorChunk::Function &&
14171           Outer.Fun.hasTrailingReturnType()) {
14172         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14173         return Ty.isNull() || !Ty->isUndeducedType();
14174       }
14175     }
14176     return false;
14177   }
14178 
14179   return true;
14180 }
14181 
canSkipFunctionBody(Decl * D)14182 bool Sema::canSkipFunctionBody(Decl *D) {
14183   // We cannot skip the body of a function (or function template) which is
14184   // constexpr, since we may need to evaluate its body in order to parse the
14185   // rest of the file.
14186   // We cannot skip the body of a function with an undeduced return type,
14187   // because any callers of that function need to know the type.
14188   if (const FunctionDecl *FD = D->getAsFunction()) {
14189     if (FD->isConstexpr())
14190       return false;
14191     // We can't simply call Type::isUndeducedType here, because inside template
14192     // auto can be deduced to a dependent type, which is not considered
14193     // "undeduced".
14194     if (FD->getReturnType()->getContainedDeducedType())
14195       return false;
14196   }
14197   return Consumer.shouldSkipFunctionBody(D);
14198 }
14199 
ActOnSkippedFunctionBody(Decl * Decl)14200 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14201   if (!Decl)
14202     return nullptr;
14203   if (FunctionDecl *FD = Decl->getAsFunction())
14204     FD->setHasSkippedBody();
14205   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14206     MD->setHasSkippedBody();
14207   return Decl;
14208 }
14209 
ActOnFinishFunctionBody(Decl * D,Stmt * BodyArg)14210 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14211   return ActOnFinishFunctionBody(D, BodyArg, false);
14212 }
14213 
14214 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14215 /// body.
14216 class ExitFunctionBodyRAII {
14217 public:
ExitFunctionBodyRAII(Sema & S,bool IsLambda)14218   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
~ExitFunctionBodyRAII()14219   ~ExitFunctionBodyRAII() {
14220     if (!IsLambda)
14221       S.PopExpressionEvaluationContext();
14222   }
14223 
14224 private:
14225   Sema &S;
14226   bool IsLambda = false;
14227 };
14228 
diagnoseImplicitlyRetainedSelf(Sema & S)14229 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14230   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14231 
14232   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14233     if (EscapeInfo.count(BD))
14234       return EscapeInfo[BD];
14235 
14236     bool R = false;
14237     const BlockDecl *CurBD = BD;
14238 
14239     do {
14240       R = !CurBD->doesNotEscape();
14241       if (R)
14242         break;
14243       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14244     } while (CurBD);
14245 
14246     return EscapeInfo[BD] = R;
14247   };
14248 
14249   // If the location where 'self' is implicitly retained is inside a escaping
14250   // block, emit a diagnostic.
14251   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14252        S.ImplicitlyRetainedSelfLocs)
14253     if (IsOrNestedInEscapingBlock(P.second))
14254       S.Diag(P.first, diag::warn_implicitly_retains_self)
14255           << FixItHint::CreateInsertion(P.first, "self->");
14256 }
14257 
ActOnFinishFunctionBody(Decl * dcl,Stmt * Body,bool IsInstantiation)14258 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14259                                     bool IsInstantiation) {
14260   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14261 
14262   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14263   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14264 
14265   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
14266     CheckCompletedCoroutineBody(FD, Body);
14267 
14268   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14269   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14270   // meant to pop the context added in ActOnStartOfFunctionDef().
14271   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14272 
14273   if (FD) {
14274     FD->setBody(Body);
14275     FD->setWillHaveBody(false);
14276 
14277     if (getLangOpts().CPlusPlus14) {
14278       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14279           FD->getReturnType()->isUndeducedType()) {
14280         // If the function has a deduced result type but contains no 'return'
14281         // statements, the result type as written must be exactly 'auto', and
14282         // the deduced result type is 'void'.
14283         if (!FD->getReturnType()->getAs<AutoType>()) {
14284           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14285               << FD->getReturnType();
14286           FD->setInvalidDecl();
14287         } else {
14288           // Substitute 'void' for the 'auto' in the type.
14289           TypeLoc ResultType = getReturnTypeLoc(FD);
14290           Context.adjustDeducedFunctionResultType(
14291               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14292         }
14293       }
14294     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14295       // In C++11, we don't use 'auto' deduction rules for lambda call
14296       // operators because we don't support return type deduction.
14297       auto *LSI = getCurLambda();
14298       if (LSI->HasImplicitReturnType) {
14299         deduceClosureReturnType(*LSI);
14300 
14301         // C++11 [expr.prim.lambda]p4:
14302         //   [...] if there are no return statements in the compound-statement
14303         //   [the deduced type is] the type void
14304         QualType RetType =
14305             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14306 
14307         // Update the return type to the deduced type.
14308         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14309         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14310                                             Proto->getExtProtoInfo()));
14311       }
14312     }
14313 
14314     // If the function implicitly returns zero (like 'main') or is naked,
14315     // don't complain about missing return statements.
14316     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14317       WP.disableCheckFallThrough();
14318 
14319     // MSVC permits the use of pure specifier (=0) on function definition,
14320     // defined at class scope, warn about this non-standard construct.
14321     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14322       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14323 
14324     if (!FD->isInvalidDecl()) {
14325       // Don't diagnose unused parameters of defaulted or deleted functions.
14326       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14327         DiagnoseUnusedParameters(FD->parameters());
14328       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14329                                              FD->getReturnType(), FD);
14330 
14331       // If this is a structor, we need a vtable.
14332       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14333         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14334       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14335         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14336 
14337       // Try to apply the named return value optimization. We have to check
14338       // if we can do this here because lambdas keep return statements around
14339       // to deduce an implicit return type.
14340       if (FD->getReturnType()->isRecordType() &&
14341           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14342         computeNRVO(Body, getCurFunction());
14343     }
14344 
14345     // GNU warning -Wmissing-prototypes:
14346     //   Warn if a global function is defined without a previous
14347     //   prototype declaration. This warning is issued even if the
14348     //   definition itself provides a prototype. The aim is to detect
14349     //   global functions that fail to be declared in header files.
14350     const FunctionDecl *PossiblePrototype = nullptr;
14351     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14352       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14353 
14354       if (PossiblePrototype) {
14355         // We found a declaration that is not a prototype,
14356         // but that could be a zero-parameter prototype
14357         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14358           TypeLoc TL = TI->getTypeLoc();
14359           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14360             Diag(PossiblePrototype->getLocation(),
14361                  diag::note_declaration_not_a_prototype)
14362                 << (FD->getNumParams() != 0)
14363                 << (FD->getNumParams() == 0
14364                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14365                         : FixItHint{});
14366         }
14367       } else {
14368         // Returns true if the token beginning at this Loc is `const`.
14369         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14370                                 const LangOptions &LangOpts) {
14371           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14372           if (LocInfo.first.isInvalid())
14373             return false;
14374 
14375           bool Invalid = false;
14376           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14377           if (Invalid)
14378             return false;
14379 
14380           if (LocInfo.second > Buffer.size())
14381             return false;
14382 
14383           const char *LexStart = Buffer.data() + LocInfo.second;
14384           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14385 
14386           return StartTok.consume_front("const") &&
14387                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14388                   StartTok.startswith("/*") || StartTok.startswith("//"));
14389         };
14390 
14391         auto findBeginLoc = [&]() {
14392           // If the return type has `const` qualifier, we want to insert
14393           // `static` before `const` (and not before the typename).
14394           if ((FD->getReturnType()->isAnyPointerType() &&
14395                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14396               FD->getReturnType().isConstQualified()) {
14397             // But only do this if we can determine where the `const` is.
14398 
14399             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14400                              getLangOpts()))
14401 
14402               return FD->getBeginLoc();
14403           }
14404           return FD->getTypeSpecStartLoc();
14405         };
14406         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14407             << /* function */ 1
14408             << (FD->getStorageClass() == SC_None
14409                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14410                     : FixItHint{});
14411       }
14412 
14413       // GNU warning -Wstrict-prototypes
14414       //   Warn if K&R function is defined without a previous declaration.
14415       //   This warning is issued only if the definition itself does not provide
14416       //   a prototype. Only K&R definitions do not provide a prototype.
14417       if (!FD->hasWrittenPrototype()) {
14418         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14419         TypeLoc TL = TI->getTypeLoc();
14420         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14421         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14422       }
14423     }
14424 
14425     // Warn on CPUDispatch with an actual body.
14426     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14427       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14428         if (!CmpndBody->body_empty())
14429           Diag(CmpndBody->body_front()->getBeginLoc(),
14430                diag::warn_dispatch_body_ignored);
14431 
14432     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14433       const CXXMethodDecl *KeyFunction;
14434       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14435           MD->isVirtual() &&
14436           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14437           MD == KeyFunction->getCanonicalDecl()) {
14438         // Update the key-function state if necessary for this ABI.
14439         if (FD->isInlined() &&
14440             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14441           Context.setNonKeyFunction(MD);
14442 
14443           // If the newly-chosen key function is already defined, then we
14444           // need to mark the vtable as used retroactively.
14445           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14446           const FunctionDecl *Definition;
14447           if (KeyFunction && KeyFunction->isDefined(Definition))
14448             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14449         } else {
14450           // We just defined they key function; mark the vtable as used.
14451           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14452         }
14453       }
14454     }
14455 
14456     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14457            "Function parsing confused");
14458   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14459     assert(MD == getCurMethodDecl() && "Method parsing confused");
14460     MD->setBody(Body);
14461     if (!MD->isInvalidDecl()) {
14462       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14463                                              MD->getReturnType(), MD);
14464 
14465       if (Body)
14466         computeNRVO(Body, getCurFunction());
14467     }
14468     if (getCurFunction()->ObjCShouldCallSuper) {
14469       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14470           << MD->getSelector().getAsString();
14471       getCurFunction()->ObjCShouldCallSuper = false;
14472     }
14473     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14474       const ObjCMethodDecl *InitMethod = nullptr;
14475       bool isDesignated =
14476           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14477       assert(isDesignated && InitMethod);
14478       (void)isDesignated;
14479 
14480       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14481         auto IFace = MD->getClassInterface();
14482         if (!IFace)
14483           return false;
14484         auto SuperD = IFace->getSuperClass();
14485         if (!SuperD)
14486           return false;
14487         return SuperD->getIdentifier() ==
14488             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14489       };
14490       // Don't issue this warning for unavailable inits or direct subclasses
14491       // of NSObject.
14492       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14493         Diag(MD->getLocation(),
14494              diag::warn_objc_designated_init_missing_super_call);
14495         Diag(InitMethod->getLocation(),
14496              diag::note_objc_designated_init_marked_here);
14497       }
14498       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14499     }
14500     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14501       // Don't issue this warning for unavaialable inits.
14502       if (!MD->isUnavailable())
14503         Diag(MD->getLocation(),
14504              diag::warn_objc_secondary_init_missing_init_call);
14505       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14506     }
14507 
14508     diagnoseImplicitlyRetainedSelf(*this);
14509   } else {
14510     // Parsing the function declaration failed in some way. Pop the fake scope
14511     // we pushed on.
14512     PopFunctionScopeInfo(ActivePolicy, dcl);
14513     return nullptr;
14514   }
14515 
14516   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14517     DiagnoseUnguardedAvailabilityViolations(dcl);
14518 
14519   assert(!getCurFunction()->ObjCShouldCallSuper &&
14520          "This should only be set for ObjC methods, which should have been "
14521          "handled in the block above.");
14522 
14523   // Verify and clean out per-function state.
14524   if (Body && (!FD || !FD->isDefaulted())) {
14525     // C++ constructors that have function-try-blocks can't have return
14526     // statements in the handlers of that block. (C++ [except.handle]p14)
14527     // Verify this.
14528     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14529       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14530 
14531     // Verify that gotos and switch cases don't jump into scopes illegally.
14532     if (getCurFunction()->NeedsScopeChecking() &&
14533         !PP.isCodeCompletionEnabled())
14534       DiagnoseInvalidJumps(Body);
14535 
14536     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14537       if (!Destructor->getParent()->isDependentType())
14538         CheckDestructor(Destructor);
14539 
14540       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14541                                              Destructor->getParent());
14542     }
14543 
14544     // If any errors have occurred, clear out any temporaries that may have
14545     // been leftover. This ensures that these temporaries won't be picked up for
14546     // deletion in some later function.
14547     if (getDiagnostics().hasUncompilableErrorOccurred() ||
14548         getDiagnostics().getSuppressAllDiagnostics()) {
14549       DiscardCleanupsInEvaluationContext();
14550     }
14551     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14552         !isa<FunctionTemplateDecl>(dcl)) {
14553       // Since the body is valid, issue any analysis-based warnings that are
14554       // enabled.
14555       ActivePolicy = &WP;
14556     }
14557 
14558     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14559         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14560       FD->setInvalidDecl();
14561 
14562     if (FD && FD->hasAttr<NakedAttr>()) {
14563       for (const Stmt *S : Body->children()) {
14564         // Allow local register variables without initializer as they don't
14565         // require prologue.
14566         bool RegisterVariables = false;
14567         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14568           for (const auto *Decl : DS->decls()) {
14569             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14570               RegisterVariables =
14571                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14572               if (!RegisterVariables)
14573                 break;
14574             }
14575           }
14576         }
14577         if (RegisterVariables)
14578           continue;
14579         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14580           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14581           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14582           FD->setInvalidDecl();
14583           break;
14584         }
14585       }
14586     }
14587 
14588     assert(ExprCleanupObjects.size() ==
14589                ExprEvalContexts.back().NumCleanupObjects &&
14590            "Leftover temporaries in function");
14591     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14592     assert(MaybeODRUseExprs.empty() &&
14593            "Leftover expressions for odr-use checking");
14594   }
14595 
14596   if (!IsInstantiation)
14597     PopDeclContext();
14598 
14599   PopFunctionScopeInfo(ActivePolicy, dcl);
14600   // If any errors have occurred, clear out any temporaries that may have
14601   // been leftover. This ensures that these temporaries won't be picked up for
14602   // deletion in some later function.
14603   if (getDiagnostics().hasUncompilableErrorOccurred()) {
14604     DiscardCleanupsInEvaluationContext();
14605   }
14606 
14607   if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) {
14608     auto ES = getEmissionStatus(FD);
14609     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14610         ES == Sema::FunctionEmissionStatus::Unknown)
14611       DeclsToCheckForDeferredDiags.push_back(FD);
14612   }
14613 
14614   return dcl;
14615 }
14616 
14617 /// When we finish delayed parsing of an attribute, we must attach it to the
14618 /// relevant Decl.
ActOnFinishDelayedAttribute(Scope * S,Decl * D,ParsedAttributes & Attrs)14619 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14620                                        ParsedAttributes &Attrs) {
14621   // Always attach attributes to the underlying decl.
14622   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14623     D = TD->getTemplatedDecl();
14624   ProcessDeclAttributeList(S, D, Attrs);
14625 
14626   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14627     if (Method->isStatic())
14628       checkThisInStaticMemberFunctionAttributes(Method);
14629 }
14630 
14631 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14632 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
ImplicitlyDefineFunction(SourceLocation Loc,IdentifierInfo & II,Scope * S)14633 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14634                                           IdentifierInfo &II, Scope *S) {
14635   // Find the scope in which the identifier is injected and the corresponding
14636   // DeclContext.
14637   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14638   // In that case, we inject the declaration into the translation unit scope
14639   // instead.
14640   Scope *BlockScope = S;
14641   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14642     BlockScope = BlockScope->getParent();
14643 
14644   Scope *ContextScope = BlockScope;
14645   while (!ContextScope->getEntity())
14646     ContextScope = ContextScope->getParent();
14647   ContextRAII SavedContext(*this, ContextScope->getEntity());
14648 
14649   // Before we produce a declaration for an implicitly defined
14650   // function, see whether there was a locally-scoped declaration of
14651   // this name as a function or variable. If so, use that
14652   // (non-visible) declaration, and complain about it.
14653   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14654   if (ExternCPrev) {
14655     // We still need to inject the function into the enclosing block scope so
14656     // that later (non-call) uses can see it.
14657     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14658 
14659     // C89 footnote 38:
14660     //   If in fact it is not defined as having type "function returning int",
14661     //   the behavior is undefined.
14662     if (!isa<FunctionDecl>(ExternCPrev) ||
14663         !Context.typesAreCompatible(
14664             cast<FunctionDecl>(ExternCPrev)->getType(),
14665             Context.getFunctionNoProtoType(Context.IntTy))) {
14666       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14667           << ExternCPrev << !getLangOpts().C99;
14668       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14669       return ExternCPrev;
14670     }
14671   }
14672 
14673   // Extension in C99.  Legal in C90, but warn about it.
14674   unsigned diag_id;
14675   if (II.getName().startswith("__builtin_"))
14676     diag_id = diag::warn_builtin_unknown;
14677   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14678   else if (getLangOpts().OpenCL)
14679     diag_id = diag::err_opencl_implicit_function_decl;
14680   else if (getLangOpts().C99)
14681     diag_id = diag::ext_implicit_function_decl;
14682   else
14683     diag_id = diag::warn_implicit_function_decl;
14684   Diag(Loc, diag_id) << &II;
14685 
14686   // If we found a prior declaration of this function, don't bother building
14687   // another one. We've already pushed that one into scope, so there's nothing
14688   // more to do.
14689   if (ExternCPrev)
14690     return ExternCPrev;
14691 
14692   // Because typo correction is expensive, only do it if the implicit
14693   // function declaration is going to be treated as an error.
14694   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14695     TypoCorrection Corrected;
14696     DeclFilterCCC<FunctionDecl> CCC{};
14697     if (S && (Corrected =
14698                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14699                               S, nullptr, CCC, CTK_NonError)))
14700       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14701                    /*ErrorRecovery*/false);
14702   }
14703 
14704   // Set a Declarator for the implicit definition: int foo();
14705   const char *Dummy;
14706   AttributeFactory attrFactory;
14707   DeclSpec DS(attrFactory);
14708   unsigned DiagID;
14709   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14710                                   Context.getPrintingPolicy());
14711   (void)Error; // Silence warning.
14712   assert(!Error && "Error setting up implicit decl!");
14713   SourceLocation NoLoc;
14714   Declarator D(DS, DeclaratorContext::BlockContext);
14715   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14716                                              /*IsAmbiguous=*/false,
14717                                              /*LParenLoc=*/NoLoc,
14718                                              /*Params=*/nullptr,
14719                                              /*NumParams=*/0,
14720                                              /*EllipsisLoc=*/NoLoc,
14721                                              /*RParenLoc=*/NoLoc,
14722                                              /*RefQualifierIsLvalueRef=*/true,
14723                                              /*RefQualifierLoc=*/NoLoc,
14724                                              /*MutableLoc=*/NoLoc, EST_None,
14725                                              /*ESpecRange=*/SourceRange(),
14726                                              /*Exceptions=*/nullptr,
14727                                              /*ExceptionRanges=*/nullptr,
14728                                              /*NumExceptions=*/0,
14729                                              /*NoexceptExpr=*/nullptr,
14730                                              /*ExceptionSpecTokens=*/nullptr,
14731                                              /*DeclsInPrototype=*/None, Loc,
14732                                              Loc, D),
14733                 std::move(DS.getAttributes()), SourceLocation());
14734   D.SetIdentifier(&II, Loc);
14735 
14736   // Insert this function into the enclosing block scope.
14737   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14738   FD->setImplicit();
14739 
14740   AddKnownFunctionAttributes(FD);
14741 
14742   return FD;
14743 }
14744 
14745 /// If this function is a C++ replaceable global allocation function
14746 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14747 /// adds any function attributes that we know a priori based on the standard.
14748 ///
14749 /// We need to check for duplicate attributes both here and where user-written
14750 /// attributes are applied to declarations.
AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl * FD)14751 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14752     FunctionDecl *FD) {
14753   if (FD->isInvalidDecl())
14754     return;
14755 
14756   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14757       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14758     return;
14759 
14760   Optional<unsigned> AlignmentParam;
14761   bool IsNothrow = false;
14762   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14763     return;
14764 
14765   // C++2a [basic.stc.dynamic.allocation]p4:
14766   //   An allocation function that has a non-throwing exception specification
14767   //   indicates failure by returning a null pointer value. Any other allocation
14768   //   function never returns a null pointer value and indicates failure only by
14769   //   throwing an exception [...]
14770   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14771     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14772 
14773   // C++2a [basic.stc.dynamic.allocation]p2:
14774   //   An allocation function attempts to allocate the requested amount of
14775   //   storage. [...] If the request succeeds, the value returned by a
14776   //   replaceable allocation function is a [...] pointer value p0 different
14777   //   from any previously returned value p1 [...]
14778   //
14779   // However, this particular information is being added in codegen,
14780   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14781 
14782   // C++2a [basic.stc.dynamic.allocation]p2:
14783   //   An allocation function attempts to allocate the requested amount of
14784   //   storage. If it is successful, it returns the address of the start of a
14785   //   block of storage whose length in bytes is at least as large as the
14786   //   requested size.
14787   if (!FD->hasAttr<AllocSizeAttr>()) {
14788     FD->addAttr(AllocSizeAttr::CreateImplicit(
14789         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14790         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14791   }
14792 
14793   // C++2a [basic.stc.dynamic.allocation]p3:
14794   //   For an allocation function [...], the pointer returned on a successful
14795   //   call shall represent the address of storage that is aligned as follows:
14796   //   (3.1) If the allocation function takes an argument of type
14797   //         std​::​align_­val_­t, the storage will have the alignment
14798   //         specified by the value of this argument.
14799   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14800     FD->addAttr(AllocAlignAttr::CreateImplicit(
14801         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14802   }
14803 
14804   // FIXME:
14805   // C++2a [basic.stc.dynamic.allocation]p3:
14806   //   For an allocation function [...], the pointer returned on a successful
14807   //   call shall represent the address of storage that is aligned as follows:
14808   //   (3.2) Otherwise, if the allocation function is named operator new[],
14809   //         the storage is aligned for any object that does not have
14810   //         new-extended alignment ([basic.align]) and is no larger than the
14811   //         requested size.
14812   //   (3.3) Otherwise, the storage is aligned for any object that does not
14813   //         have new-extended alignment and is of the requested size.
14814 }
14815 
14816 /// Adds any function attributes that we know a priori based on
14817 /// the declaration of this function.
14818 ///
14819 /// These attributes can apply both to implicitly-declared builtins
14820 /// (like __builtin___printf_chk) or to library-declared functions
14821 /// like NSLog or printf.
14822 ///
14823 /// We need to check for duplicate attributes both here and where user-written
14824 /// attributes are applied to declarations.
AddKnownFunctionAttributes(FunctionDecl * FD)14825 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14826   if (FD->isInvalidDecl())
14827     return;
14828 
14829   // If this is a built-in function, map its builtin attributes to
14830   // actual attributes.
14831   if (unsigned BuiltinID = FD->getBuiltinID()) {
14832     // Handle printf-formatting attributes.
14833     unsigned FormatIdx;
14834     bool HasVAListArg;
14835     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14836       if (!FD->hasAttr<FormatAttr>()) {
14837         const char *fmt = "printf";
14838         unsigned int NumParams = FD->getNumParams();
14839         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14840             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14841           fmt = "NSString";
14842         FD->addAttr(FormatAttr::CreateImplicit(Context,
14843                                                &Context.Idents.get(fmt),
14844                                                FormatIdx+1,
14845                                                HasVAListArg ? 0 : FormatIdx+2,
14846                                                FD->getLocation()));
14847       }
14848     }
14849     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14850                                              HasVAListArg)) {
14851      if (!FD->hasAttr<FormatAttr>())
14852        FD->addAttr(FormatAttr::CreateImplicit(Context,
14853                                               &Context.Idents.get("scanf"),
14854                                               FormatIdx+1,
14855                                               HasVAListArg ? 0 : FormatIdx+2,
14856                                               FD->getLocation()));
14857     }
14858 
14859     // Handle automatically recognized callbacks.
14860     SmallVector<int, 4> Encoding;
14861     if (!FD->hasAttr<CallbackAttr>() &&
14862         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14863       FD->addAttr(CallbackAttr::CreateImplicit(
14864           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14865 
14866     // Mark const if we don't care about errno and that is the only thing
14867     // preventing the function from being const. This allows IRgen to use LLVM
14868     // intrinsics for such functions.
14869     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14870         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14871       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14872 
14873     // We make "fma" on some platforms const because we know it does not set
14874     // errno in those environments even though it could set errno based on the
14875     // C standard.
14876     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14877     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14878         !FD->hasAttr<ConstAttr>()) {
14879       switch (BuiltinID) {
14880       case Builtin::BI__builtin_fma:
14881       case Builtin::BI__builtin_fmaf:
14882       case Builtin::BI__builtin_fmal:
14883       case Builtin::BIfma:
14884       case Builtin::BIfmaf:
14885       case Builtin::BIfmal:
14886         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14887         break;
14888       default:
14889         break;
14890       }
14891     }
14892 
14893     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14894         !FD->hasAttr<ReturnsTwiceAttr>())
14895       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14896                                          FD->getLocation()));
14897     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14898       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14899     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14900       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14901     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14902       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14903     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14904         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14905       // Add the appropriate attribute, depending on the CUDA compilation mode
14906       // and which target the builtin belongs to. For example, during host
14907       // compilation, aux builtins are __device__, while the rest are __host__.
14908       if (getLangOpts().CUDAIsDevice !=
14909           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14910         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14911       else
14912         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14913     }
14914   }
14915 
14916   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
14917 
14918   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14919   // throw, add an implicit nothrow attribute to any extern "C" function we come
14920   // across.
14921   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14922       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14923     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14924     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14925       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14926   }
14927 
14928   IdentifierInfo *Name = FD->getIdentifier();
14929   if (!Name)
14930     return;
14931   if ((!getLangOpts().CPlusPlus &&
14932        FD->getDeclContext()->isTranslationUnit()) ||
14933       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14934        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14935        LinkageSpecDecl::lang_c)) {
14936     // Okay: this could be a libc/libm/Objective-C function we know
14937     // about.
14938   } else
14939     return;
14940 
14941   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14942     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14943     // target-specific builtins, perhaps?
14944     if (!FD->hasAttr<FormatAttr>())
14945       FD->addAttr(FormatAttr::CreateImplicit(Context,
14946                                              &Context.Idents.get("printf"), 2,
14947                                              Name->isStr("vasprintf") ? 0 : 3,
14948                                              FD->getLocation()));
14949   }
14950 
14951   if (Name->isStr("__CFStringMakeConstantString")) {
14952     // We already have a __builtin___CFStringMakeConstantString,
14953     // but builds that use -fno-constant-cfstrings don't go through that.
14954     if (!FD->hasAttr<FormatArgAttr>())
14955       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14956                                                 FD->getLocation()));
14957   }
14958 }
14959 
ParseTypedefDecl(Scope * S,Declarator & D,QualType T,TypeSourceInfo * TInfo)14960 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14961                                     TypeSourceInfo *TInfo) {
14962   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14963   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14964 
14965   if (!TInfo) {
14966     assert(D.isInvalidType() && "no declarator info for valid type");
14967     TInfo = Context.getTrivialTypeSourceInfo(T);
14968   }
14969 
14970   // Scope manipulation handled by caller.
14971   TypedefDecl *NewTD =
14972       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14973                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14974 
14975   // Bail out immediately if we have an invalid declaration.
14976   if (D.isInvalidType()) {
14977     NewTD->setInvalidDecl();
14978     return NewTD;
14979   }
14980 
14981   if (D.getDeclSpec().isModulePrivateSpecified()) {
14982     if (CurContext->isFunctionOrMethod())
14983       Diag(NewTD->getLocation(), diag::err_module_private_local)
14984         << 2 << NewTD->getDeclName()
14985         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14986         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14987     else
14988       NewTD->setModulePrivate();
14989   }
14990 
14991   // C++ [dcl.typedef]p8:
14992   //   If the typedef declaration defines an unnamed class (or
14993   //   enum), the first typedef-name declared by the declaration
14994   //   to be that class type (or enum type) is used to denote the
14995   //   class type (or enum type) for linkage purposes only.
14996   // We need to check whether the type was declared in the declaration.
14997   switch (D.getDeclSpec().getTypeSpecType()) {
14998   case TST_enum:
14999   case TST_struct:
15000   case TST_interface:
15001   case TST_union:
15002   case TST_class: {
15003     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15004     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15005     break;
15006   }
15007 
15008   default:
15009     break;
15010   }
15011 
15012   return NewTD;
15013 }
15014 
15015 /// Check that this is a valid underlying type for an enum declaration.
CheckEnumUnderlyingType(TypeSourceInfo * TI)15016 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15017   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15018   QualType T = TI->getType();
15019 
15020   if (T->isDependentType())
15021     return false;
15022 
15023   // This doesn't use 'isIntegralType' despite the error message mentioning
15024   // integral type because isIntegralType would also allow enum types in C.
15025   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15026     if (BT->isInteger())
15027       return false;
15028 
15029   if (T->isExtIntType())
15030     return false;
15031 
15032   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15033 }
15034 
15035 /// Check whether this is a valid redeclaration of a previous enumeration.
15036 /// \return true if the redeclaration was invalid.
CheckEnumRedeclaration(SourceLocation EnumLoc,bool IsScoped,QualType EnumUnderlyingTy,bool IsFixed,const EnumDecl * Prev)15037 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15038                                   QualType EnumUnderlyingTy, bool IsFixed,
15039                                   const EnumDecl *Prev) {
15040   if (IsScoped != Prev->isScoped()) {
15041     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15042       << Prev->isScoped();
15043     Diag(Prev->getLocation(), diag::note_previous_declaration);
15044     return true;
15045   }
15046 
15047   if (IsFixed && Prev->isFixed()) {
15048     if (!EnumUnderlyingTy->isDependentType() &&
15049         !Prev->getIntegerType()->isDependentType() &&
15050         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15051                                         Prev->getIntegerType())) {
15052       // TODO: Highlight the underlying type of the redeclaration.
15053       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15054         << EnumUnderlyingTy << Prev->getIntegerType();
15055       Diag(Prev->getLocation(), diag::note_previous_declaration)
15056           << Prev->getIntegerTypeRange();
15057       return true;
15058     }
15059   } else if (IsFixed != Prev->isFixed()) {
15060     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15061       << Prev->isFixed();
15062     Diag(Prev->getLocation(), diag::note_previous_declaration);
15063     return true;
15064   }
15065 
15066   return false;
15067 }
15068 
15069 /// Get diagnostic %select index for tag kind for
15070 /// redeclaration diagnostic message.
15071 /// WARNING: Indexes apply to particular diagnostics only!
15072 ///
15073 /// \returns diagnostic %select index.
getRedeclDiagFromTagKind(TagTypeKind Tag)15074 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15075   switch (Tag) {
15076   case TTK_Struct: return 0;
15077   case TTK_Interface: return 1;
15078   case TTK_Class:  return 2;
15079   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15080   }
15081 }
15082 
15083 /// Determine if tag kind is a class-key compatible with
15084 /// class for redeclaration (class, struct, or __interface).
15085 ///
15086 /// \returns true iff the tag kind is compatible.
isClassCompatTagKind(TagTypeKind Tag)15087 static bool isClassCompatTagKind(TagTypeKind Tag)
15088 {
15089   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15090 }
15091 
getNonTagTypeDeclKind(const Decl * PrevDecl,TagTypeKind TTK)15092 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15093                                              TagTypeKind TTK) {
15094   if (isa<TypedefDecl>(PrevDecl))
15095     return NTK_Typedef;
15096   else if (isa<TypeAliasDecl>(PrevDecl))
15097     return NTK_TypeAlias;
15098   else if (isa<ClassTemplateDecl>(PrevDecl))
15099     return NTK_Template;
15100   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15101     return NTK_TypeAliasTemplate;
15102   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15103     return NTK_TemplateTemplateArgument;
15104   switch (TTK) {
15105   case TTK_Struct:
15106   case TTK_Interface:
15107   case TTK_Class:
15108     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15109   case TTK_Union:
15110     return NTK_NonUnion;
15111   case TTK_Enum:
15112     return NTK_NonEnum;
15113   }
15114   llvm_unreachable("invalid TTK");
15115 }
15116 
15117 /// Determine whether a tag with a given kind is acceptable
15118 /// as a redeclaration of the given tag declaration.
15119 ///
15120 /// \returns true if the new tag kind is acceptable, false otherwise.
isAcceptableTagRedeclaration(const TagDecl * Previous,TagTypeKind NewTag,bool isDefinition,SourceLocation NewTagLoc,const IdentifierInfo * Name)15121 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15122                                         TagTypeKind NewTag, bool isDefinition,
15123                                         SourceLocation NewTagLoc,
15124                                         const IdentifierInfo *Name) {
15125   // C++ [dcl.type.elab]p3:
15126   //   The class-key or enum keyword present in the
15127   //   elaborated-type-specifier shall agree in kind with the
15128   //   declaration to which the name in the elaborated-type-specifier
15129   //   refers. This rule also applies to the form of
15130   //   elaborated-type-specifier that declares a class-name or
15131   //   friend class since it can be construed as referring to the
15132   //   definition of the class. Thus, in any
15133   //   elaborated-type-specifier, the enum keyword shall be used to
15134   //   refer to an enumeration (7.2), the union class-key shall be
15135   //   used to refer to a union (clause 9), and either the class or
15136   //   struct class-key shall be used to refer to a class (clause 9)
15137   //   declared using the class or struct class-key.
15138   TagTypeKind OldTag = Previous->getTagKind();
15139   if (OldTag != NewTag &&
15140       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15141     return false;
15142 
15143   // Tags are compatible, but we might still want to warn on mismatched tags.
15144   // Non-class tags can't be mismatched at this point.
15145   if (!isClassCompatTagKind(NewTag))
15146     return true;
15147 
15148   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15149   // by our warning analysis. We don't want to warn about mismatches with (eg)
15150   // declarations in system headers that are designed to be specialized, but if
15151   // a user asks us to warn, we should warn if their code contains mismatched
15152   // declarations.
15153   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15154     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15155                                       Loc);
15156   };
15157   if (IsIgnoredLoc(NewTagLoc))
15158     return true;
15159 
15160   auto IsIgnored = [&](const TagDecl *Tag) {
15161     return IsIgnoredLoc(Tag->getLocation());
15162   };
15163   while (IsIgnored(Previous)) {
15164     Previous = Previous->getPreviousDecl();
15165     if (!Previous)
15166       return true;
15167     OldTag = Previous->getTagKind();
15168   }
15169 
15170   bool isTemplate = false;
15171   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15172     isTemplate = Record->getDescribedClassTemplate();
15173 
15174   if (inTemplateInstantiation()) {
15175     if (OldTag != NewTag) {
15176       // In a template instantiation, do not offer fix-its for tag mismatches
15177       // since they usually mess up the template instead of fixing the problem.
15178       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15179         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15180         << getRedeclDiagFromTagKind(OldTag);
15181       // FIXME: Note previous location?
15182     }
15183     return true;
15184   }
15185 
15186   if (isDefinition) {
15187     // On definitions, check all previous tags and issue a fix-it for each
15188     // one that doesn't match the current tag.
15189     if (Previous->getDefinition()) {
15190       // Don't suggest fix-its for redefinitions.
15191       return true;
15192     }
15193 
15194     bool previousMismatch = false;
15195     for (const TagDecl *I : Previous->redecls()) {
15196       if (I->getTagKind() != NewTag) {
15197         // Ignore previous declarations for which the warning was disabled.
15198         if (IsIgnored(I))
15199           continue;
15200 
15201         if (!previousMismatch) {
15202           previousMismatch = true;
15203           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15204             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15205             << getRedeclDiagFromTagKind(I->getTagKind());
15206         }
15207         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15208           << getRedeclDiagFromTagKind(NewTag)
15209           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15210                TypeWithKeyword::getTagTypeKindName(NewTag));
15211       }
15212     }
15213     return true;
15214   }
15215 
15216   // Identify the prevailing tag kind: this is the kind of the definition (if
15217   // there is a non-ignored definition), or otherwise the kind of the prior
15218   // (non-ignored) declaration.
15219   const TagDecl *PrevDef = Previous->getDefinition();
15220   if (PrevDef && IsIgnored(PrevDef))
15221     PrevDef = nullptr;
15222   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15223   if (Redecl->getTagKind() != NewTag) {
15224     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15225       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15226       << getRedeclDiagFromTagKind(OldTag);
15227     Diag(Redecl->getLocation(), diag::note_previous_use);
15228 
15229     // If there is a previous definition, suggest a fix-it.
15230     if (PrevDef) {
15231       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15232         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15233         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15234              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15235     }
15236   }
15237 
15238   return true;
15239 }
15240 
15241 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15242 /// from an outer enclosing namespace or file scope inside a friend declaration.
15243 /// This should provide the commented out code in the following snippet:
15244 ///   namespace N {
15245 ///     struct X;
15246 ///     namespace M {
15247 ///       struct Y { friend struct /*N::*/ X; };
15248 ///     }
15249 ///   }
createFriendTagNNSFixIt(Sema & SemaRef,NamedDecl * ND,Scope * S,SourceLocation NameLoc)15250 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15251                                          SourceLocation NameLoc) {
15252   // While the decl is in a namespace, do repeated lookup of that name and see
15253   // if we get the same namespace back.  If we do not, continue until
15254   // translation unit scope, at which point we have a fully qualified NNS.
15255   SmallVector<IdentifierInfo *, 4> Namespaces;
15256   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15257   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15258     // This tag should be declared in a namespace, which can only be enclosed by
15259     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15260     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15261     if (!Namespace || Namespace->isAnonymousNamespace())
15262       return FixItHint();
15263     IdentifierInfo *II = Namespace->getIdentifier();
15264     Namespaces.push_back(II);
15265     NamedDecl *Lookup = SemaRef.LookupSingleName(
15266         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15267     if (Lookup == Namespace)
15268       break;
15269   }
15270 
15271   // Once we have all the namespaces, reverse them to go outermost first, and
15272   // build an NNS.
15273   SmallString<64> Insertion;
15274   llvm::raw_svector_ostream OS(Insertion);
15275   if (DC->isTranslationUnit())
15276     OS << "::";
15277   std::reverse(Namespaces.begin(), Namespaces.end());
15278   for (auto *II : Namespaces)
15279     OS << II->getName() << "::";
15280   return FixItHint::CreateInsertion(NameLoc, Insertion);
15281 }
15282 
15283 /// Determine whether a tag originally declared in context \p OldDC can
15284 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15285 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15286 /// using-declaration).
isAcceptableTagRedeclContext(Sema & S,DeclContext * OldDC,DeclContext * NewDC)15287 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15288                                          DeclContext *NewDC) {
15289   OldDC = OldDC->getRedeclContext();
15290   NewDC = NewDC->getRedeclContext();
15291 
15292   if (OldDC->Equals(NewDC))
15293     return true;
15294 
15295   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15296   // encloses the other).
15297   if (S.getLangOpts().MSVCCompat &&
15298       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15299     return true;
15300 
15301   return false;
15302 }
15303 
15304 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15305 /// former case, Name will be non-null.  In the later case, Name will be null.
15306 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15307 /// reference/declaration/definition of a tag.
15308 ///
15309 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15310 /// trailing-type-specifier) other than one in an alias-declaration.
15311 ///
15312 /// \param SkipBody If non-null, will be set to indicate if the caller should
15313 /// skip the definition of this tag and treat it as if it were a declaration.
ActOnTag(Scope * S,unsigned TagSpec,TagUseKind TUK,SourceLocation KWLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,const ParsedAttributesView & Attrs,AccessSpecifier AS,SourceLocation ModulePrivateLoc,MultiTemplateParamsArg TemplateParameterLists,bool & OwnedDecl,bool & IsDependent,SourceLocation ScopedEnumKWLoc,bool ScopedEnumUsesClassTag,TypeResult UnderlyingType,bool IsTypeSpecifier,bool IsTemplateParamOrArg,SkipBodyInfo * SkipBody)15314 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15315                      SourceLocation KWLoc, CXXScopeSpec &SS,
15316                      IdentifierInfo *Name, SourceLocation NameLoc,
15317                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15318                      SourceLocation ModulePrivateLoc,
15319                      MultiTemplateParamsArg TemplateParameterLists,
15320                      bool &OwnedDecl, bool &IsDependent,
15321                      SourceLocation ScopedEnumKWLoc,
15322                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15323                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15324                      SkipBodyInfo *SkipBody) {
15325   // If this is not a definition, it must have a name.
15326   IdentifierInfo *OrigName = Name;
15327   assert((Name != nullptr || TUK == TUK_Definition) &&
15328          "Nameless record must be a definition!");
15329   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15330 
15331   OwnedDecl = false;
15332   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15333   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15334 
15335   // FIXME: Check member specializations more carefully.
15336   bool isMemberSpecialization = false;
15337   bool Invalid = false;
15338 
15339   // We only need to do this matching if we have template parameters
15340   // or a scope specifier, which also conveniently avoids this work
15341   // for non-C++ cases.
15342   if (TemplateParameterLists.size() > 0 ||
15343       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15344     if (TemplateParameterList *TemplateParams =
15345             MatchTemplateParametersToScopeSpecifier(
15346                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15347                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15348       if (Kind == TTK_Enum) {
15349         Diag(KWLoc, diag::err_enum_template);
15350         return nullptr;
15351       }
15352 
15353       if (TemplateParams->size() > 0) {
15354         // This is a declaration or definition of a class template (which may
15355         // be a member of another template).
15356 
15357         if (Invalid)
15358           return nullptr;
15359 
15360         OwnedDecl = false;
15361         DeclResult Result = CheckClassTemplate(
15362             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15363             AS, ModulePrivateLoc,
15364             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15365             TemplateParameterLists.data(), SkipBody);
15366         return Result.get();
15367       } else {
15368         // The "template<>" header is extraneous.
15369         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15370           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15371         isMemberSpecialization = true;
15372       }
15373     }
15374   }
15375 
15376   // Figure out the underlying type if this a enum declaration. We need to do
15377   // this early, because it's needed to detect if this is an incompatible
15378   // redeclaration.
15379   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15380   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15381 
15382   if (Kind == TTK_Enum) {
15383     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15384       // No underlying type explicitly specified, or we failed to parse the
15385       // type, default to int.
15386       EnumUnderlying = Context.IntTy.getTypePtr();
15387     } else if (UnderlyingType.get()) {
15388       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15389       // integral type; any cv-qualification is ignored.
15390       TypeSourceInfo *TI = nullptr;
15391       GetTypeFromParser(UnderlyingType.get(), &TI);
15392       EnumUnderlying = TI;
15393 
15394       if (CheckEnumUnderlyingType(TI))
15395         // Recover by falling back to int.
15396         EnumUnderlying = Context.IntTy.getTypePtr();
15397 
15398       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15399                                           UPPC_FixedUnderlyingType))
15400         EnumUnderlying = Context.IntTy.getTypePtr();
15401 
15402     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15403       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15404       // of 'int'. However, if this is an unfixed forward declaration, don't set
15405       // the underlying type unless the user enables -fms-compatibility. This
15406       // makes unfixed forward declared enums incomplete and is more conforming.
15407       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15408         EnumUnderlying = Context.IntTy.getTypePtr();
15409     }
15410   }
15411 
15412   DeclContext *SearchDC = CurContext;
15413   DeclContext *DC = CurContext;
15414   bool isStdBadAlloc = false;
15415   bool isStdAlignValT = false;
15416 
15417   RedeclarationKind Redecl = forRedeclarationInCurContext();
15418   if (TUK == TUK_Friend || TUK == TUK_Reference)
15419     Redecl = NotForRedeclaration;
15420 
15421   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15422   /// implemented asks for structural equivalence checking, the returned decl
15423   /// here is passed back to the parser, allowing the tag body to be parsed.
15424   auto createTagFromNewDecl = [&]() -> TagDecl * {
15425     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15426     // If there is an identifier, use the location of the identifier as the
15427     // location of the decl, otherwise use the location of the struct/union
15428     // keyword.
15429     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15430     TagDecl *New = nullptr;
15431 
15432     if (Kind == TTK_Enum) {
15433       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15434                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15435       // If this is an undefined enum, bail.
15436       if (TUK != TUK_Definition && !Invalid)
15437         return nullptr;
15438       if (EnumUnderlying) {
15439         EnumDecl *ED = cast<EnumDecl>(New);
15440         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15441           ED->setIntegerTypeSourceInfo(TI);
15442         else
15443           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15444         ED->setPromotionType(ED->getIntegerType());
15445       }
15446     } else { // struct/union
15447       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15448                                nullptr);
15449     }
15450 
15451     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15452       // Add alignment attributes if necessary; these attributes are checked
15453       // when the ASTContext lays out the structure.
15454       //
15455       // It is important for implementing the correct semantics that this
15456       // happen here (in ActOnTag). The #pragma pack stack is
15457       // maintained as a result of parser callbacks which can occur at
15458       // many points during the parsing of a struct declaration (because
15459       // the #pragma tokens are effectively skipped over during the
15460       // parsing of the struct).
15461       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15462         AddAlignmentAttributesForRecord(RD);
15463         AddMsStructLayoutForRecord(RD);
15464       }
15465     }
15466     New->setLexicalDeclContext(CurContext);
15467     return New;
15468   };
15469 
15470   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15471   if (Name && SS.isNotEmpty()) {
15472     // We have a nested-name tag ('struct foo::bar').
15473 
15474     // Check for invalid 'foo::'.
15475     if (SS.isInvalid()) {
15476       Name = nullptr;
15477       goto CreateNewDecl;
15478     }
15479 
15480     // If this is a friend or a reference to a class in a dependent
15481     // context, don't try to make a decl for it.
15482     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15483       DC = computeDeclContext(SS, false);
15484       if (!DC) {
15485         IsDependent = true;
15486         return nullptr;
15487       }
15488     } else {
15489       DC = computeDeclContext(SS, true);
15490       if (!DC) {
15491         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15492           << SS.getRange();
15493         return nullptr;
15494       }
15495     }
15496 
15497     if (RequireCompleteDeclContext(SS, DC))
15498       return nullptr;
15499 
15500     SearchDC = DC;
15501     // Look-up name inside 'foo::'.
15502     LookupQualifiedName(Previous, DC);
15503 
15504     if (Previous.isAmbiguous())
15505       return nullptr;
15506 
15507     if (Previous.empty()) {
15508       // Name lookup did not find anything. However, if the
15509       // nested-name-specifier refers to the current instantiation,
15510       // and that current instantiation has any dependent base
15511       // classes, we might find something at instantiation time: treat
15512       // this as a dependent elaborated-type-specifier.
15513       // But this only makes any sense for reference-like lookups.
15514       if (Previous.wasNotFoundInCurrentInstantiation() &&
15515           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15516         IsDependent = true;
15517         return nullptr;
15518       }
15519 
15520       // A tag 'foo::bar' must already exist.
15521       Diag(NameLoc, diag::err_not_tag_in_scope)
15522         << Kind << Name << DC << SS.getRange();
15523       Name = nullptr;
15524       Invalid = true;
15525       goto CreateNewDecl;
15526     }
15527   } else if (Name) {
15528     // C++14 [class.mem]p14:
15529     //   If T is the name of a class, then each of the following shall have a
15530     //   name different from T:
15531     //    -- every member of class T that is itself a type
15532     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15533         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15534       return nullptr;
15535 
15536     // If this is a named struct, check to see if there was a previous forward
15537     // declaration or definition.
15538     // FIXME: We're looking into outer scopes here, even when we
15539     // shouldn't be. Doing so can result in ambiguities that we
15540     // shouldn't be diagnosing.
15541     LookupName(Previous, S);
15542 
15543     // When declaring or defining a tag, ignore ambiguities introduced
15544     // by types using'ed into this scope.
15545     if (Previous.isAmbiguous() &&
15546         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15547       LookupResult::Filter F = Previous.makeFilter();
15548       while (F.hasNext()) {
15549         NamedDecl *ND = F.next();
15550         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15551                 SearchDC->getRedeclContext()))
15552           F.erase();
15553       }
15554       F.done();
15555     }
15556 
15557     // C++11 [namespace.memdef]p3:
15558     //   If the name in a friend declaration is neither qualified nor
15559     //   a template-id and the declaration is a function or an
15560     //   elaborated-type-specifier, the lookup to determine whether
15561     //   the entity has been previously declared shall not consider
15562     //   any scopes outside the innermost enclosing namespace.
15563     //
15564     // MSVC doesn't implement the above rule for types, so a friend tag
15565     // declaration may be a redeclaration of a type declared in an enclosing
15566     // scope.  They do implement this rule for friend functions.
15567     //
15568     // Does it matter that this should be by scope instead of by
15569     // semantic context?
15570     if (!Previous.empty() && TUK == TUK_Friend) {
15571       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15572       LookupResult::Filter F = Previous.makeFilter();
15573       bool FriendSawTagOutsideEnclosingNamespace = false;
15574       while (F.hasNext()) {
15575         NamedDecl *ND = F.next();
15576         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15577         if (DC->isFileContext() &&
15578             !EnclosingNS->Encloses(ND->getDeclContext())) {
15579           if (getLangOpts().MSVCCompat)
15580             FriendSawTagOutsideEnclosingNamespace = true;
15581           else
15582             F.erase();
15583         }
15584       }
15585       F.done();
15586 
15587       // Diagnose this MSVC extension in the easy case where lookup would have
15588       // unambiguously found something outside the enclosing namespace.
15589       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15590         NamedDecl *ND = Previous.getFoundDecl();
15591         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15592             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15593       }
15594     }
15595 
15596     // Note:  there used to be some attempt at recovery here.
15597     if (Previous.isAmbiguous())
15598       return nullptr;
15599 
15600     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15601       // FIXME: This makes sure that we ignore the contexts associated
15602       // with C structs, unions, and enums when looking for a matching
15603       // tag declaration or definition. See the similar lookup tweak
15604       // in Sema::LookupName; is there a better way to deal with this?
15605       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15606         SearchDC = SearchDC->getParent();
15607     }
15608   }
15609 
15610   if (Previous.isSingleResult() &&
15611       Previous.getFoundDecl()->isTemplateParameter()) {
15612     // Maybe we will complain about the shadowed template parameter.
15613     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15614     // Just pretend that we didn't see the previous declaration.
15615     Previous.clear();
15616   }
15617 
15618   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15619       DC->Equals(getStdNamespace())) {
15620     if (Name->isStr("bad_alloc")) {
15621       // This is a declaration of or a reference to "std::bad_alloc".
15622       isStdBadAlloc = true;
15623 
15624       // If std::bad_alloc has been implicitly declared (but made invisible to
15625       // name lookup), fill in this implicit declaration as the previous
15626       // declaration, so that the declarations get chained appropriately.
15627       if (Previous.empty() && StdBadAlloc)
15628         Previous.addDecl(getStdBadAlloc());
15629     } else if (Name->isStr("align_val_t")) {
15630       isStdAlignValT = true;
15631       if (Previous.empty() && StdAlignValT)
15632         Previous.addDecl(getStdAlignValT());
15633     }
15634   }
15635 
15636   // If we didn't find a previous declaration, and this is a reference
15637   // (or friend reference), move to the correct scope.  In C++, we
15638   // also need to do a redeclaration lookup there, just in case
15639   // there's a shadow friend decl.
15640   if (Name && Previous.empty() &&
15641       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15642     if (Invalid) goto CreateNewDecl;
15643     assert(SS.isEmpty());
15644 
15645     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15646       // C++ [basic.scope.pdecl]p5:
15647       //   -- for an elaborated-type-specifier of the form
15648       //
15649       //          class-key identifier
15650       //
15651       //      if the elaborated-type-specifier is used in the
15652       //      decl-specifier-seq or parameter-declaration-clause of a
15653       //      function defined in namespace scope, the identifier is
15654       //      declared as a class-name in the namespace that contains
15655       //      the declaration; otherwise, except as a friend
15656       //      declaration, the identifier is declared in the smallest
15657       //      non-class, non-function-prototype scope that contains the
15658       //      declaration.
15659       //
15660       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15661       // C structs and unions.
15662       //
15663       // It is an error in C++ to declare (rather than define) an enum
15664       // type, including via an elaborated type specifier.  We'll
15665       // diagnose that later; for now, declare the enum in the same
15666       // scope as we would have picked for any other tag type.
15667       //
15668       // GNU C also supports this behavior as part of its incomplete
15669       // enum types extension, while GNU C++ does not.
15670       //
15671       // Find the context where we'll be declaring the tag.
15672       // FIXME: We would like to maintain the current DeclContext as the
15673       // lexical context,
15674       SearchDC = getTagInjectionContext(SearchDC);
15675 
15676       // Find the scope where we'll be declaring the tag.
15677       S = getTagInjectionScope(S, getLangOpts());
15678     } else {
15679       assert(TUK == TUK_Friend);
15680       // C++ [namespace.memdef]p3:
15681       //   If a friend declaration in a non-local class first declares a
15682       //   class or function, the friend class or function is a member of
15683       //   the innermost enclosing namespace.
15684       SearchDC = SearchDC->getEnclosingNamespaceContext();
15685     }
15686 
15687     // In C++, we need to do a redeclaration lookup to properly
15688     // diagnose some problems.
15689     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15690     // hidden declaration so that we don't get ambiguity errors when using a
15691     // type declared by an elaborated-type-specifier.  In C that is not correct
15692     // and we should instead merge compatible types found by lookup.
15693     if (getLangOpts().CPlusPlus) {
15694       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15695       LookupQualifiedName(Previous, SearchDC);
15696     } else {
15697       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15698       LookupName(Previous, S);
15699     }
15700   }
15701 
15702   // If we have a known previous declaration to use, then use it.
15703   if (Previous.empty() && SkipBody && SkipBody->Previous)
15704     Previous.addDecl(SkipBody->Previous);
15705 
15706   if (!Previous.empty()) {
15707     NamedDecl *PrevDecl = Previous.getFoundDecl();
15708     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15709 
15710     // It's okay to have a tag decl in the same scope as a typedef
15711     // which hides a tag decl in the same scope.  Finding this
15712     // insanity with a redeclaration lookup can only actually happen
15713     // in C++.
15714     //
15715     // This is also okay for elaborated-type-specifiers, which is
15716     // technically forbidden by the current standard but which is
15717     // okay according to the likely resolution of an open issue;
15718     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15719     if (getLangOpts().CPlusPlus) {
15720       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15721         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15722           TagDecl *Tag = TT->getDecl();
15723           if (Tag->getDeclName() == Name &&
15724               Tag->getDeclContext()->getRedeclContext()
15725                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15726             PrevDecl = Tag;
15727             Previous.clear();
15728             Previous.addDecl(Tag);
15729             Previous.resolveKind();
15730           }
15731         }
15732       }
15733     }
15734 
15735     // If this is a redeclaration of a using shadow declaration, it must
15736     // declare a tag in the same context. In MSVC mode, we allow a
15737     // redefinition if either context is within the other.
15738     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15739       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15740       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15741           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15742           !(OldTag && isAcceptableTagRedeclContext(
15743                           *this, OldTag->getDeclContext(), SearchDC))) {
15744         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15745         Diag(Shadow->getTargetDecl()->getLocation(),
15746              diag::note_using_decl_target);
15747         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15748             << 0;
15749         // Recover by ignoring the old declaration.
15750         Previous.clear();
15751         goto CreateNewDecl;
15752       }
15753     }
15754 
15755     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15756       // If this is a use of a previous tag, or if the tag is already declared
15757       // in the same scope (so that the definition/declaration completes or
15758       // rementions the tag), reuse the decl.
15759       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15760           isDeclInScope(DirectPrevDecl, SearchDC, S,
15761                         SS.isNotEmpty() || isMemberSpecialization)) {
15762         // Make sure that this wasn't declared as an enum and now used as a
15763         // struct or something similar.
15764         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15765                                           TUK == TUK_Definition, KWLoc,
15766                                           Name)) {
15767           bool SafeToContinue
15768             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15769                Kind != TTK_Enum);
15770           if (SafeToContinue)
15771             Diag(KWLoc, diag::err_use_with_wrong_tag)
15772               << Name
15773               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15774                                               PrevTagDecl->getKindName());
15775           else
15776             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15777           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15778 
15779           if (SafeToContinue)
15780             Kind = PrevTagDecl->getTagKind();
15781           else {
15782             // Recover by making this an anonymous redefinition.
15783             Name = nullptr;
15784             Previous.clear();
15785             Invalid = true;
15786           }
15787         }
15788 
15789         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15790           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15791           if (TUK == TUK_Reference || TUK == TUK_Friend)
15792             return PrevTagDecl;
15793 
15794           QualType EnumUnderlyingTy;
15795           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15796             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15797           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15798             EnumUnderlyingTy = QualType(T, 0);
15799 
15800           // All conflicts with previous declarations are recovered by
15801           // returning the previous declaration, unless this is a definition,
15802           // in which case we want the caller to bail out.
15803           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15804                                      ScopedEnum, EnumUnderlyingTy,
15805                                      IsFixed, PrevEnum))
15806             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15807         }
15808 
15809         // C++11 [class.mem]p1:
15810         //   A member shall not be declared twice in the member-specification,
15811         //   except that a nested class or member class template can be declared
15812         //   and then later defined.
15813         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15814             S->isDeclScope(PrevDecl)) {
15815           Diag(NameLoc, diag::ext_member_redeclared);
15816           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15817         }
15818 
15819         if (!Invalid) {
15820           // If this is a use, just return the declaration we found, unless
15821           // we have attributes.
15822           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15823             if (!Attrs.empty()) {
15824               // FIXME: Diagnose these attributes. For now, we create a new
15825               // declaration to hold them.
15826             } else if (TUK == TUK_Reference &&
15827                        (PrevTagDecl->getFriendObjectKind() ==
15828                             Decl::FOK_Undeclared ||
15829                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15830                        SS.isEmpty()) {
15831               // This declaration is a reference to an existing entity, but
15832               // has different visibility from that entity: it either makes
15833               // a friend visible or it makes a type visible in a new module.
15834               // In either case, create a new declaration. We only do this if
15835               // the declaration would have meant the same thing if no prior
15836               // declaration were found, that is, if it was found in the same
15837               // scope where we would have injected a declaration.
15838               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15839                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15840                 return PrevTagDecl;
15841               // This is in the injected scope, create a new declaration in
15842               // that scope.
15843               S = getTagInjectionScope(S, getLangOpts());
15844             } else {
15845               return PrevTagDecl;
15846             }
15847           }
15848 
15849           // Diagnose attempts to redefine a tag.
15850           if (TUK == TUK_Definition) {
15851             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15852               // If we're defining a specialization and the previous definition
15853               // is from an implicit instantiation, don't emit an error
15854               // here; we'll catch this in the general case below.
15855               bool IsExplicitSpecializationAfterInstantiation = false;
15856               if (isMemberSpecialization) {
15857                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15858                   IsExplicitSpecializationAfterInstantiation =
15859                     RD->getTemplateSpecializationKind() !=
15860                     TSK_ExplicitSpecialization;
15861                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15862                   IsExplicitSpecializationAfterInstantiation =
15863                     ED->getTemplateSpecializationKind() !=
15864                     TSK_ExplicitSpecialization;
15865               }
15866 
15867               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15868               // not keep more that one definition around (merge them). However,
15869               // ensure the decl passes the structural compatibility check in
15870               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15871               NamedDecl *Hidden = nullptr;
15872               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15873                 // There is a definition of this tag, but it is not visible. We
15874                 // explicitly make use of C++'s one definition rule here, and
15875                 // assume that this definition is identical to the hidden one
15876                 // we already have. Make the existing definition visible and
15877                 // use it in place of this one.
15878                 if (!getLangOpts().CPlusPlus) {
15879                   // Postpone making the old definition visible until after we
15880                   // complete parsing the new one and do the structural
15881                   // comparison.
15882                   SkipBody->CheckSameAsPrevious = true;
15883                   SkipBody->New = createTagFromNewDecl();
15884                   SkipBody->Previous = Def;
15885                   return Def;
15886                 } else {
15887                   SkipBody->ShouldSkip = true;
15888                   SkipBody->Previous = Def;
15889                   makeMergedDefinitionVisible(Hidden);
15890                   // Carry on and handle it like a normal definition. We'll
15891                   // skip starting the definitiion later.
15892                 }
15893               } else if (!IsExplicitSpecializationAfterInstantiation) {
15894                 // A redeclaration in function prototype scope in C isn't
15895                 // visible elsewhere, so merely issue a warning.
15896                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15897                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15898                 else
15899                   Diag(NameLoc, diag::err_redefinition) << Name;
15900                 notePreviousDefinition(Def,
15901                                        NameLoc.isValid() ? NameLoc : KWLoc);
15902                 // If this is a redefinition, recover by making this
15903                 // struct be anonymous, which will make any later
15904                 // references get the previous definition.
15905                 Name = nullptr;
15906                 Previous.clear();
15907                 Invalid = true;
15908               }
15909             } else {
15910               // If the type is currently being defined, complain
15911               // about a nested redefinition.
15912               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15913               if (TD->isBeingDefined()) {
15914                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15915                 Diag(PrevTagDecl->getLocation(),
15916                      diag::note_previous_definition);
15917                 Name = nullptr;
15918                 Previous.clear();
15919                 Invalid = true;
15920               }
15921             }
15922 
15923             // Okay, this is definition of a previously declared or referenced
15924             // tag. We're going to create a new Decl for it.
15925           }
15926 
15927           // Okay, we're going to make a redeclaration.  If this is some kind
15928           // of reference, make sure we build the redeclaration in the same DC
15929           // as the original, and ignore the current access specifier.
15930           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15931             SearchDC = PrevTagDecl->getDeclContext();
15932             AS = AS_none;
15933           }
15934         }
15935         // If we get here we have (another) forward declaration or we
15936         // have a definition.  Just create a new decl.
15937 
15938       } else {
15939         // If we get here, this is a definition of a new tag type in a nested
15940         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15941         // new decl/type.  We set PrevDecl to NULL so that the entities
15942         // have distinct types.
15943         Previous.clear();
15944       }
15945       // If we get here, we're going to create a new Decl. If PrevDecl
15946       // is non-NULL, it's a definition of the tag declared by
15947       // PrevDecl. If it's NULL, we have a new definition.
15948 
15949     // Otherwise, PrevDecl is not a tag, but was found with tag
15950     // lookup.  This is only actually possible in C++, where a few
15951     // things like templates still live in the tag namespace.
15952     } else {
15953       // Use a better diagnostic if an elaborated-type-specifier
15954       // found the wrong kind of type on the first
15955       // (non-redeclaration) lookup.
15956       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15957           !Previous.isForRedeclaration()) {
15958         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15959         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15960                                                        << Kind;
15961         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15962         Invalid = true;
15963 
15964       // Otherwise, only diagnose if the declaration is in scope.
15965       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15966                                 SS.isNotEmpty() || isMemberSpecialization)) {
15967         // do nothing
15968 
15969       // Diagnose implicit declarations introduced by elaborated types.
15970       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15971         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15972         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15973         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15974         Invalid = true;
15975 
15976       // Otherwise it's a declaration.  Call out a particularly common
15977       // case here.
15978       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15979         unsigned Kind = 0;
15980         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15981         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15982           << Name << Kind << TND->getUnderlyingType();
15983         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15984         Invalid = true;
15985 
15986       // Otherwise, diagnose.
15987       } else {
15988         // The tag name clashes with something else in the target scope,
15989         // issue an error and recover by making this tag be anonymous.
15990         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15991         notePreviousDefinition(PrevDecl, NameLoc);
15992         Name = nullptr;
15993         Invalid = true;
15994       }
15995 
15996       // The existing declaration isn't relevant to us; we're in a
15997       // new scope, so clear out the previous declaration.
15998       Previous.clear();
15999     }
16000   }
16001 
16002 CreateNewDecl:
16003 
16004   TagDecl *PrevDecl = nullptr;
16005   if (Previous.isSingleResult())
16006     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16007 
16008   // If there is an identifier, use the location of the identifier as the
16009   // location of the decl, otherwise use the location of the struct/union
16010   // keyword.
16011   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16012 
16013   // Otherwise, create a new declaration. If there is a previous
16014   // declaration of the same entity, the two will be linked via
16015   // PrevDecl.
16016   TagDecl *New;
16017 
16018   if (Kind == TTK_Enum) {
16019     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16020     // enum X { A, B, C } D;    D should chain to X.
16021     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16022                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16023                            ScopedEnumUsesClassTag, IsFixed);
16024 
16025     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16026       StdAlignValT = cast<EnumDecl>(New);
16027 
16028     // If this is an undefined enum, warn.
16029     if (TUK != TUK_Definition && !Invalid) {
16030       TagDecl *Def;
16031       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16032         // C++0x: 7.2p2: opaque-enum-declaration.
16033         // Conflicts are diagnosed above. Do nothing.
16034       }
16035       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16036         Diag(Loc, diag::ext_forward_ref_enum_def)
16037           << New;
16038         Diag(Def->getLocation(), diag::note_previous_definition);
16039       } else {
16040         unsigned DiagID = diag::ext_forward_ref_enum;
16041         if (getLangOpts().MSVCCompat)
16042           DiagID = diag::ext_ms_forward_ref_enum;
16043         else if (getLangOpts().CPlusPlus)
16044           DiagID = diag::err_forward_ref_enum;
16045         Diag(Loc, DiagID);
16046       }
16047     }
16048 
16049     if (EnumUnderlying) {
16050       EnumDecl *ED = cast<EnumDecl>(New);
16051       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16052         ED->setIntegerTypeSourceInfo(TI);
16053       else
16054         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16055       ED->setPromotionType(ED->getIntegerType());
16056       assert(ED->isComplete() && "enum with type should be complete");
16057     }
16058   } else {
16059     // struct/union/class
16060 
16061     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16062     // struct X { int A; } D;    D should chain to X.
16063     if (getLangOpts().CPlusPlus) {
16064       // FIXME: Look for a way to use RecordDecl for simple structs.
16065       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16066                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16067 
16068       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16069         StdBadAlloc = cast<CXXRecordDecl>(New);
16070     } else
16071       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16072                                cast_or_null<RecordDecl>(PrevDecl));
16073   }
16074 
16075   // C++11 [dcl.type]p3:
16076   //   A type-specifier-seq shall not define a class or enumeration [...].
16077   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16078       TUK == TUK_Definition) {
16079     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16080       << Context.getTagDeclType(New);
16081     Invalid = true;
16082   }
16083 
16084   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16085       DC->getDeclKind() == Decl::Enum) {
16086     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16087       << Context.getTagDeclType(New);
16088     Invalid = true;
16089   }
16090 
16091   // Maybe add qualifier info.
16092   if (SS.isNotEmpty()) {
16093     if (SS.isSet()) {
16094       // If this is either a declaration or a definition, check the
16095       // nested-name-specifier against the current context.
16096       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16097           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16098                                        isMemberSpecialization))
16099         Invalid = true;
16100 
16101       New->setQualifierInfo(SS.getWithLocInContext(Context));
16102       if (TemplateParameterLists.size() > 0) {
16103         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16104       }
16105     }
16106     else
16107       Invalid = true;
16108   }
16109 
16110   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16111     // Add alignment attributes if necessary; these attributes are checked when
16112     // the ASTContext lays out the structure.
16113     //
16114     // It is important for implementing the correct semantics that this
16115     // happen here (in ActOnTag). The #pragma pack stack is
16116     // maintained as a result of parser callbacks which can occur at
16117     // many points during the parsing of a struct declaration (because
16118     // the #pragma tokens are effectively skipped over during the
16119     // parsing of the struct).
16120     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16121       AddAlignmentAttributesForRecord(RD);
16122       AddMsStructLayoutForRecord(RD);
16123     }
16124   }
16125 
16126   if (ModulePrivateLoc.isValid()) {
16127     if (isMemberSpecialization)
16128       Diag(New->getLocation(), diag::err_module_private_specialization)
16129         << 2
16130         << FixItHint::CreateRemoval(ModulePrivateLoc);
16131     // __module_private__ does not apply to local classes. However, we only
16132     // diagnose this as an error when the declaration specifiers are
16133     // freestanding. Here, we just ignore the __module_private__.
16134     else if (!SearchDC->isFunctionOrMethod())
16135       New->setModulePrivate();
16136   }
16137 
16138   // If this is a specialization of a member class (of a class template),
16139   // check the specialization.
16140   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16141     Invalid = true;
16142 
16143   // If we're declaring or defining a tag in function prototype scope in C,
16144   // note that this type can only be used within the function and add it to
16145   // the list of decls to inject into the function definition scope.
16146   if ((Name || Kind == TTK_Enum) &&
16147       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16148     if (getLangOpts().CPlusPlus) {
16149       // C++ [dcl.fct]p6:
16150       //   Types shall not be defined in return or parameter types.
16151       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16152         Diag(Loc, diag::err_type_defined_in_param_type)
16153             << Name;
16154         Invalid = true;
16155       }
16156     } else if (!PrevDecl) {
16157       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16158     }
16159   }
16160 
16161   if (Invalid)
16162     New->setInvalidDecl();
16163 
16164   // Set the lexical context. If the tag has a C++ scope specifier, the
16165   // lexical context will be different from the semantic context.
16166   New->setLexicalDeclContext(CurContext);
16167 
16168   // Mark this as a friend decl if applicable.
16169   // In Microsoft mode, a friend declaration also acts as a forward
16170   // declaration so we always pass true to setObjectOfFriendDecl to make
16171   // the tag name visible.
16172   if (TUK == TUK_Friend)
16173     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16174 
16175   // Set the access specifier.
16176   if (!Invalid && SearchDC->isRecord())
16177     SetMemberAccessSpecifier(New, PrevDecl, AS);
16178 
16179   if (PrevDecl)
16180     CheckRedeclarationModuleOwnership(New, PrevDecl);
16181 
16182   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16183     New->startDefinition();
16184 
16185   ProcessDeclAttributeList(S, New, Attrs);
16186   AddPragmaAttributes(S, New);
16187 
16188   // If this has an identifier, add it to the scope stack.
16189   if (TUK == TUK_Friend) {
16190     // We might be replacing an existing declaration in the lookup tables;
16191     // if so, borrow its access specifier.
16192     if (PrevDecl)
16193       New->setAccess(PrevDecl->getAccess());
16194 
16195     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16196     DC->makeDeclVisibleInContext(New);
16197     if (Name) // can be null along some error paths
16198       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16199         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16200   } else if (Name) {
16201     S = getNonFieldDeclScope(S);
16202     PushOnScopeChains(New, S, true);
16203   } else {
16204     CurContext->addDecl(New);
16205   }
16206 
16207   // If this is the C FILE type, notify the AST context.
16208   if (IdentifierInfo *II = New->getIdentifier())
16209     if (!New->isInvalidDecl() &&
16210         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16211         II->isStr("FILE"))
16212       Context.setFILEDecl(New);
16213 
16214   if (PrevDecl)
16215     mergeDeclAttributes(New, PrevDecl);
16216 
16217   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16218     inferGslOwnerPointerAttribute(CXXRD);
16219 
16220   // If there's a #pragma GCC visibility in scope, set the visibility of this
16221   // record.
16222   AddPushedVisibilityAttribute(New);
16223 
16224   if (isMemberSpecialization && !New->isInvalidDecl())
16225     CompleteMemberSpecialization(New, Previous);
16226 
16227   OwnedDecl = true;
16228   // In C++, don't return an invalid declaration. We can't recover well from
16229   // the cases where we make the type anonymous.
16230   if (Invalid && getLangOpts().CPlusPlus) {
16231     if (New->isBeingDefined())
16232       if (auto RD = dyn_cast<RecordDecl>(New))
16233         RD->completeDefinition();
16234     return nullptr;
16235   } else if (SkipBody && SkipBody->ShouldSkip) {
16236     return SkipBody->Previous;
16237   } else {
16238     return New;
16239   }
16240 }
16241 
ActOnTagStartDefinition(Scope * S,Decl * TagD)16242 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16243   AdjustDeclIfTemplate(TagD);
16244   TagDecl *Tag = cast<TagDecl>(TagD);
16245 
16246   // Enter the tag context.
16247   PushDeclContext(S, Tag);
16248 
16249   ActOnDocumentableDecl(TagD);
16250 
16251   // If there's a #pragma GCC visibility in scope, set the visibility of this
16252   // record.
16253   AddPushedVisibilityAttribute(Tag);
16254 }
16255 
ActOnDuplicateDefinition(DeclSpec & DS,Decl * Prev,SkipBodyInfo & SkipBody)16256 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16257                                     SkipBodyInfo &SkipBody) {
16258   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16259     return false;
16260 
16261   // Make the previous decl visible.
16262   makeMergedDefinitionVisible(SkipBody.Previous);
16263   return true;
16264 }
16265 
ActOnObjCContainerStartDefinition(Decl * IDecl)16266 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16267   assert(isa<ObjCContainerDecl>(IDecl) &&
16268          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16269   DeclContext *OCD = cast<DeclContext>(IDecl);
16270   assert(OCD->getLexicalParent() == CurContext &&
16271       "The next DeclContext should be lexically contained in the current one.");
16272   CurContext = OCD;
16273   return IDecl;
16274 }
16275 
ActOnStartCXXMemberDeclarations(Scope * S,Decl * TagD,SourceLocation FinalLoc,bool IsFinalSpelledSealed,SourceLocation LBraceLoc)16276 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16277                                            SourceLocation FinalLoc,
16278                                            bool IsFinalSpelledSealed,
16279                                            SourceLocation LBraceLoc) {
16280   AdjustDeclIfTemplate(TagD);
16281   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16282 
16283   FieldCollector->StartClass();
16284 
16285   if (!Record->getIdentifier())
16286     return;
16287 
16288   if (FinalLoc.isValid())
16289     Record->addAttr(FinalAttr::Create(
16290         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16291         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16292 
16293   // C++ [class]p2:
16294   //   [...] The class-name is also inserted into the scope of the
16295   //   class itself; this is known as the injected-class-name. For
16296   //   purposes of access checking, the injected-class-name is treated
16297   //   as if it were a public member name.
16298   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16299       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16300       Record->getLocation(), Record->getIdentifier(),
16301       /*PrevDecl=*/nullptr,
16302       /*DelayTypeCreation=*/true);
16303   Context.getTypeDeclType(InjectedClassName, Record);
16304   InjectedClassName->setImplicit();
16305   InjectedClassName->setAccess(AS_public);
16306   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16307       InjectedClassName->setDescribedClassTemplate(Template);
16308   PushOnScopeChains(InjectedClassName, S);
16309   assert(InjectedClassName->isInjectedClassName() &&
16310          "Broken injected-class-name");
16311 }
16312 
ActOnTagFinishDefinition(Scope * S,Decl * TagD,SourceRange BraceRange)16313 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16314                                     SourceRange BraceRange) {
16315   AdjustDeclIfTemplate(TagD);
16316   TagDecl *Tag = cast<TagDecl>(TagD);
16317   Tag->setBraceRange(BraceRange);
16318 
16319   // Make sure we "complete" the definition even it is invalid.
16320   if (Tag->isBeingDefined()) {
16321     assert(Tag->isInvalidDecl() && "We should already have completed it");
16322     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16323       RD->completeDefinition();
16324   }
16325 
16326   if (isa<CXXRecordDecl>(Tag)) {
16327     FieldCollector->FinishClass();
16328   }
16329 
16330   // Exit this scope of this tag's definition.
16331   PopDeclContext();
16332 
16333   if (getCurLexicalContext()->isObjCContainer() &&
16334       Tag->getDeclContext()->isFileContext())
16335     Tag->setTopLevelDeclInObjCContainer();
16336 
16337   // Notify the consumer that we've defined a tag.
16338   if (!Tag->isInvalidDecl()) {
16339     Consumer.HandleTagDeclDefinition(Tag);
16340     // Don't try to compute excess padding (which can be expensive) if the diag
16341     // is ignored.
16342     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16343       if (!RD->isDependentContext() && !Diags.isIgnored(diag::warn_excess_padding, RD->getLocation())) {
16344         unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
16345         unsigned NumFields = 0;
16346         unsigned LastFieldEnd = 0;
16347         unsigned Padding = 0;
16348         const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
16349         unsigned BitEnd = 0;
16350         for (auto F : RD->fields()) {
16351           unsigned Offset = Layout.getFieldOffset(NumFields);
16352           NumFields++;
16353           // Count the bits in a bitfield.
16354           if (F->isBitField()) {
16355             BitEnd += F->getBitWidthValue(Context);
16356             continue;
16357           }
16358           // If the last field was a bitfield then round the width up to a char
16359           // and use that.
16360           if (BitEnd) {
16361             LastFieldEnd += (BitEnd + (CharBitNum - 1)) / CharBitNum;
16362             BitEnd = 0;
16363           }
16364           Padding += Offset - LastFieldEnd;
16365           LastFieldEnd = Offset + Context.getTypeSizeInChars(F->getType()).getQuantity();
16366         }
16367         unsigned Size = Layout.getSize().getQuantity();
16368         Padding += Size - LastFieldEnd;
16369         unsigned UnpaddedSize = Size - Padding;
16370 
16371         // Don't warn for empty structs even though they have 1 byte padding in
16372         // a 1 byte record
16373         if (NumFields > 0)
16374           if ((Padding > 8) || ((Padding * 3) > (UnpaddedSize * 4)))
16375             getDiagnostics().Report(RD->getLocation(),
16376                                     diag::warn_excess_padding)
16377                 << Context.getTypeDeclType(RD) << Padding << Size;
16378       }
16379   }
16380 }
16381 
ActOnObjCContainerFinishDefinition()16382 void Sema::ActOnObjCContainerFinishDefinition() {
16383   // Exit this scope of this interface definition.
16384   PopDeclContext();
16385 }
16386 
ActOnObjCTemporaryExitContainerContext(DeclContext * DC)16387 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16388   assert(DC == CurContext && "Mismatch of container contexts");
16389   OriginalLexicalContext = DC;
16390   ActOnObjCContainerFinishDefinition();
16391 }
16392 
ActOnObjCReenterContainerContext(DeclContext * DC)16393 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16394   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16395   OriginalLexicalContext = nullptr;
16396 }
16397 
ActOnTagDefinitionError(Scope * S,Decl * TagD)16398 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16399   AdjustDeclIfTemplate(TagD);
16400   TagDecl *Tag = cast<TagDecl>(TagD);
16401   Tag->setInvalidDecl();
16402 
16403   // Make sure we "complete" the definition even it is invalid.
16404   if (Tag->isBeingDefined()) {
16405     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16406       RD->completeDefinition();
16407   }
16408 
16409   // We're undoing ActOnTagStartDefinition here, not
16410   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16411   // the FieldCollector.
16412 
16413   PopDeclContext();
16414 }
16415 
16416 // Note that FieldName may be null for anonymous bitfields.
VerifyBitField(SourceLocation FieldLoc,IdentifierInfo * FieldName,QualType FieldTy,bool IsMsStruct,Expr * BitWidth,bool * ZeroWidth)16417 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16418                                 IdentifierInfo *FieldName,
16419                                 QualType FieldTy, bool IsMsStruct,
16420                                 Expr *BitWidth, bool *ZeroWidth) {
16421   assert(BitWidth);
16422   if (BitWidth->containsErrors())
16423     return ExprError();
16424 
16425   // Default to true; that shouldn't confuse checks for emptiness
16426   if (ZeroWidth)
16427     *ZeroWidth = true;
16428 
16429   // C99 6.7.2.1p4 - verify the field type.
16430   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16431   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16432     // Handle incomplete and sizeless types with a specific error.
16433     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16434                                  diag::err_field_incomplete_or_sizeless))
16435       return ExprError();
16436     if (FieldName)
16437       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16438         << FieldName << FieldTy << BitWidth->getSourceRange();
16439     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16440       << FieldTy << BitWidth->getSourceRange();
16441   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16442                                              UPPC_BitFieldWidth))
16443     return ExprError();
16444 
16445   // If the bit-width is type- or value-dependent, don't try to check
16446   // it now.
16447   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16448     return BitWidth;
16449 
16450   llvm::APSInt Value;
16451   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
16452   if (ICE.isInvalid())
16453     return ICE;
16454   BitWidth = ICE.get();
16455 
16456   if (Value != 0 && ZeroWidth)
16457     *ZeroWidth = false;
16458 
16459   // Zero-width bitfield is ok for anonymous field.
16460   if (Value == 0 && FieldName)
16461     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16462 
16463   if (Value.isSigned() && Value.isNegative()) {
16464     if (FieldName)
16465       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16466                << FieldName << Value.toString(10);
16467     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16468       << Value.toString(10);
16469   }
16470 
16471   if (!FieldTy->isDependentType()) {
16472     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16473     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16474     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16475 
16476     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16477     // ABI.
16478     bool CStdConstraintViolation =
16479         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16480     bool MSBitfieldViolation =
16481         Value.ugt(TypeStorageSize) &&
16482         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16483     if (CStdConstraintViolation || MSBitfieldViolation) {
16484       unsigned DiagWidth =
16485           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16486       if (FieldName)
16487         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16488                << FieldName << (unsigned)Value.getZExtValue()
16489                << !CStdConstraintViolation << DiagWidth;
16490 
16491       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16492              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
16493              << DiagWidth;
16494     }
16495 
16496     // Warn on types where the user might conceivably expect to get all
16497     // specified bits as value bits: that's all integral types other than
16498     // 'bool'.
16499     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
16500       if (FieldName)
16501         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16502             << FieldName << (unsigned)Value.getZExtValue()
16503             << (unsigned)TypeWidth;
16504       else
16505         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16506             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16507     }
16508   }
16509 
16510   return BitWidth;
16511 }
16512 
16513 /// ActOnField - Each field of a C struct/union is passed into this in order
16514 /// to create a FieldDecl object for it.
ActOnField(Scope * S,Decl * TagD,SourceLocation DeclStart,Declarator & D,Expr * BitfieldWidth)16515 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16516                        Declarator &D, Expr *BitfieldWidth) {
16517   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16518                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16519                                /*InitStyle=*/ICIS_NoInit, AS_public);
16520   return Res;
16521 }
16522 
16523 /// HandleField - Analyze a field of a C struct or a C++ data member.
16524 ///
HandleField(Scope * S,RecordDecl * Record,SourceLocation DeclStart,Declarator & D,Expr * BitWidth,InClassInitStyle InitStyle,AccessSpecifier AS)16525 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16526                              SourceLocation DeclStart,
16527                              Declarator &D, Expr *BitWidth,
16528                              InClassInitStyle InitStyle,
16529                              AccessSpecifier AS) {
16530   if (D.isDecompositionDeclarator()) {
16531     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16532     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16533       << Decomp.getSourceRange();
16534     return nullptr;
16535   }
16536 
16537   IdentifierInfo *II = D.getIdentifier();
16538   SourceLocation Loc = DeclStart;
16539   if (II) Loc = D.getIdentifierLoc();
16540 
16541   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16542   QualType T = TInfo->getType();
16543   if (getLangOpts().CPlusPlus) {
16544     CheckExtraCXXDefaultArguments(D);
16545 
16546     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16547                                         UPPC_DataMemberType)) {
16548       D.setInvalidType();
16549       T = Context.IntTy;
16550       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16551     }
16552   }
16553 
16554   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16555 
16556   if (D.getDeclSpec().isInlineSpecified())
16557     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16558         << getLangOpts().CPlusPlus17;
16559   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16560     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16561          diag::err_invalid_thread)
16562       << DeclSpec::getSpecifierName(TSCS);
16563 
16564   // Check to see if this name was declared as a member previously
16565   NamedDecl *PrevDecl = nullptr;
16566   LookupResult Previous(*this, II, Loc, LookupMemberName,
16567                         ForVisibleRedeclaration);
16568   LookupName(Previous, S);
16569   switch (Previous.getResultKind()) {
16570     case LookupResult::Found:
16571     case LookupResult::FoundUnresolvedValue:
16572       PrevDecl = Previous.getAsSingle<NamedDecl>();
16573       break;
16574 
16575     case LookupResult::FoundOverloaded:
16576       PrevDecl = Previous.getRepresentativeDecl();
16577       break;
16578 
16579     case LookupResult::NotFound:
16580     case LookupResult::NotFoundInCurrentInstantiation:
16581     case LookupResult::Ambiguous:
16582       break;
16583   }
16584   Previous.suppressDiagnostics();
16585 
16586   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16587     // Maybe we will complain about the shadowed template parameter.
16588     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16589     // Just pretend that we didn't see the previous declaration.
16590     PrevDecl = nullptr;
16591   }
16592 
16593   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16594     PrevDecl = nullptr;
16595 
16596   bool Mutable
16597     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16598   SourceLocation TSSL = D.getBeginLoc();
16599   FieldDecl *NewFD
16600     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16601                      TSSL, AS, PrevDecl, &D);
16602 
16603   if (NewFD->isInvalidDecl())
16604     Record->setInvalidDecl();
16605 
16606   if (D.getDeclSpec().isModulePrivateSpecified())
16607     NewFD->setModulePrivate();
16608 
16609   if (NewFD->isInvalidDecl() && PrevDecl) {
16610     // Don't introduce NewFD into scope; there's already something
16611     // with the same name in the same scope.
16612   } else if (II) {
16613     PushOnScopeChains(NewFD, S);
16614   } else
16615     Record->addDecl(NewFD);
16616 
16617   return NewFD;
16618 }
16619 
16620 /// Build a new FieldDecl and check its well-formedness.
16621 ///
16622 /// This routine builds a new FieldDecl given the fields name, type,
16623 /// record, etc. \p PrevDecl should refer to any previous declaration
16624 /// with the same name and in the same scope as the field to be
16625 /// created.
16626 ///
16627 /// \returns a new FieldDecl.
16628 ///
16629 /// \todo The Declarator argument is a hack. It will be removed once
CheckFieldDecl(DeclarationName Name,QualType T,TypeSourceInfo * TInfo,RecordDecl * Record,SourceLocation Loc,bool Mutable,Expr * BitWidth,InClassInitStyle InitStyle,SourceLocation TSSL,AccessSpecifier AS,NamedDecl * PrevDecl,Declarator * D)16630 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16631                                 TypeSourceInfo *TInfo,
16632                                 RecordDecl *Record, SourceLocation Loc,
16633                                 bool Mutable, Expr *BitWidth,
16634                                 InClassInitStyle InitStyle,
16635                                 SourceLocation TSSL,
16636                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16637                                 Declarator *D) {
16638   IdentifierInfo *II = Name.getAsIdentifierInfo();
16639   bool InvalidDecl = false;
16640   if (D) InvalidDecl = D->isInvalidType();
16641 
16642   // If we receive a broken type, recover by assuming 'int' and
16643   // marking this declaration as invalid.
16644   if (T.isNull() || T->containsErrors()) {
16645     InvalidDecl = true;
16646     T = Context.IntTy;
16647   }
16648 
16649   QualType EltTy = Context.getBaseElementType(T);
16650   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16651     if (RequireCompleteSizedType(Loc, EltTy,
16652                                  diag::err_field_incomplete_or_sizeless)) {
16653       // Fields of incomplete type force their record to be invalid.
16654       Record->setInvalidDecl();
16655       InvalidDecl = true;
16656     } else {
16657       NamedDecl *Def;
16658       EltTy->isIncompleteType(&Def);
16659       if (Def && Def->isInvalidDecl()) {
16660         Record->setInvalidDecl();
16661         InvalidDecl = true;
16662       }
16663     }
16664   }
16665 
16666   // TR 18037 does not allow fields to be declared with address space
16667   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16668       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16669     Diag(Loc, diag::err_field_with_address_space);
16670     Record->setInvalidDecl();
16671     InvalidDecl = true;
16672   }
16673 
16674   if (LangOpts.OpenCL) {
16675     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16676     // used as structure or union field: image, sampler, event or block types.
16677     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16678         T->isBlockPointerType()) {
16679       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16680       Record->setInvalidDecl();
16681       InvalidDecl = true;
16682     }
16683     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16684     if (BitWidth) {
16685       Diag(Loc, diag::err_opencl_bitfields);
16686       InvalidDecl = true;
16687     }
16688   }
16689 
16690   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16691   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16692       T.hasQualifiers()) {
16693     InvalidDecl = true;
16694     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16695   }
16696 
16697   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16698   // than a variably modified type.
16699   if (!InvalidDecl && T->isVariablyModifiedType()) {
16700     bool SizeIsNegative;
16701     llvm::APSInt Oversized;
16702 
16703     TypeSourceInfo *FixedTInfo =
16704       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16705                                                     SizeIsNegative,
16706                                                     Oversized);
16707     if (FixedTInfo) {
16708       Diag(Loc, diag::warn_illegal_constant_array_size);
16709       TInfo = FixedTInfo;
16710       T = FixedTInfo->getType();
16711     } else {
16712       if (SizeIsNegative)
16713         Diag(Loc, diag::err_typecheck_negative_array_size);
16714       else if (Oversized.getBoolValue())
16715         Diag(Loc, diag::err_array_too_large)
16716           << Oversized.toString(10);
16717       else
16718         Diag(Loc, diag::err_typecheck_field_variable_size);
16719       InvalidDecl = true;
16720     }
16721   }
16722 
16723   // Fields can not have abstract class types
16724   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16725                                              diag::err_abstract_type_in_decl,
16726                                              AbstractFieldType))
16727     InvalidDecl = true;
16728 
16729   bool ZeroWidth = false;
16730   if (InvalidDecl)
16731     BitWidth = nullptr;
16732   // If this is declared as a bit-field, check the bit-field.
16733   if (BitWidth) {
16734     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16735                               &ZeroWidth).get();
16736     if (!BitWidth) {
16737       InvalidDecl = true;
16738       BitWidth = nullptr;
16739       ZeroWidth = false;
16740     }
16741 
16742     // Only data members can have in-class initializers.
16743     if (BitWidth && !II && InitStyle) {
16744       Diag(Loc, diag::err_anon_bitfield_init);
16745       InvalidDecl = true;
16746       BitWidth = nullptr;
16747       ZeroWidth = false;
16748     }
16749   }
16750 
16751   // Check that 'mutable' is consistent with the type of the declaration.
16752   if (!InvalidDecl && Mutable) {
16753     unsigned DiagID = 0;
16754     if (T->isReferenceType())
16755       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16756                                         : diag::err_mutable_reference;
16757     else if (T.isConstQualified())
16758       DiagID = diag::err_mutable_const;
16759 
16760     if (DiagID) {
16761       SourceLocation ErrLoc = Loc;
16762       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16763         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16764       Diag(ErrLoc, DiagID);
16765       if (DiagID != diag::ext_mutable_reference) {
16766         Mutable = false;
16767         InvalidDecl = true;
16768       }
16769     }
16770   }
16771 
16772   // C++11 [class.union]p8 (DR1460):
16773   //   At most one variant member of a union may have a
16774   //   brace-or-equal-initializer.
16775   if (InitStyle != ICIS_NoInit)
16776     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16777 
16778   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16779                                        BitWidth, Mutable, InitStyle);
16780   if (InvalidDecl)
16781     NewFD->setInvalidDecl();
16782 
16783   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16784     Diag(Loc, diag::err_duplicate_member) << II;
16785     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16786     NewFD->setInvalidDecl();
16787   }
16788 
16789   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16790     if (Record->isUnion()) {
16791       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16792         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16793         if (RDecl->getDefinition()) {
16794           // C++ [class.union]p1: An object of a class with a non-trivial
16795           // constructor, a non-trivial copy constructor, a non-trivial
16796           // destructor, or a non-trivial copy assignment operator
16797           // cannot be a member of a union, nor can an array of such
16798           // objects.
16799           if (CheckNontrivialField(NewFD))
16800             NewFD->setInvalidDecl();
16801         }
16802       }
16803 
16804       // C++ [class.union]p1: If a union contains a member of reference type,
16805       // the program is ill-formed, except when compiling with MSVC extensions
16806       // enabled.
16807       if (EltTy->isReferenceType()) {
16808         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16809                                     diag::ext_union_member_of_reference_type :
16810                                     diag::err_union_member_of_reference_type)
16811           << NewFD->getDeclName() << EltTy;
16812         if (!getLangOpts().MicrosoftExt)
16813           NewFD->setInvalidDecl();
16814       }
16815     }
16816   }
16817 
16818   // FIXME: We need to pass in the attributes given an AST
16819   // representation, not a parser representation.
16820   if (D) {
16821     // FIXME: The current scope is almost... but not entirely... correct here.
16822     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16823 
16824     if (NewFD->hasAttrs())
16825       CheckAlignasUnderalignment(NewFD);
16826   }
16827 
16828   // In auto-retain/release, infer strong retension for fields of
16829   // retainable type.
16830   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16831     NewFD->setInvalidDecl();
16832 
16833   if (T.isObjCGCWeak())
16834     Diag(Loc, diag::warn_attribute_weak_on_field);
16835 
16836   NewFD->setAccess(AS);
16837   return NewFD;
16838 }
16839 
CheckNontrivialField(FieldDecl * FD)16840 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16841   assert(FD);
16842   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16843 
16844   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16845     return false;
16846 
16847   QualType EltTy = Context.getBaseElementType(FD->getType());
16848   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16849     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16850     if (RDecl->getDefinition()) {
16851       // We check for copy constructors before constructors
16852       // because otherwise we'll never get complaints about
16853       // copy constructors.
16854 
16855       CXXSpecialMember member = CXXInvalid;
16856       // We're required to check for any non-trivial constructors. Since the
16857       // implicit default constructor is suppressed if there are any
16858       // user-declared constructors, we just need to check that there is a
16859       // trivial default constructor and a trivial copy constructor. (We don't
16860       // worry about move constructors here, since this is a C++98 check.)
16861       if (RDecl->hasNonTrivialCopyConstructor())
16862         member = CXXCopyConstructor;
16863       else if (!RDecl->hasTrivialDefaultConstructor())
16864         member = CXXDefaultConstructor;
16865       else if (RDecl->hasNonTrivialCopyAssignment())
16866         member = CXXCopyAssignment;
16867       else if (RDecl->hasNonTrivialDestructor())
16868         member = CXXDestructor;
16869 
16870       if (member != CXXInvalid) {
16871         if (!getLangOpts().CPlusPlus11 &&
16872             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16873           // Objective-C++ ARC: it is an error to have a non-trivial field of
16874           // a union. However, system headers in Objective-C programs
16875           // occasionally have Objective-C lifetime objects within unions,
16876           // and rather than cause the program to fail, we make those
16877           // members unavailable.
16878           SourceLocation Loc = FD->getLocation();
16879           if (getSourceManager().isInSystemHeader(Loc)) {
16880             if (!FD->hasAttr<UnavailableAttr>())
16881               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16882                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16883             return false;
16884           }
16885         }
16886 
16887         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16888                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16889                diag::err_illegal_union_or_anon_struct_member)
16890           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16891         DiagnoseNontrivial(RDecl, member);
16892         return !getLangOpts().CPlusPlus11;
16893       }
16894     }
16895   }
16896 
16897   return false;
16898 }
16899 
16900 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16901 ///  AST enum value.
16902 static ObjCIvarDecl::AccessControl
TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility)16903 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16904   switch (ivarVisibility) {
16905   default: llvm_unreachable("Unknown visitibility kind");
16906   case tok::objc_private: return ObjCIvarDecl::Private;
16907   case tok::objc_public: return ObjCIvarDecl::Public;
16908   case tok::objc_protected: return ObjCIvarDecl::Protected;
16909   case tok::objc_package: return ObjCIvarDecl::Package;
16910   }
16911 }
16912 
16913 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16914 /// in order to create an IvarDecl object for it.
ActOnIvar(Scope * S,SourceLocation DeclStart,Declarator & D,Expr * BitfieldWidth,tok::ObjCKeywordKind Visibility)16915 Decl *Sema::ActOnIvar(Scope *S,
16916                                 SourceLocation DeclStart,
16917                                 Declarator &D, Expr *BitfieldWidth,
16918                                 tok::ObjCKeywordKind Visibility) {
16919 
16920   IdentifierInfo *II = D.getIdentifier();
16921   Expr *BitWidth = (Expr*)BitfieldWidth;
16922   SourceLocation Loc = DeclStart;
16923   if (II) Loc = D.getIdentifierLoc();
16924 
16925   // FIXME: Unnamed fields can be handled in various different ways, for
16926   // example, unnamed unions inject all members into the struct namespace!
16927 
16928   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16929   QualType T = TInfo->getType();
16930 
16931   if (BitWidth) {
16932     // 6.7.2.1p3, 6.7.2.1p4
16933     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16934     if (!BitWidth)
16935       D.setInvalidType();
16936   } else {
16937     // Not a bitfield.
16938 
16939     // validate II.
16940 
16941   }
16942   if (T->isReferenceType()) {
16943     Diag(Loc, diag::err_ivar_reference_type);
16944     D.setInvalidType();
16945   }
16946   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16947   // than a variably modified type.
16948   else if (T->isVariablyModifiedType()) {
16949     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16950     D.setInvalidType();
16951   }
16952 
16953   // Get the visibility (access control) for this ivar.
16954   ObjCIvarDecl::AccessControl ac =
16955     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16956                                         : ObjCIvarDecl::None;
16957   // Must set ivar's DeclContext to its enclosing interface.
16958   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16959   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16960     return nullptr;
16961   ObjCContainerDecl *EnclosingContext;
16962   if (ObjCImplementationDecl *IMPDecl =
16963       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16964     if (LangOpts.ObjCRuntime.isFragile()) {
16965     // Case of ivar declared in an implementation. Context is that of its class.
16966       EnclosingContext = IMPDecl->getClassInterface();
16967       assert(EnclosingContext && "Implementation has no class interface!");
16968     }
16969     else
16970       EnclosingContext = EnclosingDecl;
16971   } else {
16972     if (ObjCCategoryDecl *CDecl =
16973         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16974       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16975         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16976         return nullptr;
16977       }
16978     }
16979     EnclosingContext = EnclosingDecl;
16980   }
16981 
16982   // Construct the decl.
16983   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16984                                              DeclStart, Loc, II, T,
16985                                              TInfo, ac, (Expr *)BitfieldWidth);
16986 
16987   if (II) {
16988     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16989                                            ForVisibleRedeclaration);
16990     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16991         && !isa<TagDecl>(PrevDecl)) {
16992       Diag(Loc, diag::err_duplicate_member) << II;
16993       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16994       NewID->setInvalidDecl();
16995     }
16996   }
16997 
16998   // Process attributes attached to the ivar.
16999   ProcessDeclAttributes(S, NewID, D);
17000 
17001   if (D.isInvalidType())
17002     NewID->setInvalidDecl();
17003 
17004   // In ARC, infer 'retaining' for ivars of retainable type.
17005   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17006     NewID->setInvalidDecl();
17007 
17008   if (D.getDeclSpec().isModulePrivateSpecified())
17009     NewID->setModulePrivate();
17010 
17011   if (II) {
17012     // FIXME: When interfaces are DeclContexts, we'll need to add
17013     // these to the interface.
17014     S->AddDecl(NewID);
17015     IdResolver.AddDecl(NewID);
17016   }
17017 
17018   if (LangOpts.ObjCRuntime.isNonFragile() &&
17019       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17020     Diag(Loc, diag::warn_ivars_in_interface);
17021 
17022   return NewID;
17023 }
17024 
17025 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17026 /// class and class extensions. For every class \@interface and class
17027 /// extension \@interface, if the last ivar is a bitfield of any type,
17028 /// then add an implicit `char :0` ivar to the end of that interface.
ActOnLastBitfield(SourceLocation DeclLoc,SmallVectorImpl<Decl * > & AllIvarDecls)17029 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17030                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17031   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17032     return;
17033 
17034   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17035   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17036 
17037   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17038     return;
17039   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17040   if (!ID) {
17041     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17042       if (!CD->IsClassExtension())
17043         return;
17044     }
17045     // No need to add this to end of @implementation.
17046     else
17047       return;
17048   }
17049   // All conditions are met. Add a new bitfield to the tail end of ivars.
17050   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17051   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17052 
17053   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17054                               DeclLoc, DeclLoc, nullptr,
17055                               Context.CharTy,
17056                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17057                                                                DeclLoc),
17058                               ObjCIvarDecl::Private, BW,
17059                               true);
17060   AllIvarDecls.push_back(Ivar);
17061 }
17062 
ActOnFields(Scope * S,SourceLocation RecLoc,Decl * EnclosingDecl,ArrayRef<Decl * > Fields,SourceLocation LBrac,SourceLocation RBrac,const ParsedAttributesView & Attrs)17063 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17064                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17065                        SourceLocation RBrac,
17066                        const ParsedAttributesView &Attrs) {
17067   assert(EnclosingDecl && "missing record or interface decl");
17068 
17069   // If this is an Objective-C @implementation or category and we have
17070   // new fields here we should reset the layout of the interface since
17071   // it will now change.
17072   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17073     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17074     switch (DC->getKind()) {
17075     default: break;
17076     case Decl::ObjCCategory:
17077       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17078       break;
17079     case Decl::ObjCImplementation:
17080       Context.
17081         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17082       break;
17083     }
17084   }
17085 
17086   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17087   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17088 
17089   // Start counting up the number of named members; make sure to include
17090   // members of anonymous structs and unions in the total.
17091   unsigned NumNamedMembers = 0;
17092   if (Record) {
17093     for (const auto *I : Record->decls()) {
17094       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17095         if (IFD->getDeclName())
17096           ++NumNamedMembers;
17097     }
17098   }
17099 
17100   // Verify that all the fields are okay.
17101   SmallVector<FieldDecl*, 32> RecFields;
17102 
17103   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17104        i != end; ++i) {
17105     FieldDecl *FD = cast<FieldDecl>(*i);
17106 
17107     // Get the type for the field.
17108     const Type *FDTy = FD->getType().getTypePtr();
17109 
17110     if (!FD->isAnonymousStructOrUnion()) {
17111       // Remember all fields written by the user.
17112       RecFields.push_back(FD);
17113     }
17114 
17115     // If the field is already invalid for some reason, don't emit more
17116     // diagnostics about it.
17117     if (FD->isInvalidDecl()) {
17118       EnclosingDecl->setInvalidDecl();
17119       continue;
17120     }
17121 
17122     // C99 6.7.2.1p2:
17123     //   A structure or union shall not contain a member with
17124     //   incomplete or function type (hence, a structure shall not
17125     //   contain an instance of itself, but may contain a pointer to
17126     //   an instance of itself), except that the last member of a
17127     //   structure with more than one named member may have incomplete
17128     //   array type; such a structure (and any union containing,
17129     //   possibly recursively, a member that is such a structure)
17130     //   shall not be a member of a structure or an element of an
17131     //   array.
17132     bool IsLastField = (i + 1 == Fields.end());
17133     if (FDTy->isFunctionType()) {
17134       // Field declared as a function.
17135       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17136         << FD->getDeclName();
17137       FD->setInvalidDecl();
17138       EnclosingDecl->setInvalidDecl();
17139       continue;
17140     } else if (FDTy->isIncompleteArrayType() &&
17141                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17142       if (Record) {
17143         // Flexible array member.
17144         // Microsoft and g++ is more permissive regarding flexible array.
17145         // It will accept flexible array in union and also
17146         // as the sole element of a struct/class.
17147         unsigned DiagID = 0;
17148         if (!Record->isUnion() && !IsLastField) {
17149           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17150             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17151           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17152           FD->setInvalidDecl();
17153           EnclosingDecl->setInvalidDecl();
17154           continue;
17155         } else if (Record->isUnion())
17156           DiagID = getLangOpts().MicrosoftExt
17157                        ? diag::ext_flexible_array_union_ms
17158                        : getLangOpts().CPlusPlus
17159                              ? diag::ext_flexible_array_union_gnu
17160                              : diag::err_flexible_array_union;
17161         else if (NumNamedMembers < 1)
17162           DiagID = getLangOpts().MicrosoftExt
17163                        ? diag::ext_flexible_array_empty_aggregate_ms
17164                        : getLangOpts().CPlusPlus
17165                              ? diag::ext_flexible_array_empty_aggregate_gnu
17166                              : diag::err_flexible_array_empty_aggregate;
17167 
17168         if (DiagID)
17169           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17170                                           << Record->getTagKind();
17171         // While the layout of types that contain virtual bases is not specified
17172         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17173         // virtual bases after the derived members.  This would make a flexible
17174         // array member declared at the end of an object not adjacent to the end
17175         // of the type.
17176         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17177           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17178               << FD->getDeclName() << Record->getTagKind();
17179         if (!getLangOpts().C99)
17180           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17181             << FD->getDeclName() << Record->getTagKind();
17182 
17183         // If the element type has a non-trivial destructor, we would not
17184         // implicitly destroy the elements, so disallow it for now.
17185         //
17186         // FIXME: GCC allows this. We should probably either implicitly delete
17187         // the destructor of the containing class, or just allow this.
17188         QualType BaseElem = Context.getBaseElementType(FD->getType());
17189         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17190           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17191             << FD->getDeclName() << FD->getType();
17192           FD->setInvalidDecl();
17193           EnclosingDecl->setInvalidDecl();
17194           continue;
17195         }
17196         // Okay, we have a legal flexible array member at the end of the struct.
17197         Record->setHasFlexibleArrayMember(true);
17198       } else {
17199         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17200         // unless they are followed by another ivar. That check is done
17201         // elsewhere, after synthesized ivars are known.
17202       }
17203     } else if (!FDTy->isDependentType() &&
17204                RequireCompleteSizedType(
17205                    FD->getLocation(), FD->getType(),
17206                    diag::err_field_incomplete_or_sizeless)) {
17207       // Incomplete type
17208       FD->setInvalidDecl();
17209       EnclosingDecl->setInvalidDecl();
17210       continue;
17211     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17212       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17213         // A type which contains a flexible array member is considered to be a
17214         // flexible array member.
17215         Record->setHasFlexibleArrayMember(true);
17216         if (!Record->isUnion()) {
17217           // If this is a struct/class and this is not the last element, reject
17218           // it.  Note that GCC supports variable sized arrays in the middle of
17219           // structures.
17220           if (!IsLastField)
17221             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17222               << FD->getDeclName() << FD->getType();
17223           else {
17224             // We support flexible arrays at the end of structs in
17225             // other structs as an extension.
17226             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17227               << FD->getDeclName();
17228           }
17229         }
17230       }
17231       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17232           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17233                                  diag::err_abstract_type_in_decl,
17234                                  AbstractIvarType)) {
17235         // Ivars can not have abstract class types
17236         FD->setInvalidDecl();
17237       }
17238       if (Record && FDTTy->getDecl()->hasObjectMember())
17239         Record->setHasObjectMember(true);
17240       if (Record && FDTTy->getDecl()->hasVolatileMember())
17241         Record->setHasVolatileMember(true);
17242     } else if (FDTy->isObjCObjectType()) {
17243       /// A field cannot be an Objective-c object
17244       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17245         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17246       QualType T = Context.getObjCObjectPointerType(FD->getType());
17247       FD->setType(T);
17248     } else if (Record && Record->isUnion() &&
17249                FD->getType().hasNonTrivialObjCLifetime() &&
17250                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17251                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17252                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17253                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17254       // For backward compatibility, fields of C unions declared in system
17255       // headers that have non-trivial ObjC ownership qualifications are marked
17256       // as unavailable unless the qualifier is explicit and __strong. This can
17257       // break ABI compatibility between programs compiled with ARC and MRR, but
17258       // is a better option than rejecting programs using those unions under
17259       // ARC.
17260       FD->addAttr(UnavailableAttr::CreateImplicit(
17261           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17262           FD->getLocation()));
17263     } else if (getLangOpts().ObjC &&
17264                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17265                !Record->hasObjectMember()) {
17266       if (FD->getType()->isObjCObjectPointerType() ||
17267           FD->getType().isObjCGCStrong())
17268         Record->setHasObjectMember(true);
17269       else if (Context.getAsArrayType(FD->getType())) {
17270         QualType BaseType = Context.getBaseElementType(FD->getType());
17271         if (BaseType->isRecordType() &&
17272             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17273           Record->setHasObjectMember(true);
17274         else if (BaseType->isObjCObjectPointerType() ||
17275                  BaseType.isObjCGCStrong())
17276                Record->setHasObjectMember(true);
17277       }
17278     }
17279 
17280     if (Record && !getLangOpts().CPlusPlus &&
17281         !shouldIgnoreForRecordTriviality(FD)) {
17282       QualType FT = FD->getType();
17283       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17284         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17285         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17286             Record->isUnion())
17287           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17288       }
17289       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17290       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17291         Record->setNonTrivialToPrimitiveCopy(true);
17292         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17293           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17294       }
17295       if (FT.isDestructedType()) {
17296         Record->setNonTrivialToPrimitiveDestroy(true);
17297         Record->setParamDestroyedInCallee(true);
17298         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17299           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17300       }
17301 
17302       if (const auto *RT = FT->getAs<RecordType>()) {
17303         if (RT->getDecl()->getArgPassingRestrictions() ==
17304             RecordDecl::APK_CanNeverPassInRegs)
17305           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17306       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17307         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17308     }
17309 
17310     if (Record && FD->getType().isVolatileQualified())
17311       Record->setHasVolatileMember(true);
17312     // Keep track of the number of named members.
17313     if (FD->getIdentifier())
17314       ++NumNamedMembers;
17315   }
17316 
17317   // Okay, we successfully defined 'Record'.
17318   if (Record) {
17319     bool Completed = false;
17320     if (CXXRecord) {
17321       if (!CXXRecord->isInvalidDecl()) {
17322         // Set access bits correctly on the directly-declared conversions.
17323         for (CXXRecordDecl::conversion_iterator
17324                I = CXXRecord->conversion_begin(),
17325                E = CXXRecord->conversion_end(); I != E; ++I)
17326           I.setAccess((*I)->getAccess());
17327       }
17328 
17329       // Add any implicitly-declared members to this class.
17330       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17331 
17332       if (!CXXRecord->isDependentType()) {
17333         if (!CXXRecord->isInvalidDecl()) {
17334           // If we have virtual base classes, we may end up finding multiple
17335           // final overriders for a given virtual function. Check for this
17336           // problem now.
17337           if (CXXRecord->getNumVBases()) {
17338             CXXFinalOverriderMap FinalOverriders;
17339             CXXRecord->getFinalOverriders(FinalOverriders);
17340 
17341             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17342                                              MEnd = FinalOverriders.end();
17343                  M != MEnd; ++M) {
17344               for (OverridingMethods::iterator SO = M->second.begin(),
17345                                             SOEnd = M->second.end();
17346                    SO != SOEnd; ++SO) {
17347                 assert(SO->second.size() > 0 &&
17348                        "Virtual function without overriding functions?");
17349                 if (SO->second.size() == 1)
17350                   continue;
17351 
17352                 // C++ [class.virtual]p2:
17353                 //   In a derived class, if a virtual member function of a base
17354                 //   class subobject has more than one final overrider the
17355                 //   program is ill-formed.
17356                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17357                   << (const NamedDecl *)M->first << Record;
17358                 Diag(M->first->getLocation(),
17359                      diag::note_overridden_virtual_function);
17360                 for (OverridingMethods::overriding_iterator
17361                           OM = SO->second.begin(),
17362                        OMEnd = SO->second.end();
17363                      OM != OMEnd; ++OM)
17364                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17365                     << (const NamedDecl *)M->first << OM->Method->getParent();
17366 
17367                 Record->setInvalidDecl();
17368               }
17369             }
17370             CXXRecord->completeDefinition(&FinalOverriders);
17371             Completed = true;
17372           }
17373         }
17374       }
17375     }
17376 
17377     if (!Completed)
17378       Record->completeDefinition();
17379 
17380     // Handle attributes before checking the layout.
17381     ProcessDeclAttributeList(S, Record, Attrs);
17382 
17383     // We may have deferred checking for a deleted destructor. Check now.
17384     if (CXXRecord) {
17385       auto *Dtor = CXXRecord->getDestructor();
17386       if (Dtor && Dtor->isImplicit() &&
17387           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17388         CXXRecord->setImplicitDestructorIsDeleted();
17389         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17390       }
17391     }
17392 
17393     if (Record->hasAttrs()) {
17394       CheckAlignasUnderalignment(Record);
17395 
17396       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17397         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17398                                            IA->getRange(), IA->getBestCase(),
17399                                            IA->getInheritanceModel());
17400     }
17401 
17402     // Check if the structure/union declaration is a type that can have zero
17403     // size in C. For C this is a language extension, for C++ it may cause
17404     // compatibility problems.
17405     bool CheckForZeroSize;
17406     if (!getLangOpts().CPlusPlus) {
17407       CheckForZeroSize = true;
17408     } else {
17409       // For C++ filter out types that cannot be referenced in C code.
17410       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17411       CheckForZeroSize =
17412           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17413           !CXXRecord->isDependentType() &&
17414           CXXRecord->isCLike();
17415     }
17416     if (CheckForZeroSize) {
17417       bool ZeroSize = true;
17418       bool IsEmpty = true;
17419       unsigned NonBitFields = 0;
17420       for (RecordDecl::field_iterator I = Record->field_begin(),
17421                                       E = Record->field_end();
17422            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17423         IsEmpty = false;
17424         if (I->isUnnamedBitfield()) {
17425           if (!I->isZeroLengthBitField(Context))
17426             ZeroSize = false;
17427         } else {
17428           ++NonBitFields;
17429           QualType FieldType = I->getType();
17430           if (FieldType->isIncompleteType() ||
17431               !Context.getTypeSizeInChars(FieldType).isZero())
17432             ZeroSize = false;
17433         }
17434       }
17435 
17436       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17437       // allowed in C++, but warn if its declaration is inside
17438       // extern "C" block.
17439       if (ZeroSize) {
17440         Diag(RecLoc, getLangOpts().CPlusPlus ?
17441                          diag::warn_zero_size_struct_union_in_extern_c :
17442                          diag::warn_zero_size_struct_union_compat)
17443           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17444       }
17445 
17446       // Structs without named members are extension in C (C99 6.7.2.1p7),
17447       // but are accepted by GCC.
17448       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17449         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17450                                diag::ext_no_named_members_in_struct_union)
17451           << Record->isUnion();
17452       }
17453     }
17454   } else {
17455     ObjCIvarDecl **ClsFields =
17456       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17457     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17458       ID->setEndOfDefinitionLoc(RBrac);
17459       // Add ivar's to class's DeclContext.
17460       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17461         ClsFields[i]->setLexicalDeclContext(ID);
17462         ID->addDecl(ClsFields[i]);
17463       }
17464       // Must enforce the rule that ivars in the base classes may not be
17465       // duplicates.
17466       if (ID->getSuperClass())
17467         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17468     } else if (ObjCImplementationDecl *IMPDecl =
17469                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17470       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17471       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17472         // Ivar declared in @implementation never belongs to the implementation.
17473         // Only it is in implementation's lexical context.
17474         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17475       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17476       IMPDecl->setIvarLBraceLoc(LBrac);
17477       IMPDecl->setIvarRBraceLoc(RBrac);
17478     } else if (ObjCCategoryDecl *CDecl =
17479                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17480       // case of ivars in class extension; all other cases have been
17481       // reported as errors elsewhere.
17482       // FIXME. Class extension does not have a LocEnd field.
17483       // CDecl->setLocEnd(RBrac);
17484       // Add ivar's to class extension's DeclContext.
17485       // Diagnose redeclaration of private ivars.
17486       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17487       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17488         if (IDecl) {
17489           if (const ObjCIvarDecl *ClsIvar =
17490               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17491             Diag(ClsFields[i]->getLocation(),
17492                  diag::err_duplicate_ivar_declaration);
17493             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17494             continue;
17495           }
17496           for (const auto *Ext : IDecl->known_extensions()) {
17497             if (const ObjCIvarDecl *ClsExtIvar
17498                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17499               Diag(ClsFields[i]->getLocation(),
17500                    diag::err_duplicate_ivar_declaration);
17501               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17502               continue;
17503             }
17504           }
17505         }
17506         ClsFields[i]->setLexicalDeclContext(CDecl);
17507         CDecl->addDecl(ClsFields[i]);
17508       }
17509       CDecl->setIvarLBraceLoc(LBrac);
17510       CDecl->setIvarRBraceLoc(RBrac);
17511     }
17512   }
17513   if (Record && Record->hasAttr<PackedAttr>() && !Record->isDependentType()) {
17514     std::function<bool(const RecordDecl *R)> contains_capabilities =
17515       [&](const RecordDecl *R) {
17516         for (const auto *F : R->fields()) {
17517           auto FTy = F->getType();
17518           if (FTy->isCHERICapabilityType(getASTContext()))
17519             return true;
17520           if (FTy->isRecordType() &&
17521               contains_capabilities(FTy->getAs<RecordType>()->getDecl()))
17522             return true;
17523         }
17524         return false;
17525       };
17526     const FieldDecl *CheckForUseInArray = nullptr;
17527     for (const auto *F : Record->fields()) {
17528       auto FTy = F->getType();
17529       // We shouldn't be calling Context.getTypeAlign() as this alters the
17530       // order in which some Record layouts get initialized and therefore
17531       // breaks CodeGen/override-layout.c and CodeGenCXX/override-layout.cpp
17532       // Context.getDeclAlign() appears to be the correct function to call
17533       // but it will always return 1 byte alignment for fields in a struct
17534       // that has a packed attribute and is only an estimate otherwise (and
17535       // appears to be wrong quite frequently).
17536       // To avoid breaking any existing test cases that depend on the order, we
17537       // make sure to only call getTypeAlign() if the field is actually a
17538       // capability type
17539       auto checkCapabilityFieldAlignment = [&](unsigned DiagID) {
17540         // Calling getTypeAlign on dependent types will fail, so we need to fall
17541         // back to an estimate from GetDeclAlign
17542         unsigned CapAlign = FTy->isDependentType() ?
17543             Context.toBits(Context.getDeclAlign(F)) : Context.getTypeAlign(FTy);
17544         unsigned FieldOffset = Context.getFieldOffset(F);
17545         if (FieldOffset % CapAlign) {
17546           Diag(F->getLocation(), DiagID)
17547               << (unsigned)Context.toCharUnitsFromBits(FieldOffset).getQuantity();
17548           // only check use in array if we haven't diagnosed anything yet
17549           CheckForUseInArray = nullptr;
17550         } else {
17551           CheckForUseInArray = F;
17552         }
17553       };
17554       if (FTy->isCHERICapabilityType(Context)) {
17555         checkCapabilityFieldAlignment(diag::warn_packed_capability);
17556       } else if (FTy->isRecordType() &&
17557                  contains_capabilities(FTy->getAs<RecordType>()->getDecl())) {
17558         checkCapabilityFieldAlignment(diag::warn_packed_struct_capability);
17559       }
17560     }
17561     if (CheckForUseInArray) {
17562       assert(!Record->isDependentType());
17563       unsigned RecordAlign = Context.getTypeAlign(Record->getTypeForDecl());
17564       unsigned RecordSize = Context.getTypeSize(Record->getTypeForDecl());
17565       unsigned CapAlign = Context.getTargetInfo().getCHERICapabilityAlign();
17566       // Warn if alignment is not a multiple of CapAlign unless size is a
17567       // multiple of CapAlign
17568       // I.e. struct { char pad[sizeof(void*)]; void* cap; char bad; } __packed
17569       // will cause a warning but
17570       // struct { char pad[sizeof(void*)]; void* cap; } __packed is okay
17571       if ((RecordAlign % CapAlign) && (RecordSize % CapAlign)) {
17572         unsigned AlignBytes = Context.toCharUnitsFromBits(CapAlign).getQuantity();
17573         unsigned FieldOffset = Context.toCharUnitsFromBits(
17574             Context.getFieldOffset(CheckForUseInArray)).getQuantity();
17575         Diag(CheckForUseInArray->getLocation(),
17576              diag::warn_packed_capability_in_array) << FieldOffset;
17577         Diag(Record->getSourceRange().getEnd(),
17578             diag::note_insert_attribute_aligned) << AlignBytes
17579             << FixItHint::CreateInsertion(Record->getSourceRange().getEnd(),
17580             ("__attribute__((aligned(" + Twine(AlignBytes) + ")))").str());
17581       }
17582     }
17583   }
17584 }
17585 
17586 /// Determine whether the given integral value is representable within
17587 /// the given type T.
isRepresentableIntegerValue(ASTContext & Context,llvm::APSInt & Value,QualType T)17588 static bool isRepresentableIntegerValue(ASTContext &Context,
17589                                         llvm::APSInt &Value,
17590                                         QualType T) {
17591   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17592          "Integral type required!");
17593   unsigned BitWidth = Context.getIntWidth(T);
17594 
17595   if (Value.isUnsigned() || Value.isNonNegative()) {
17596     if (T->isSignedIntegerOrEnumerationType())
17597       --BitWidth;
17598     return Value.getActiveBits() <= BitWidth;
17599   }
17600   return Value.getMinSignedBits() <= BitWidth;
17601 }
17602 
17603 // Given an integral type, return the next larger integral type
17604 // (or a NULL type of no such type exists).
getNextLargerIntegralType(ASTContext & Context,QualType T)17605 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17606   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17607   // enum checking below.
17608   assert((T->isIntegralType(Context) ||
17609          T->isEnumeralType()) && "Integral type required!");
17610   const unsigned NumTypes = 4;
17611   QualType SignedIntegralTypes[NumTypes] = {
17612     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17613   };
17614   QualType UnsignedIntegralTypes[NumTypes] = {
17615     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17616     Context.UnsignedLongLongTy
17617   };
17618 
17619   unsigned BitWidth = Context.getTypeSize(T);
17620   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17621                                                         : UnsignedIntegralTypes;
17622   for (unsigned I = 0; I != NumTypes; ++I)
17623     if (Context.getTypeSize(Types[I]) > BitWidth)
17624       return Types[I];
17625 
17626   return QualType();
17627 }
17628 
CheckEnumConstant(EnumDecl * Enum,EnumConstantDecl * LastEnumConst,SourceLocation IdLoc,IdentifierInfo * Id,Expr * Val)17629 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17630                                           EnumConstantDecl *LastEnumConst,
17631                                           SourceLocation IdLoc,
17632                                           IdentifierInfo *Id,
17633                                           Expr *Val) {
17634   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17635   llvm::APSInt EnumVal(IntWidth);
17636   QualType EltTy;
17637 
17638   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17639     Val = nullptr;
17640 
17641   if (Val)
17642     Val = DefaultLvalueConversion(Val).get();
17643 
17644   if (Val) {
17645     if (Enum->isDependentType() || Val->isTypeDependent())
17646       EltTy = Context.DependentTy;
17647     else {
17648       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17649         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17650         // constant-expression in the enumerator-definition shall be a converted
17651         // constant expression of the underlying type.
17652         EltTy = Enum->getIntegerType();
17653         ExprResult Converted =
17654           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17655                                            CCEK_Enumerator);
17656         if (Converted.isInvalid())
17657           Val = nullptr;
17658         else
17659           Val = Converted.get();
17660       } else if (!Val->isValueDependent() &&
17661                  !(Val = VerifyIntegerConstantExpression(Val,
17662                                                          &EnumVal).get())) {
17663         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17664       } else {
17665         if (Enum->isComplete()) {
17666           EltTy = Enum->getIntegerType();
17667 
17668           // In Obj-C and Microsoft mode, require the enumeration value to be
17669           // representable in the underlying type of the enumeration. In C++11,
17670           // we perform a non-narrowing conversion as part of converted constant
17671           // expression checking.
17672           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17673             if (Context.getTargetInfo()
17674                     .getTriple()
17675                     .isWindowsMSVCEnvironment()) {
17676               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17677             } else {
17678               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17679             }
17680           }
17681 
17682           // Cast to the underlying type.
17683           Val = ImpCastExprToType(Val, EltTy,
17684                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17685                                                          : CK_IntegralCast)
17686                     .get();
17687         } else if (getLangOpts().CPlusPlus) {
17688           // C++11 [dcl.enum]p5:
17689           //   If the underlying type is not fixed, the type of each enumerator
17690           //   is the type of its initializing value:
17691           //     - If an initializer is specified for an enumerator, the
17692           //       initializing value has the same type as the expression.
17693           EltTy = Val->getType();
17694         } else {
17695           // C99 6.7.2.2p2:
17696           //   The expression that defines the value of an enumeration constant
17697           //   shall be an integer constant expression that has a value
17698           //   representable as an int.
17699 
17700           // Complain if the value is not representable in an int.
17701           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17702             Diag(IdLoc, diag::ext_enum_value_not_int)
17703               << EnumVal.toString(10) << Val->getSourceRange()
17704               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17705           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17706             // Force the type of the expression to 'int'.
17707             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17708           }
17709           EltTy = Val->getType();
17710         }
17711       }
17712     }
17713   }
17714 
17715   if (!Val) {
17716     if (Enum->isDependentType())
17717       EltTy = Context.DependentTy;
17718     else if (!LastEnumConst) {
17719       // C++0x [dcl.enum]p5:
17720       //   If the underlying type is not fixed, the type of each enumerator
17721       //   is the type of its initializing value:
17722       //     - If no initializer is specified for the first enumerator, the
17723       //       initializing value has an unspecified integral type.
17724       //
17725       // GCC uses 'int' for its unspecified integral type, as does
17726       // C99 6.7.2.2p3.
17727       if (Enum->isFixed()) {
17728         EltTy = Enum->getIntegerType();
17729       }
17730       else {
17731         EltTy = Context.IntTy;
17732       }
17733     } else {
17734       // Assign the last value + 1.
17735       EnumVal = LastEnumConst->getInitVal();
17736       ++EnumVal;
17737       EltTy = LastEnumConst->getType();
17738 
17739       // Check for overflow on increment.
17740       if (EnumVal < LastEnumConst->getInitVal()) {
17741         // C++0x [dcl.enum]p5:
17742         //   If the underlying type is not fixed, the type of each enumerator
17743         //   is the type of its initializing value:
17744         //
17745         //     - Otherwise the type of the initializing value is the same as
17746         //       the type of the initializing value of the preceding enumerator
17747         //       unless the incremented value is not representable in that type,
17748         //       in which case the type is an unspecified integral type
17749         //       sufficient to contain the incremented value. If no such type
17750         //       exists, the program is ill-formed.
17751         QualType T = getNextLargerIntegralType(Context, EltTy);
17752         if (T.isNull() || Enum->isFixed()) {
17753           // There is no integral type larger enough to represent this
17754           // value. Complain, then allow the value to wrap around.
17755           EnumVal = LastEnumConst->getInitVal();
17756           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17757           ++EnumVal;
17758           if (Enum->isFixed())
17759             // When the underlying type is fixed, this is ill-formed.
17760             Diag(IdLoc, diag::err_enumerator_wrapped)
17761               << EnumVal.toString(10)
17762               << EltTy;
17763           else
17764             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17765               << EnumVal.toString(10);
17766         } else {
17767           EltTy = T;
17768         }
17769 
17770         // Retrieve the last enumerator's value, extent that type to the
17771         // type that is supposed to be large enough to represent the incremented
17772         // value, then increment.
17773         EnumVal = LastEnumConst->getInitVal();
17774         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17775         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17776         ++EnumVal;
17777 
17778         // If we're not in C++, diagnose the overflow of enumerator values,
17779         // which in C99 means that the enumerator value is not representable in
17780         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17781         // permits enumerator values that are representable in some larger
17782         // integral type.
17783         if (!getLangOpts().CPlusPlus && !T.isNull())
17784           Diag(IdLoc, diag::warn_enum_value_overflow);
17785       } else if (!getLangOpts().CPlusPlus &&
17786                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17787         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17788         Diag(IdLoc, diag::ext_enum_value_not_int)
17789           << EnumVal.toString(10) << 1;
17790       }
17791     }
17792   }
17793 
17794   if (!EltTy->isDependentType()) {
17795     // Make the enumerator value match the signedness and size of the
17796     // enumerator's type.
17797     EnumVal = EnumVal.extOrTrunc(Context.getIntRange(EltTy));
17798     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17799   }
17800 
17801   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17802                                   Val, EnumVal);
17803 }
17804 
shouldSkipAnonEnumBody(Scope * S,IdentifierInfo * II,SourceLocation IILoc)17805 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17806                                                 SourceLocation IILoc) {
17807   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17808       !getLangOpts().CPlusPlus)
17809     return SkipBodyInfo();
17810 
17811   // We have an anonymous enum definition. Look up the first enumerator to
17812   // determine if we should merge the definition with an existing one and
17813   // skip the body.
17814   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17815                                          forRedeclarationInCurContext());
17816   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17817   if (!PrevECD)
17818     return SkipBodyInfo();
17819 
17820   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17821   NamedDecl *Hidden;
17822   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17823     SkipBodyInfo Skip;
17824     Skip.Previous = Hidden;
17825     return Skip;
17826   }
17827 
17828   return SkipBodyInfo();
17829 }
17830 
ActOnEnumConstant(Scope * S,Decl * theEnumDecl,Decl * lastEnumConst,SourceLocation IdLoc,IdentifierInfo * Id,const ParsedAttributesView & Attrs,SourceLocation EqualLoc,Expr * Val)17831 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17832                               SourceLocation IdLoc, IdentifierInfo *Id,
17833                               const ParsedAttributesView &Attrs,
17834                               SourceLocation EqualLoc, Expr *Val) {
17835   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17836   EnumConstantDecl *LastEnumConst =
17837     cast_or_null<EnumConstantDecl>(lastEnumConst);
17838 
17839   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17840   // we find one that is.
17841   S = getNonFieldDeclScope(S);
17842 
17843   // Verify that there isn't already something declared with this name in this
17844   // scope.
17845   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17846   LookupName(R, S);
17847   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17848 
17849   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17850     // Maybe we will complain about the shadowed template parameter.
17851     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17852     // Just pretend that we didn't see the previous declaration.
17853     PrevDecl = nullptr;
17854   }
17855 
17856   // C++ [class.mem]p15:
17857   // If T is the name of a class, then each of the following shall have a name
17858   // different from T:
17859   // - every enumerator of every member of class T that is an unscoped
17860   // enumerated type
17861   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17862     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17863                             DeclarationNameInfo(Id, IdLoc));
17864 
17865   EnumConstantDecl *New =
17866     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17867   if (!New)
17868     return nullptr;
17869 
17870   if (PrevDecl) {
17871     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17872       // Check for other kinds of shadowing not already handled.
17873       CheckShadow(New, PrevDecl, R);
17874     }
17875 
17876     // When in C++, we may get a TagDecl with the same name; in this case the
17877     // enum constant will 'hide' the tag.
17878     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17879            "Received TagDecl when not in C++!");
17880     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17881       if (isa<EnumConstantDecl>(PrevDecl))
17882         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17883       else
17884         Diag(IdLoc, diag::err_redefinition) << Id;
17885       notePreviousDefinition(PrevDecl, IdLoc);
17886       return nullptr;
17887     }
17888   }
17889 
17890   // Process attributes.
17891   ProcessDeclAttributeList(S, New, Attrs);
17892   AddPragmaAttributes(S, New);
17893 
17894   // Register this decl in the current scope stack.
17895   New->setAccess(TheEnumDecl->getAccess());
17896   PushOnScopeChains(New, S);
17897 
17898   ActOnDocumentableDecl(New);
17899 
17900   return New;
17901 }
17902 
17903 // Returns true when the enum initial expression does not trigger the
17904 // duplicate enum warning.  A few common cases are exempted as follows:
17905 // Element2 = Element1
17906 // Element2 = Element1 + 1
17907 // Element2 = Element1 - 1
17908 // Where Element2 and Element1 are from the same enum.
ValidDuplicateEnum(EnumConstantDecl * ECD,EnumDecl * Enum)17909 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17910   Expr *InitExpr = ECD->getInitExpr();
17911   if (!InitExpr)
17912     return true;
17913   InitExpr = InitExpr->IgnoreImpCasts();
17914 
17915   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17916     if (!BO->isAdditiveOp())
17917       return true;
17918     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17919     if (!IL)
17920       return true;
17921     if (IL->getValue() != 1)
17922       return true;
17923 
17924     InitExpr = BO->getLHS();
17925   }
17926 
17927   // This checks if the elements are from the same enum.
17928   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17929   if (!DRE)
17930     return true;
17931 
17932   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17933   if (!EnumConstant)
17934     return true;
17935 
17936   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17937       Enum)
17938     return true;
17939 
17940   return false;
17941 }
17942 
17943 // Emits a warning when an element is implicitly set a value that
17944 // a previous element has already been set to.
CheckForDuplicateEnumValues(Sema & S,ArrayRef<Decl * > Elements,EnumDecl * Enum,QualType EnumType)17945 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17946                                         EnumDecl *Enum, QualType EnumType) {
17947   // Avoid anonymous enums
17948   if (!Enum->getIdentifier())
17949     return;
17950 
17951   // Only check for small enums.
17952   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17953     return;
17954 
17955   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17956     return;
17957 
17958   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17959   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17960 
17961   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17962 
17963   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17964   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17965 
17966   // Use int64_t as a key to avoid needing special handling for map keys.
17967   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17968     llvm::APSInt Val = D->getInitVal();
17969     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17970   };
17971 
17972   DuplicatesVector DupVector;
17973   ValueToVectorMap EnumMap;
17974 
17975   // Populate the EnumMap with all values represented by enum constants without
17976   // an initializer.
17977   for (auto *Element : Elements) {
17978     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17979 
17980     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17981     // this constant.  Skip this enum since it may be ill-formed.
17982     if (!ECD) {
17983       return;
17984     }
17985 
17986     // Constants with initalizers are handled in the next loop.
17987     if (ECD->getInitExpr())
17988       continue;
17989 
17990     // Duplicate values are handled in the next loop.
17991     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17992   }
17993 
17994   if (EnumMap.size() == 0)
17995     return;
17996 
17997   // Create vectors for any values that has duplicates.
17998   for (auto *Element : Elements) {
17999     // The last loop returned if any constant was null.
18000     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18001     if (!ValidDuplicateEnum(ECD, Enum))
18002       continue;
18003 
18004     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18005     if (Iter == EnumMap.end())
18006       continue;
18007 
18008     DeclOrVector& Entry = Iter->second;
18009     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18010       // Ensure constants are different.
18011       if (D == ECD)
18012         continue;
18013 
18014       // Create new vector and push values onto it.
18015       auto Vec = std::make_unique<ECDVector>();
18016       Vec->push_back(D);
18017       Vec->push_back(ECD);
18018 
18019       // Update entry to point to the duplicates vector.
18020       Entry = Vec.get();
18021 
18022       // Store the vector somewhere we can consult later for quick emission of
18023       // diagnostics.
18024       DupVector.emplace_back(std::move(Vec));
18025       continue;
18026     }
18027 
18028     ECDVector *Vec = Entry.get<ECDVector*>();
18029     // Make sure constants are not added more than once.
18030     if (*Vec->begin() == ECD)
18031       continue;
18032 
18033     Vec->push_back(ECD);
18034   }
18035 
18036   // Emit diagnostics.
18037   for (const auto &Vec : DupVector) {
18038     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18039 
18040     // Emit warning for one enum constant.
18041     auto *FirstECD = Vec->front();
18042     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18043       << FirstECD << FirstECD->getInitVal().toString(10)
18044       << FirstECD->getSourceRange();
18045 
18046     // Emit one note for each of the remaining enum constants with
18047     // the same value.
18048     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
18049       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18050         << ECD << ECD->getInitVal().toString(10)
18051         << ECD->getSourceRange();
18052   }
18053 }
18054 
IsValueInFlagEnum(const EnumDecl * ED,const llvm::APInt & Val,bool AllowMask) const18055 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18056                              bool AllowMask) const {
18057   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18058   assert(ED->isCompleteDefinition() && "expected enum definition");
18059 
18060   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18061   llvm::APInt &FlagBits = R.first->second;
18062 
18063   if (R.second) {
18064     for (auto *E : ED->enumerators()) {
18065       const auto &EVal = E->getInitVal();
18066       // Only single-bit enumerators introduce new flag values.
18067       if (EVal.isPowerOf2())
18068         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18069     }
18070   }
18071 
18072   // A value is in a flag enum if either its bits are a subset of the enum's
18073   // flag bits (the first condition) or we are allowing masks and the same is
18074   // true of its complement (the second condition). When masks are allowed, we
18075   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18076   //
18077   // While it's true that any value could be used as a mask, the assumption is
18078   // that a mask will have all of the insignificant bits set. Anything else is
18079   // likely a logic error.
18080   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18081   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18082 }
18083 
ActOnEnumBody(SourceLocation EnumLoc,SourceRange BraceRange,Decl * EnumDeclX,ArrayRef<Decl * > Elements,Scope * S,const ParsedAttributesView & Attrs)18084 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18085                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18086                          const ParsedAttributesView &Attrs) {
18087   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18088   QualType EnumType = Context.getTypeDeclType(Enum);
18089 
18090   ProcessDeclAttributeList(S, Enum, Attrs);
18091 
18092   if (Enum->isDependentType()) {
18093     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18094       EnumConstantDecl *ECD =
18095         cast_or_null<EnumConstantDecl>(Elements[i]);
18096       if (!ECD) continue;
18097 
18098       ECD->setType(EnumType);
18099     }
18100 
18101     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18102     return;
18103   }
18104 
18105   // TODO: If the result value doesn't fit in an int, it must be a long or long
18106   // long value.  ISO C does not support this, but GCC does as an extension,
18107   // emit a warning.
18108   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18109   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18110   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18111 
18112   // Verify that all the values are okay, compute the size of the values, and
18113   // reverse the list.
18114   unsigned NumNegativeBits = 0;
18115   unsigned NumPositiveBits = 0;
18116 
18117   // Keep track of whether all elements have type int.
18118   bool AllElementsInt = true;
18119 
18120   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18121     EnumConstantDecl *ECD =
18122       cast_or_null<EnumConstantDecl>(Elements[i]);
18123     if (!ECD) continue;  // Already issued a diagnostic.
18124 
18125     const llvm::APSInt &InitVal = ECD->getInitVal();
18126 
18127     // Keep track of the size of positive and negative values.
18128     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18129       NumPositiveBits = std::max(NumPositiveBits,
18130                                  (unsigned)InitVal.getActiveBits());
18131     else
18132       NumNegativeBits = std::max(NumNegativeBits,
18133                                  (unsigned)InitVal.getMinSignedBits());
18134 
18135     // Keep track of whether every enum element has type int (very common).
18136     if (AllElementsInt)
18137       AllElementsInt = ECD->getType() == Context.IntTy;
18138   }
18139 
18140   // Figure out the type that should be used for this enum.
18141   QualType BestType;
18142   unsigned BestWidth;
18143 
18144   // C++0x N3000 [conv.prom]p3:
18145   //   An rvalue of an unscoped enumeration type whose underlying
18146   //   type is not fixed can be converted to an rvalue of the first
18147   //   of the following types that can represent all the values of
18148   //   the enumeration: int, unsigned int, long int, unsigned long
18149   //   int, long long int, or unsigned long long int.
18150   // C99 6.4.4.3p2:
18151   //   An identifier declared as an enumeration constant has type int.
18152   // The C99 rule is modified by a gcc extension
18153   QualType BestPromotionType;
18154 
18155   bool Packed = Enum->hasAttr<PackedAttr>();
18156   // -fshort-enums is the equivalent to specifying the packed attribute on all
18157   // enum definitions.
18158   if (LangOpts.ShortEnums)
18159     Packed = true;
18160 
18161   // If the enum already has a type because it is fixed or dictated by the
18162   // target, promote that type instead of analyzing the enumerators.
18163   if (Enum->isComplete()) {
18164     BestType = Enum->getIntegerType();
18165     if (BestType->isPromotableIntegerType())
18166       BestPromotionType = Context.getPromotedIntegerType(BestType);
18167     else
18168       BestPromotionType = BestType;
18169 
18170     BestWidth = Context.getIntWidth(BestType);
18171   }
18172   else if (NumNegativeBits) {
18173     // If there is a negative value, figure out the smallest integer type (of
18174     // int/long/longlong) that fits.
18175     // If it's packed, check also if it fits a char or a short.
18176     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18177       BestType = Context.SignedCharTy;
18178       BestWidth = CharWidth;
18179     } else if (Packed && NumNegativeBits <= ShortWidth &&
18180                NumPositiveBits < ShortWidth) {
18181       BestType = Context.ShortTy;
18182       BestWidth = ShortWidth;
18183     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18184       BestType = Context.IntTy;
18185       BestWidth = IntWidth;
18186     } else {
18187       BestWidth = Context.getTargetInfo().getLongWidth();
18188 
18189       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18190         BestType = Context.LongTy;
18191       } else {
18192         BestWidth = Context.getTargetInfo().getLongLongWidth();
18193 
18194         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18195           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18196         BestType = Context.LongLongTy;
18197       }
18198     }
18199     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18200   } else {
18201     // If there is no negative value, figure out the smallest type that fits
18202     // all of the enumerator values.
18203     // If it's packed, check also if it fits a char or a short.
18204     if (Packed && NumPositiveBits <= CharWidth) {
18205       BestType = Context.UnsignedCharTy;
18206       BestPromotionType = Context.IntTy;
18207       BestWidth = CharWidth;
18208     } else if (Packed && NumPositiveBits <= ShortWidth) {
18209       BestType = Context.UnsignedShortTy;
18210       BestPromotionType = Context.IntTy;
18211       BestWidth = ShortWidth;
18212     } else if (NumPositiveBits <= IntWidth) {
18213       BestType = Context.UnsignedIntTy;
18214       BestWidth = IntWidth;
18215       BestPromotionType
18216         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18217                            ? Context.UnsignedIntTy : Context.IntTy;
18218     } else if (NumPositiveBits <=
18219                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18220       BestType = Context.UnsignedLongTy;
18221       BestPromotionType
18222         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18223                            ? Context.UnsignedLongTy : Context.LongTy;
18224     } else {
18225       BestWidth = Context.getTargetInfo().getLongLongWidth();
18226       assert(NumPositiveBits <= BestWidth &&
18227              "How could an initializer get larger than ULL?");
18228       BestType = Context.UnsignedLongLongTy;
18229       BestPromotionType
18230         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18231                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18232     }
18233   }
18234 
18235   // Loop over all of the enumerator constants, changing their types to match
18236   // the type of the enum if needed.
18237   for (auto *D : Elements) {
18238     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18239     if (!ECD) continue;  // Already issued a diagnostic.
18240 
18241     // Standard C says the enumerators have int type, but we allow, as an
18242     // extension, the enumerators to be larger than int size.  If each
18243     // enumerator value fits in an int, type it as an int, otherwise type it the
18244     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18245     // that X has type 'int', not 'unsigned'.
18246 
18247     // Determine whether the value fits into an int.
18248     llvm::APSInt InitVal = ECD->getInitVal();
18249 
18250     // If it fits into an integer type, force it.  Otherwise force it to match
18251     // the enum decl type.
18252     QualType NewTy;
18253     unsigned NewWidth;
18254     bool NewSign;
18255     if (!getLangOpts().CPlusPlus &&
18256         !Enum->isFixed() &&
18257         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18258       NewTy = Context.IntTy;
18259       NewWidth = IntWidth;
18260       NewSign = true;
18261     } else if (ECD->getType() == BestType) {
18262       // Already the right type!
18263       if (getLangOpts().CPlusPlus)
18264         // C++ [dcl.enum]p4: Following the closing brace of an
18265         // enum-specifier, each enumerator has the type of its
18266         // enumeration.
18267         ECD->setType(EnumType);
18268       continue;
18269     } else {
18270       NewTy = BestType;
18271       NewWidth = BestWidth;
18272       NewSign = BestType->isSignedIntegerOrEnumerationType();
18273     }
18274 
18275     // Adjust the APSInt value.
18276     InitVal = InitVal.extOrTrunc(NewWidth);
18277     InitVal.setIsSigned(NewSign);
18278     ECD->setInitVal(InitVal);
18279 
18280     // Adjust the Expr initializer and type.
18281     if (ECD->getInitExpr() &&
18282         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18283       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
18284                                                 CK_IntegralCast,
18285                                                 ECD->getInitExpr(),
18286                                                 /*base paths*/ nullptr,
18287                                                 VK_RValue));
18288     if (getLangOpts().CPlusPlus)
18289       // C++ [dcl.enum]p4: Following the closing brace of an
18290       // enum-specifier, each enumerator has the type of its
18291       // enumeration.
18292       ECD->setType(EnumType);
18293     else
18294       ECD->setType(NewTy);
18295   }
18296 
18297   Enum->completeDefinition(BestType, BestPromotionType,
18298                            NumPositiveBits, NumNegativeBits);
18299 
18300   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18301 
18302   if (Enum->isClosedFlag()) {
18303     for (Decl *D : Elements) {
18304       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18305       if (!ECD) continue;  // Already issued a diagnostic.
18306 
18307       llvm::APSInt InitVal = ECD->getInitVal();
18308       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18309           !IsValueInFlagEnum(Enum, InitVal, true))
18310         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18311           << ECD << Enum;
18312     }
18313   }
18314 
18315   // Now that the enum type is defined, ensure it's not been underaligned.
18316   if (Enum->hasAttrs())
18317     CheckAlignasUnderalignment(Enum);
18318 }
18319 
ActOnFileScopeAsmDecl(Expr * expr,SourceLocation StartLoc,SourceLocation EndLoc)18320 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18321                                   SourceLocation StartLoc,
18322                                   SourceLocation EndLoc) {
18323   StringLiteral *AsmString = cast<StringLiteral>(expr);
18324 
18325   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18326                                                    AsmString, StartLoc,
18327                                                    EndLoc);
18328   CurContext->addDecl(New);
18329   return New;
18330 }
18331 
ActOnPragmaOpaque(IdentifierInfo * TypeName,IdentifierInfo * KeyName,SourceLocation PragmaLoc,SourceLocation TypeLoc,SourceLocation KeyLoc)18332 void Sema::ActOnPragmaOpaque(IdentifierInfo* TypeName,
18333                              IdentifierInfo* KeyName,
18334                              SourceLocation PragmaLoc,
18335                              SourceLocation TypeLoc,
18336                              SourceLocation KeyLoc) {
18337 
18338   Decl *TD = LookupSingleName(TUScope, TypeName, TypeLoc, LookupOrdinaryName);
18339   TypedefDecl *TypeDecl = TD ? dyn_cast<TypedefDecl>(TD) : 0;
18340   // Check that this is a valid typedef of an opaque type
18341   if (!TypeDecl || !TypeDecl->getUnderlyingType()->isPointerType()) {
18342     Diag(TypeLoc, diag::err_pragma_opaque_invalid_type);
18343     return;
18344   }
18345 
18346   Decl *KD = LookupSingleName(TUScope, KeyName, KeyLoc, LookupOrdinaryName);
18347   VarDecl *KeyDecl = KD ? dyn_cast<VarDecl>(KD) : 0;
18348 
18349   if (!KeyDecl) {
18350     Diag(KeyLoc, diag::err_pragma_opaque_invalid_key);
18351     return;
18352   }
18353 
18354   TypeDecl->setOpaqueKey(KeyDecl);
18355 }
18356 
ActOnPragmaRedefineExtname(IdentifierInfo * Name,IdentifierInfo * AliasName,SourceLocation PragmaLoc,SourceLocation NameLoc,SourceLocation AliasNameLoc)18357 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18358                                       IdentifierInfo* AliasName,
18359                                       SourceLocation PragmaLoc,
18360                                       SourceLocation NameLoc,
18361                                       SourceLocation AliasNameLoc) {
18362   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18363                                          LookupOrdinaryName);
18364   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18365                            AttributeCommonInfo::AS_Pragma);
18366   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18367       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18368 
18369   // If a declaration that:
18370   // 1) declares a function or a variable
18371   // 2) has external linkage
18372   // already exists, add a label attribute to it.
18373   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18374     if (isDeclExternC(PrevDecl))
18375       PrevDecl->addAttr(Attr);
18376     else
18377       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18378           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18379   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18380   } else
18381     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18382 }
18383 
ActOnPragmaWeakID(IdentifierInfo * Name,SourceLocation PragmaLoc,SourceLocation NameLoc)18384 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18385                              SourceLocation PragmaLoc,
18386                              SourceLocation NameLoc) {
18387   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18388 
18389   if (PrevDecl) {
18390     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18391   } else {
18392     (void)WeakUndeclaredIdentifiers.insert(
18393       std::pair<IdentifierInfo*,WeakInfo>
18394         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18395   }
18396 }
18397 
ActOnPragmaWeakAlias(IdentifierInfo * Name,IdentifierInfo * AliasName,SourceLocation PragmaLoc,SourceLocation NameLoc,SourceLocation AliasNameLoc)18398 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18399                                 IdentifierInfo* AliasName,
18400                                 SourceLocation PragmaLoc,
18401                                 SourceLocation NameLoc,
18402                                 SourceLocation AliasNameLoc) {
18403   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18404                                     LookupOrdinaryName);
18405   WeakInfo W = WeakInfo(Name, NameLoc);
18406 
18407   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18408     if (!PrevDecl->hasAttr<AliasAttr>())
18409       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18410         DeclApplyPragmaWeak(TUScope, ND, W);
18411   } else {
18412     (void)WeakUndeclaredIdentifiers.insert(
18413       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18414   }
18415 }
18416 
getObjCDeclContext() const18417 Decl *Sema::getObjCDeclContext() const {
18418   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18419 }
18420 
getEmissionStatus(FunctionDecl * FD,bool Final)18421 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18422                                                      bool Final) {
18423   // SYCL functions can be template, so we check if they have appropriate
18424   // attribute prior to checking if it is a template.
18425   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18426     return FunctionEmissionStatus::Emitted;
18427 
18428   // Templates are emitted when they're instantiated.
18429   if (FD->isDependentContext())
18430     return FunctionEmissionStatus::TemplateDiscarded;
18431 
18432   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
18433   if (LangOpts.OpenMPIsDevice) {
18434     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18435         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18436     if (DevTy.hasValue()) {
18437       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18438         OMPES = FunctionEmissionStatus::OMPDiscarded;
18439       else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
18440                *DevTy == OMPDeclareTargetDeclAttr::DT_Any) {
18441         OMPES = FunctionEmissionStatus::Emitted;
18442       }
18443     }
18444   } else if (LangOpts.OpenMP) {
18445     // In OpenMP 4.5 all the functions are host functions.
18446     if (LangOpts.OpenMP <= 45) {
18447       OMPES = FunctionEmissionStatus::Emitted;
18448     } else {
18449       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18450           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18451       // In OpenMP 5.0 or above, DevTy may be changed later by
18452       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
18453       // having no value does not imply host. The emission status will be
18454       // checked again at the end of compilation unit.
18455       if (DevTy.hasValue()) {
18456         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
18457           OMPES = FunctionEmissionStatus::OMPDiscarded;
18458         } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host ||
18459                    *DevTy == OMPDeclareTargetDeclAttr::DT_Any)
18460           OMPES = FunctionEmissionStatus::Emitted;
18461       } else if (Final)
18462         OMPES = FunctionEmissionStatus::Emitted;
18463     }
18464   }
18465   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
18466       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
18467     return OMPES;
18468 
18469   if (LangOpts.CUDA) {
18470     // When compiling for device, host functions are never emitted.  Similarly,
18471     // when compiling for host, device and global functions are never emitted.
18472     // (Technically, we do emit a host-side stub for global functions, but this
18473     // doesn't count for our purposes here.)
18474     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18475     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18476       return FunctionEmissionStatus::CUDADiscarded;
18477     if (!LangOpts.CUDAIsDevice &&
18478         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18479       return FunctionEmissionStatus::CUDADiscarded;
18480 
18481     // Check whether this function is externally visible -- if so, it's
18482     // known-emitted.
18483     //
18484     // We have to check the GVA linkage of the function's *definition* -- if we
18485     // only have a declaration, we don't know whether or not the function will
18486     // be emitted, because (say) the definition could include "inline".
18487     FunctionDecl *Def = FD->getDefinition();
18488 
18489     if (Def &&
18490         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
18491         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
18492       return FunctionEmissionStatus::Emitted;
18493   }
18494 
18495   // Otherwise, the function is known-emitted if it's in our set of
18496   // known-emitted functions.
18497   return FunctionEmissionStatus::Unknown;
18498 }
18499 
shouldIgnoreInHostDeviceCheck(FunctionDecl * Callee)18500 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18501   // Host-side references to a __global__ function refer to the stub, so the
18502   // function itself is never emitted and therefore should not be marked.
18503   // If we have host fn calls kernel fn calls host+device, the HD function
18504   // does not get instantiated on the host. We model this by omitting at the
18505   // call to the kernel from the callgraph. This ensures that, when compiling
18506   // for host, only HD functions actually called from the host get marked as
18507   // known-emitted.
18508   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18509          IdentifyCUDATarget(Callee) == CFT_Global;
18510 }
18511