Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Sema/SemaDecl.cpp
Line
Count
Source (jump to first uncovered line)
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/CXXInheritance.h"
18
#include "clang/AST/CharUnits.h"
19
#include "clang/AST/CommentDiagnostic.h"
20
#include "clang/AST/Decl.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/Randstruct.h"
29
#include "clang/AST/StmtCXX.h"
30
#include "clang/AST/Type.h"
31
#include "clang/Basic/Builtins.h"
32
#include "clang/Basic/HLSLRuntime.h"
33
#include "clang/Basic/PartialDiagnostic.h"
34
#include "clang/Basic/SourceManager.h"
35
#include "clang/Basic/TargetInfo.h"
36
#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37
#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38
#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39
#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
40
#include "clang/Sema/CXXFieldCollector.h"
41
#include "clang/Sema/DeclSpec.h"
42
#include "clang/Sema/DelayedDiagnostic.h"
43
#include "clang/Sema/Initialization.h"
44
#include "clang/Sema/Lookup.h"
45
#include "clang/Sema/ParsedTemplate.h"
46
#include "clang/Sema/Scope.h"
47
#include "clang/Sema/ScopeInfo.h"
48
#include "clang/Sema/SemaInternal.h"
49
#include "clang/Sema/Template.h"
50
#include "llvm/ADT/SmallString.h"
51
#include "llvm/ADT/StringExtras.h"
52
#include "llvm/TargetParser/Triple.h"
53
#include <algorithm>
54
#include <cstring>
55
#include <functional>
56
#include <optional>
57
#include <unordered_map>
58
59
using namespace clang;
60
using namespace sema;
61
62
703
Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
63
703
  if (OwnedType) {
64
0
    Decl *Group[2] = { OwnedType, Ptr };
65
0
    return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
66
0
  }
67
68
703
  return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
69
703
}
70
71
namespace {
72
73
class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
74
 public:
75
   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
76
                        bool AllowTemplates = false,
77
                        bool AllowNonTemplates = true)
78
       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
79
10.2k
         AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
80
10.2k
     WantExpressionKeywords = false;
81
10.2k
     WantCXXNamedCasts = false;
82
10.2k
     WantRemainingKeywords = false;
83
10.2k
  }
84
85
199
  bool ValidateCandidate(const TypoCorrection &candidate) override {
86
199
    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
87
199
      if (!AllowInvalidDecl && ND->isInvalidDecl())
88
186
        return false;
89
90
13
      if (getAsTypeTemplateDecl(ND))
91
0
        return AllowTemplates;
92
93
13
      bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
94
13
      if (!IsType)
95
13
        return false;
96
97
0
      if (AllowNonTemplates)
98
0
        return true;
99
100
      // An injected-class-name of a class template (specialization) is valid
101
      // as a template or as a non-template.
102
0
      if (AllowTemplates) {
103
0
        auto *RD = dyn_cast<CXXRecordDecl>(ND);
104
0
        if (!RD || !RD->isInjectedClassName())
105
0
          return false;
106
0
        RD = cast<CXXRecordDecl>(RD->getDeclContext());
107
0
        return RD->getDescribedClassTemplate() ||
108
0
               isa<ClassTemplateSpecializationDecl>(RD);
109
0
      }
110
111
0
      return false;
112
0
    }
113
114
0
    return !WantClassName && candidate.isKeyword();
115
199
  }
116
117
1.44k
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
118
1.44k
    return std::make_unique<TypeNameValidatorCCC>(*this);
119
1.44k
  }
120
121
 private:
122
  bool AllowInvalidDecl;
123
  bool WantClassName;
124
  bool AllowTemplates;
125
  bool AllowNonTemplates;
126
};
127
128
} // end anonymous namespace
129
130
/// Determine whether the token kind starts a simple-type-specifier.
131
0
bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
132
0
  switch (Kind) {
133
  // FIXME: Take into account the current language when deciding whether a
134
  // token kind is a valid type specifier
135
0
  case tok::kw_short:
136
0
  case tok::kw_long:
137
0
  case tok::kw___int64:
138
0
  case tok::kw___int128:
139
0
  case tok::kw_signed:
140
0
  case tok::kw_unsigned:
141
0
  case tok::kw_void:
142
0
  case tok::kw_char:
143
0
  case tok::kw_int:
144
0
  case tok::kw_half:
145
0
  case tok::kw_float:
146
0
  case tok::kw_double:
147
0
  case tok::kw___bf16:
148
0
  case tok::kw__Float16:
149
0
  case tok::kw___float128:
150
0
  case tok::kw___ibm128:
151
0
  case tok::kw_wchar_t:
152
0
  case tok::kw_bool:
153
0
  case tok::kw__Accum:
154
0
  case tok::kw__Fract:
155
0
  case tok::kw__Sat:
156
0
#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
157
0
#include "clang/Basic/TransformTypeTraits.def"
158
0
  case tok::kw___auto_type:
159
0
    return true;
160
161
0
  case tok::annot_typename:
162
0
  case tok::kw_char16_t:
163
0
  case tok::kw_char32_t:
164
0
  case tok::kw_typeof:
165
0
  case tok::annot_decltype:
166
0
  case tok::kw_decltype:
167
0
    return getLangOpts().CPlusPlus;
168
169
0
  case tok::kw_char8_t:
170
0
    return getLangOpts().Char8;
171
172
0
  default:
173
0
    break;
174
0
  }
175
176
0
  return false;
177
0
}
178
179
namespace {
180
enum class UnqualifiedTypeNameLookupResult {
181
  NotFound,
182
  FoundNonType,
183
  FoundType
184
};
185
} // end anonymous namespace
186
187
/// Tries to perform unqualified lookup of the type decls in bases for
188
/// dependent class.
189
/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
190
/// type decl, \a FoundType if only type decls are found.
191
static UnqualifiedTypeNameLookupResult
192
lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
193
                                SourceLocation NameLoc,
194
0
                                const CXXRecordDecl *RD) {
195
0
  if (!RD->hasDefinition())
196
0
    return UnqualifiedTypeNameLookupResult::NotFound;
197
  // Look for type decls in base classes.
198
0
  UnqualifiedTypeNameLookupResult FoundTypeDecl =
199
0
      UnqualifiedTypeNameLookupResult::NotFound;
200
0
  for (const auto &Base : RD->bases()) {
201
0
    const CXXRecordDecl *BaseRD = nullptr;
202
0
    if (auto *BaseTT = Base.getType()->getAs<TagType>())
203
0
      BaseRD = BaseTT->getAsCXXRecordDecl();
204
0
    else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
205
      // Look for type decls in dependent base classes that have known primary
206
      // templates.
207
0
      if (!TST || !TST->isDependentType())
208
0
        continue;
209
0
      auto *TD = TST->getTemplateName().getAsTemplateDecl();
210
0
      if (!TD)
211
0
        continue;
212
0
      if (auto *BasePrimaryTemplate =
213
0
          dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
214
0
        if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
215
0
          BaseRD = BasePrimaryTemplate;
216
0
        else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
217
0
          if (const ClassTemplatePartialSpecializationDecl *PS =
218
0
                  CTD->findPartialSpecialization(Base.getType()))
219
0
            if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
220
0
              BaseRD = PS;
221
0
        }
222
0
      }
223
0
    }
224
0
    if (BaseRD) {
225
0
      for (NamedDecl *ND : BaseRD->lookup(&II)) {
226
0
        if (!isa<TypeDecl>(ND))
227
0
          return UnqualifiedTypeNameLookupResult::FoundNonType;
228
0
        FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
229
0
      }
230
0
      if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
231
0
        switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
232
0
        case UnqualifiedTypeNameLookupResult::FoundNonType:
233
0
          return UnqualifiedTypeNameLookupResult::FoundNonType;
234
0
        case UnqualifiedTypeNameLookupResult::FoundType:
235
0
          FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
236
0
          break;
237
0
        case UnqualifiedTypeNameLookupResult::NotFound:
238
0
          break;
239
0
        }
240
0
      }
241
0
    }
242
0
  }
243
244
0
  return FoundTypeDecl;
245
0
}
246
247
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
248
                                                      const IdentifierInfo &II,
249
0
                                                      SourceLocation NameLoc) {
250
  // Lookup in the parent class template context, if any.
251
0
  const CXXRecordDecl *RD = nullptr;
252
0
  UnqualifiedTypeNameLookupResult FoundTypeDecl =
253
0
      UnqualifiedTypeNameLookupResult::NotFound;
254
0
  for (DeclContext *DC = S.CurContext;
255
0
       DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
256
0
       DC = DC->getParent()) {
257
    // Look for type decls in dependent base classes that have known primary
258
    // templates.
259
0
    RD = dyn_cast<CXXRecordDecl>(DC);
260
0
    if (RD && RD->getDescribedClassTemplate())
261
0
      FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
262
0
  }
263
0
  if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
264
0
    return nullptr;
265
266
  // We found some types in dependent base classes.  Recover as if the user
267
  // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
268
  // lookup during template instantiation.
269
0
  S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
270
271
0
  ASTContext &Context = S.Context;
272
0
  auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
273
0
                                          cast<Type>(Context.getRecordType(RD)));
274
0
  QualType T =
275
0
      Context.getDependentNameType(ElaboratedTypeKeyword::Typename, NNS, &II);
276
277
0
  CXXScopeSpec SS;
278
0
  SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
279
280
0
  TypeLocBuilder Builder;
281
0
  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
282
0
  DepTL.setNameLoc(NameLoc);
283
0
  DepTL.setElaboratedKeywordLoc(SourceLocation());
284
0
  DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
285
0
  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
286
0
}
287
288
/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
289
static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
290
                                 SourceLocation NameLoc,
291
0
                                 bool WantNontrivialTypeSourceInfo = true) {
292
0
  switch (T->getTypeClass()) {
293
0
  case Type::DeducedTemplateSpecialization:
294
0
  case Type::Enum:
295
0
  case Type::InjectedClassName:
296
0
  case Type::Record:
297
0
  case Type::Typedef:
298
0
  case Type::UnresolvedUsing:
299
0
  case Type::Using:
300
0
    break;
301
  // These can never be qualified so an ElaboratedType node
302
  // would carry no additional meaning.
303
0
  case Type::ObjCInterface:
304
0
  case Type::ObjCTypeParam:
305
0
  case Type::TemplateTypeParm:
306
0
    return ParsedType::make(T);
307
0
  default:
308
0
    llvm_unreachable("Unexpected Type Class");
309
0
  }
310
311
0
  if (!SS || SS->isEmpty())
312
0
    return ParsedType::make(S.Context.getElaboratedType(
313
0
        ElaboratedTypeKeyword::None, nullptr, T, nullptr));
314
315
0
  QualType ElTy = S.getElaboratedType(ElaboratedTypeKeyword::None, *SS, T);
316
0
  if (!WantNontrivialTypeSourceInfo)
317
0
    return ParsedType::make(ElTy);
318
319
0
  TypeLocBuilder Builder;
320
0
  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
321
0
  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
322
0
  ElabTL.setElaboratedKeywordLoc(SourceLocation());
323
0
  ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context));
324
0
  return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
325
0
}
326
327
/// If the identifier refers to a type name within this scope,
328
/// return the declaration of that type.
329
///
330
/// This routine performs ordinary name lookup of the identifier II
331
/// within the given scope, with optional C++ scope specifier SS, to
332
/// determine whether the name refers to a type. If so, returns an
333
/// opaque pointer (actually a QualType) corresponding to that
334
/// type. Otherwise, returns NULL.
335
ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
336
                             Scope *S, CXXScopeSpec *SS, bool isClassName,
337
                             bool HasTrailingDot, ParsedType ObjectTypePtr,
338
                             bool IsCtorOrDtorName,
339
                             bool WantNontrivialTypeSourceInfo,
340
                             bool IsClassTemplateDeductionContext,
341
                             ImplicitTypenameContext AllowImplicitTypename,
342
12.9k
                             IdentifierInfo **CorrectedII) {
343
  // FIXME: Consider allowing this outside C++1z mode as an extension.
344
12.9k
  bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
345
12.9k
                              getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
346
12.9k
                              !isClassName && !HasTrailingDot;
347
348
  // Determine where we will perform name lookup.
349
12.9k
  DeclContext *LookupCtx = nullptr;
350
12.9k
  if (ObjectTypePtr) {
351
0
    QualType ObjectType = ObjectTypePtr.get();
352
0
    if (ObjectType->isRecordType())
353
0
      LookupCtx = computeDeclContext(ObjectType);
354
12.9k
  } else if (SS && SS->isNotEmpty()) {
355
0
    LookupCtx = computeDeclContext(*SS, false);
356
357
0
    if (!LookupCtx) {
358
0
      if (isDependentScopeSpecifier(*SS)) {
359
        // C++ [temp.res]p3:
360
        //   A qualified-id that refers to a type and in which the
361
        //   nested-name-specifier depends on a template-parameter (14.6.2)
362
        //   shall be prefixed by the keyword typename to indicate that the
363
        //   qualified-id denotes a type, forming an
364
        //   elaborated-type-specifier (7.1.5.3).
365
        //
366
        // We therefore do not perform any name lookup if the result would
367
        // refer to a member of an unknown specialization.
368
        // In C++2a, in several contexts a 'typename' is not required. Also
369
        // allow this as an extension.
370
0
        if (AllowImplicitTypename == ImplicitTypenameContext::No &&
371
0
            !isClassName && !IsCtorOrDtorName)
372
0
          return nullptr;
373
0
        bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
374
0
        if (IsImplicitTypename) {
375
0
          SourceLocation QualifiedLoc = SS->getRange().getBegin();
376
0
          if (getLangOpts().CPlusPlus20)
377
0
            Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
378
0
          else
379
0
            Diag(QualifiedLoc, diag::ext_implicit_typename)
380
0
                << SS->getScopeRep() << II.getName()
381
0
                << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
382
0
        }
383
384
        // We know from the grammar that this name refers to a type,
385
        // so build a dependent node to describe the type.
386
0
        if (WantNontrivialTypeSourceInfo)
387
0
          return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
388
0
                                   (ImplicitTypenameContext)IsImplicitTypename)
389
0
              .get();
390
391
0
        NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
392
0
        QualType T = CheckTypenameType(
393
0
            IsImplicitTypename ? ElaboratedTypeKeyword::Typename
394
0
                               : ElaboratedTypeKeyword::None,
395
0
            SourceLocation(), QualifierLoc, II, NameLoc);
396
0
        return ParsedType::make(T);
397
0
      }
398
399
0
      return nullptr;
400
0
    }
401
402
0
    if (!LookupCtx->isDependentContext() &&
403
0
        RequireCompleteDeclContext(*SS, LookupCtx))
404
0
      return nullptr;
405
0
  }
406
407
  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
408
  // lookup for class-names.
409
12.9k
  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
410
12.9k
                                      LookupOrdinaryName;
411
12.9k
  LookupResult Result(*this, &II, NameLoc, Kind);
412
12.9k
  if (LookupCtx) {
413
    // Perform "qualified" name lookup into the declaration context we
414
    // computed, which is either the type of the base of a member access
415
    // expression or the declaration context associated with a prior
416
    // nested-name-specifier.
417
0
    LookupQualifiedName(Result, LookupCtx);
418
419
0
    if (ObjectTypePtr && Result.empty()) {
420
      // C++ [basic.lookup.classref]p3:
421
      //   If the unqualified-id is ~type-name, the type-name is looked up
422
      //   in the context of the entire postfix-expression. If the type T of
423
      //   the object expression is of a class type C, the type-name is also
424
      //   looked up in the scope of class C. At least one of the lookups shall
425
      //   find a name that refers to (possibly cv-qualified) T.
426
0
      LookupName(Result, S);
427
0
    }
428
12.9k
  } else {
429
    // Perform unqualified name lookup.
430
12.9k
    LookupName(Result, S);
431
432
    // For unqualified lookup in a class template in MSVC mode, look into
433
    // dependent base classes where the primary class template is known.
434
12.9k
    if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
435
0
      if (ParsedType TypeInBase =
436
0
              recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
437
0
        return TypeInBase;
438
0
    }
439
12.9k
  }
440
441
12.9k
  NamedDecl *IIDecl = nullptr;
442
12.9k
  UsingShadowDecl *FoundUsingShadow = nullptr;
443
12.9k
  switch (Result.getResultKind()) {
444
8.51k
  case LookupResult::NotFound:
445
8.51k
    if (CorrectedII) {
446
0
      TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
447
0
                               AllowDeducedTemplate);
448
0
      TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
449
0
                                              S, SS, CCC, CTK_ErrorRecovery);
450
0
      IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
451
0
      TemplateTy Template;
452
0
      bool MemberOfUnknownSpecialization;
453
0
      UnqualifiedId TemplateName;
454
0
      TemplateName.setIdentifier(NewII, NameLoc);
455
0
      NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
456
0
      CXXScopeSpec NewSS, *NewSSPtr = SS;
457
0
      if (SS && NNS) {
458
0
        NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
459
0
        NewSSPtr = &NewSS;
460
0
      }
461
0
      if (Correction && (NNS || NewII != &II) &&
462
          // Ignore a correction to a template type as the to-be-corrected
463
          // identifier is not a template (typo correction for template names
464
          // is handled elsewhere).
465
0
          !(getLangOpts().CPlusPlus && NewSSPtr &&
466
0
            isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
467
0
                           Template, MemberOfUnknownSpecialization))) {
468
0
        ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
469
0
                                    isClassName, HasTrailingDot, ObjectTypePtr,
470
0
                                    IsCtorOrDtorName,
471
0
                                    WantNontrivialTypeSourceInfo,
472
0
                                    IsClassTemplateDeductionContext);
473
0
        if (Ty) {
474
0
          diagnoseTypo(Correction,
475
0
                       PDiag(diag::err_unknown_type_or_class_name_suggest)
476
0
                         << Result.getLookupName() << isClassName);
477
0
          if (SS && NNS)
478
0
            SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
479
0
          *CorrectedII = NewII;
480
0
          return Ty;
481
0
        }
482
0
      }
483
0
    }
484
8.51k
    Result.suppressDiagnostics();
485
8.51k
    return nullptr;
486
0
  case LookupResult::NotFoundInCurrentInstantiation:
487
0
    if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
488
0
      QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
489
0
                                                SS->getScopeRep(), &II);
490
0
      TypeLocBuilder TLB;
491
0
      DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
492
0
      TL.setElaboratedKeywordLoc(SourceLocation());
493
0
      TL.setQualifierLoc(SS->getWithLocInContext(Context));
494
0
      TL.setNameLoc(NameLoc);
495
0
      return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
496
0
    }
497
0
    [[fallthrough]];
498
0
  case LookupResult::FoundOverloaded:
499
0
  case LookupResult::FoundUnresolvedValue:
500
0
    Result.suppressDiagnostics();
501
0
    return nullptr;
502
503
0
  case LookupResult::Ambiguous:
504
    // Recover from type-hiding ambiguities by hiding the type.  We'll
505
    // do the lookup again when looking for an object, and we can
506
    // diagnose the error then.  If we don't do this, then the error
507
    // about hiding the type will be immediately followed by an error
508
    // that only makes sense if the identifier was treated like a type.
509
0
    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
510
0
      Result.suppressDiagnostics();
511
0
      return nullptr;
512
0
    }
513
514
    // Look to see if we have a type anywhere in the list of results.
515
0
    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
516
0
         Res != ResEnd; ++Res) {
517
0
      NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
518
0
      if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
519
0
              RealRes) ||
520
0
          (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
521
0
        if (!IIDecl ||
522
            // Make the selection of the recovery decl deterministic.
523
0
            RealRes->getLocation() < IIDecl->getLocation()) {
524
0
          IIDecl = RealRes;
525
0
          FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
526
0
        }
527
0
      }
528
0
    }
529
530
0
    if (!IIDecl) {
531
      // None of the entities we found is a type, so there is no way
532
      // to even assume that the result is a type. In this case, don't
533
      // complain about the ambiguity. The parser will either try to
534
      // perform this lookup again (e.g., as an object name), which
535
      // will produce the ambiguity, or will complain that it expected
536
      // a type name.
537
0
      Result.suppressDiagnostics();
538
0
      return nullptr;
539
0
    }
540
541
    // We found a type within the ambiguous lookup; diagnose the
542
    // ambiguity and then return that type. This might be the right
543
    // answer, or it might not be, but it suppresses any attempt to
544
    // perform the name lookup again.
545
0
    break;
546
547
4.47k
  case LookupResult::Found:
548
4.47k
    IIDecl = Result.getFoundDecl();
549
4.47k
    FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
550
4.47k
    break;
551
12.9k
  }
552
553
4.47k
  assert(IIDecl && "Didn't find decl");
554
555
0
  QualType T;
556
4.47k
  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
557
    // C++ [class.qual]p2: A lookup that would find the injected-class-name
558
    // instead names the constructors of the class, except when naming a class.
559
    // This is ill-formed when we're not actually forming a ctor or dtor name.
560
0
    auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
561
0
    auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
562
0
    if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
563
0
        FoundRD->isInjectedClassName() &&
564
0
        declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
565
0
      Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
566
0
          << &II << /*Type*/1;
567
568
0
    DiagnoseUseOfDecl(IIDecl, NameLoc);
569
570
0
    T = Context.getTypeDeclType(TD);
571
0
    MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
572
4.47k
  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
573
0
    (void)DiagnoseUseOfDecl(IDecl, NameLoc);
574
0
    if (!HasTrailingDot)
575
0
      T = Context.getObjCInterfaceType(IDecl);
576
0
    FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
577
4.47k
  } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
578
0
    (void)DiagnoseUseOfDecl(UD, NameLoc);
579
    // Recover with 'int'
580
0
    return ParsedType::make(Context.IntTy);
581
4.47k
  } else if (AllowDeducedTemplate) {
582
2.67k
    if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
583
0
      assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
584
0
      TemplateName Template =
585
0
          FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
586
0
      T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
587
0
                                                       false);
588
      // Don't wrap in a further UsingType.
589
0
      FoundUsingShadow = nullptr;
590
0
    }
591
2.67k
  }
592
593
4.47k
  if (T.isNull()) {
594
    // If it's not plausibly a type, suppress diagnostics.
595
4.47k
    Result.suppressDiagnostics();
596
4.47k
    return nullptr;
597
4.47k
  }
598
599
0
  if (FoundUsingShadow)
600
0
    T = Context.getUsingType(FoundUsingShadow, T);
601
602
0
  return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
603
4.47k
}
604
605
// Builds a fake NNS for the given decl context.
606
static NestedNameSpecifier *
607
0
synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
608
0
  for (;; DC = DC->getLookupParent()) {
609
0
    DC = DC->getPrimaryContext();
610
0
    auto *ND = dyn_cast<NamespaceDecl>(DC);
611
0
    if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
612
0
      return NestedNameSpecifier::Create(Context, nullptr, ND);
613
0
    else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
614
0
      return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
615
0
                                         RD->getTypeForDecl());
616
0
    else if (isa<TranslationUnitDecl>(DC))
617
0
      return NestedNameSpecifier::GlobalSpecifier(Context);
618
0
  }
619
0
  llvm_unreachable("something isn't in TU scope?");
620
0
}
621
622
/// Find the parent class with dependent bases of the innermost enclosing method
623
/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
624
/// up allowing unqualified dependent type names at class-level, which MSVC
625
/// correctly rejects.
626
static const CXXRecordDecl *
627
0
findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
628
0
  for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
629
0
    DC = DC->getPrimaryContext();
630
0
    if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
631
0
      if (MD->getParent()->hasAnyDependentBases())
632
0
        return MD->getParent();
633
0
  }
634
0
  return nullptr;
635
0
}
636
637
ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
638
                                          SourceLocation NameLoc,
639
0
                                          bool IsTemplateTypeArg) {
640
0
  assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
641
642
0
  NestedNameSpecifier *NNS = nullptr;
643
0
  if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
644
    // If we weren't able to parse a default template argument, delay lookup
645
    // until instantiation time by making a non-dependent DependentTypeName. We
646
    // pretend we saw a NestedNameSpecifier referring to the current scope, and
647
    // lookup is retried.
648
    // FIXME: This hurts our diagnostic quality, since we get errors like "no
649
    // type named 'Foo' in 'current_namespace'" when the user didn't write any
650
    // name specifiers.
651
0
    NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
652
0
    Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
653
0
  } else if (const CXXRecordDecl *RD =
654
0
                 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
655
    // Build a DependentNameType that will perform lookup into RD at
656
    // instantiation time.
657
0
    NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
658
0
                                      RD->getTypeForDecl());
659
660
    // Diagnose that this identifier was undeclared, and retry the lookup during
661
    // template instantiation.
662
0
    Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
663
0
                                                                      << RD;
664
0
  } else {
665
    // This is not a situation that we should recover from.
666
0
    return ParsedType();
667
0
  }
668
669
0
  QualType T =
670
0
      Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
671
672
  // Build type location information.  We synthesized the qualifier, so we have
673
  // to build a fake NestedNameSpecifierLoc.
674
0
  NestedNameSpecifierLocBuilder NNSLocBuilder;
675
0
  NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
676
0
  NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
677
678
0
  TypeLocBuilder Builder;
679
0
  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
680
0
  DepTL.setNameLoc(NameLoc);
681
0
  DepTL.setElaboratedKeywordLoc(SourceLocation());
682
0
  DepTL.setQualifierLoc(QualifierLoc);
683
0
  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
684
0
}
685
686
/// isTagName() - This method is called *for error recovery purposes only*
687
/// to determine if the specified name is a valid tag name ("struct foo").  If
688
/// so, this returns the TST for the tag corresponding to it (TST_enum,
689
/// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
690
/// cases in C where the user forgot to specify the tag.
691
10.6k
DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
692
  // Do a tag name lookup in this scope.
693
10.6k
  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
694
10.6k
  LookupName(R, S, false);
695
10.6k
  R.suppressDiagnostics();
696
10.6k
  if (R.getResultKind() == LookupResult::Found)
697
0
    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
698
0
      switch (TD->getTagKind()) {
699
0
      case TagTypeKind::Struct:
700
0
        return DeclSpec::TST_struct;
701
0
      case TagTypeKind::Interface:
702
0
        return DeclSpec::TST_interface;
703
0
      case TagTypeKind::Union:
704
0
        return DeclSpec::TST_union;
705
0
      case TagTypeKind::Class:
706
0
        return DeclSpec::TST_class;
707
0
      case TagTypeKind::Enum:
708
0
        return DeclSpec::TST_enum;
709
0
      }
710
0
    }
711
712
10.6k
  return DeclSpec::TST_unspecified;
713
10.6k
}
714
715
/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
716
/// if a CXXScopeSpec's type is equal to the type of one of the base classes
717
/// then downgrade the missing typename error to a warning.
718
/// This is needed for MSVC compatibility; Example:
719
/// @code
720
/// template<class T> class A {
721
/// public:
722
///   typedef int TYPE;
723
/// };
724
/// template<class T> class B : public A<T> {
725
/// public:
726
///   A<T>::TYPE a; // no typename required because A<T> is a base class.
727
/// };
728
/// @endcode
729
0
bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
730
0
  if (CurContext->isRecord()) {
731
0
    if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
732
0
      return true;
733
734
0
    const Type *Ty = SS->getScopeRep()->getAsType();
735
736
0
    CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
737
0
    for (const auto &Base : RD->bases())
738
0
      if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
739
0
        return true;
740
0
    return S->isFunctionPrototypeScope();
741
0
  }
742
0
  return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
743
0
}
744
745
void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
746
                                   SourceLocation IILoc,
747
                                   Scope *S,
748
                                   CXXScopeSpec *SS,
749
                                   ParsedType &SuggestedType,
750
10.2k
                                   bool IsTemplateName) {
751
  // Don't report typename errors for editor placeholders.
752
10.2k
  if (II->isEditorPlaceholder())
753
0
    return;
754
  // We don't have anything to suggest (yet).
755
10.2k
  SuggestedType = nullptr;
756
757
  // There may have been a typo in the name of the type. Look up typo
758
  // results, in case we have something that we can suggest.
759
10.2k
  TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
760
10.2k
                           /*AllowTemplates=*/IsTemplateName,
761
10.2k
                           /*AllowNonTemplates=*/!IsTemplateName);
762
10.2k
  if (TypoCorrection Corrected =
763
10.2k
          CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
764
10.2k
                      CCC, CTK_ErrorRecovery)) {
765
    // FIXME: Support error recovery for the template-name case.
766
0
    bool CanRecover = !IsTemplateName;
767
0
    if (Corrected.isKeyword()) {
768
      // We corrected to a keyword.
769
0
      diagnoseTypo(Corrected,
770
0
                   PDiag(IsTemplateName ? diag::err_no_template_suggest
771
0
                                        : diag::err_unknown_typename_suggest)
772
0
                       << II);
773
0
      II = Corrected.getCorrectionAsIdentifierInfo();
774
0
    } else {
775
      // We found a similarly-named type or interface; suggest that.
776
0
      if (!SS || !SS->isSet()) {
777
0
        diagnoseTypo(Corrected,
778
0
                     PDiag(IsTemplateName ? diag::err_no_template_suggest
779
0
                                          : diag::err_unknown_typename_suggest)
780
0
                         << II, CanRecover);
781
0
      } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
782
0
        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
783
0
        bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
784
0
                                II->getName().equals(CorrectedStr);
785
0
        diagnoseTypo(Corrected,
786
0
                     PDiag(IsTemplateName
787
0
                               ? diag::err_no_member_template_suggest
788
0
                               : diag::err_unknown_nested_typename_suggest)
789
0
                         << II << DC << DroppedSpecifier << SS->getRange(),
790
0
                     CanRecover);
791
0
      } else {
792
0
        llvm_unreachable("could not have corrected a typo here");
793
0
      }
794
795
0
      if (!CanRecover)
796
0
        return;
797
798
0
      CXXScopeSpec tmpSS;
799
0
      if (Corrected.getCorrectionSpecifier())
800
0
        tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
801
0
                          SourceRange(IILoc));
802
      // FIXME: Support class template argument deduction here.
803
0
      SuggestedType =
804
0
          getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
805
0
                      tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
806
0
                      /*IsCtorOrDtorName=*/false,
807
0
                      /*WantNontrivialTypeSourceInfo=*/true);
808
0
    }
809
0
    return;
810
0
  }
811
812
10.2k
  if (getLangOpts().CPlusPlus && !IsTemplateName) {
813
    // See if II is a class template that the user forgot to pass arguments to.
814
4.87k
    UnqualifiedId Name;
815
4.87k
    Name.setIdentifier(II, IILoc);
816
4.87k
    CXXScopeSpec EmptySS;
817
4.87k
    TemplateTy TemplateResult;
818
4.87k
    bool MemberOfUnknownSpecialization;
819
4.87k
    if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
820
4.87k
                       Name, nullptr, true, TemplateResult,
821
4.87k
                       MemberOfUnknownSpecialization) == TNK_Type_template) {
822
0
      diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
823
0
      return;
824
0
    }
825
4.87k
  }
826
827
  // FIXME: Should we move the logic that tries to recover from a missing tag
828
  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
829
830
10.2k
  if (!SS || (!SS->isSet() && !SS->isInvalid()))
831
10.2k
    Diag(IILoc, IsTemplateName ? diag::err_no_template
832
10.2k
                               : diag::err_unknown_typename)
833
10.2k
        << II;
834
0
  else if (DeclContext *DC = computeDeclContext(*SS, false))
835
0
    Diag(IILoc, IsTemplateName ? diag::err_no_member_template
836
0
                               : diag::err_typename_nested_not_found)
837
0
        << II << DC << SS->getRange();
838
0
  else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
839
0
    SuggestedType =
840
0
        ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
841
0
  } else if (isDependentScopeSpecifier(*SS)) {
842
0
    unsigned DiagID = diag::err_typename_missing;
843
0
    if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
844
0
      DiagID = diag::ext_typename_missing;
845
846
0
    Diag(SS->getRange().getBegin(), DiagID)
847
0
      << SS->getScopeRep() << II->getName()
848
0
      << SourceRange(SS->getRange().getBegin(), IILoc)
849
0
      << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
850
0
    SuggestedType = ActOnTypenameType(S, SourceLocation(),
851
0
                                      *SS, *II, IILoc).get();
852
0
  } else {
853
0
    assert(SS && SS->isInvalid() &&
854
0
           "Invalid scope specifier has already been diagnosed");
855
0
  }
856
10.2k
}
857
858
/// Determine whether the given result set contains either a type name
859
/// or
860
0
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
861
0
  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
862
0
                       NextToken.is(tok::less);
863
864
0
  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
865
0
    if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
866
0
      return true;
867
868
0
    if (CheckTemplate && isa<TemplateDecl>(*I))
869
0
      return true;
870
0
  }
871
872
0
  return false;
873
0
}
874
875
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
876
                                    Scope *S, CXXScopeSpec &SS,
877
                                    IdentifierInfo *&Name,
878
0
                                    SourceLocation NameLoc) {
879
0
  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
880
0
  SemaRef.LookupParsedName(R, S, &SS);
881
0
  if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
882
0
    StringRef FixItTagName;
883
0
    switch (Tag->getTagKind()) {
884
0
    case TagTypeKind::Class:
885
0
      FixItTagName = "class ";
886
0
      break;
887
888
0
    case TagTypeKind::Enum:
889
0
      FixItTagName = "enum ";
890
0
      break;
891
892
0
    case TagTypeKind::Struct:
893
0
      FixItTagName = "struct ";
894
0
      break;
895
896
0
    case TagTypeKind::Interface:
897
0
      FixItTagName = "__interface ";
898
0
      break;
899
900
0
    case TagTypeKind::Union:
901
0
      FixItTagName = "union ";
902
0
      break;
903
0
    }
904
905
0
    StringRef TagName = FixItTagName.drop_back();
906
0
    SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
907
0
      << Name << TagName << SemaRef.getLangOpts().CPlusPlus
908
0
      << FixItHint::CreateInsertion(NameLoc, FixItTagName);
909
910
0
    for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
911
0
         I != IEnd; ++I)
912
0
      SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
913
0
        << Name << TagName;
914
915
    // Replace lookup results with just the tag decl.
916
0
    Result.clear(Sema::LookupTagName);
917
0
    SemaRef.LookupParsedName(Result, S, &SS);
918
0
    return true;
919
0
  }
920
921
0
  return false;
922
0
}
923
924
Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
925
                                            IdentifierInfo *&Name,
926
                                            SourceLocation NameLoc,
927
                                            const Token &NextToken,
928
178
                                            CorrectionCandidateCallback *CCC) {
929
178
  DeclarationNameInfo NameInfo(Name, NameLoc);
930
178
  ObjCMethodDecl *CurMethod = getCurMethodDecl();
931
932
178
  assert(NextToken.isNot(tok::coloncolon) &&
933
178
         "parse nested name specifiers before calling ClassifyName");
934
178
  if (getLangOpts().CPlusPlus && SS.isSet() &&
935
178
      isCurrentClassName(*Name, S, &SS)) {
936
    // Per [class.qual]p2, this names the constructors of SS, not the
937
    // injected-class-name. We don't have a classification for that.
938
    // There's not much point caching this result, since the parser
939
    // will reject it later.
940
0
    return NameClassification::Unknown();
941
0
  }
942
943
178
  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
944
178
  LookupParsedName(Result, S, &SS, !CurMethod);
945
946
178
  if (SS.isInvalid())
947
0
    return NameClassification::Error();
948
949
  // For unqualified lookup in a class template in MSVC mode, look into
950
  // dependent base classes where the primary class template is known.
951
178
  if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
952
0
    if (ParsedType TypeInBase =
953
0
            recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
954
0
      return TypeInBase;
955
0
  }
956
957
  // Perform lookup for Objective-C instance variables (including automatically
958
  // synthesized instance variables), if we're in an Objective-C method.
959
  // FIXME: This lookup really, really needs to be folded in to the normal
960
  // unqualified lookup mechanism.
961
178
  if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
962
0
    DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
963
0
    if (Ivar.isInvalid())
964
0
      return NameClassification::Error();
965
0
    if (Ivar.isUsable())
966
0
      return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
967
968
    // We defer builtin creation until after ivar lookup inside ObjC methods.
969
0
    if (Result.empty())
970
0
      LookupBuiltin(Result);
971
0
  }
972
973
178
  bool SecondTry = false;
974
178
  bool IsFilteredTemplateName = false;
975
976
178
Corrected:
977
178
  switch (Result.getResultKind()) {
978
135
  case LookupResult::NotFound:
979
    // If an unqualified-id is followed by a '(', then we have a function
980
    // call.
981
135
    if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
982
      // In C++, this is an ADL-only call.
983
      // FIXME: Reference?
984
0
      if (getLangOpts().CPlusPlus)
985
0
        return NameClassification::UndeclaredNonType();
986
987
      // C90 6.3.2.2:
988
      //   If the expression that precedes the parenthesized argument list in a
989
      //   function call consists solely of an identifier, and if no
990
      //   declaration is visible for this identifier, the identifier is
991
      //   implicitly declared exactly as if, in the innermost block containing
992
      //   the function call, the declaration
993
      //
994
      //     extern int identifier ();
995
      //
996
      //   appeared.
997
      //
998
      // We also allow this in C99 as an extension. However, this is not
999
      // allowed in all language modes as functions without prototypes may not
1000
      // be supported.
1001
0
      if (getLangOpts().implicitFunctionsAllowed()) {
1002
0
        if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
1003
0
          return NameClassification::NonType(D);
1004
0
      }
1005
0
    }
1006
1007
135
    if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
1008
      // In C++20 onwards, this could be an ADL-only call to a function
1009
      // template, and we're required to assume that this is a template name.
1010
      //
1011
      // FIXME: Find a way to still do typo correction in this case.
1012
0
      TemplateName Template =
1013
0
          Context.getAssumedTemplateName(NameInfo.getName());
1014
0
      return NameClassification::UndeclaredTemplate(Template);
1015
0
    }
1016
1017
    // In C, we first see whether there is a tag type by the same name, in
1018
    // which case it's likely that the user just forgot to write "enum",
1019
    // "struct", or "union".
1020
135
    if (!getLangOpts().CPlusPlus && !SecondTry &&
1021
135
        isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1022
0
      break;
1023
0
    }
1024
1025
    // Perform typo correction to determine if there is another name that is
1026
    // close to this name.
1027
135
    if (!SecondTry && CCC) {
1028
135
      SecondTry = true;
1029
135
      if (TypoCorrection Corrected =
1030
135
              CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1031
135
                          &SS, *CCC, CTK_ErrorRecovery)) {
1032
0
        unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1033
0
        unsigned QualifiedDiag = diag::err_no_member_suggest;
1034
1035
0
        NamedDecl *FirstDecl = Corrected.getFoundDecl();
1036
0
        NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1037
0
        if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1038
0
            UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1039
0
          UnqualifiedDiag = diag::err_no_template_suggest;
1040
0
          QualifiedDiag = diag::err_no_member_template_suggest;
1041
0
        } else if (UnderlyingFirstDecl &&
1042
0
                   (isa<TypeDecl>(UnderlyingFirstDecl) ||
1043
0
                    isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1044
0
                    isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1045
0
          UnqualifiedDiag = diag::err_unknown_typename_suggest;
1046
0
          QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1047
0
        }
1048
1049
0
        if (SS.isEmpty()) {
1050
0
          diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1051
0
        } else {// FIXME: is this even reachable? Test it.
1052
0
          std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1053
0
          bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1054
0
                                  Name->getName().equals(CorrectedStr);
1055
0
          diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1056
0
                                    << Name << computeDeclContext(SS, false)
1057
0
                                    << DroppedSpecifier << SS.getRange());
1058
0
        }
1059
1060
        // Update the name, so that the caller has the new name.
1061
0
        Name = Corrected.getCorrectionAsIdentifierInfo();
1062
1063
        // Typo correction corrected to a keyword.
1064
0
        if (Corrected.isKeyword())
1065
0
          return Name;
1066
1067
        // Also update the LookupResult...
1068
        // FIXME: This should probably go away at some point
1069
0
        Result.clear();
1070
0
        Result.setLookupName(Corrected.getCorrection());
1071
0
        if (FirstDecl)
1072
0
          Result.addDecl(FirstDecl);
1073
1074
        // If we found an Objective-C instance variable, let
1075
        // LookupInObjCMethod build the appropriate expression to
1076
        // reference the ivar.
1077
        // FIXME: This is a gross hack.
1078
0
        if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1079
0
          DeclResult R =
1080
0
              LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1081
0
          if (R.isInvalid())
1082
0
            return NameClassification::Error();
1083
0
          if (R.isUsable())
1084
0
            return NameClassification::NonType(Ivar);
1085
0
        }
1086
1087
0
        goto Corrected;
1088
0
      }
1089
135
    }
1090
1091
    // We failed to correct; just fall through and let the parser deal with it.
1092
135
    Result.suppressDiagnostics();
1093
135
    return NameClassification::Unknown();
1094
1095
0
  case LookupResult::NotFoundInCurrentInstantiation: {
1096
    // We performed name lookup into the current instantiation, and there were
1097
    // dependent bases, so we treat this result the same way as any other
1098
    // dependent nested-name-specifier.
1099
1100
    // C++ [temp.res]p2:
1101
    //   A name used in a template declaration or definition and that is
1102
    //   dependent on a template-parameter is assumed not to name a type
1103
    //   unless the applicable name lookup finds a type name or the name is
1104
    //   qualified by the keyword typename.
1105
    //
1106
    // FIXME: If the next token is '<', we might want to ask the parser to
1107
    // perform some heroics to see if we actually have a
1108
    // template-argument-list, which would indicate a missing 'template'
1109
    // keyword here.
1110
0
    return NameClassification::DependentNonType();
1111
135
  }
1112
1113
43
  case LookupResult::Found:
1114
43
  case LookupResult::FoundOverloaded:
1115
43
  case LookupResult::FoundUnresolvedValue:
1116
43
    break;
1117
1118
0
  case LookupResult::Ambiguous:
1119
0
    if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1120
0
        hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1121
0
                                      /*AllowDependent=*/false)) {
1122
      // C++ [temp.local]p3:
1123
      //   A lookup that finds an injected-class-name (10.2) can result in an
1124
      //   ambiguity in certain cases (for example, if it is found in more than
1125
      //   one base class). If all of the injected-class-names that are found
1126
      //   refer to specializations of the same class template, and if the name
1127
      //   is followed by a template-argument-list, the reference refers to the
1128
      //   class template itself and not a specialization thereof, and is not
1129
      //   ambiguous.
1130
      //
1131
      // This filtering can make an ambiguous result into an unambiguous one,
1132
      // so try again after filtering out template names.
1133
0
      FilterAcceptableTemplateNames(Result);
1134
0
      if (!Result.isAmbiguous()) {
1135
0
        IsFilteredTemplateName = true;
1136
0
        break;
1137
0
      }
1138
0
    }
1139
1140
    // Diagnose the ambiguity and return an error.
1141
0
    return NameClassification::Error();
1142
178
  }
1143
1144
43
  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1145
43
      (IsFilteredTemplateName ||
1146
0
       hasAnyAcceptableTemplateNames(
1147
0
           Result, /*AllowFunctionTemplates=*/true,
1148
0
           /*AllowDependent=*/false,
1149
0
           /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1150
0
               getLangOpts().CPlusPlus20))) {
1151
    // C++ [temp.names]p3:
1152
    //   After name lookup (3.4) finds that a name is a template-name or that
1153
    //   an operator-function-id or a literal- operator-id refers to a set of
1154
    //   overloaded functions any member of which is a function template if
1155
    //   this is followed by a <, the < is always taken as the delimiter of a
1156
    //   template-argument-list and never as the less-than operator.
1157
    // C++2a [temp.names]p2:
1158
    //   A name is also considered to refer to a template if it is an
1159
    //   unqualified-id followed by a < and name lookup finds either one
1160
    //   or more functions or finds nothing.
1161
0
    if (!IsFilteredTemplateName)
1162
0
      FilterAcceptableTemplateNames(Result);
1163
1164
0
    bool IsFunctionTemplate;
1165
0
    bool IsVarTemplate;
1166
0
    TemplateName Template;
1167
0
    if (Result.end() - Result.begin() > 1) {
1168
0
      IsFunctionTemplate = true;
1169
0
      Template = Context.getOverloadedTemplateName(Result.begin(),
1170
0
                                                   Result.end());
1171
0
    } else if (!Result.empty()) {
1172
0
      auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1173
0
          *Result.begin(), /*AllowFunctionTemplates=*/true,
1174
0
          /*AllowDependent=*/false));
1175
0
      IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1176
0
      IsVarTemplate = isa<VarTemplateDecl>(TD);
1177
1178
0
      UsingShadowDecl *FoundUsingShadow =
1179
0
          dyn_cast<UsingShadowDecl>(*Result.begin());
1180
0
      assert(!FoundUsingShadow ||
1181
0
             TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1182
0
      Template =
1183
0
          FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1184
0
      if (SS.isNotEmpty())
1185
0
        Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1186
0
                                                    /*TemplateKeyword=*/false,
1187
0
                                                    Template);
1188
0
    } else {
1189
      // All results were non-template functions. This is a function template
1190
      // name.
1191
0
      IsFunctionTemplate = true;
1192
0
      Template = Context.getAssumedTemplateName(NameInfo.getName());
1193
0
    }
1194
1195
0
    if (IsFunctionTemplate) {
1196
      // Function templates always go through overload resolution, at which
1197
      // point we'll perform the various checks (e.g., accessibility) we need
1198
      // to based on which function we selected.
1199
0
      Result.suppressDiagnostics();
1200
1201
0
      return NameClassification::FunctionTemplate(Template);
1202
0
    }
1203
1204
0
    return IsVarTemplate ? NameClassification::VarTemplate(Template)
1205
0
                         : NameClassification::TypeTemplate(Template);
1206
0
  }
1207
1208
43
  auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1209
0
    QualType T = Context.getTypeDeclType(Type);
1210
0
    if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1211
0
      T = Context.getUsingType(USD, T);
1212
0
    return buildNamedType(*this, &SS, T, NameLoc);
1213
0
  };
1214
1215
43
  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1216
43
  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1217
0
    DiagnoseUseOfDecl(Type, NameLoc);
1218
0
    MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1219
0
    return BuildTypeFor(Type, *Result.begin());
1220
0
  }
1221
1222
43
  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1223
43
  if (!Class) {
1224
    // FIXME: It's unfortunate that we don't have a Type node for handling this.
1225
43
    if (ObjCCompatibleAliasDecl *Alias =
1226
43
            dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1227
0
      Class = Alias->getClassInterface();
1228
43
  }
1229
1230
43
  if (Class) {
1231
0
    DiagnoseUseOfDecl(Class, NameLoc);
1232
1233
0
    if (NextToken.is(tok::period)) {
1234
      // Interface. <something> is parsed as a property reference expression.
1235
      // Just return "unknown" as a fall-through for now.
1236
0
      Result.suppressDiagnostics();
1237
0
      return NameClassification::Unknown();
1238
0
    }
1239
1240
0
    QualType T = Context.getObjCInterfaceType(Class);
1241
0
    return ParsedType::make(T);
1242
0
  }
1243
1244
43
  if (isa<ConceptDecl>(FirstDecl))
1245
0
    return NameClassification::Concept(
1246
0
        TemplateName(cast<TemplateDecl>(FirstDecl)));
1247
1248
43
  if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1249
0
    (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1250
0
    return NameClassification::Error();
1251
0
  }
1252
1253
  // We can have a type template here if we're classifying a template argument.
1254
43
  if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1255
43
      !isa<VarTemplateDecl>(FirstDecl))
1256
0
    return NameClassification::TypeTemplate(
1257
0
        TemplateName(cast<TemplateDecl>(FirstDecl)));
1258
1259
  // Check for a tag type hidden by a non-type decl in a few cases where it
1260
  // seems likely a type is wanted instead of the non-type that was found.
1261
43
  bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1262
43
  if ((NextToken.is(tok::identifier) ||
1263
43
       (NextIsOp &&
1264
43
        FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1265
43
      isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1266
0
    TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1267
0
    DiagnoseUseOfDecl(Type, NameLoc);
1268
0
    return BuildTypeFor(Type, *Result.begin());
1269
0
  }
1270
1271
  // If we already know which single declaration is referenced, just annotate
1272
  // that declaration directly. Defer resolving even non-overloaded class
1273
  // member accesses, as we need to defer certain access checks until we know
1274
  // the context.
1275
43
  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1276
43
  if (Result.isSingleResult() && !ADL &&
1277
43
      (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1278
43
    return NameClassification::NonType(Result.getRepresentativeDecl());
1279
1280
  // Otherwise, this is an overload set that we will need to resolve later.
1281
0
  Result.suppressDiagnostics();
1282
0
  return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1283
0
      Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1284
0
      Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1285
0
      Result.begin(), Result.end()));
1286
43
}
1287
1288
ExprResult
1289
Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1290
0
                                             SourceLocation NameLoc) {
1291
0
  assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1292
0
  CXXScopeSpec SS;
1293
0
  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1294
0
  return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1295
0
}
1296
1297
ExprResult
1298
Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1299
                                            IdentifierInfo *Name,
1300
                                            SourceLocation NameLoc,
1301
0
                                            bool IsAddressOfOperand) {
1302
0
  DeclarationNameInfo NameInfo(Name, NameLoc);
1303
0
  return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1304
0
                                    NameInfo, IsAddressOfOperand,
1305
0
                                    /*TemplateArgs=*/nullptr);
1306
0
}
1307
1308
ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1309
                                              NamedDecl *Found,
1310
                                              SourceLocation NameLoc,
1311
42
                                              const Token &NextToken) {
1312
42
  if (getCurMethodDecl() && SS.isEmpty())
1313
0
    if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1314
0
      return BuildIvarRefExpr(S, NameLoc, Ivar);
1315
1316
  // Reconstruct the lookup result.
1317
42
  LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1318
42
  Result.addDecl(Found);
1319
42
  Result.resolveKind();
1320
1321
42
  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1322
42
  return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1323
42
}
1324
1325
0
ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1326
  // For an implicit class member access, transform the result into a member
1327
  // access expression if necessary.
1328
0
  auto *ULE = cast<UnresolvedLookupExpr>(E);
1329
0
  if ((*ULE->decls_begin())->isCXXClassMember()) {
1330
0
    CXXScopeSpec SS;
1331
0
    SS.Adopt(ULE->getQualifierLoc());
1332
1333
    // Reconstruct the lookup result.
1334
0
    LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1335
0
                        LookupOrdinaryName);
1336
0
    Result.setNamingClass(ULE->getNamingClass());
1337
0
    for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1338
0
      Result.addDecl(*I, I.getAccess());
1339
0
    Result.resolveKind();
1340
0
    return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1341
0
                                           nullptr, S);
1342
0
  }
1343
1344
  // Otherwise, this is already in the form we needed, and no further checks
1345
  // are necessary.
1346
0
  return ULE;
1347
0
}
1348
1349
Sema::TemplateNameKindForDiagnostics
1350
0
Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1351
0
  auto *TD = Name.getAsTemplateDecl();
1352
0
  if (!TD)
1353
0
    return TemplateNameKindForDiagnostics::DependentTemplate;
1354
0
  if (isa<ClassTemplateDecl>(TD))
1355
0
    return TemplateNameKindForDiagnostics::ClassTemplate;
1356
0
  if (isa<FunctionTemplateDecl>(TD))
1357
0
    return TemplateNameKindForDiagnostics::FunctionTemplate;
1358
0
  if (isa<VarTemplateDecl>(TD))
1359
0
    return TemplateNameKindForDiagnostics::VarTemplate;
1360
0
  if (isa<TypeAliasTemplateDecl>(TD))
1361
0
    return TemplateNameKindForDiagnostics::AliasTemplate;
1362
0
  if (isa<TemplateTemplateParmDecl>(TD))
1363
0
    return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1364
0
  if (isa<ConceptDecl>(TD))
1365
0
    return TemplateNameKindForDiagnostics::Concept;
1366
0
  return TemplateNameKindForDiagnostics::DependentTemplate;
1367
0
}
1368
1369
51
void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1370
51
  assert(DC->getLexicalParent() == CurContext &&
1371
51
      "The next DeclContext should be lexically contained in the current one.");
1372
0
  CurContext = DC;
1373
51
  S->setEntity(DC);
1374
51
}
1375
1376
5
void Sema::PopDeclContext() {
1377
5
  assert(CurContext && "DeclContext imbalance!");
1378
1379
0
  CurContext = CurContext->getLexicalParent();
1380
5
  assert(CurContext && "Popped translation unit!");
1381
5
}
1382
1383
Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1384
0
                                                                    Decl *D) {
1385
  // Unlike PushDeclContext, the context to which we return is not necessarily
1386
  // the containing DC of TD, because the new context will be some pre-existing
1387
  // TagDecl definition instead of a fresh one.
1388
0
  auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1389
0
  CurContext = cast<TagDecl>(D)->getDefinition();
1390
0
  assert(CurContext && "skipping definition of undefined tag");
1391
  // Start lookups from the parent of the current context; we don't want to look
1392
  // into the pre-existing complete definition.
1393
0
  S->setEntity(CurContext->getLookupParent());
1394
0
  return Result;
1395
0
}
1396
1397
0
void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1398
0
  CurContext = static_cast<decltype(CurContext)>(Context);
1399
0
}
1400
1401
/// EnterDeclaratorContext - Used when we must lookup names in the context
1402
/// of a declarator's nested name specifier.
1403
///
1404
0
void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1405
  // C++0x [basic.lookup.unqual]p13:
1406
  //   A name used in the definition of a static data member of class
1407
  //   X (after the qualified-id of the static member) is looked up as
1408
  //   if the name was used in a member function of X.
1409
  // C++0x [basic.lookup.unqual]p14:
1410
  //   If a variable member of a namespace is defined outside of the
1411
  //   scope of its namespace then any name used in the definition of
1412
  //   the variable member (after the declarator-id) is looked up as
1413
  //   if the definition of the variable member occurred in its
1414
  //   namespace.
1415
  // Both of these imply that we should push a scope whose context
1416
  // is the semantic context of the declaration.  We can't use
1417
  // PushDeclContext here because that context is not necessarily
1418
  // lexically contained in the current context.  Fortunately,
1419
  // the containing scope should have the appropriate information.
1420
1421
0
  assert(!S->getEntity() && "scope already has entity");
1422
1423
0
#ifndef NDEBUG
1424
0
  Scope *Ancestor = S->getParent();
1425
0
  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1426
0
  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1427
0
#endif
1428
1429
0
  CurContext = DC;
1430
0
  S->setEntity(DC);
1431
1432
0
  if (S->getParent()->isTemplateParamScope()) {
1433
    // Also set the corresponding entities for all immediately-enclosing
1434
    // template parameter scopes.
1435
0
    EnterTemplatedContext(S->getParent(), DC);
1436
0
  }
1437
0
}
1438
1439
0
void Sema::ExitDeclaratorContext(Scope *S) {
1440
0
  assert(S->getEntity() == CurContext && "Context imbalance!");
1441
1442
  // Switch back to the lexical context.  The safety of this is
1443
  // enforced by an assert in EnterDeclaratorContext.
1444
0
  Scope *Ancestor = S->getParent();
1445
0
  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1446
0
  CurContext = Ancestor->getEntity();
1447
1448
  // We don't need to do anything with the scope, which is going to
1449
  // disappear.
1450
0
}
1451
1452
0
void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1453
0
  assert(S->isTemplateParamScope() &&
1454
0
         "expected to be initializing a template parameter scope");
1455
1456
  // C++20 [temp.local]p7:
1457
  //   In the definition of a member of a class template that appears outside
1458
  //   of the class template definition, the name of a member of the class
1459
  //   template hides the name of a template-parameter of any enclosing class
1460
  //   templates (but not a template-parameter of the member if the member is a
1461
  //   class or function template).
1462
  // C++20 [temp.local]p9:
1463
  //   In the definition of a class template or in the definition of a member
1464
  //   of such a template that appears outside of the template definition, for
1465
  //   each non-dependent base class (13.8.2.1), if the name of the base class
1466
  //   or the name of a member of the base class is the same as the name of a
1467
  //   template-parameter, the base class name or member name hides the
1468
  //   template-parameter name (6.4.10).
1469
  //
1470
  // This means that a template parameter scope should be searched immediately
1471
  // after searching the DeclContext for which it is a template parameter
1472
  // scope. For example, for
1473
  //   template<typename T> template<typename U> template<typename V>
1474
  //     void N::A<T>::B<U>::f(...)
1475
  // we search V then B<U> (and base classes) then U then A<T> (and base
1476
  // classes) then T then N then ::.
1477
0
  unsigned ScopeDepth = getTemplateDepth(S);
1478
0
  for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1479
0
    DeclContext *SearchDCAfterScope = DC;
1480
0
    for (; DC; DC = DC->getLookupParent()) {
1481
0
      if (const TemplateParameterList *TPL =
1482
0
              cast<Decl>(DC)->getDescribedTemplateParams()) {
1483
0
        unsigned DCDepth = TPL->getDepth() + 1;
1484
0
        if (DCDepth > ScopeDepth)
1485
0
          continue;
1486
0
        if (ScopeDepth == DCDepth)
1487
0
          SearchDCAfterScope = DC = DC->getLookupParent();
1488
0
        break;
1489
0
      }
1490
0
    }
1491
0
    S->setLookupEntity(SearchDCAfterScope);
1492
0
  }
1493
0
}
1494
1495
0
void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1496
  // We assume that the caller has already called
1497
  // ActOnReenterTemplateScope so getTemplatedDecl() works.
1498
0
  FunctionDecl *FD = D->getAsFunction();
1499
0
  if (!FD)
1500
0
    return;
1501
1502
  // Same implementation as PushDeclContext, but enters the context
1503
  // from the lexical parent, rather than the top-level class.
1504
0
  assert(CurContext == FD->getLexicalParent() &&
1505
0
    "The next DeclContext should be lexically contained in the current one.");
1506
0
  CurContext = FD;
1507
0
  S->setEntity(CurContext);
1508
1509
0
  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1510
0
    ParmVarDecl *Param = FD->getParamDecl(P);
1511
    // If the parameter has an identifier, then add it to the scope
1512
0
    if (Param->getIdentifier()) {
1513
0
      S->AddDecl(Param);
1514
0
      IdResolver.AddDecl(Param);
1515
0
    }
1516
0
  }
1517
0
}
1518
1519
0
void Sema::ActOnExitFunctionContext() {
1520
  // Same implementation as PopDeclContext, but returns to the lexical parent,
1521
  // rather than the top-level class.
1522
0
  assert(CurContext && "DeclContext imbalance!");
1523
0
  CurContext = CurContext->getLexicalParent();
1524
0
  assert(CurContext && "Popped translation unit!");
1525
0
}
1526
1527
/// Determine whether overloading is allowed for a new function
1528
/// declaration considering prior declarations of the same name.
1529
///
1530
/// This routine determines whether overloading is possible, not
1531
/// whether a new declaration actually overloads a previous one.
1532
/// It will return true in C++ (where overloads are alway permitted)
1533
/// or, as a C extension, when either the new declaration or a
1534
/// previous one is declared with the 'overloadable' attribute.
1535
static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1536
                                       ASTContext &Context,
1537
3
                                       const FunctionDecl *New) {
1538
3
  if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1539
0
    return true;
1540
1541
  // Multiversion function declarations are not overloads in the
1542
  // usual sense of that term, but lookup will report that an
1543
  // overload set was found if more than one multiversion function
1544
  // declaration is present for the same name. It is therefore
1545
  // inadequate to assume that some prior declaration(s) had
1546
  // the overloadable attribute; checking is required. Since one
1547
  // declaration is permitted to omit the attribute, it is necessary
1548
  // to check at least two; hence the 'any_of' check below. Note that
1549
  // the overloadable attribute is implicitly added to declarations
1550
  // that were required to have it but did not.
1551
3
  if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1552
0
    return llvm::any_of(Previous, [](const NamedDecl *ND) {
1553
0
      return ND->hasAttr<OverloadableAttr>();
1554
0
    });
1555
3
  } else if (Previous.getResultKind() == LookupResult::Found)
1556
3
    return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1557
1558
0
  return false;
1559
3
}
1560
1561
/// Add this decl to the scope shadowed decl chains.
1562
5.41k
void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1563
  // Move up the scope chain until we find the nearest enclosing
1564
  // non-transparent context. The declaration will be introduced into this
1565
  // scope.
1566
5.41k
  while (S->getEntity() && S->getEntity()->isTransparentContext())
1567
0
    S = S->getParent();
1568
1569
  // Add scoped declarations into their context, so that they can be
1570
  // found later. Declarations without a context won't be inserted
1571
  // into any context.
1572
5.41k
  if (AddToContext)
1573
5.41k
    CurContext->addDecl(D);
1574
1575
  // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1576
  // are function-local declarations.
1577
5.41k
  if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1578
0
    return;
1579
1580
  // Template instantiations should also not be pushed into scope.
1581
5.41k
  if (isa<FunctionDecl>(D) &&
1582
5.41k
      cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1583
0
    return;
1584
1585
  // If this replaces anything in the current scope,
1586
5.41k
  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1587
5.41k
                               IEnd = IdResolver.end();
1588
25.2k
  for (; I != IEnd; ++I) {
1589
20.0k
    if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1590
183
      S->RemoveDecl(*I);
1591
183
      IdResolver.RemoveDecl(*I);
1592
1593
      // Should only need to replace one decl.
1594
183
      break;
1595
183
    }
1596
20.0k
  }
1597
1598
5.41k
  S->AddDecl(D);
1599
1600
5.41k
  if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1601
    // Implicitly-generated labels may end up getting generated in an order that
1602
    // isn't strictly lexical, which breaks name lookup. Be careful to insert
1603
    // the label at the appropriate place in the identifier chain.
1604
0
    for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1605
0
      DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1606
0
      if (IDC == CurContext) {
1607
0
        if (!S->isDeclScope(*I))
1608
0
          continue;
1609
0
      } else if (IDC->Encloses(CurContext))
1610
0
        break;
1611
0
    }
1612
1613
0
    IdResolver.InsertDeclAfter(I, D);
1614
5.41k
  } else {
1615
5.41k
    IdResolver.AddDecl(D);
1616
5.41k
  }
1617
5.41k
  warnOnReservedIdentifier(D);
1618
5.41k
}
1619
1620
bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1621
2.19k
                         bool AllowInlineNamespace) const {
1622
2.19k
  return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1623
2.19k
}
1624
1625
0
Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1626
0
  DeclContext *TargetDC = DC->getPrimaryContext();
1627
0
  do {
1628
0
    if (DeclContext *ScopeDC = S->getEntity())
1629
0
      if (ScopeDC->getPrimaryContext() == TargetDC)
1630
0
        return S;
1631
0
  } while ((S = S->getParent()));
1632
1633
0
  return nullptr;
1634
0
}
1635
1636
static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1637
                                            DeclContext*,
1638
                                            ASTContext&);
1639
1640
/// Filters out lookup results that don't fall within the given scope
1641
/// as determined by isDeclInScope.
1642
void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1643
                                bool ConsiderLinkage,
1644
5.08k
                                bool AllowInlineNamespace) {
1645
5.08k
  LookupResult::Filter F = R.makeFilter();
1646
7.28k
  while (F.hasNext()) {
1647
2.19k
    NamedDecl *D = F.next();
1648
1649
2.19k
    if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1650
2.19k
      continue;
1651
1652
0
    if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1653
0
      continue;
1654
1655
0
    F.erase();
1656
0
  }
1657
1658
5.08k
  F.done();
1659
5.08k
}
1660
1661
/// We've determined that \p New is a redeclaration of \p Old. Check that they
1662
/// have compatible owning modules.
1663
183
bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1664
  // [module.interface]p7:
1665
  // A declaration is attached to a module as follows:
1666
  // - If the declaration is a non-dependent friend declaration that nominates a
1667
  // function with a declarator-id that is a qualified-id or template-id or that
1668
  // nominates a class other than with an elaborated-type-specifier with neither
1669
  // a nested-name-specifier nor a simple-template-id, it is attached to the
1670
  // module to which the friend is attached ([basic.link]).
1671
183
  if (New->getFriendObjectKind() &&
1672
183
      Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1673
0
    New->setLocalOwningModule(Old->getOwningModule());
1674
0
    makeMergedDefinitionVisible(New);
1675
0
    return false;
1676
0
  }
1677
1678
183
  Module *NewM = New->getOwningModule();
1679
183
  Module *OldM = Old->getOwningModule();
1680
1681
183
  if (NewM && NewM->isPrivateModule())
1682
0
    NewM = NewM->Parent;
1683
183
  if (OldM && OldM->isPrivateModule())
1684
0
    OldM = OldM->Parent;
1685
1686
183
  if (NewM == OldM)
1687
183
    return false;
1688
1689
0
  if (NewM && OldM) {
1690
    // A module implementation unit has visibility of the decls in its
1691
    // implicitly imported interface.
1692
0
    if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1693
0
      return false;
1694
1695
    // Partitions are part of the module, but a partition could import another
1696
    // module, so verify that the PMIs agree.
1697
0
    if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1698
0
        NewM->getPrimaryModuleInterfaceName() ==
1699
0
            OldM->getPrimaryModuleInterfaceName())
1700
0
      return false;
1701
0
  }
1702
1703
0
  bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1704
0
  bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1705
0
  if (NewIsModuleInterface || OldIsModuleInterface) {
1706
    // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1707
    //   if a declaration of D [...] appears in the purview of a module, all
1708
    //   other such declarations shall appear in the purview of the same module
1709
0
    Diag(New->getLocation(), diag::err_mismatched_owning_module)
1710
0
      << New
1711
0
      << NewIsModuleInterface
1712
0
      << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1713
0
      << OldIsModuleInterface
1714
0
      << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1715
0
    Diag(Old->getLocation(), diag::note_previous_declaration);
1716
0
    New->setInvalidDecl();
1717
0
    return true;
1718
0
  }
1719
1720
0
  return false;
1721
0
}
1722
1723
// [module.interface]p6:
1724
// A redeclaration of an entity X is implicitly exported if X was introduced by
1725
// an exported declaration; otherwise it shall not be exported.
1726
183
bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1727
  // [module.interface]p1:
1728
  // An export-declaration shall inhabit a namespace scope.
1729
  //
1730
  // So it is meaningless to talk about redeclaration which is not at namespace
1731
  // scope.
1732
183
  if (!New->getLexicalDeclContext()
1733
183
           ->getNonTransparentContext()
1734
183
           ->isFileContext() ||
1735
183
      !Old->getLexicalDeclContext()
1736
183
           ->getNonTransparentContext()
1737
183
           ->isFileContext())
1738
0
    return false;
1739
1740
183
  bool IsNewExported = New->isInExportDeclContext();
1741
183
  bool IsOldExported = Old->isInExportDeclContext();
1742
1743
  // It should be irrevelant if both of them are not exported.
1744
183
  if (!IsNewExported && !IsOldExported)
1745
183
    return false;
1746
1747
0
  if (IsOldExported)
1748
0
    return false;
1749
1750
0
  assert(IsNewExported);
1751
1752
0
  auto Lk = Old->getFormalLinkage();
1753
0
  int S = 0;
1754
0
  if (Lk == Linkage::Internal)
1755
0
    S = 1;
1756
0
  else if (Lk == Linkage::Module)
1757
0
    S = 2;
1758
0
  Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1759
0
  Diag(Old->getLocation(), diag::note_previous_declaration);
1760
0
  return true;
1761
0
}
1762
1763
// A wrapper function for checking the semantic restrictions of
1764
// a redeclaration within a module.
1765
183
bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1766
183
  if (CheckRedeclarationModuleOwnership(New, Old))
1767
0
    return true;
1768
1769
183
  if (CheckRedeclarationExported(New, Old))
1770
0
    return true;
1771
1772
183
  return false;
1773
183
}
1774
1775
// Check the redefinition in C++20 Modules.
1776
//
1777
// [basic.def.odr]p14:
1778
// For any definable item D with definitions in multiple translation units,
1779
// - if D is a non-inline non-templated function or variable, or
1780
// - if the definitions in different translation units do not satisfy the
1781
// following requirements,
1782
//   the program is ill-formed; a diagnostic is required only if the definable
1783
//   item is attached to a named module and a prior definition is reachable at
1784
//   the point where a later definition occurs.
1785
// - Each such definition shall not be attached to a named module
1786
// ([module.unit]).
1787
// - Each such definition shall consist of the same sequence of tokens, ...
1788
// ...
1789
//
1790
// Return true if the redefinition is not allowed. Return false otherwise.
1791
bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1792
0
                                     const NamedDecl *Old) const {
1793
0
  assert(getASTContext().isSameEntity(New, Old) &&
1794
0
         "New and Old are not the same definition, we should diagnostic it "
1795
0
         "immediately instead of checking it.");
1796
0
  assert(const_cast<Sema *>(this)->isReachable(New) &&
1797
0
         const_cast<Sema *>(this)->isReachable(Old) &&
1798
0
         "We shouldn't see unreachable definitions here.");
1799
1800
0
  Module *NewM = New->getOwningModule();
1801
0
  Module *OldM = Old->getOwningModule();
1802
1803
  // We only checks for named modules here. The header like modules is skipped.
1804
  // FIXME: This is not right if we import the header like modules in the module
1805
  // purview.
1806
  //
1807
  // For example, assuming "header.h" provides definition for `D`.
1808
  // ```C++
1809
  // //--- M.cppm
1810
  // export module M;
1811
  // import "header.h"; // or #include "header.h" but import it by clang modules
1812
  // actually.
1813
  //
1814
  // //--- Use.cpp
1815
  // import M;
1816
  // import "header.h"; // or uses clang modules.
1817
  // ```
1818
  //
1819
  // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1820
  // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1821
  // reject it. But the current implementation couldn't detect the case since we
1822
  // don't record the information about the importee modules.
1823
  //
1824
  // But this might not be painful in practice. Since the design of C++20 Named
1825
  // Modules suggests us to use headers in global module fragment instead of
1826
  // module purview.
1827
0
  if (NewM && NewM->isHeaderLikeModule())
1828
0
    NewM = nullptr;
1829
0
  if (OldM && OldM->isHeaderLikeModule())
1830
0
    OldM = nullptr;
1831
1832
0
  if (!NewM && !OldM)
1833
0
    return true;
1834
1835
  // [basic.def.odr]p14.3
1836
  // Each such definition shall not be attached to a named module
1837
  // ([module.unit]).
1838
0
  if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1839
0
    return true;
1840
1841
  // Then New and Old lives in the same TU if their share one same module unit.
1842
0
  if (NewM)
1843
0
    NewM = NewM->getTopLevelModule();
1844
0
  if (OldM)
1845
0
    OldM = OldM->getTopLevelModule();
1846
0
  return OldM == NewM;
1847
0
}
1848
1849
0
static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1850
0
  if (D->getDeclContext()->isFileContext())
1851
0
    return false;
1852
1853
0
  return isa<UsingShadowDecl>(D) ||
1854
0
         isa<UnresolvedUsingTypenameDecl>(D) ||
1855
0
         isa<UnresolvedUsingValueDecl>(D);
1856
0
}
1857
1858
/// Removes using shadow declarations not at class scope from the lookup
1859
/// results.
1860
0
static void RemoveUsingDecls(LookupResult &R) {
1861
0
  LookupResult::Filter F = R.makeFilter();
1862
0
  while (F.hasNext())
1863
0
    if (isUsingDeclNotAtClassScope(F.next()))
1864
0
      F.erase();
1865
1866
0
  F.done();
1867
0
}
1868
1869
/// Check for this common pattern:
1870
/// @code
1871
/// class S {
1872
///   S(const S&); // DO NOT IMPLEMENT
1873
///   void operator=(const S&); // DO NOT IMPLEMENT
1874
/// };
1875
/// @endcode
1876
0
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1877
  // FIXME: Should check for private access too but access is set after we get
1878
  // the decl here.
1879
0
  if (D->doesThisDeclarationHaveABody())
1880
0
    return false;
1881
1882
0
  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1883
0
    return CD->isCopyConstructor();
1884
0
  return D->isCopyAssignmentOperator();
1885
0
}
1886
1887
// We need this to handle
1888
//
1889
// typedef struct {
1890
//   void *foo() { return 0; }
1891
// } A;
1892
//
1893
// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1894
// for example. If 'A', foo will have external linkage. If we have '*A',
1895
// foo will have no linkage. Since we can't know until we get to the end
1896
// of the typedef, this function finds out if D might have non-external linkage.
1897
// Callers should verify at the end of the TU if it D has external linkage or
1898
// not.
1899
6
bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1900
6
  const DeclContext *DC = D->getDeclContext();
1901
6
  while (!DC->isTranslationUnit()) {
1902
0
    if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1903
0
      if (!RD->hasNameForLinkage())
1904
0
        return true;
1905
0
    }
1906
0
    DC = DC->getParent();
1907
0
  }
1908
1909
6
  return !D->isExternallyVisible();
1910
6
}
1911
1912
// FIXME: This needs to be refactored; some other isInMainFile users want
1913
// these semantics.
1914
502
static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1915
502
  if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1916
0
    return false;
1917
502
  return S.SourceMgr.isInMainFile(Loc);
1918
502
}
1919
1920
5.27k
bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1921
5.27k
  assert(D);
1922
1923
5.27k
  if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1924
4.76k
    return false;
1925
1926
  // Ignore all entities declared within templates, and out-of-line definitions
1927
  // of members of class templates.
1928
508
  if (D->getDeclContext()->isDependentContext() ||
1929
508
      D->getLexicalDeclContext()->isDependentContext())
1930
0
    return false;
1931
1932
508
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1933
6
    if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1934
0
      return false;
1935
    // A non-out-of-line declaration of a member specialization was implicitly
1936
    // instantiated; it's the out-of-line declaration that we're interested in.
1937
6
    if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1938
6
        FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1939
0
      return false;
1940
1941
6
    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1942
0
      if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1943
0
        return false;
1944
6
    } else {
1945
      // 'static inline' functions are defined in headers; don't warn.
1946
6
      if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1947
0
        return false;
1948
6
    }
1949
1950
6
    if (FD->doesThisDeclarationHaveABody() &&
1951
6
        Context.DeclMustBeEmitted(FD))
1952
0
      return false;
1953
502
  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1954
    // Constants and utility variables are defined in headers with internal
1955
    // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1956
    // like "inline".)
1957
502
    if (!isMainFileLoc(*this, VD->getLocation()))
1958
0
      return false;
1959
1960
502
    if (Context.DeclMustBeEmitted(VD))
1961
502
      return false;
1962
1963
0
    if (VD->isStaticDataMember() &&
1964
0
        VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1965
0
      return false;
1966
0
    if (VD->isStaticDataMember() &&
1967
0
        VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1968
0
        VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1969
0
      return false;
1970
1971
0
    if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1972
0
      return false;
1973
0
  } else {
1974
0
    return false;
1975
0
  }
1976
1977
  // Only warn for unused decls internal to the translation unit.
1978
  // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1979
  // for inline functions defined in the main source file, for instance.
1980
6
  return mightHaveNonExternalLinkage(D);
1981
508
}
1982
1983
5.08k
void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1984
5.08k
  if (!D)
1985
0
    return;
1986
1987
5.08k
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1988
19
    const FunctionDecl *First = FD->getFirstDecl();
1989
19
    if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1990
0
      return; // First should already be in the vector.
1991
19
  }
1992
1993
5.08k
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1994
5.07k
    const VarDecl *First = VD->getFirstDecl();
1995
5.07k
    if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1996
0
      return; // First should already be in the vector.
1997
5.07k
  }
1998
1999
5.08k
  if (ShouldWarnIfUnusedFileScopedDecl(D))
2000
0
    UnusedFileScopedDecls.push_back(D);
2001
5.08k
}
2002
2003
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2004
0
                                     const NamedDecl *D) {
2005
0
  if (D->isInvalidDecl())
2006
0
    return false;
2007
2008
0
  if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
2009
    // For a decomposition declaration, warn if none of the bindings are
2010
    // referenced, instead of if the variable itself is referenced (which
2011
    // it is, by the bindings' expressions).
2012
0
    bool IsAllPlaceholders = true;
2013
0
    for (const auto *BD : DD->bindings()) {
2014
0
      if (BD->isReferenced())
2015
0
        return false;
2016
0
      IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
2017
0
    }
2018
0
    if (IsAllPlaceholders)
2019
0
      return false;
2020
0
  } else if (!D->getDeclName()) {
2021
0
    return false;
2022
0
  } else if (D->isReferenced() || D->isUsed()) {
2023
0
    return false;
2024
0
  }
2025
2026
0
  if (D->isPlaceholderVar(LangOpts))
2027
0
    return false;
2028
2029
0
  if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2030
0
      D->hasAttr<CleanupAttr>())
2031
0
    return false;
2032
2033
0
  if (isa<LabelDecl>(D))
2034
0
    return true;
2035
2036
  // Except for labels, we only care about unused decls that are local to
2037
  // functions.
2038
0
  bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2039
0
  if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2040
    // For dependent types, the diagnostic is deferred.
2041
0
    WithinFunction =
2042
0
        WithinFunction || (R->isLocalClass() && !R->isDependentType());
2043
0
  if (!WithinFunction)
2044
0
    return false;
2045
2046
0
  if (isa<TypedefNameDecl>(D))
2047
0
    return true;
2048
2049
  // White-list anything that isn't a local variable.
2050
0
  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2051
0
    return false;
2052
2053
  // Types of valid local variables should be complete, so this should succeed.
2054
0
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2055
2056
0
    const Expr *Init = VD->getInit();
2057
0
    if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2058
0
      Init = Cleanups->getSubExpr();
2059
2060
0
    const auto *Ty = VD->getType().getTypePtr();
2061
2062
    // Only look at the outermost level of typedef.
2063
0
    if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2064
      // Allow anything marked with __attribute__((unused)).
2065
0
      if (TT->getDecl()->hasAttr<UnusedAttr>())
2066
0
        return false;
2067
0
    }
2068
2069
    // Warn for reference variables whose initializtion performs lifetime
2070
    // extension.
2071
0
    if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2072
0
        MTE && MTE->getExtendingDecl()) {
2073
0
      Ty = VD->getType().getNonReferenceType().getTypePtr();
2074
0
      Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2075
0
    }
2076
2077
    // If we failed to complete the type for some reason, or if the type is
2078
    // dependent, don't diagnose the variable.
2079
0
    if (Ty->isIncompleteType() || Ty->isDependentType())
2080
0
      return false;
2081
2082
    // Look at the element type to ensure that the warning behaviour is
2083
    // consistent for both scalars and arrays.
2084
0
    Ty = Ty->getBaseElementTypeUnsafe();
2085
2086
0
    if (const TagType *TT = Ty->getAs<TagType>()) {
2087
0
      const TagDecl *Tag = TT->getDecl();
2088
0
      if (Tag->hasAttr<UnusedAttr>())
2089
0
        return false;
2090
2091
0
      if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2092
0
        if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2093
0
          return false;
2094
2095
0
        if (Init) {
2096
0
          const auto *Construct = dyn_cast<CXXConstructExpr>(Init);
2097
0
          if (Construct && !Construct->isElidable()) {
2098
0
            const CXXConstructorDecl *CD = Construct->getConstructor();
2099
0
            if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2100
0
                (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2101
0
              return false;
2102
0
          }
2103
2104
          // Suppress the warning if we don't know how this is constructed, and
2105
          // it could possibly be non-trivial constructor.
2106
0
          if (Init->isTypeDependent()) {
2107
0
            for (const CXXConstructorDecl *Ctor : RD->ctors())
2108
0
              if (!Ctor->isTrivial())
2109
0
                return false;
2110
0
          }
2111
2112
          // Suppress the warning if the constructor is unresolved because
2113
          // its arguments are dependent.
2114
0
          if (isa<CXXUnresolvedConstructExpr>(Init))
2115
0
            return false;
2116
0
        }
2117
0
      }
2118
0
    }
2119
2120
    // TODO: __attribute__((unused)) templates?
2121
0
  }
2122
2123
0
  return true;
2124
0
}
2125
2126
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2127
0
                                     FixItHint &Hint) {
2128
0
  if (isa<LabelDecl>(D)) {
2129
0
    SourceLocation AfterColon = Lexer::findLocationAfterToken(
2130
0
        D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2131
0
        /*SkipTrailingWhitespaceAndNewline=*/false);
2132
0
    if (AfterColon.isInvalid())
2133
0
      return;
2134
0
    Hint = FixItHint::CreateRemoval(
2135
0
        CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2136
0
  }
2137
0
}
2138
2139
0
void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2140
0
  DiagnoseUnusedNestedTypedefs(
2141
0
      D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2142
0
}
2143
2144
void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2145
0
                                        DiagReceiverTy DiagReceiver) {
2146
0
  if (D->getTypeForDecl()->isDependentType())
2147
0
    return;
2148
2149
0
  for (auto *TmpD : D->decls()) {
2150
0
    if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2151
0
      DiagnoseUnusedDecl(T, DiagReceiver);
2152
0
    else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2153
0
      DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2154
0
  }
2155
0
}
2156
2157
0
void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2158
0
  DiagnoseUnusedDecl(
2159
0
      D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2160
0
}
2161
2162
/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2163
/// unless they are marked attr(unused).
2164
0
void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2165
0
  if (!ShouldDiagnoseUnusedDecl(getLangOpts(), D))
2166
0
    return;
2167
2168
0
  if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2169
    // typedefs can be referenced later on, so the diagnostics are emitted
2170
    // at end-of-translation-unit.
2171
0
    UnusedLocalTypedefNameCandidates.insert(TD);
2172
0
    return;
2173
0
  }
2174
2175
0
  FixItHint Hint;
2176
0
  GenerateFixForUnusedDecl(D, Context, Hint);
2177
2178
0
  unsigned DiagID;
2179
0
  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2180
0
    DiagID = diag::warn_unused_exception_param;
2181
0
  else if (isa<LabelDecl>(D))
2182
0
    DiagID = diag::warn_unused_label;
2183
0
  else
2184
0
    DiagID = diag::warn_unused_variable;
2185
2186
0
  SourceLocation DiagLoc = D->getLocation();
2187
0
  DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2188
0
}
2189
2190
void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2191
0
                                    DiagReceiverTy DiagReceiver) {
2192
  // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2193
  // it's not really unused.
2194
0
  if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2195
0
    return;
2196
2197
  //  In C++, `_` variables behave as if they were maybe_unused
2198
0
  if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2199
0
    return;
2200
2201
0
  const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2202
2203
0
  if (Ty->isReferenceType() || Ty->isDependentType())
2204
0
    return;
2205
2206
0
  if (const TagType *TT = Ty->getAs<TagType>()) {
2207
0
    const TagDecl *Tag = TT->getDecl();
2208
0
    if (Tag->hasAttr<UnusedAttr>())
2209
0
      return;
2210
    // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2211
    // mimic gcc's behavior.
2212
0
    if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2213
0
        RD && !RD->hasAttr<WarnUnusedAttr>())
2214
0
      return;
2215
0
  }
2216
2217
  // Don't warn about __block Objective-C pointer variables, as they might
2218
  // be assigned in the block but not used elsewhere for the purpose of lifetime
2219
  // extension.
2220
0
  if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2221
0
    return;
2222
2223
  // Don't warn about Objective-C pointer variables with precise lifetime
2224
  // semantics; they can be used to ensure ARC releases the object at a known
2225
  // time, which may mean assignment but no other references.
2226
0
  if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2227
0
    return;
2228
2229
0
  auto iter = RefsMinusAssignments.find(VD);
2230
0
  if (iter == RefsMinusAssignments.end())
2231
0
    return;
2232
2233
0
  assert(iter->getSecond() >= 0 &&
2234
0
         "Found a negative number of references to a VarDecl");
2235
0
  if (iter->getSecond() != 0)
2236
0
    return;
2237
0
  unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2238
0
                                         : diag::warn_unused_but_set_variable;
2239
0
  DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2240
0
}
2241
2242
static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2243
0
                             Sema::DiagReceiverTy DiagReceiver) {
2244
  // Verify that we have no forward references left.  If so, there was a goto
2245
  // or address of a label taken, but no definition of it.  Label fwd
2246
  // definitions are indicated with a null substmt which is also not a resolved
2247
  // MS inline assembly label name.
2248
0
  bool Diagnose = false;
2249
0
  if (L->isMSAsmLabel())
2250
0
    Diagnose = !L->isResolvedMSAsmLabel();
2251
0
  else
2252
0
    Diagnose = L->getStmt() == nullptr;
2253
0
  if (Diagnose)
2254
0
    DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2255
0
                                       << L);
2256
0
}
2257
2258
144
void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2259
144
  S->applyNRVO();
2260
2261
144
  if (S->decl_empty()) return;
2262
40
  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2263
40
         "Scope shouldn't contain decls!");
2264
2265
  /// We visit the decls in non-deterministic order, but we want diagnostics
2266
  /// emitted in deterministic order. Collect any diagnostic that may be emitted
2267
  /// and sort the diagnostics before emitting them, after we visited all decls.
2268
0
  struct LocAndDiag {
2269
40
    SourceLocation Loc;
2270
40
    std::optional<SourceLocation> PreviousDeclLoc;
2271
40
    PartialDiagnostic PD;
2272
40
  };
2273
40
  SmallVector<LocAndDiag, 16> DeclDiags;
2274
40
  auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2275
0
    DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2276
0
  };
2277
40
  auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2278
40
                                      SourceLocation PreviousDeclLoc,
2279
40
                                      PartialDiagnostic PD) {
2280
0
    DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2281
0
  };
2282
2283
40
  for (auto *TmpD : S->decls()) {
2284
40
    assert(TmpD && "This decl didn't get pushed??");
2285
2286
0
    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2287
0
    NamedDecl *D = cast<NamedDecl>(TmpD);
2288
2289
    // Diagnose unused variables in this scope.
2290
40
    if (!S->hasUnrecoverableErrorOccurred()) {
2291
0
      DiagnoseUnusedDecl(D, addDiag);
2292
0
      if (const auto *RD = dyn_cast<RecordDecl>(D))
2293
0
        DiagnoseUnusedNestedTypedefs(RD, addDiag);
2294
0
      if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2295
0
        DiagnoseUnusedButSetDecl(VD, addDiag);
2296
0
        RefsMinusAssignments.erase(VD);
2297
0
      }
2298
0
    }
2299
2300
40
    if (!D->getDeclName()) continue;
2301
2302
    // If this was a forward reference to a label, verify it was defined.
2303
21
    if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2304
0
      CheckPoppedLabel(LD, *this, addDiag);
2305
2306
    // Remove this name from our lexical scope, and warn on it if we haven't
2307
    // already.
2308
21
    IdResolver.RemoveDecl(D);
2309
21
    auto ShadowI = ShadowingDecls.find(D);
2310
21
    if (ShadowI != ShadowingDecls.end()) {
2311
0
      if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2312
0
        addDiagWithPrev(D->getLocation(), FD->getLocation(),
2313
0
                        PDiag(diag::warn_ctor_parm_shadows_field)
2314
0
                            << D << FD << FD->getParent());
2315
0
      }
2316
0
      ShadowingDecls.erase(ShadowI);
2317
0
    }
2318
2319
21
    if (!getLangOpts().CPlusPlus && S->isClassScope()) {
2320
0
      if (auto *FD = dyn_cast<FieldDecl>(TmpD);
2321
0
          FD && FD->hasAttr<CountedByAttr>())
2322
0
        CheckCountedByAttr(S, FD);
2323
0
    }
2324
21
  }
2325
2326
40
  llvm::sort(DeclDiags,
2327
40
             [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2328
               // The particular order for diagnostics is not important, as long
2329
               // as the order is deterministic. Using the raw location is going
2330
               // to generally be in source order unless there are macro
2331
               // expansions involved.
2332
0
               return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2333
0
             });
2334
40
  for (const LocAndDiag &D : DeclDiags) {
2335
0
    Diag(D.Loc, D.PD);
2336
0
    if (D.PreviousDeclLoc)
2337
0
      Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2338
0
  }
2339
40
}
2340
2341
/// Look for an Objective-C class in the translation unit.
2342
///
2343
/// \param Id The name of the Objective-C class we're looking for. If
2344
/// typo-correction fixes this name, the Id will be updated
2345
/// to the fixed name.
2346
///
2347
/// \param IdLoc The location of the name in the translation unit.
2348
///
2349
/// \param DoTypoCorrection If true, this routine will attempt typo correction
2350
/// if there is no class with the given name.
2351
///
2352
/// \returns The declaration of the named Objective-C class, or NULL if the
2353
/// class could not be found.
2354
ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2355
                                              SourceLocation IdLoc,
2356
0
                                              bool DoTypoCorrection) {
2357
  // The third "scope" argument is 0 since we aren't enabling lazy built-in
2358
  // creation from this context.
2359
0
  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2360
2361
0
  if (!IDecl && DoTypoCorrection) {
2362
    // Perform typo correction at the given location, but only if we
2363
    // find an Objective-C class name.
2364
0
    DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2365
0
    if (TypoCorrection C =
2366
0
            CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2367
0
                        TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2368
0
      diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2369
0
      IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2370
0
      Id = IDecl->getIdentifier();
2371
0
    }
2372
0
  }
2373
0
  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2374
  // This routine must always return a class definition, if any.
2375
0
  if (Def && Def->getDefinition())
2376
0
      Def = Def->getDefinition();
2377
0
  return Def;
2378
0
}
2379
2380
/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2381
/// from S, where a non-field would be declared. This routine copes
2382
/// with the difference between C and C++ scoping rules in structs and
2383
/// unions. For example, the following code is well-formed in C but
2384
/// ill-formed in C++:
2385
/// @code
2386
/// struct S6 {
2387
///   enum { BAR } e;
2388
/// };
2389
///
2390
/// void test_S6() {
2391
///   struct S6 a;
2392
///   a.e = BAR;
2393
/// }
2394
/// @endcode
2395
/// For the declaration of BAR, this routine will return a different
2396
/// scope. The scope S will be the scope of the unnamed enumeration
2397
/// within S6. In C++, this routine will return the scope associated
2398
/// with S6, because the enumeration's scope is a transparent
2399
/// context but structures can contain non-field names. In C, this
2400
/// routine will return the translation unit scope, since the
2401
/// enumeration's scope is a transparent context and structures cannot
2402
/// contain non-field names.
2403
0
Scope *Sema::getNonFieldDeclScope(Scope *S) {
2404
0
  while (((S->getFlags() & Scope::DeclScope) == 0) ||
2405
0
         (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2406
0
         (S->isClassScope() && !getLangOpts().CPlusPlus))
2407
0
    S = S->getParent();
2408
0
  return S;
2409
0
}
2410
2411
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2412
0
                               ASTContext::GetBuiltinTypeError Error) {
2413
0
  switch (Error) {
2414
0
  case ASTContext::GE_None:
2415
0
    return "";
2416
0
  case ASTContext::GE_Missing_type:
2417
0
    return BuiltinInfo.getHeaderName(ID);
2418
0
  case ASTContext::GE_Missing_stdio:
2419
0
    return "stdio.h";
2420
0
  case ASTContext::GE_Missing_setjmp:
2421
0
    return "setjmp.h";
2422
0
  case ASTContext::GE_Missing_ucontext:
2423
0
    return "ucontext.h";
2424
0
  }
2425
0
  llvm_unreachable("unhandled error kind");
2426
0
}
2427
2428
FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2429
0
                                  unsigned ID, SourceLocation Loc) {
2430
0
  DeclContext *Parent = Context.getTranslationUnitDecl();
2431
2432
0
  if (getLangOpts().CPlusPlus) {
2433
0
    LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2434
0
        Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2435
0
    CLinkageDecl->setImplicit();
2436
0
    Parent->addDecl(CLinkageDecl);
2437
0
    Parent = CLinkageDecl;
2438
0
  }
2439
2440
0
  FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2441
0
                                           /*TInfo=*/nullptr, SC_Extern,
2442
0
                                           getCurFPFeatures().isFPConstrained(),
2443
0
                                           false, Type->isFunctionProtoType());
2444
0
  New->setImplicit();
2445
0
  New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2446
2447
  // Create Decl objects for each parameter, adding them to the
2448
  // FunctionDecl.
2449
0
  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2450
0
    SmallVector<ParmVarDecl *, 16> Params;
2451
0
    for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2452
0
      ParmVarDecl *parm = ParmVarDecl::Create(
2453
0
          Context, New, SourceLocation(), SourceLocation(), nullptr,
2454
0
          FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2455
0
      parm->setScopeInfo(0, i);
2456
0
      Params.push_back(parm);
2457
0
    }
2458
0
    New->setParams(Params);
2459
0
  }
2460
2461
0
  AddKnownFunctionAttributes(New);
2462
0
  return New;
2463
0
}
2464
2465
/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2466
/// file scope.  lazily create a decl for it. ForRedeclaration is true
2467
/// if we're creating this built-in in anticipation of redeclaring the
2468
/// built-in.
2469
NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2470
                                     Scope *S, bool ForRedeclaration,
2471
0
                                     SourceLocation Loc) {
2472
0
  LookupNecessaryTypesForBuiltin(S, ID);
2473
2474
0
  ASTContext::GetBuiltinTypeError Error;
2475
0
  QualType R = Context.GetBuiltinType(ID, Error);
2476
0
  if (Error) {
2477
0
    if (!ForRedeclaration)
2478
0
      return nullptr;
2479
2480
    // If we have a builtin without an associated type we should not emit a
2481
    // warning when we were not able to find a type for it.
2482
0
    if (Error == ASTContext::GE_Missing_type ||
2483
0
        Context.BuiltinInfo.allowTypeMismatch(ID))
2484
0
      return nullptr;
2485
2486
    // If we could not find a type for setjmp it is because the jmp_buf type was
2487
    // not defined prior to the setjmp declaration.
2488
0
    if (Error == ASTContext::GE_Missing_setjmp) {
2489
0
      Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2490
0
          << Context.BuiltinInfo.getName(ID);
2491
0
      return nullptr;
2492
0
    }
2493
2494
    // Generally, we emit a warning that the declaration requires the
2495
    // appropriate header.
2496
0
    Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2497
0
        << getHeaderName(Context.BuiltinInfo, ID, Error)
2498
0
        << Context.BuiltinInfo.getName(ID);
2499
0
    return nullptr;
2500
0
  }
2501
2502
0
  if (!ForRedeclaration &&
2503
0
      (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2504
0
       Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2505
0
    Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2506
0
                           : diag::ext_implicit_lib_function_decl)
2507
0
        << Context.BuiltinInfo.getName(ID) << R;
2508
0
    if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2509
0
      Diag(Loc, diag::note_include_header_or_declare)
2510
0
          << Header << Context.BuiltinInfo.getName(ID);
2511
0
  }
2512
2513
0
  if (R.isNull())
2514
0
    return nullptr;
2515
2516
0
  FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2517
0
  RegisterLocallyScopedExternCDecl(New, S);
2518
2519
  // TUScope is the translation-unit scope to insert this function into.
2520
  // FIXME: This is hideous. We need to teach PushOnScopeChains to
2521
  // relate Scopes to DeclContexts, and probably eliminate CurContext
2522
  // entirely, but we're not there yet.
2523
0
  DeclContext *SavedContext = CurContext;
2524
0
  CurContext = New->getDeclContext();
2525
0
  PushOnScopeChains(New, TUScope);
2526
0
  CurContext = SavedContext;
2527
0
  return New;
2528
0
}
2529
2530
/// Typedef declarations don't have linkage, but they still denote the same
2531
/// entity if their types are the same.
2532
/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2533
/// isSameEntity.
2534
static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2535
                                                     TypedefNameDecl *Decl,
2536
0
                                                     LookupResult &Previous) {
2537
  // This is only interesting when modules are enabled.
2538
0
  if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2539
0
    return;
2540
2541
  // Empty sets are uninteresting.
2542
0
  if (Previous.empty())
2543
0
    return;
2544
2545
0
  LookupResult::Filter Filter = Previous.makeFilter();
2546
0
  while (Filter.hasNext()) {
2547
0
    NamedDecl *Old = Filter.next();
2548
2549
    // Non-hidden declarations are never ignored.
2550
0
    if (S.isVisible(Old))
2551
0
      continue;
2552
2553
    // Declarations of the same entity are not ignored, even if they have
2554
    // different linkages.
2555
0
    if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2556
0
      if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2557
0
                                Decl->getUnderlyingType()))
2558
0
        continue;
2559
2560
      // If both declarations give a tag declaration a typedef name for linkage
2561
      // purposes, then they declare the same entity.
2562
0
      if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2563
0
          Decl->getAnonDeclWithTypedefName())
2564
0
        continue;
2565
0
    }
2566
2567
0
    Filter.erase();
2568
0
  }
2569
2570
0
  Filter.done();
2571
0
}
2572
2573
0
bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2574
0
  QualType OldType;
2575
0
  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2576
0
    OldType = OldTypedef->getUnderlyingType();
2577
0
  else
2578
0
    OldType = Context.getTypeDeclType(Old);
2579
0
  QualType NewType = New->getUnderlyingType();
2580
2581
0
  if (NewType->isVariablyModifiedType()) {
2582
    // Must not redefine a typedef with a variably-modified type.
2583
0
    int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2584
0
    Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2585
0
      << Kind << NewType;
2586
0
    if (Old->getLocation().isValid())
2587
0
      notePreviousDefinition(Old, New->getLocation());
2588
0
    New->setInvalidDecl();
2589
0
    return true;
2590
0
  }
2591
2592
0
  if (OldType != NewType &&
2593
0
      !OldType->isDependentType() &&
2594
0
      !NewType->isDependentType() &&
2595
0
      !Context.hasSameType(OldType, NewType)) {
2596
0
    int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2597
0
    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2598
0
      << Kind << NewType << OldType;
2599
0
    if (Old->getLocation().isValid())
2600
0
      notePreviousDefinition(Old, New->getLocation());
2601
0
    New->setInvalidDecl();
2602
0
    return true;
2603
0
  }
2604
0
  return false;
2605
0
}
2606
2607
/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2608
/// same name and scope as a previous declaration 'Old'.  Figure out
2609
/// how to resolve this situation, merging decls or emitting
2610
/// diagnostics as appropriate. If there was an error, set New to be invalid.
2611
///
2612
void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2613
0
                                LookupResult &OldDecls) {
2614
  // If the new decl is known invalid already, don't bother doing any
2615
  // merging checks.
2616
0
  if (New->isInvalidDecl()) return;
2617
2618
  // Allow multiple definitions for ObjC built-in typedefs.
2619
  // FIXME: Verify the underlying types are equivalent!
2620
0
  if (getLangOpts().ObjC) {
2621
0
    const IdentifierInfo *TypeID = New->getIdentifier();
2622
0
    switch (TypeID->getLength()) {
2623
0
    default: break;
2624
0
    case 2:
2625
0
      {
2626
0
        if (!TypeID->isStr("id"))
2627
0
          break;
2628
0
        QualType T = New->getUnderlyingType();
2629
0
        if (!T->isPointerType())
2630
0
          break;
2631
0
        if (!T->isVoidPointerType()) {
2632
0
          QualType PT = T->castAs<PointerType>()->getPointeeType();
2633
0
          if (!PT->isStructureType())
2634
0
            break;
2635
0
        }
2636
0
        Context.setObjCIdRedefinitionType(T);
2637
        // Install the built-in type for 'id', ignoring the current definition.
2638
0
        New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2639
0
        return;
2640
0
      }
2641
0
    case 5:
2642
0
      if (!TypeID->isStr("Class"))
2643
0
        break;
2644
0
      Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2645
      // Install the built-in type for 'Class', ignoring the current definition.
2646
0
      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2647
0
      return;
2648
0
    case 3:
2649
0
      if (!TypeID->isStr("SEL"))
2650
0
        break;
2651
0
      Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2652
      // Install the built-in type for 'SEL', ignoring the current definition.
2653
0
      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2654
0
      return;
2655
0
    }
2656
    // Fall through - the typedef name was not a builtin type.
2657
0
  }
2658
2659
  // Verify the old decl was also a type.
2660
0
  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2661
0
  if (!Old) {
2662
0
    Diag(New->getLocation(), diag::err_redefinition_different_kind)
2663
0
      << New->getDeclName();
2664
2665
0
    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2666
0
    if (OldD->getLocation().isValid())
2667
0
      notePreviousDefinition(OldD, New->getLocation());
2668
2669
0
    return New->setInvalidDecl();
2670
0
  }
2671
2672
  // If the old declaration is invalid, just give up here.
2673
0
  if (Old->isInvalidDecl())
2674
0
    return New->setInvalidDecl();
2675
2676
0
  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2677
0
    auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2678
0
    auto *NewTag = New->getAnonDeclWithTypedefName();
2679
0
    NamedDecl *Hidden = nullptr;
2680
0
    if (OldTag && NewTag &&
2681
0
        OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2682
0
        !hasVisibleDefinition(OldTag, &Hidden)) {
2683
      // There is a definition of this tag, but it is not visible. Use it
2684
      // instead of our tag.
2685
0
      New->setTypeForDecl(OldTD->getTypeForDecl());
2686
0
      if (OldTD->isModed())
2687
0
        New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2688
0
                                    OldTD->getUnderlyingType());
2689
0
      else
2690
0
        New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2691
2692
      // Make the old tag definition visible.
2693
0
      makeMergedDefinitionVisible(Hidden);
2694
2695
      // If this was an unscoped enumeration, yank all of its enumerators
2696
      // out of the scope.
2697
0
      if (isa<EnumDecl>(NewTag)) {
2698
0
        Scope *EnumScope = getNonFieldDeclScope(S);
2699
0
        for (auto *D : NewTag->decls()) {
2700
0
          auto *ED = cast<EnumConstantDecl>(D);
2701
0
          assert(EnumScope->isDeclScope(ED));
2702
0
          EnumScope->RemoveDecl(ED);
2703
0
          IdResolver.RemoveDecl(ED);
2704
0
          ED->getLexicalDeclContext()->removeDecl(ED);
2705
0
        }
2706
0
      }
2707
0
    }
2708
0
  }
2709
2710
  // If the typedef types are not identical, reject them in all languages and
2711
  // with any extensions enabled.
2712
0
  if (isIncompatibleTypedef(Old, New))
2713
0
    return;
2714
2715
  // The types match.  Link up the redeclaration chain and merge attributes if
2716
  // the old declaration was a typedef.
2717
0
  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2718
0
    New->setPreviousDecl(Typedef);
2719
0
    mergeDeclAttributes(New, Old);
2720
0
  }
2721
2722
0
  if (getLangOpts().MicrosoftExt)
2723
0
    return;
2724
2725
0
  if (getLangOpts().CPlusPlus) {
2726
    // C++ [dcl.typedef]p2:
2727
    //   In a given non-class scope, a typedef specifier can be used to
2728
    //   redefine the name of any type declared in that scope to refer
2729
    //   to the type to which it already refers.
2730
0
    if (!isa<CXXRecordDecl>(CurContext))
2731
0
      return;
2732
2733
    // C++0x [dcl.typedef]p4:
2734
    //   In a given class scope, a typedef specifier can be used to redefine
2735
    //   any class-name declared in that scope that is not also a typedef-name
2736
    //   to refer to the type to which it already refers.
2737
    //
2738
    // This wording came in via DR424, which was a correction to the
2739
    // wording in DR56, which accidentally banned code like:
2740
    //
2741
    //   struct S {
2742
    //     typedef struct A { } A;
2743
    //   };
2744
    //
2745
    // in the C++03 standard. We implement the C++0x semantics, which
2746
    // allow the above but disallow
2747
    //
2748
    //   struct S {
2749
    //     typedef int I;
2750
    //     typedef int I;
2751
    //   };
2752
    //
2753
    // since that was the intent of DR56.
2754
0
    if (!isa<TypedefNameDecl>(Old))
2755
0
      return;
2756
2757
0
    Diag(New->getLocation(), diag::err_redefinition)
2758
0
      << New->getDeclName();
2759
0
    notePreviousDefinition(Old, New->getLocation());
2760
0
    return New->setInvalidDecl();
2761
0
  }
2762
2763
  // Modules always permit redefinition of typedefs, as does C11.
2764
0
  if (getLangOpts().Modules || getLangOpts().C11)
2765
0
    return;
2766
2767
  // If we have a redefinition of a typedef in C, emit a warning.  This warning
2768
  // is normally mapped to an error, but can be controlled with
2769
  // -Wtypedef-redefinition.  If either the original or the redefinition is
2770
  // in a system header, don't emit this for compatibility with GCC.
2771
0
  if (getDiagnostics().getSuppressSystemWarnings() &&
2772
      // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2773
0
      (Old->isImplicit() ||
2774
0
       Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2775
0
       Context.getSourceManager().isInSystemHeader(New->getLocation())))
2776
0
    return;
2777
2778
0
  Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2779
0
    << New->getDeclName();
2780
0
  notePreviousDefinition(Old, New->getLocation());
2781
0
}
2782
2783
/// DeclhasAttr - returns true if decl Declaration already has the target
2784
/// attribute.
2785
0
static bool DeclHasAttr(const Decl *D, const Attr *A) {
2786
0
  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2787
0
  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2788
0
  for (const auto *i : D->attrs())
2789
0
    if (i->getKind() == A->getKind()) {
2790
0
      if (Ann) {
2791
0
        if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2792
0
          return true;
2793
0
        continue;
2794
0
      }
2795
      // FIXME: Don't hardcode this check
2796
0
      if (OA && isa<OwnershipAttr>(i))
2797
0
        return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2798
0
      return true;
2799
0
    }
2800
2801
0
  return false;
2802
0
}
2803
2804
0
static bool isAttributeTargetADefinition(Decl *D) {
2805
0
  if (VarDecl *VD = dyn_cast<VarDecl>(D))
2806
0
    return VD->isThisDeclarationADefinition();
2807
0
  if (TagDecl *TD = dyn_cast<TagDecl>(D))
2808
0
    return TD->isCompleteDefinition() || TD->isBeingDefined();
2809
0
  return true;
2810
0
}
2811
2812
/// Merge alignment attributes from \p Old to \p New, taking into account the
2813
/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2814
///
2815
/// \return \c true if any attributes were added to \p New.
2816
0
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2817
  // Look for alignas attributes on Old, and pick out whichever attribute
2818
  // specifies the strictest alignment requirement.
2819
0
  AlignedAttr *OldAlignasAttr = nullptr;
2820
0
  AlignedAttr *OldStrictestAlignAttr = nullptr;
2821
0
  unsigned OldAlign = 0;
2822
0
  for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2823
    // FIXME: We have no way of representing inherited dependent alignments
2824
    // in a case like:
2825
    //   template<int A, int B> struct alignas(A) X;
2826
    //   template<int A, int B> struct alignas(B) X {};
2827
    // For now, we just ignore any alignas attributes which are not on the
2828
    // definition in such a case.
2829
0
    if (I->isAlignmentDependent())
2830
0
      return false;
2831
2832
0
    if (I->isAlignas())
2833
0
      OldAlignasAttr = I;
2834
2835
0
    unsigned Align = I->getAlignment(S.Context);
2836
0
    if (Align > OldAlign) {
2837
0
      OldAlign = Align;
2838
0
      OldStrictestAlignAttr = I;
2839
0
    }
2840
0
  }
2841
2842
  // Look for alignas attributes on New.
2843
0
  AlignedAttr *NewAlignasAttr = nullptr;
2844
0
  unsigned NewAlign = 0;
2845
0
  for (auto *I : New->specific_attrs<AlignedAttr>()) {
2846
0
    if (I->isAlignmentDependent())
2847
0
      return false;
2848
2849
0
    if (I->isAlignas())
2850
0
      NewAlignasAttr = I;
2851
2852
0
    unsigned Align = I->getAlignment(S.Context);
2853
0
    if (Align > NewAlign)
2854
0
      NewAlign = Align;
2855
0
  }
2856
2857
0
  if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2858
    // Both declarations have 'alignas' attributes. We require them to match.
2859
    // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2860
    // fall short. (If two declarations both have alignas, they must both match
2861
    // every definition, and so must match each other if there is a definition.)
2862
2863
    // If either declaration only contains 'alignas(0)' specifiers, then it
2864
    // specifies the natural alignment for the type.
2865
0
    if (OldAlign == 0 || NewAlign == 0) {
2866
0
      QualType Ty;
2867
0
      if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2868
0
        Ty = VD->getType();
2869
0
      else
2870
0
        Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2871
2872
0
      if (OldAlign == 0)
2873
0
        OldAlign = S.Context.getTypeAlign(Ty);
2874
0
      if (NewAlign == 0)
2875
0
        NewAlign = S.Context.getTypeAlign(Ty);
2876
0
    }
2877
2878
0
    if (OldAlign != NewAlign) {
2879
0
      S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2880
0
        << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2881
0
        << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2882
0
      S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2883
0
    }
2884
0
  }
2885
2886
0
  if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2887
    // C++11 [dcl.align]p6:
2888
    //   if any declaration of an entity has an alignment-specifier,
2889
    //   every defining declaration of that entity shall specify an
2890
    //   equivalent alignment.
2891
    // C11 6.7.5/7:
2892
    //   If the definition of an object does not have an alignment
2893
    //   specifier, any other declaration of that object shall also
2894
    //   have no alignment specifier.
2895
0
    S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2896
0
      << OldAlignasAttr;
2897
0
    S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2898
0
      << OldAlignasAttr;
2899
0
  }
2900
2901
0
  bool AnyAdded = false;
2902
2903
  // Ensure we have an attribute representing the strictest alignment.
2904
0
  if (OldAlign > NewAlign) {
2905
0
    AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2906
0
    Clone->setInherited(true);
2907
0
    New->addAttr(Clone);
2908
0
    AnyAdded = true;
2909
0
  }
2910
2911
  // Ensure we have an alignas attribute if the old declaration had one.
2912
0
  if (OldAlignasAttr && !NewAlignasAttr &&
2913
0
      !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2914
0
    AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2915
0
    Clone->setInherited(true);
2916
0
    New->addAttr(Clone);
2917
0
    AnyAdded = true;
2918
0
  }
2919
2920
0
  return AnyAdded;
2921
0
}
2922
2923
#define WANT_DECL_MERGE_LOGIC
2924
#include "clang/Sema/AttrParsedAttrImpl.inc"
2925
#undef WANT_DECL_MERGE_LOGIC
2926
2927
static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2928
                               const InheritableAttr *Attr,
2929
0
                               Sema::AvailabilityMergeKind AMK) {
2930
  // Diagnose any mutual exclusions between the attribute that we want to add
2931
  // and attributes that already exist on the declaration.
2932
0
  if (!DiagnoseMutualExclusions(S, D, Attr))
2933
0
    return false;
2934
2935
  // This function copies an attribute Attr from a previous declaration to the
2936
  // new declaration D if the new declaration doesn't itself have that attribute
2937
  // yet or if that attribute allows duplicates.
2938
  // If you're adding a new attribute that requires logic different from
2939
  // "use explicit attribute on decl if present, else use attribute from
2940
  // previous decl", for example if the attribute needs to be consistent
2941
  // between redeclarations, you need to call a custom merge function here.
2942
0
  InheritableAttr *NewAttr = nullptr;
2943
0
  if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2944
0
    NewAttr = S.mergeAvailabilityAttr(
2945
0
        D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2946
0
        AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2947
0
        AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2948
0
        AA->getPriority());
2949
0
  else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2950
0
    NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2951
0
  else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2952
0
    NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2953
0
  else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2954
0
    NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2955
0
  else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2956
0
    NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2957
0
  else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2958
0
    NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2959
0
  else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2960
0
    NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2961
0
                                FA->getFirstArg());
2962
0
  else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2963
0
    NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2964
0
  else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2965
0
    NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2966
0
  else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2967
0
    NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2968
0
                                       IA->getInheritanceModel());
2969
0
  else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2970
0
    NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2971
0
                                      &S.Context.Idents.get(AA->getSpelling()));
2972
0
  else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2973
0
           (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2974
0
            isa<CUDAGlobalAttr>(Attr))) {
2975
    // CUDA target attributes are part of function signature for
2976
    // overloading purposes and must not be merged.
2977
0
    return false;
2978
0
  } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2979
0
    NewAttr = S.mergeMinSizeAttr(D, *MA);
2980
0
  else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2981
0
    NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2982
0
  else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2983
0
    NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2984
0
  else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2985
0
    NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2986
0
  else if (isa<AlignedAttr>(Attr))
2987
    // AlignedAttrs are handled separately, because we need to handle all
2988
    // such attributes on a declaration at the same time.
2989
0
    NewAttr = nullptr;
2990
0
  else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2991
0
           (AMK == Sema::AMK_Override ||
2992
0
            AMK == Sema::AMK_ProtocolImplementation ||
2993
0
            AMK == Sema::AMK_OptionalProtocolImplementation))
2994
0
    NewAttr = nullptr;
2995
0
  else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2996
0
    NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2997
0
  else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2998
0
    NewAttr = S.mergeImportModuleAttr(D, *IMA);
2999
0
  else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
3000
0
    NewAttr = S.mergeImportNameAttr(D, *INA);
3001
0
  else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
3002
0
    NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
3003
0
  else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
3004
0
    NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
3005
0
  else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
3006
0
    NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
3007
0
  else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
3008
0
    NewAttr =
3009
0
        S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
3010
0
  else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
3011
0
    NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
3012
0
  else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
3013
0
    NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
3014
3015
0
  if (NewAttr) {
3016
0
    NewAttr->setInherited(true);
3017
0
    D->addAttr(NewAttr);
3018
0
    if (isa<MSInheritanceAttr>(NewAttr))
3019
0
      S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
3020
0
    return true;
3021
0
  }
3022
3023
0
  return false;
3024
0
}
3025
3026
0
static const NamedDecl *getDefinition(const Decl *D) {
3027
0
  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
3028
0
    return TD->getDefinition();
3029
0
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3030
0
    const VarDecl *Def = VD->getDefinition();
3031
0
    if (Def)
3032
0
      return Def;
3033
0
    return VD->getActingDefinition();
3034
0
  }
3035
0
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3036
0
    const FunctionDecl *Def = nullptr;
3037
0
    if (FD->isDefined(Def, true))
3038
0
      return Def;
3039
0
  }
3040
0
  return nullptr;
3041
0
}
3042
3043
0
static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3044
0
  for (const auto *Attribute : D->attrs())
3045
0
    if (Attribute->getKind() == Kind)
3046
0
      return true;
3047
0
  return false;
3048
0
}
3049
3050
/// checkNewAttributesAfterDef - If we already have a definition, check that
3051
/// there are no new attributes in this declaration.
3052
0
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3053
0
  if (!New->hasAttrs())
3054
0
    return;
3055
3056
0
  const NamedDecl *Def = getDefinition(Old);
3057
0
  if (!Def || Def == New)
3058
0
    return;
3059
3060
0
  AttrVec &NewAttributes = New->getAttrs();
3061
0
  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3062
0
    const Attr *NewAttribute = NewAttributes[I];
3063
3064
0
    if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3065
0
      if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3066
0
        Sema::SkipBodyInfo SkipBody;
3067
0
        S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3068
3069
        // If we're skipping this definition, drop the "alias" attribute.
3070
0
        if (SkipBody.ShouldSkip) {
3071
0
          NewAttributes.erase(NewAttributes.begin() + I);
3072
0
          --E;
3073
0
          continue;
3074
0
        }
3075
0
      } else {
3076
0
        VarDecl *VD = cast<VarDecl>(New);
3077
0
        unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3078
0
                                VarDecl::TentativeDefinition
3079
0
                            ? diag::err_alias_after_tentative
3080
0
                            : diag::err_redefinition;
3081
0
        S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3082
0
        if (Diag == diag::err_redefinition)
3083
0
          S.notePreviousDefinition(Def, VD->getLocation());
3084
0
        else
3085
0
          S.Diag(Def->getLocation(), diag::note_previous_definition);
3086
0
        VD->setInvalidDecl();
3087
0
      }
3088
0
      ++I;
3089
0
      continue;
3090
0
    }
3091
3092
0
    if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3093
      // Tentative definitions are only interesting for the alias check above.
3094
0
      if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3095
0
        ++I;
3096
0
        continue;
3097
0
      }
3098
0
    }
3099
3100
0
    if (hasAttribute(Def, NewAttribute->getKind())) {
3101
0
      ++I;
3102
0
      continue; // regular attr merging will take care of validating this.
3103
0
    }
3104
3105
0
    if (isa<C11NoReturnAttr>(NewAttribute)) {
3106
      // C's _Noreturn is allowed to be added to a function after it is defined.
3107
0
      ++I;
3108
0
      continue;
3109
0
    } else if (isa<UuidAttr>(NewAttribute)) {
3110
      // msvc will allow a subsequent definition to add an uuid to a class
3111
0
      ++I;
3112
0
      continue;
3113
0
    } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3114
0
      if (AA->isAlignas()) {
3115
        // C++11 [dcl.align]p6:
3116
        //   if any declaration of an entity has an alignment-specifier,
3117
        //   every defining declaration of that entity shall specify an
3118
        //   equivalent alignment.
3119
        // C11 6.7.5/7:
3120
        //   If the definition of an object does not have an alignment
3121
        //   specifier, any other declaration of that object shall also
3122
        //   have no alignment specifier.
3123
0
        S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3124
0
          << AA;
3125
0
        S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3126
0
          << AA;
3127
0
        NewAttributes.erase(NewAttributes.begin() + I);
3128
0
        --E;
3129
0
        continue;
3130
0
      }
3131
0
    } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3132
      // If there is a C definition followed by a redeclaration with this
3133
      // attribute then there are two different definitions. In C++, prefer the
3134
      // standard diagnostics.
3135
0
      if (!S.getLangOpts().CPlusPlus) {
3136
0
        S.Diag(NewAttribute->getLocation(),
3137
0
               diag::err_loader_uninitialized_redeclaration);
3138
0
        S.Diag(Def->getLocation(), diag::note_previous_definition);
3139
0
        NewAttributes.erase(NewAttributes.begin() + I);
3140
0
        --E;
3141
0
        continue;
3142
0
      }
3143
0
    } else if (isa<SelectAnyAttr>(NewAttribute) &&
3144
0
               cast<VarDecl>(New)->isInline() &&
3145
0
               !cast<VarDecl>(New)->isInlineSpecified()) {
3146
      // Don't warn about applying selectany to implicitly inline variables.
3147
      // Older compilers and language modes would require the use of selectany
3148
      // to make such variables inline, and it would have no effect if we
3149
      // honored it.
3150
0
      ++I;
3151
0
      continue;
3152
0
    } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3153
      // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3154
      // declarations after definitions.
3155
0
      ++I;
3156
0
      continue;
3157
0
    }
3158
3159
0
    S.Diag(NewAttribute->getLocation(),
3160
0
           diag::warn_attribute_precede_definition);
3161
0
    S.Diag(Def->getLocation(), diag::note_previous_definition);
3162
0
    NewAttributes.erase(NewAttributes.begin() + I);
3163
0
    --E;
3164
0
  }
3165
0
}
3166
3167
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3168
                                     const ConstInitAttr *CIAttr,
3169
0
                                     bool AttrBeforeInit) {
3170
0
  SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3171
3172
  // Figure out a good way to write this specifier on the old declaration.
3173
  // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3174
  // enough of the attribute list spelling information to extract that without
3175
  // heroics.
3176
0
  std::string SuitableSpelling;
3177
0
  if (S.getLangOpts().CPlusPlus20)
3178
0
    SuitableSpelling = std::string(
3179
0
        S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3180
0
  if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3181
0
    SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3182
0
        InsertLoc, {tok::l_square, tok::l_square,
3183
0
                    S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3184
0
                    S.PP.getIdentifierInfo("require_constant_initialization"),
3185
0
                    tok::r_square, tok::r_square}));
3186
0
  if (SuitableSpelling.empty())
3187
0
    SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3188
0
        InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3189
0
                    S.PP.getIdentifierInfo("require_constant_initialization"),
3190
0
                    tok::r_paren, tok::r_paren}));
3191
0
  if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3192
0
    SuitableSpelling = "constinit";
3193
0
  if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3194
0
    SuitableSpelling = "[[clang::require_constant_initialization]]";
3195
0
  if (SuitableSpelling.empty())
3196
0
    SuitableSpelling = "__attribute__((require_constant_initialization))";
3197
0
  SuitableSpelling += " ";
3198
3199
0
  if (AttrBeforeInit) {
3200
    // extern constinit int a;
3201
    // int a = 0; // error (missing 'constinit'), accepted as extension
3202
0
    assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3203
0
    S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3204
0
        << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3205
0
    S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3206
0
  } else {
3207
    // int a = 0;
3208
    // constinit extern int a; // error (missing 'constinit')
3209
0
    S.Diag(CIAttr->getLocation(),
3210
0
           CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3211
0
                                 : diag::warn_require_const_init_added_too_late)
3212
0
        << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3213
0
    S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3214
0
        << CIAttr->isConstinit()
3215
0
        << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3216
0
  }
3217
0
}
3218
3219
/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3220
void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3221
193
                               AvailabilityMergeKind AMK) {
3222
193
  if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3223
0
    UsedAttr *NewAttr = OldAttr->clone(Context);
3224
0
    NewAttr->setInherited(true);
3225
0
    New->addAttr(NewAttr);
3226
0
  }
3227
193
  if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3228
0
    RetainAttr *NewAttr = OldAttr->clone(Context);
3229
0
    NewAttr->setInherited(true);
3230
0
    New->addAttr(NewAttr);
3231
0
  }
3232
3233
193
  if (!Old->hasAttrs() && !New->hasAttrs())
3234
193
    return;
3235
3236
  // [dcl.constinit]p1:
3237
  //   If the [constinit] specifier is applied to any declaration of a
3238
  //   variable, it shall be applied to the initializing declaration.
3239
0
  const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3240
0
  const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3241
0
  if (bool(OldConstInit) != bool(NewConstInit)) {
3242
0
    const auto *OldVD = cast<VarDecl>(Old);
3243
0
    auto *NewVD = cast<VarDecl>(New);
3244
3245
    // Find the initializing declaration. Note that we might not have linked
3246
    // the new declaration into the redeclaration chain yet.
3247
0
    const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3248
0
    if (!InitDecl &&
3249
0
        (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3250
0
      InitDecl = NewVD;
3251
3252
0
    if (InitDecl == NewVD) {
3253
      // This is the initializing declaration. If it would inherit 'constinit',
3254
      // that's ill-formed. (Note that we do not apply this to the attribute
3255
      // form).
3256
0
      if (OldConstInit && OldConstInit->isConstinit())
3257
0
        diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3258
0
                                 /*AttrBeforeInit=*/true);
3259
0
    } else if (NewConstInit) {
3260
      // This is the first time we've been told that this declaration should
3261
      // have a constant initializer. If we already saw the initializing
3262
      // declaration, this is too late.
3263
0
      if (InitDecl && InitDecl != NewVD) {
3264
0
        diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3265
0
                                 /*AttrBeforeInit=*/false);
3266
0
        NewVD->dropAttr<ConstInitAttr>();
3267
0
      }
3268
0
    }
3269
0
  }
3270
3271
  // Attributes declared post-definition are currently ignored.
3272
0
  checkNewAttributesAfterDef(*this, New, Old);
3273
3274
0
  if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3275
0
    if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3276
0
      if (!OldA->isEquivalent(NewA)) {
3277
        // This redeclaration changes __asm__ label.
3278
0
        Diag(New->getLocation(), diag::err_different_asm_label);
3279
0
        Diag(OldA->getLocation(), diag::note_previous_declaration);
3280
0
      }
3281
0
    } else if (Old->isUsed()) {
3282
      // This redeclaration adds an __asm__ label to a declaration that has
3283
      // already been ODR-used.
3284
0
      Diag(New->getLocation(), diag::err_late_asm_label_name)
3285
0
        << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3286
0
    }
3287
0
  }
3288
3289
  // Re-declaration cannot add abi_tag's.
3290
0
  if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3291
0
    if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3292
0
      for (const auto &NewTag : NewAbiTagAttr->tags()) {
3293
0
        if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3294
0
          Diag(NewAbiTagAttr->getLocation(),
3295
0
               diag::err_new_abi_tag_on_redeclaration)
3296
0
              << NewTag;
3297
0
          Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3298
0
        }
3299
0
      }
3300
0
    } else {
3301
0
      Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3302
0
      Diag(Old->getLocation(), diag::note_previous_declaration);
3303
0
    }
3304
0
  }
3305
3306
  // This redeclaration adds a section attribute.
3307
0
  if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3308
0
    if (auto *VD = dyn_cast<VarDecl>(New)) {
3309
0
      if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3310
0
        Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3311
0
        Diag(Old->getLocation(), diag::note_previous_declaration);
3312
0
      }
3313
0
    }
3314
0
  }
3315
3316
  // Redeclaration adds code-seg attribute.
3317
0
  const auto *NewCSA = New->getAttr<CodeSegAttr>();
3318
0
  if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3319
0
      !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3320
0
    Diag(New->getLocation(), diag::warn_mismatched_section)
3321
0
         << 0 /*codeseg*/;
3322
0
    Diag(Old->getLocation(), diag::note_previous_declaration);
3323
0
  }
3324
3325
0
  if (!Old->hasAttrs())
3326
0
    return;
3327
3328
0
  bool foundAny = New->hasAttrs();
3329
3330
  // Ensure that any moving of objects within the allocated map is done before
3331
  // we process them.
3332
0
  if (!foundAny) New->setAttrs(AttrVec());
3333
3334
0
  for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3335
    // Ignore deprecated/unavailable/availability attributes if requested.
3336
0
    AvailabilityMergeKind LocalAMK = AMK_None;
3337
0
    if (isa<DeprecatedAttr>(I) ||
3338
0
        isa<UnavailableAttr>(I) ||
3339
0
        isa<AvailabilityAttr>(I)) {
3340
0
      switch (AMK) {
3341
0
      case AMK_None:
3342
0
        continue;
3343
3344
0
      case AMK_Redeclaration:
3345
0
      case AMK_Override:
3346
0
      case AMK_ProtocolImplementation:
3347
0
      case AMK_OptionalProtocolImplementation:
3348
0
        LocalAMK = AMK;
3349
0
        break;
3350
0
      }
3351
0
    }
3352
3353
    // Already handled.
3354
0
    if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3355
0
      continue;
3356
3357
0
    if (mergeDeclAttribute(*this, New, I, LocalAMK))
3358
0
      foundAny = true;
3359
0
  }
3360
3361
0
  if (mergeAlignedAttrs(*this, New, Old))
3362
0
    foundAny = true;
3363
3364
0
  if (!foundAny) New->dropAttrs();
3365
0
}
3366
3367
/// mergeParamDeclAttributes - Copy attributes from the old parameter
3368
/// to the new one.
3369
static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3370
                                     const ParmVarDecl *oldDecl,
3371
0
                                     Sema &S) {
3372
  // C++11 [dcl.attr.depend]p2:
3373
  //   The first declaration of a function shall specify the
3374
  //   carries_dependency attribute for its declarator-id if any declaration
3375
  //   of the function specifies the carries_dependency attribute.
3376
0
  const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3377
0
  if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3378
0
    S.Diag(CDA->getLocation(),
3379
0
           diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3380
    // Find the first declaration of the parameter.
3381
    // FIXME: Should we build redeclaration chains for function parameters?
3382
0
    const FunctionDecl *FirstFD =
3383
0
      cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3384
0
    const ParmVarDecl *FirstVD =
3385
0
      FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3386
0
    S.Diag(FirstVD->getLocation(),
3387
0
           diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3388
0
  }
3389
3390
  // HLSL parameter declarations for inout and out must match between
3391
  // declarations. In HLSL inout and out are ambiguous at the call site, but
3392
  // have different calling behavior, so you cannot overload a method based on a
3393
  // difference between inout and out annotations.
3394
0
  if (S.getLangOpts().HLSL) {
3395
0
    const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>();
3396
0
    const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>();
3397
    // We don't need to cover the case where one declaration doesn't have an
3398
    // attribute. The only possible case there is if one declaration has an `in`
3399
    // attribute and the other declaration has no attribute. This case is
3400
    // allowed since parameters are `in` by default.
3401
0
    if (NDAttr && ODAttr &&
3402
0
        NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) {
3403
0
      S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch)
3404
0
          << NDAttr << newDecl;
3405
0
      S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as)
3406
0
          << ODAttr;
3407
0
    }
3408
0
  }
3409
3410
0
  if (!oldDecl->hasAttrs())
3411
0
    return;
3412
3413
0
  bool foundAny = newDecl->hasAttrs();
3414
3415
  // Ensure that any moving of objects within the allocated map is
3416
  // done before we process them.
3417
0
  if (!foundAny) newDecl->setAttrs(AttrVec());
3418
3419
0
  for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3420
0
    if (!DeclHasAttr(newDecl, I)) {
3421
0
      InheritableAttr *newAttr =
3422
0
        cast<InheritableParamAttr>(I->clone(S.Context));
3423
0
      newAttr->setInherited(true);
3424
0
      newDecl->addAttr(newAttr);
3425
0
      foundAny = true;
3426
0
    }
3427
0
  }
3428
3429
0
  if (!foundAny) newDecl->dropAttrs();
3430
0
}
3431
3432
static bool EquivalentArrayTypes(QualType Old, QualType New,
3433
0
                                 const ASTContext &Ctx) {
3434
3435
0
  auto NoSizeInfo = [&Ctx](QualType Ty) {
3436
0
    if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3437
0
      return true;
3438
0
    if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3439
0
      return VAT->getSizeModifier() == ArraySizeModifier::Star;
3440
0
    return false;
3441
0
  };
3442
3443
  // `type[]` is equivalent to `type *` and `type[*]`.
3444
0
  if (NoSizeInfo(Old) && NoSizeInfo(New))
3445
0
    return true;
3446
3447
  // Don't try to compare VLA sizes, unless one of them has the star modifier.
3448
0
  if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3449
0
    const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3450
0
    const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3451
0
    if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3452
0
        (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3453
0
      return false;
3454
0
    return true;
3455
0
  }
3456
3457
  // Only compare size, ignore Size modifiers and CVR.
3458
0
  if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3459
0
    return Ctx.getAsConstantArrayType(Old)->getSize() ==
3460
0
           Ctx.getAsConstantArrayType(New)->getSize();
3461
0
  }
3462
3463
  // Don't try to compare dependent sized array
3464
0
  if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3465
0
    return true;
3466
0
  }
3467
3468
0
  return Old == New;
3469
0
}
3470
3471
static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3472
                                const ParmVarDecl *OldParam,
3473
0
                                Sema &S) {
3474
0
  if (auto Oldnullability = OldParam->getType()->getNullability()) {
3475
0
    if (auto Newnullability = NewParam->getType()->getNullability()) {
3476
0
      if (*Oldnullability != *Newnullability) {
3477
0
        S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3478
0
          << DiagNullabilityKind(
3479
0
               *Newnullability,
3480
0
               ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3481
0
                != 0))
3482
0
          << DiagNullabilityKind(
3483
0
               *Oldnullability,
3484
0
               ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3485
0
                != 0));
3486
0
        S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3487
0
      }
3488
0
    } else {
3489
0
      QualType NewT = NewParam->getType();
3490
0
      NewT = S.Context.getAttributedType(
3491
0
                         AttributedType::getNullabilityAttrKind(*Oldnullability),
3492
0
                         NewT, NewT);
3493
0
      NewParam->setType(NewT);
3494
0
    }
3495
0
  }
3496
0
  const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3497
0
  const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3498
0
  if (OldParamDT && NewParamDT &&
3499
0
      OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3500
0
    QualType OldParamOT = OldParamDT->getOriginalType();
3501
0
    QualType NewParamOT = NewParamDT->getOriginalType();
3502
0
    if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3503
0
      S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3504
0
          << NewParam << NewParamOT;
3505
0
      S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3506
0
          << OldParamOT;
3507
0
    }
3508
0
  }
3509
0
}
3510
3511
namespace {
3512
3513
/// Used in MergeFunctionDecl to keep track of function parameters in
3514
/// C.
3515
struct GNUCompatibleParamWarning {
3516
  ParmVarDecl *OldParm;
3517
  ParmVarDecl *NewParm;
3518
  QualType PromotedType;
3519
};
3520
3521
} // end anonymous namespace
3522
3523
// Determine whether the previous declaration was a definition, implicit
3524
// declaration, or a declaration.
3525
template <typename T>
3526
static std::pair<diag::kind, SourceLocation>
3527
193
getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3528
193
  diag::kind PrevDiag;
3529
193
  SourceLocation OldLocation = Old->getLocation();
3530
193
  if (Old->isThisDeclarationADefinition())
3531
193
    PrevDiag = diag::note_previous_definition;
3532
0
  else if (Old->isImplicit()) {
3533
0
    PrevDiag = diag::note_previous_implicit_declaration;
3534
0
    if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3535
0
      if (FD->getBuiltinID())
3536
0
        PrevDiag = diag::note_previous_builtin_declaration;
3537
0
    }
3538
0
    if (OldLocation.isInvalid())
3539
0
      OldLocation = New->getLocation();
3540
0
  } else
3541
0
    PrevDiag = diag::note_previous_declaration;
3542
193
  return std::make_pair(PrevDiag, OldLocation);
3543
193
}
Unexecuted instantiation: SemaDecl.cpp:std::__1::pair<unsigned int, clang::SourceLocation> getNoteDiagForInvalidRedeclaration<clang::FunctionDecl>(clang::FunctionDecl const*, clang::FunctionDecl const*)
SemaDecl.cpp:std::__1::pair<unsigned int, clang::SourceLocation> getNoteDiagForInvalidRedeclaration<clang::VarDecl>(clang::VarDecl const*, clang::VarDecl const*)
Line
Count
Source
3527
193
getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3528
193
  diag::kind PrevDiag;
3529
193
  SourceLocation OldLocation = Old->getLocation();
3530
193
  if (Old->isThisDeclarationADefinition())
3531
193
    PrevDiag = diag::note_previous_definition;
3532
0
  else if (Old->isImplicit()) {
3533
0
    PrevDiag = diag::note_previous_implicit_declaration;
3534
0
    if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3535
0
      if (FD->getBuiltinID())
3536
0
        PrevDiag = diag::note_previous_builtin_declaration;
3537
0
    }
3538
0
    if (OldLocation.isInvalid())
3539
0
      OldLocation = New->getLocation();
3540
0
  } else
3541
0
    PrevDiag = diag::note_previous_declaration;
3542
193
  return std::make_pair(PrevDiag, OldLocation);
3543
193
}
3544
3545
/// canRedefineFunction - checks if a function can be redefined. Currently,
3546
/// only extern inline functions can be redefined, and even then only in
3547
/// GNU89 mode.
3548
static bool canRedefineFunction(const FunctionDecl *FD,
3549
0
                                const LangOptions& LangOpts) {
3550
0
  return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3551
0
          !LangOpts.CPlusPlus &&
3552
0
          FD->isInlineSpecified() &&
3553
0
          FD->getStorageClass() == SC_Extern);
3554
0
}
3555
3556
0
const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3557
0
  const AttributedType *AT = T->getAs<AttributedType>();
3558
0
  while (AT && !AT->isCallingConv())
3559
0
    AT = AT->getModifiedType()->getAs<AttributedType>();
3560
0
  return AT;
3561
0
}
3562
3563
template <typename T>
3564
183
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3565
183
  const DeclContext *DC = Old->getDeclContext();
3566
183
  if (DC->isRecord())
3567
0
    return false;
3568
3569
183
  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3570
183
  if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3571
0
    return true;
3572
183
  if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3573
0
    return true;
3574
183
  return false;
3575
183
}
Unexecuted instantiation: SemaDecl.cpp:bool haveIncompatibleLanguageLinkages<clang::FunctionDecl>(clang::FunctionDecl const*, clang::FunctionDecl const*)
SemaDecl.cpp:bool haveIncompatibleLanguageLinkages<clang::VarDecl>(clang::VarDecl const*, clang::VarDecl const*)
Line
Count
Source
3564
183
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3565
183
  const DeclContext *DC = Old->getDeclContext();
3566
183
  if (DC->isRecord())
3567
0
    return false;
3568
3569
183
  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3570
183
  if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3571
0
    return true;
3572
183
  if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3573
0
    return true;
3574
183
  return false;
3575
183
}
3576
3577
0
template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
Unexecuted instantiation: SemaDecl.cpp:bool isExternC<clang::FunctionDecl>(clang::FunctionDecl*)
Unexecuted instantiation: SemaDecl.cpp:bool isExternC<clang::VarDecl>(clang::VarDecl*)
3578
0
static bool isExternC(VarTemplateDecl *) { return false; }
3579
0
static bool isExternC(FunctionTemplateDecl *) { return false; }
3580
3581
/// Check whether a redeclaration of an entity introduced by a
3582
/// using-declaration is valid, given that we know it's not an overload
3583
/// (nor a hidden tag declaration).
3584
template<typename ExpectedDecl>
3585
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3586
0
                                   ExpectedDecl *New) {
3587
  // C++11 [basic.scope.declarative]p4:
3588
  //   Given a set of declarations in a single declarative region, each of
3589
  //   which specifies the same unqualified name,
3590
  //   -- they shall all refer to the same entity, or all refer to functions
3591
  //      and function templates; or
3592
  //   -- exactly one declaration shall declare a class name or enumeration
3593
  //      name that is not a typedef name and the other declarations shall all
3594
  //      refer to the same variable or enumerator, or all refer to functions
3595
  //      and function templates; in this case the class name or enumeration
3596
  //      name is hidden (3.3.10).
3597
3598
  // C++11 [namespace.udecl]p14:
3599
  //   If a function declaration in namespace scope or block scope has the
3600
  //   same name and the same parameter-type-list as a function introduced
3601
  //   by a using-declaration, and the declarations do not declare the same
3602
  //   function, the program is ill-formed.
3603
3604
0
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3605
0
  if (Old &&
3606
0
      !Old->getDeclContext()->getRedeclContext()->Equals(
3607
0
          New->getDeclContext()->getRedeclContext()) &&
3608
0
      !(isExternC(Old) && isExternC(New)))
3609
0
    Old = nullptr;
3610
3611
0
  if (!Old) {
3612
0
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3613
0
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3614
0
    S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3615
0
    return true;
3616
0
  }
3617
0
  return false;
3618
0
}
Unexecuted instantiation: SemaDecl.cpp:bool checkUsingShadowRedecl<clang::FunctionTemplateDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::FunctionTemplateDecl*)
Unexecuted instantiation: SemaDecl.cpp:bool checkUsingShadowRedecl<clang::FunctionDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::FunctionDecl*)
Unexecuted instantiation: SemaDecl.cpp:bool checkUsingShadowRedecl<clang::VarTemplateDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::VarTemplateDecl*)
Unexecuted instantiation: SemaDecl.cpp:bool checkUsingShadowRedecl<clang::VarDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::VarDecl*)
3619
3620
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3621
0
                                            const FunctionDecl *B) {
3622
0
  assert(A->getNumParams() == B->getNumParams());
3623
3624
0
  auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3625
0
    const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3626
0
    const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3627
0
    if (AttrA == AttrB)
3628
0
      return true;
3629
0
    return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3630
0
           AttrA->isDynamic() == AttrB->isDynamic();
3631
0
  };
3632
3633
0
  return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3634
0
}
3635
3636
/// If necessary, adjust the semantic declaration context for a qualified
3637
/// declaration to name the correct inline namespace within the qualifier.
3638
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3639
193
                                               DeclaratorDecl *OldD) {
3640
  // The only case where we need to update the DeclContext is when
3641
  // redeclaration lookup for a qualified name finds a declaration
3642
  // in an inline namespace within the context named by the qualifier:
3643
  //
3644
  //   inline namespace N { int f(); }
3645
  //   int ::f(); // Sema DC needs adjusting from :: to N::.
3646
  //
3647
  // For unqualified declarations, the semantic context *can* change
3648
  // along the redeclaration chain (for local extern declarations,
3649
  // extern "C" declarations, and friend declarations in particular).
3650
193
  if (!NewD->getQualifier())
3651
193
    return;
3652
3653
  // NewD is probably already in the right context.
3654
0
  auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3655
0
  auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3656
0
  if (NamedDC->Equals(SemaDC))
3657
0
    return;
3658
3659
0
  assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3660
0
          NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3661
0
         "unexpected context for redeclaration");
3662
3663
0
  auto *LexDC = NewD->getLexicalDeclContext();
3664
0
  auto FixSemaDC = [=](NamedDecl *D) {
3665
0
    if (!D)
3666
0
      return;
3667
0
    D->setDeclContext(SemaDC);
3668
0
    D->setLexicalDeclContext(LexDC);
3669
0
  };
3670
3671
0
  FixSemaDC(NewD);
3672
0
  if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3673
0
    FixSemaDC(FD->getDescribedFunctionTemplate());
3674
0
  else if (auto *VD = dyn_cast<VarDecl>(NewD))
3675
0
    FixSemaDC(VD->getDescribedVarTemplate());
3676
0
}
3677
3678
/// MergeFunctionDecl - We just parsed a function 'New' from
3679
/// declarator D which has the same name and scope as a previous
3680
/// declaration 'Old'.  Figure out how to resolve this situation,
3681
/// merging decls or emitting diagnostics as appropriate.
3682
///
3683
/// In C++, New and Old must be declarations that are not
3684
/// overloaded. Use IsOverload to determine whether New and Old are
3685
/// overloaded, and to select the Old declaration that New should be
3686
/// merged with.
3687
///
3688
/// Returns true if there was an error, false otherwise.
3689
bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3690
3
                             bool MergeTypeWithOld, bool NewDeclIsDefn) {
3691
  // Verify the old decl was also a function.
3692
3
  FunctionDecl *Old = OldD->getAsFunction();
3693
3
  if (!Old) {
3694
3
    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3695
0
      if (New->getFriendObjectKind()) {
3696
0
        Diag(New->getLocation(), diag::err_using_decl_friend);
3697
0
        Diag(Shadow->getTargetDecl()->getLocation(),
3698
0
             diag::note_using_decl_target);
3699
0
        Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3700
0
            << 0;
3701
0
        return true;
3702
0
      }
3703
3704
      // Check whether the two declarations might declare the same function or
3705
      // function template.
3706
0
      if (FunctionTemplateDecl *NewTemplate =
3707
0
              New->getDescribedFunctionTemplate()) {
3708
0
        if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3709
0
                                                         NewTemplate))
3710
0
          return true;
3711
0
        OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3712
0
                         ->getAsFunction();
3713
0
      } else {
3714
0
        if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3715
0
          return true;
3716
0
        OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3717
0
      }
3718
3
    } else {
3719
3
      Diag(New->getLocation(), diag::err_redefinition_different_kind)
3720
3
        << New->getDeclName();
3721
3
      notePreviousDefinition(OldD, New->getLocation());
3722
3
      return true;
3723
3
    }
3724
3
  }
3725
3726
  // If the old declaration was found in an inline namespace and the new
3727
  // declaration was qualified, update the DeclContext to match.
3728
0
  adjustDeclContextForDeclaratorDecl(New, Old);
3729
3730
  // If the old declaration is invalid, just give up here.
3731
0
  if (Old->isInvalidDecl())
3732
0
    return true;
3733
3734
  // Disallow redeclaration of some builtins.
3735
0
  if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3736
0
    Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3737
0
    Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3738
0
        << Old << Old->getType();
3739
0
    return true;
3740
0
  }
3741
3742
0
  diag::kind PrevDiag;
3743
0
  SourceLocation OldLocation;
3744
0
  std::tie(PrevDiag, OldLocation) =
3745
0
      getNoteDiagForInvalidRedeclaration(Old, New);
3746
3747
  // Don't complain about this if we're in GNU89 mode and the old function
3748
  // is an extern inline function.
3749
  // Don't complain about specializations. They are not supposed to have
3750
  // storage classes.
3751
0
  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3752
0
      New->getStorageClass() == SC_Static &&
3753
0
      Old->hasExternalFormalLinkage() &&
3754
0
      !New->getTemplateSpecializationInfo() &&
3755
0
      !canRedefineFunction(Old, getLangOpts())) {
3756
0
    if (getLangOpts().MicrosoftExt) {
3757
0
      Diag(New->getLocation(), diag::ext_static_non_static) << New;
3758
0
      Diag(OldLocation, PrevDiag) << Old << Old->getType();
3759
0
    } else {
3760
0
      Diag(New->getLocation(), diag::err_static_non_static) << New;
3761
0
      Diag(OldLocation, PrevDiag) << Old << Old->getType();
3762
0
      return true;
3763
0
    }
3764
0
  }
3765
3766
0
  if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3767
0
    if (!Old->hasAttr<InternalLinkageAttr>()) {
3768
0
      Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3769
0
          << ILA;
3770
0
      Diag(Old->getLocation(), diag::note_previous_declaration);
3771
0
      New->dropAttr<InternalLinkageAttr>();
3772
0
    }
3773
3774
0
  if (auto *EA = New->getAttr<ErrorAttr>()) {
3775
0
    if (!Old->hasAttr<ErrorAttr>()) {
3776
0
      Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3777
0
      Diag(Old->getLocation(), diag::note_previous_declaration);
3778
0
      New->dropAttr<ErrorAttr>();
3779
0
    }
3780
0
  }
3781
3782
0
  if (CheckRedeclarationInModule(New, Old))
3783
0
    return true;
3784
3785
0
  if (!getLangOpts().CPlusPlus) {
3786
0
    bool OldOvl = Old->hasAttr<OverloadableAttr>();
3787
0
    if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3788
0
      Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3789
0
        << New << OldOvl;
3790
3791
      // Try our best to find a decl that actually has the overloadable
3792
      // attribute for the note. In most cases (e.g. programs with only one
3793
      // broken declaration/definition), this won't matter.
3794
      //
3795
      // FIXME: We could do this if we juggled some extra state in
3796
      // OverloadableAttr, rather than just removing it.
3797
0
      const Decl *DiagOld = Old;
3798
0
      if (OldOvl) {
3799
0
        auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3800
0
          const auto *A = D->getAttr<OverloadableAttr>();
3801
0
          return A && !A->isImplicit();
3802
0
        });
3803
        // If we've implicitly added *all* of the overloadable attrs to this
3804
        // chain, emitting a "previous redecl" note is pointless.
3805
0
        DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3806
0
      }
3807
3808
0
      if (DiagOld)
3809
0
        Diag(DiagOld->getLocation(),
3810
0
             diag::note_attribute_overloadable_prev_overload)
3811
0
          << OldOvl;
3812
3813
0
      if (OldOvl)
3814
0
        New->addAttr(OverloadableAttr::CreateImplicit(Context));
3815
0
      else
3816
0
        New->dropAttr<OverloadableAttr>();
3817
0
    }
3818
0
  }
3819
3820
  // It is not permitted to redeclare an SME function with different SME
3821
  // attributes.
3822
0
  if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3823
0
    Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3824
0
        << New->getType() << Old->getType();
3825
0
    Diag(OldLocation, diag::note_previous_declaration);
3826
0
    return true;
3827
0
  }
3828
3829
  // If a function is first declared with a calling convention, but is later
3830
  // declared or defined without one, all following decls assume the calling
3831
  // convention of the first.
3832
  //
3833
  // It's OK if a function is first declared without a calling convention,
3834
  // but is later declared or defined with the default calling convention.
3835
  //
3836
  // To test if either decl has an explicit calling convention, we look for
3837
  // AttributedType sugar nodes on the type as written.  If they are missing or
3838
  // were canonicalized away, we assume the calling convention was implicit.
3839
  //
3840
  // Note also that we DO NOT return at this point, because we still have
3841
  // other tests to run.
3842
0
  QualType OldQType = Context.getCanonicalType(Old->getType());
3843
0
  QualType NewQType = Context.getCanonicalType(New->getType());
3844
0
  const FunctionType *OldType = cast<FunctionType>(OldQType);
3845
0
  const FunctionType *NewType = cast<FunctionType>(NewQType);
3846
0
  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3847
0
  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3848
0
  bool RequiresAdjustment = false;
3849
3850
0
  if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3851
0
    FunctionDecl *First = Old->getFirstDecl();
3852
0
    const FunctionType *FT =
3853
0
        First->getType().getCanonicalType()->castAs<FunctionType>();
3854
0
    FunctionType::ExtInfo FI = FT->getExtInfo();
3855
0
    bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3856
0
    if (!NewCCExplicit) {
3857
      // Inherit the CC from the previous declaration if it was specified
3858
      // there but not here.
3859
0
      NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3860
0
      RequiresAdjustment = true;
3861
0
    } else if (Old->getBuiltinID()) {
3862
      // Builtin attribute isn't propagated to the new one yet at this point,
3863
      // so we check if the old one is a builtin.
3864
3865
      // Calling Conventions on a Builtin aren't really useful and setting a
3866
      // default calling convention and cdecl'ing some builtin redeclarations is
3867
      // common, so warn and ignore the calling convention on the redeclaration.
3868
0
      Diag(New->getLocation(), diag::warn_cconv_unsupported)
3869
0
          << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3870
0
          << (int)CallingConventionIgnoredReason::BuiltinFunction;
3871
0
      NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3872
0
      RequiresAdjustment = true;
3873
0
    } else {
3874
      // Calling conventions aren't compatible, so complain.
3875
0
      bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3876
0
      Diag(New->getLocation(), diag::err_cconv_change)
3877
0
        << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3878
0
        << !FirstCCExplicit
3879
0
        << (!FirstCCExplicit ? "" :
3880
0
            FunctionType::getNameForCallConv(FI.getCC()));
3881
3882
      // Put the note on the first decl, since it is the one that matters.
3883
0
      Diag(First->getLocation(), diag::note_previous_declaration);
3884
0
      return true;
3885
0
    }
3886
0
  }
3887
3888
  // FIXME: diagnose the other way around?
3889
0
  if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3890
0
    NewTypeInfo = NewTypeInfo.withNoReturn(true);
3891
0
    RequiresAdjustment = true;
3892
0
  }
3893
3894
  // Merge regparm attribute.
3895
0
  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3896
0
      OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3897
0
    if (NewTypeInfo.getHasRegParm()) {
3898
0
      Diag(New->getLocation(), diag::err_regparm_mismatch)
3899
0
        << NewType->getRegParmType()
3900
0
        << OldType->getRegParmType();
3901
0
      Diag(OldLocation, diag::note_previous_declaration);
3902
0
      return true;
3903
0
    }
3904
3905
0
    NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3906
0
    RequiresAdjustment = true;
3907
0
  }
3908
3909
  // Merge ns_returns_retained attribute.
3910
0
  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3911
0
    if (NewTypeInfo.getProducesResult()) {
3912
0
      Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3913
0
          << "'ns_returns_retained'";
3914
0
      Diag(OldLocation, diag::note_previous_declaration);
3915
0
      return true;
3916
0
    }
3917
3918
0
    NewTypeInfo = NewTypeInfo.withProducesResult(true);
3919
0
    RequiresAdjustment = true;
3920
0
  }
3921
3922
0
  if (OldTypeInfo.getNoCallerSavedRegs() !=
3923
0
      NewTypeInfo.getNoCallerSavedRegs()) {
3924
0
    if (NewTypeInfo.getNoCallerSavedRegs()) {
3925
0
      AnyX86NoCallerSavedRegistersAttr *Attr =
3926
0
        New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3927
0
      Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3928
0
      Diag(OldLocation, diag::note_previous_declaration);
3929
0
      return true;
3930
0
    }
3931
3932
0
    NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3933
0
    RequiresAdjustment = true;
3934
0
  }
3935
3936
0
  if (RequiresAdjustment) {
3937
0
    const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3938
0
    AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3939
0
    New->setType(QualType(AdjustedType, 0));
3940
0
    NewQType = Context.getCanonicalType(New->getType());
3941
0
  }
3942
3943
  // If this redeclaration makes the function inline, we may need to add it to
3944
  // UndefinedButUsed.
3945
0
  if (!Old->isInlined() && New->isInlined() &&
3946
0
      !New->hasAttr<GNUInlineAttr>() &&
3947
0
      !getLangOpts().GNUInline &&
3948
0
      Old->isUsed(false) &&
3949
0
      !Old->isDefined() && !New->isThisDeclarationADefinition())
3950
0
    UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3951
0
                                           SourceLocation()));
3952
3953
  // If this redeclaration makes it newly gnu_inline, we don't want to warn
3954
  // about it.
3955
0
  if (New->hasAttr<GNUInlineAttr>() &&
3956
0
      Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3957
0
    UndefinedButUsed.erase(Old->getCanonicalDecl());
3958
0
  }
3959
3960
  // If pass_object_size params don't match up perfectly, this isn't a valid
3961
  // redeclaration.
3962
0
  if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3963
0
      !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3964
0
    Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3965
0
        << New->getDeclName();
3966
0
    Diag(OldLocation, PrevDiag) << Old << Old->getType();
3967
0
    return true;
3968
0
  }
3969
3970
0
  if (getLangOpts().CPlusPlus) {
3971
0
    OldQType = Context.getCanonicalType(Old->getType());
3972
0
    NewQType = Context.getCanonicalType(New->getType());
3973
3974
    // Go back to the type source info to compare the declared return types,
3975
    // per C++1y [dcl.type.auto]p13:
3976
    //   Redeclarations or specializations of a function or function template
3977
    //   with a declared return type that uses a placeholder type shall also
3978
    //   use that placeholder, not a deduced type.
3979
0
    QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3980
0
    QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3981
0
    if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3982
0
        canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3983
0
                                       OldDeclaredReturnType)) {
3984
0
      QualType ResQT;
3985
0
      if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3986
0
          OldDeclaredReturnType->isObjCObjectPointerType())
3987
        // FIXME: This does the wrong thing for a deduced return type.
3988
0
        ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3989
0
      if (ResQT.isNull()) {
3990
0
        if (New->isCXXClassMember() && New->isOutOfLine())
3991
0
          Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3992
0
              << New << New->getReturnTypeSourceRange();
3993
0
        else
3994
0
          Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3995
0
              << New->getReturnTypeSourceRange();
3996
0
        Diag(OldLocation, PrevDiag) << Old << Old->getType()
3997
0
                                    << Old->getReturnTypeSourceRange();
3998
0
        return true;
3999
0
      }
4000
0
      else
4001
0
        NewQType = ResQT;
4002
0
    }
4003
4004
0
    QualType OldReturnType = OldType->getReturnType();
4005
0
    QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4006
0
    if (OldReturnType != NewReturnType) {
4007
      // If this function has a deduced return type and has already been
4008
      // defined, copy the deduced value from the old declaration.
4009
0
      AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4010
0
      if (OldAT && OldAT->isDeduced()) {
4011
0
        QualType DT = OldAT->getDeducedType();
4012
0
        if (DT.isNull()) {
4013
0
          New->setType(SubstAutoTypeDependent(New->getType()));
4014
0
          NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4015
0
        } else {
4016
0
          New->setType(SubstAutoType(New->getType(), DT));
4017
0
          NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4018
0
        }
4019
0
      }
4020
0
    }
4021
4022
0
    const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4023
0
    CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4024
0
    if (OldMethod && NewMethod) {
4025
      // Preserve triviality.
4026
0
      NewMethod->setTrivial(OldMethod->isTrivial());
4027
4028
      // MSVC allows explicit template specialization at class scope:
4029
      // 2 CXXMethodDecls referring to the same function will be injected.
4030
      // We don't want a redeclaration error.
4031
0
      bool IsClassScopeExplicitSpecialization =
4032
0
                              OldMethod->isFunctionTemplateSpecialization() &&
4033
0
                              NewMethod->isFunctionTemplateSpecialization();
4034
0
      bool isFriend = NewMethod->getFriendObjectKind();
4035
4036
0
      if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4037
0
          !IsClassScopeExplicitSpecialization) {
4038
        //    -- Member function declarations with the same name and the
4039
        //       same parameter types cannot be overloaded if any of them
4040
        //       is a static member function declaration.
4041
0
        if (OldMethod->isStatic() != NewMethod->isStatic()) {
4042
0
          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4043
0
          Diag(OldLocation, PrevDiag) << Old << Old->getType();
4044
0
          return true;
4045
0
        }
4046
4047
        // C++ [class.mem]p1:
4048
        //   [...] A member shall not be declared twice in the
4049
        //   member-specification, except that a nested class or member
4050
        //   class template can be declared and then later defined.
4051
0
        if (!inTemplateInstantiation()) {
4052
0
          unsigned NewDiag;
4053
0
          if (isa<CXXConstructorDecl>(OldMethod))
4054
0
            NewDiag = diag::err_constructor_redeclared;
4055
0
          else if (isa<CXXDestructorDecl>(NewMethod))
4056
0
            NewDiag = diag::err_destructor_redeclared;
4057
0
          else if (isa<CXXConversionDecl>(NewMethod))
4058
0
            NewDiag = diag::err_conv_function_redeclared;
4059
0
          else
4060
0
            NewDiag = diag::err_member_redeclared;
4061
4062
0
          Diag(New->getLocation(), NewDiag);
4063
0
        } else {
4064
0
          Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4065
0
            << New << New->getType();
4066
0
        }
4067
0
        Diag(OldLocation, PrevDiag) << Old << Old->getType();
4068
0
        return true;
4069
4070
      // Complain if this is an explicit declaration of a special
4071
      // member that was initially declared implicitly.
4072
      //
4073
      // As an exception, it's okay to befriend such methods in order
4074
      // to permit the implicit constructor/destructor/operator calls.
4075
0
      } else if (OldMethod->isImplicit()) {
4076
0
        if (isFriend) {
4077
0
          NewMethod->setImplicit();
4078
0
        } else {
4079
0
          Diag(NewMethod->getLocation(),
4080
0
               diag::err_definition_of_implicitly_declared_member)
4081
0
            << New << getSpecialMember(OldMethod);
4082
0
          return true;
4083
0
        }
4084
0
      } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4085
0
        Diag(NewMethod->getLocation(),
4086
0
             diag::err_definition_of_explicitly_defaulted_member)
4087
0
          << getSpecialMember(OldMethod);
4088
0
        return true;
4089
0
      }
4090
0
    }
4091
4092
    // C++1z [over.load]p2
4093
    //   Certain function declarations cannot be overloaded:
4094
    //     -- Function declarations that differ only in the return type,
4095
    //        the exception specification, or both cannot be overloaded.
4096
4097
    // Check the exception specifications match. This may recompute the type of
4098
    // both Old and New if it resolved exception specifications, so grab the
4099
    // types again after this. Because this updates the type, we do this before
4100
    // any of the other checks below, which may update the "de facto" NewQType
4101
    // but do not necessarily update the type of New.
4102
0
    if (CheckEquivalentExceptionSpec(Old, New))
4103
0
      return true;
4104
4105
    // C++11 [dcl.attr.noreturn]p1:
4106
    //   The first declaration of a function shall specify the noreturn
4107
    //   attribute if any declaration of that function specifies the noreturn
4108
    //   attribute.
4109
0
    if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4110
0
      if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4111
0
        Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4112
0
            << NRA;
4113
0
        Diag(Old->getLocation(), diag::note_previous_declaration);
4114
0
      }
4115
4116
    // C++11 [dcl.attr.depend]p2:
4117
    //   The first declaration of a function shall specify the
4118
    //   carries_dependency attribute for its declarator-id if any declaration
4119
    //   of the function specifies the carries_dependency attribute.
4120
0
    const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4121
0
    if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4122
0
      Diag(CDA->getLocation(),
4123
0
           diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4124
0
      Diag(Old->getFirstDecl()->getLocation(),
4125
0
           diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4126
0
    }
4127
4128
    // (C++98 8.3.5p3):
4129
    //   All declarations for a function shall agree exactly in both the
4130
    //   return type and the parameter-type-list.
4131
    // We also want to respect all the extended bits except noreturn.
4132
4133
    // noreturn should now match unless the old type info didn't have it.
4134
0
    QualType OldQTypeForComparison = OldQType;
4135
0
    if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4136
0
      auto *OldType = OldQType->castAs<FunctionProtoType>();
4137
0
      const FunctionType *OldTypeForComparison
4138
0
        = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4139
0
      OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4140
0
      assert(OldQTypeForComparison.isCanonical());
4141
0
    }
4142
4143
0
    if (haveIncompatibleLanguageLinkages(Old, New)) {
4144
      // As a special case, retain the language linkage from previous
4145
      // declarations of a friend function as an extension.
4146
      //
4147
      // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4148
      // and is useful because there's otherwise no way to specify language
4149
      // linkage within class scope.
4150
      //
4151
      // Check cautiously as the friend object kind isn't yet complete.
4152
0
      if (New->getFriendObjectKind() != Decl::FOK_None) {
4153
0
        Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4154
0
        Diag(OldLocation, PrevDiag);
4155
0
      } else {
4156
0
        Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4157
0
        Diag(OldLocation, PrevDiag);
4158
0
        return true;
4159
0
      }
4160
0
    }
4161
4162
    // If the function types are compatible, merge the declarations. Ignore the
4163
    // exception specifier because it was already checked above in
4164
    // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4165
    // about incompatible types under -fms-compatibility.
4166
0
    if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4167
0
                                                         NewQType))
4168
0
      return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4169
4170
    // If the types are imprecise (due to dependent constructs in friends or
4171
    // local extern declarations), it's OK if they differ. We'll check again
4172
    // during instantiation.
4173
0
    if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4174
0
      return false;
4175
4176
    // Fall through for conflicting redeclarations and redefinitions.
4177
0
  }
4178
4179
  // C: Function types need to be compatible, not identical. This handles
4180
  // duplicate function decls like "void f(int); void f(enum X);" properly.
4181
0
  if (!getLangOpts().CPlusPlus) {
4182
    // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4183
    // type is specified by a function definition that contains a (possibly
4184
    // empty) identifier list, both shall agree in the number of parameters
4185
    // and the type of each parameter shall be compatible with the type that
4186
    // results from the application of default argument promotions to the
4187
    // type of the corresponding identifier. ...
4188
    // This cannot be handled by ASTContext::typesAreCompatible() because that
4189
    // doesn't know whether the function type is for a definition or not when
4190
    // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4191
    // we need to cover here is that the number of arguments agree as the
4192
    // default argument promotion rules were already checked by
4193
    // ASTContext::typesAreCompatible().
4194
0
    if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4195
0
        Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4196
0
      if (Old->hasInheritedPrototype())
4197
0
        Old = Old->getCanonicalDecl();
4198
0
      Diag(New->getLocation(), diag::err_conflicting_types) << New;
4199
0
      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4200
0
      return true;
4201
0
    }
4202
4203
    // If we are merging two functions where only one of them has a prototype,
4204
    // we may have enough information to decide to issue a diagnostic that the
4205
    // function without a protoype will change behavior in C23. This handles
4206
    // cases like:
4207
    //   void i(); void i(int j);
4208
    //   void i(int j); void i();
4209
    //   void i(); void i(int j) {}
4210
    // See ActOnFinishFunctionBody() for other cases of the behavior change
4211
    // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4212
    // type without a prototype.
4213
0
    if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4214
0
        !New->isImplicit() && !Old->isImplicit()) {
4215
0
      const FunctionDecl *WithProto, *WithoutProto;
4216
0
      if (New->hasWrittenPrototype()) {
4217
0
        WithProto = New;
4218
0
        WithoutProto = Old;
4219
0
      } else {
4220
0
        WithProto = Old;
4221
0
        WithoutProto = New;
4222
0
      }
4223
4224
0
      if (WithProto->getNumParams() != 0) {
4225
0
        if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4226
          // The one without the prototype will be changing behavior in C23, so
4227
          // warn about that one so long as it's a user-visible declaration.
4228
0
          bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4229
0
          if (WithoutProto == New)
4230
0
            IsWithoutProtoADef = NewDeclIsDefn;
4231
0
          else
4232
0
            IsWithProtoADef = NewDeclIsDefn;
4233
0
          Diag(WithoutProto->getLocation(),
4234
0
               diag::warn_non_prototype_changes_behavior)
4235
0
              << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4236
0
              << (WithoutProto == Old) << IsWithProtoADef;
4237
4238
          // The reason the one without the prototype will be changing behavior
4239
          // is because of the one with the prototype, so note that so long as
4240
          // it's a user-visible declaration. There is one exception to this:
4241
          // when the new declaration is a definition without a prototype, the
4242
          // old declaration with a prototype is not the cause of the issue,
4243
          // and that does not need to be noted because the one with a
4244
          // prototype will not change behavior in C23.
4245
0
          if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4246
0
              !IsWithoutProtoADef)
4247
0
            Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4248
0
        }
4249
0
      }
4250
0
    }
4251
4252
0
    if (Context.typesAreCompatible(OldQType, NewQType)) {
4253
0
      const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4254
0
      const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4255
0
      const FunctionProtoType *OldProto = nullptr;
4256
0
      if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4257
0
          (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4258
        // The old declaration provided a function prototype, but the
4259
        // new declaration does not. Merge in the prototype.
4260
0
        assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4261
0
        NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4262
0
                                           OldProto->getParamTypes(),
4263
0
                                           OldProto->getExtProtoInfo());
4264
0
        New->setType(NewQType);
4265
0
        New->setHasInheritedPrototype();
4266
4267
        // Synthesize parameters with the same types.
4268
0
        SmallVector<ParmVarDecl *, 16> Params;
4269
0
        for (const auto &ParamType : OldProto->param_types()) {
4270
0
          ParmVarDecl *Param = ParmVarDecl::Create(
4271
0
              Context, New, SourceLocation(), SourceLocation(), nullptr,
4272
0
              ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4273
0
          Param->setScopeInfo(0, Params.size());
4274
0
          Param->setImplicit();
4275
0
          Params.push_back(Param);
4276
0
        }
4277
4278
0
        New->setParams(Params);
4279
0
      }
4280
4281
0
      return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4282
0
    }
4283
0
  }
4284
4285
  // Check if the function types are compatible when pointer size address
4286
  // spaces are ignored.
4287
0
  if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4288
0
    return false;
4289
4290
  // GNU C permits a K&R definition to follow a prototype declaration
4291
  // if the declared types of the parameters in the K&R definition
4292
  // match the types in the prototype declaration, even when the
4293
  // promoted types of the parameters from the K&R definition differ
4294
  // from the types in the prototype. GCC then keeps the types from
4295
  // the prototype.
4296
  //
4297
  // If a variadic prototype is followed by a non-variadic K&R definition,
4298
  // the K&R definition becomes variadic.  This is sort of an edge case, but
4299
  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4300
  // C99 6.9.1p8.
4301
0
  if (!getLangOpts().CPlusPlus &&
4302
0
      Old->hasPrototype() && !New->hasPrototype() &&
4303
0
      New->getType()->getAs<FunctionProtoType>() &&
4304
0
      Old->getNumParams() == New->getNumParams()) {
4305
0
    SmallVector<QualType, 16> ArgTypes;
4306
0
    SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4307
0
    const FunctionProtoType *OldProto
4308
0
      = Old->getType()->getAs<FunctionProtoType>();
4309
0
    const FunctionProtoType *NewProto
4310
0
      = New->getType()->getAs<FunctionProtoType>();
4311
4312
    // Determine whether this is the GNU C extension.
4313
0
    QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4314
0
                                               NewProto->getReturnType());
4315
0
    bool LooseCompatible = !MergedReturn.isNull();
4316
0
    for (unsigned Idx = 0, End = Old->getNumParams();
4317
0
         LooseCompatible && Idx != End; ++Idx) {
4318
0
      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4319
0
      ParmVarDecl *NewParm = New->getParamDecl(Idx);
4320
0
      if (Context.typesAreCompatible(OldParm->getType(),
4321
0
                                     NewProto->getParamType(Idx))) {
4322
0
        ArgTypes.push_back(NewParm->getType());
4323
0
      } else if (Context.typesAreCompatible(OldParm->getType(),
4324
0
                                            NewParm->getType(),
4325
0
                                            /*CompareUnqualified=*/true)) {
4326
0
        GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4327
0
                                           NewProto->getParamType(Idx) };
4328
0
        Warnings.push_back(Warn);
4329
0
        ArgTypes.push_back(NewParm->getType());
4330
0
      } else
4331
0
        LooseCompatible = false;
4332
0
    }
4333
4334
0
    if (LooseCompatible) {
4335
0
      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4336
0
        Diag(Warnings[Warn].NewParm->getLocation(),
4337
0
             diag::ext_param_promoted_not_compatible_with_prototype)
4338
0
          << Warnings[Warn].PromotedType
4339
0
          << Warnings[Warn].OldParm->getType();
4340
0
        if (Warnings[Warn].OldParm->getLocation().isValid())
4341
0
          Diag(Warnings[Warn].OldParm->getLocation(),
4342
0
               diag::note_previous_declaration);
4343
0
      }
4344
4345
0
      if (MergeTypeWithOld)
4346
0
        New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4347
0
                                             OldProto->getExtProtoInfo()));
4348
0
      return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4349
0
    }
4350
4351
    // Fall through to diagnose conflicting types.
4352
0
  }
4353
4354
  // A function that has already been declared has been redeclared or
4355
  // defined with a different type; show an appropriate diagnostic.
4356
4357
  // If the previous declaration was an implicitly-generated builtin
4358
  // declaration, then at the very least we should use a specialized note.
4359
0
  unsigned BuiltinID;
4360
0
  if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4361
    // If it's actually a library-defined builtin function like 'malloc'
4362
    // or 'printf', just warn about the incompatible redeclaration.
4363
0
    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4364
0
      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4365
0
      Diag(OldLocation, diag::note_previous_builtin_declaration)
4366
0
        << Old << Old->getType();
4367
0
      return false;
4368
0
    }
4369
4370
0
    PrevDiag = diag::note_previous_builtin_declaration;
4371
0
  }
4372
4373
0
  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4374
0
  Diag(OldLocation, PrevDiag) << Old << Old->getType();
4375
0
  return true;
4376
0
}
4377
4378
/// Completes the merge of two function declarations that are
4379
/// known to be compatible.
4380
///
4381
/// This routine handles the merging of attributes and other
4382
/// properties of function declarations from the old declaration to
4383
/// the new declaration, once we know that New is in fact a
4384
/// redeclaration of Old.
4385
///
4386
/// \returns false
4387
bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4388
0
                                        Scope *S, bool MergeTypeWithOld) {
4389
  // Merge the attributes
4390
0
  mergeDeclAttributes(New, Old);
4391
4392
  // Merge "pure" flag.
4393
0
  if (Old->isPure())
4394
0
    New->setPure();
4395
4396
  // Merge "used" flag.
4397
0
  if (Old->getMostRecentDecl()->isUsed(false))
4398
0
    New->setIsUsed();
4399
4400
  // Merge attributes from the parameters.  These can mismatch with K&R
4401
  // declarations.
4402
0
  if (New->getNumParams() == Old->getNumParams())
4403
0
      for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4404
0
        ParmVarDecl *NewParam = New->getParamDecl(i);
4405
0
        ParmVarDecl *OldParam = Old->getParamDecl(i);
4406
0
        mergeParamDeclAttributes(NewParam, OldParam, *this);
4407
0
        mergeParamDeclTypes(NewParam, OldParam, *this);
4408
0
      }
4409
4410
0
  if (getLangOpts().CPlusPlus)
4411
0
    return MergeCXXFunctionDecl(New, Old, S);
4412
4413
  // Merge the function types so the we get the composite types for the return
4414
  // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4415
  // was visible.
4416
0
  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4417
0
  if (!Merged.isNull() && MergeTypeWithOld)
4418
0
    New->setType(Merged);
4419
4420
0
  return false;
4421
0
}
4422
4423
void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4424
0
                                ObjCMethodDecl *oldMethod) {
4425
  // Merge the attributes, including deprecated/unavailable
4426
0
  AvailabilityMergeKind MergeKind =
4427
0
      isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4428
0
          ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4429
0
                                     : AMK_ProtocolImplementation)
4430
0
          : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4431
0
                                                           : AMK_Override;
4432
4433
0
  mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4434
4435
  // Merge attributes from the parameters.
4436
0
  ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4437
0
                                       oe = oldMethod->param_end();
4438
0
  for (ObjCMethodDecl::param_iterator
4439
0
         ni = newMethod->param_begin(), ne = newMethod->param_end();
4440
0
       ni != ne && oi != oe; ++ni, ++oi)
4441
0
    mergeParamDeclAttributes(*ni, *oi, *this);
4442
4443
0
  CheckObjCMethodOverride(newMethod, oldMethod);
4444
0
}
4445
4446
10
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4447
10
  assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4448
4449
10
  S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4450
10
         ? diag::err_redefinition_different_type
4451
10
         : diag::err_redeclaration_different_type)
4452
10
    << New->getDeclName() << New->getType() << Old->getType();
4453
4454
10
  diag::kind PrevDiag;
4455
10
  SourceLocation OldLocation;
4456
10
  std::tie(PrevDiag, OldLocation)
4457
10
    = getNoteDiagForInvalidRedeclaration(Old, New);
4458
10
  S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4459
10
  New->setInvalidDecl();
4460
10
}
4461
4462
/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4463
/// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4464
/// emitting diagnostics as appropriate.
4465
///
4466
/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4467
/// to here in AddInitializerToDecl. We can't check them before the initializer
4468
/// is attached.
4469
void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4470
193
                             bool MergeTypeWithOld) {
4471
193
  if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4472
129
    return;
4473
4474
64
  QualType MergedT;
4475
64
  if (getLangOpts().CPlusPlus) {
4476
0
    if (New->getType()->isUndeducedType()) {
4477
      // We don't know what the new type is until the initializer is attached.
4478
0
      return;
4479
0
    } else if (Context.hasSameType(New->getType(), Old->getType())) {
4480
      // These could still be something that needs exception specs checked.
4481
0
      return MergeVarDeclExceptionSpecs(New, Old);
4482
0
    }
4483
    // C++ [basic.link]p10:
4484
    //   [...] the types specified by all declarations referring to a given
4485
    //   object or function shall be identical, except that declarations for an
4486
    //   array object can specify array types that differ by the presence or
4487
    //   absence of a major array bound (8.3.4).
4488
0
    else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4489
0
      const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4490
0
      const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4491
4492
      // We are merging a variable declaration New into Old. If it has an array
4493
      // bound, and that bound differs from Old's bound, we should diagnose the
4494
      // mismatch.
4495
0
      if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4496
0
        for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4497
0
             PrevVD = PrevVD->getPreviousDecl()) {
4498
0
          QualType PrevVDTy = PrevVD->getType();
4499
0
          if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4500
0
            continue;
4501
4502
0
          if (!Context.hasSameType(New->getType(), PrevVDTy))
4503
0
            return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4504
0
        }
4505
0
      }
4506
4507
0
      if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4508
0
        if (Context.hasSameType(OldArray->getElementType(),
4509
0
                                NewArray->getElementType()))
4510
0
          MergedT = New->getType();
4511
0
      }
4512
      // FIXME: Check visibility. New is hidden but has a complete type. If New
4513
      // has no array bound, it should not inherit one from Old, if Old is not
4514
      // visible.
4515
0
      else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4516
0
        if (Context.hasSameType(OldArray->getElementType(),
4517
0
                                NewArray->getElementType()))
4518
0
          MergedT = Old->getType();
4519
0
      }
4520
0
    }
4521
0
    else if (New->getType()->isObjCObjectPointerType() &&
4522
0
               Old->getType()->isObjCObjectPointerType()) {
4523
0
      MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4524
0
                                              Old->getType());
4525
0
    }
4526
64
  } else {
4527
    // C 6.2.7p2:
4528
    //   All declarations that refer to the same object or function shall have
4529
    //   compatible type.
4530
64
    MergedT = Context.mergeTypes(New->getType(), Old->getType());
4531
64
  }
4532
64
  if (MergedT.isNull()) {
4533
    // It's OK if we couldn't merge types if either type is dependent, for a
4534
    // block-scope variable. In other cases (static data members of class
4535
    // templates, variable templates, ...), we require the types to be
4536
    // equivalent.
4537
    // FIXME: The C++ standard doesn't say anything about this.
4538
10
    if ((New->getType()->isDependentType() ||
4539
10
         Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4540
      // If the old type was dependent, we can't merge with it, so the new type
4541
      // becomes dependent for now. We'll reproduce the original type when we
4542
      // instantiate the TypeSourceInfo for the variable.
4543
0
      if (!New->getType()->isDependentType() && MergeTypeWithOld)
4544
0
        New->setType(Context.DependentTy);
4545
0
      return;
4546
0
    }
4547
10
    return diagnoseVarDeclTypeMismatch(*this, New, Old);
4548
10
  }
4549
4550
  // Don't actually update the type on the new declaration if the old
4551
  // declaration was an extern declaration in a different scope.
4552
54
  if (MergeTypeWithOld)
4553
54
    New->setType(MergedT);
4554
54
}
4555
4556
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4557
193
                                  LookupResult &Previous) {
4558
  // C11 6.2.7p4:
4559
  //   For an identifier with internal or external linkage declared
4560
  //   in a scope in which a prior declaration of that identifier is
4561
  //   visible, if the prior declaration specifies internal or
4562
  //   external linkage, the type of the identifier at the later
4563
  //   declaration becomes the composite type.
4564
  //
4565
  // If the variable isn't visible, we do not merge with its type.
4566
193
  if (Previous.isShadowed())
4567
0
    return false;
4568
4569
193
  if (S.getLangOpts().CPlusPlus) {
4570
    // C++11 [dcl.array]p3:
4571
    //   If there is a preceding declaration of the entity in the same
4572
    //   scope in which the bound was specified, an omitted array bound
4573
    //   is taken to be the same as in that earlier declaration.
4574
0
    return NewVD->isPreviousDeclInSameBlockScope() ||
4575
0
           (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4576
0
            !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4577
193
  } else {
4578
    // If the old declaration was function-local, don't merge with its
4579
    // type unless we're in the same function.
4580
193
    return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4581
193
           OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4582
193
  }
4583
193
}
4584
4585
/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4586
/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4587
/// situation, merging decls or emitting diagnostics as appropriate.
4588
///
4589
/// Tentative definition rules (C99 6.9.2p2) are checked by
4590
/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4591
/// definitions here, since the initializer hasn't been attached.
4592
///
4593
194
void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4594
  // If the new decl is already invalid, don't do any other checking.
4595
194
  if (New->isInvalidDecl())
4596
0
    return;
4597
4598
194
  if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4599
0
    return;
4600
4601
194
  VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4602
4603
  // Verify the old decl was also a variable or variable template.
4604
194
  VarDecl *Old = nullptr;
4605
194
  VarTemplateDecl *OldTemplate = nullptr;
4606
194
  if (Previous.isSingleResult()) {
4607
194
    if (NewTemplate) {
4608
0
      OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4609
0
      Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4610
4611
0
      if (auto *Shadow =
4612
0
              dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4613
0
        if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4614
0
          return New->setInvalidDecl();
4615
194
    } else {
4616
194
      Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4617
4618
194
      if (auto *Shadow =
4619
194
              dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4620
0
        if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4621
0
          return New->setInvalidDecl();
4622
194
    }
4623
194
  }
4624
194
  if (!Old) {
4625
1
    Diag(New->getLocation(), diag::err_redefinition_different_kind)
4626
1
        << New->getDeclName();
4627
1
    notePreviousDefinition(Previous.getRepresentativeDecl(),
4628
1
                           New->getLocation());
4629
1
    return New->setInvalidDecl();
4630
1
  }
4631
4632
  // If the old declaration was found in an inline namespace and the new
4633
  // declaration was qualified, update the DeclContext to match.
4634
193
  adjustDeclContextForDeclaratorDecl(New, Old);
4635
4636
  // Ensure the template parameters are compatible.
4637
193
  if (NewTemplate &&
4638
193
      !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4639
0
                                      OldTemplate->getTemplateParameters(),
4640
0
                                      /*Complain=*/true, TPL_TemplateMatch))
4641
0
    return New->setInvalidDecl();
4642
4643
  // C++ [class.mem]p1:
4644
  //   A member shall not be declared twice in the member-specification [...]
4645
  //
4646
  // Here, we need only consider static data members.
4647
193
  if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4648
0
    Diag(New->getLocation(), diag::err_duplicate_member)
4649
0
      << New->getIdentifier();
4650
0
    Diag(Old->getLocation(), diag::note_previous_declaration);
4651
0
    New->setInvalidDecl();
4652
0
  }
4653
4654
193
  mergeDeclAttributes(New, Old);
4655
  // Warn if an already-declared variable is made a weak_import in a subsequent
4656
  // declaration
4657
193
  if (New->hasAttr<WeakImportAttr>() &&
4658
193
      Old->getStorageClass() == SC_None &&
4659
193
      !Old->hasAttr<WeakImportAttr>()) {
4660
0
    Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4661
0
    Diag(Old->getLocation(), diag::note_previous_declaration);
4662
    // Remove weak_import attribute on new declaration.
4663
0
    New->dropAttr<WeakImportAttr>();
4664
0
  }
4665
4666
193
  if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4667
0
    if (!Old->hasAttr<InternalLinkageAttr>()) {
4668
0
      Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4669
0
          << ILA;
4670
0
      Diag(Old->getLocation(), diag::note_previous_declaration);
4671
0
      New->dropAttr<InternalLinkageAttr>();
4672
0
    }
4673
4674
  // Merge the types.
4675
193
  VarDecl *MostRecent = Old->getMostRecentDecl();
4676
193
  if (MostRecent != Old) {
4677
0
    MergeVarDeclTypes(New, MostRecent,
4678
0
                      mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4679
0
    if (New->isInvalidDecl())
4680
0
      return;
4681
0
  }
4682
4683
193
  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4684
193
  if (New->isInvalidDecl())
4685
10
    return;
4686
4687
183
  diag::kind PrevDiag;
4688
183
  SourceLocation OldLocation;
4689
183
  std::tie(PrevDiag, OldLocation) =
4690
183
      getNoteDiagForInvalidRedeclaration(Old, New);
4691
4692
  // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4693
183
  if (New->getStorageClass() == SC_Static &&
4694
183
      !New->isStaticDataMember() &&
4695
183
      Old->hasExternalFormalLinkage()) {
4696
0
    if (getLangOpts().MicrosoftExt) {
4697
0
      Diag(New->getLocation(), diag::ext_static_non_static)
4698
0
          << New->getDeclName();
4699
0
      Diag(OldLocation, PrevDiag);
4700
0
    } else {
4701
0
      Diag(New->getLocation(), diag::err_static_non_static)
4702
0
          << New->getDeclName();
4703
0
      Diag(OldLocation, PrevDiag);
4704
0
      return New->setInvalidDecl();
4705
0
    }
4706
0
  }
4707
  // C99 6.2.2p4:
4708
  //   For an identifier declared with the storage-class specifier
4709
  //   extern in a scope in which a prior declaration of that
4710
  //   identifier is visible,23) if the prior declaration specifies
4711
  //   internal or external linkage, the linkage of the identifier at
4712
  //   the later declaration is the same as the linkage specified at
4713
  //   the prior declaration. If no prior declaration is visible, or
4714
  //   if the prior declaration specifies no linkage, then the
4715
  //   identifier has external linkage.
4716
183
  if (New->hasExternalStorage() && Old->hasLinkage())
4717
0
    /* Okay */;
4718
183
  else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4719
183
           !New->isStaticDataMember() &&
4720
183
           Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4721
0
    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4722
0
    Diag(OldLocation, PrevDiag);
4723
0
    return New->setInvalidDecl();
4724
0
  }
4725
4726
  // Check if extern is followed by non-extern and vice-versa.
4727
183
  if (New->hasExternalStorage() &&
4728
183
      !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4729
0
    Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4730
0
    Diag(OldLocation, PrevDiag);
4731
0
    return New->setInvalidDecl();
4732
0
  }
4733
183
  if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4734
183
      !New->hasExternalStorage()) {
4735
0
    Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4736
0
    Diag(OldLocation, PrevDiag);
4737
0
    return New->setInvalidDecl();
4738
0
  }
4739
4740
183
  if (CheckRedeclarationInModule(New, Old))
4741
0
    return;
4742
4743
  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4744
4745
  // FIXME: The test for external storage here seems wrong? We still
4746
  // need to check for mismatches.
4747
183
  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4748
      // Don't complain about out-of-line definitions of static members.
4749
183
      !(Old->getLexicalDeclContext()->isRecord() &&
4750
0
        !New->getLexicalDeclContext()->isRecord())) {
4751
0
    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4752
0
    Diag(OldLocation, PrevDiag);
4753
0
    return New->setInvalidDecl();
4754
0
  }
4755
4756
183
  if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4757
0
    if (VarDecl *Def = Old->getDefinition()) {
4758
      // C++1z [dcl.fcn.spec]p4:
4759
      //   If the definition of a variable appears in a translation unit before
4760
      //   its first declaration as inline, the program is ill-formed.
4761
0
      Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4762
0
      Diag(Def->getLocation(), diag::note_previous_definition);
4763
0
    }
4764
0
  }
4765
4766
  // If this redeclaration makes the variable inline, we may need to add it to
4767
  // UndefinedButUsed.
4768
183
  if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4769
183
      !Old->getDefinition() && !New->isThisDeclarationADefinition())
4770
0
    UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4771
0
                                           SourceLocation()));
4772
4773
183
  if (New->getTLSKind() != Old->getTLSKind()) {
4774
0
    if (!Old->getTLSKind()) {
4775
0
      Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4776
0
      Diag(OldLocation, PrevDiag);
4777
0
    } else if (!New->getTLSKind()) {
4778
0
      Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4779
0
      Diag(OldLocation, PrevDiag);
4780
0
    } else {
4781
      // Do not allow redeclaration to change the variable between requiring
4782
      // static and dynamic initialization.
4783
      // FIXME: GCC allows this, but uses the TLS keyword on the first
4784
      // declaration to determine the kind. Do we need to be compatible here?
4785
0
      Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4786
0
        << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4787
0
      Diag(OldLocation, PrevDiag);
4788
0
    }
4789
0
  }
4790
4791
  // C++ doesn't have tentative definitions, so go right ahead and check here.
4792
183
  if (getLangOpts().CPlusPlus) {
4793
0
    if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4794
0
        Old->getCanonicalDecl()->isConstexpr()) {
4795
      // This definition won't be a definition any more once it's been merged.
4796
0
      Diag(New->getLocation(),
4797
0
           diag::warn_deprecated_redundant_constexpr_static_def);
4798
0
    } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4799
0
      VarDecl *Def = Old->getDefinition();
4800
0
      if (Def && checkVarDeclRedefinition(Def, New))
4801
0
        return;
4802
0
    }
4803
0
  }
4804
4805
183
  if (haveIncompatibleLanguageLinkages(Old, New)) {
4806
0
    Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4807
0
    Diag(OldLocation, PrevDiag);
4808
0
    New->setInvalidDecl();
4809
0
    return;
4810
0
  }
4811
4812
  // Merge "used" flag.
4813
183
  if (Old->getMostRecentDecl()->isUsed(false))
4814
6
    New->setIsUsed();
4815
4816
  // Keep a chain of previous declarations.
4817
183
  New->setPreviousDecl(Old);
4818
183
  if (NewTemplate)
4819
0
    NewTemplate->setPreviousDecl(OldTemplate);
4820
4821
  // Inherit access appropriately.
4822
183
  New->setAccess(Old->getAccess());
4823
183
  if (NewTemplate)
4824
0
    NewTemplate->setAccess(New->getAccess());
4825
4826
183
  if (Old->isInline())
4827
0
    New->setImplicitlyInline();
4828
183
}
4829
4830
4
void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4831
4
  SourceManager &SrcMgr = getSourceManager();
4832
4
  auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4833
4
  auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4834
4
  auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4835
4
  auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4836
4
  auto &HSI = PP.getHeaderSearchInfo();
4837
4
  StringRef HdrFilename =
4838
4
      SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4839
4840
4
  auto noteFromModuleOrInclude = [&](Module *Mod,
4841
4
                                     SourceLocation IncLoc) -> bool {
4842
    // Redefinition errors with modules are common with non modular mapped
4843
    // headers, example: a non-modular header H in module A that also gets
4844
    // included directly in a TU. Pointing twice to the same header/definition
4845
    // is confusing, try to get better diagnostics when modules is on.
4846
0
    if (IncLoc.isValid()) {
4847
0
      if (Mod) {
4848
0
        Diag(IncLoc, diag::note_redefinition_modules_same_file)
4849
0
            << HdrFilename.str() << Mod->getFullModuleName();
4850
0
        if (!Mod->DefinitionLoc.isInvalid())
4851
0
          Diag(Mod->DefinitionLoc, diag::note_defined_here)
4852
0
              << Mod->getFullModuleName();
4853
0
      } else {
4854
0
        Diag(IncLoc, diag::note_redefinition_include_same_file)
4855
0
            << HdrFilename.str();
4856
0
      }
4857
0
      return true;
4858
0
    }
4859
4860
0
    return false;
4861
0
  };
4862
4863
  // Is it the same file and same offset? Provide more information on why
4864
  // this leads to a redefinition error.
4865
4
  if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4866
0
    SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4867
0
    SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4868
0
    bool EmittedDiag =
4869
0
        noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4870
0
    EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4871
4872
    // If the header has no guards, emit a note suggesting one.
4873
0
    if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4874
0
      Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4875
4876
0
    if (EmittedDiag)
4877
0
      return;
4878
0
  }
4879
4880
  // Redefinition coming from different files or couldn't do better above.
4881
4
  if (Old->getLocation().isValid())
4882
4
    Diag(Old->getLocation(), diag::note_previous_definition);
4883
4
}
4884
4885
/// We've just determined that \p Old and \p New both appear to be definitions
4886
/// of the same variable. Either diagnose or fix the problem.
4887
0
bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4888
0
  if (!hasVisibleDefinition(Old) &&
4889
0
      (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4890
0
       isa<VarTemplateSpecializationDecl>(New) ||
4891
0
       New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4892
0
       New->getDeclContext()->isDependentContext())) {
4893
    // The previous definition is hidden, and multiple definitions are
4894
    // permitted (in separate TUs). Demote this to a declaration.
4895
0
    New->demoteThisDefinitionToDeclaration();
4896
4897
    // Make the canonical definition visible.
4898
0
    if (auto *OldTD = Old->getDescribedVarTemplate())
4899
0
      makeMergedDefinitionVisible(OldTD);
4900
0
    makeMergedDefinitionVisible(Old);
4901
0
    return false;
4902
0
  } else {
4903
0
    Diag(New->getLocation(), diag::err_redefinition) << New;
4904
0
    notePreviousDefinition(Old, New->getLocation());
4905
0
    New->setInvalidDecl();
4906
0
    return true;
4907
0
  }
4908
0
}
4909
4910
/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4911
/// no declarator (e.g. "struct foo;") is parsed.
4912
Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4913
                                       DeclSpec &DS,
4914
                                       const ParsedAttributesView &DeclAttrs,
4915
39
                                       RecordDecl *&AnonRecord) {
4916
39
  return ParsedFreeStandingDeclSpec(
4917
39
      S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4918
39
}
4919
4920
// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4921
// disambiguate entities defined in different scopes.
4922
// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4923
// compatibility.
4924
// We will pick our mangling number depending on which version of MSVC is being
4925
// targeted.
4926
0
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4927
0
  return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4928
0
             ? S->getMSCurManglingNumber()
4929
0
             : S->getMSLastManglingNumber();
4930
0
}
4931
4932
0
void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4933
0
  if (!Context.getLangOpts().CPlusPlus)
4934
0
    return;
4935
4936
0
  if (isa<CXXRecordDecl>(Tag->getParent())) {
4937
    // If this tag is the direct child of a class, number it if
4938
    // it is anonymous.
4939
0
    if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4940
0
      return;
4941
0
    MangleNumberingContext &MCtx =
4942
0
        Context.getManglingNumberContext(Tag->getParent());
4943
0
    Context.setManglingNumber(
4944
0
        Tag, MCtx.getManglingNumber(
4945
0
                 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4946
0
    return;
4947
0
  }
4948
4949
  // If this tag isn't a direct child of a class, number it if it is local.
4950
0
  MangleNumberingContext *MCtx;
4951
0
  Decl *ManglingContextDecl;
4952
0
  std::tie(MCtx, ManglingContextDecl) =
4953
0
      getCurrentMangleNumberContext(Tag->getDeclContext());
4954
0
  if (MCtx) {
4955
0
    Context.setManglingNumber(
4956
0
        Tag, MCtx->getManglingNumber(
4957
0
                 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4958
0
  }
4959
0
}
4960
4961
namespace {
4962
struct NonCLikeKind {
4963
  enum {
4964
    None,
4965
    BaseClass,
4966
    DefaultMemberInit,
4967
    Lambda,
4968
    Friend,
4969
    OtherMember,
4970
    Invalid,
4971
  } Kind = None;
4972
  SourceRange Range;
4973
4974
0
  explicit operator bool() { return Kind != None; }
4975
};
4976
}
4977
4978
/// Determine whether a class is C-like, according to the rules of C++
4979
/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4980
0
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4981
0
  if (RD->isInvalidDecl())
4982
0
    return {NonCLikeKind::Invalid, {}};
4983
4984
  // C++ [dcl.typedef]p9: [P1766R1]
4985
  //   An unnamed class with a typedef name for linkage purposes shall not
4986
  //
4987
  //    -- have any base classes
4988
0
  if (RD->getNumBases())
4989
0
    return {NonCLikeKind::BaseClass,
4990
0
            SourceRange(RD->bases_begin()->getBeginLoc(),
4991
0
                        RD->bases_end()[-1].getEndLoc())};
4992
0
  bool Invalid = false;
4993
0
  for (Decl *D : RD->decls()) {
4994
    // Don't complain about things we already diagnosed.
4995
0
    if (D->isInvalidDecl()) {
4996
0
      Invalid = true;
4997
0
      continue;
4998
0
    }
4999
5000
    //  -- have any [...] default member initializers
5001
0
    if (auto *FD = dyn_cast<FieldDecl>(D)) {
5002
0
      if (FD->hasInClassInitializer()) {
5003
0
        auto *Init = FD->getInClassInitializer();
5004
0
        return {NonCLikeKind::DefaultMemberInit,
5005
0
                Init ? Init->getSourceRange() : D->getSourceRange()};
5006
0
      }
5007
0
      continue;
5008
0
    }
5009
5010
    // FIXME: We don't allow friend declarations. This violates the wording of
5011
    // P1766, but not the intent.
5012
0
    if (isa<FriendDecl>(D))
5013
0
      return {NonCLikeKind::Friend, D->getSourceRange()};
5014
5015
    //  -- declare any members other than non-static data members, member
5016
    //     enumerations, or member classes,
5017
0
    if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
5018
0
        isa<EnumDecl>(D))
5019
0
      continue;
5020
0
    auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5021
0
    if (!MemberRD) {
5022
0
      if (D->isImplicit())
5023
0
        continue;
5024
0
      return {NonCLikeKind::OtherMember, D->getSourceRange()};
5025
0
    }
5026
5027
    //  -- contain a lambda-expression,
5028
0
    if (MemberRD->isLambda())
5029
0
      return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5030
5031
    //  and all member classes shall also satisfy these requirements
5032
    //  (recursively).
5033
0
    if (MemberRD->isThisDeclarationADefinition()) {
5034
0
      if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5035
0
        return Kind;
5036
0
    }
5037
0
  }
5038
5039
0
  return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5040
0
}
5041
5042
void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5043
0
                                        TypedefNameDecl *NewTD) {
5044
0
  if (TagFromDeclSpec->isInvalidDecl())
5045
0
    return;
5046
5047
  // Do nothing if the tag already has a name for linkage purposes.
5048
0
  if (TagFromDeclSpec->hasNameForLinkage())
5049
0
    return;
5050
5051
  // A well-formed anonymous tag must always be a TUK_Definition.
5052
0
  assert(TagFromDeclSpec->isThisDeclarationADefinition());
5053
5054
  // The type must match the tag exactly;  no qualifiers allowed.
5055
0
  if (!Context.hasSameType(NewTD->getUnderlyingType(),
5056
0
                           Context.getTagDeclType(TagFromDeclSpec))) {
5057
0
    if (getLangOpts().CPlusPlus)
5058
0
      Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5059
0
    return;
5060
0
  }
5061
5062
  // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5063
  //   An unnamed class with a typedef name for linkage purposes shall [be
5064
  //   C-like].
5065
  //
5066
  // FIXME: Also diagnose if we've already computed the linkage. That ideally
5067
  // shouldn't happen, but there are constructs that the language rule doesn't
5068
  // disallow for which we can't reasonably avoid computing linkage early.
5069
0
  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5070
0
  NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5071
0
                             : NonCLikeKind();
5072
0
  bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5073
0
  if (NonCLike || ChangesLinkage) {
5074
0
    if (NonCLike.Kind == NonCLikeKind::Invalid)
5075
0
      return;
5076
5077
0
    unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5078
0
    if (ChangesLinkage) {
5079
      // If the linkage changes, we can't accept this as an extension.
5080
0
      if (NonCLike.Kind == NonCLikeKind::None)
5081
0
        DiagID = diag::err_typedef_changes_linkage;
5082
0
      else
5083
0
        DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5084
0
    }
5085
5086
0
    SourceLocation FixitLoc =
5087
0
        getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5088
0
    llvm::SmallString<40> TextToInsert;
5089
0
    TextToInsert += ' ';
5090
0
    TextToInsert += NewTD->getIdentifier()->getName();
5091
5092
0
    Diag(FixitLoc, DiagID)
5093
0
      << isa<TypeAliasDecl>(NewTD)
5094
0
      << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5095
0
    if (NonCLike.Kind != NonCLikeKind::None) {
5096
0
      Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5097
0
        << NonCLike.Kind - 1 << NonCLike.Range;
5098
0
    }
5099
0
    Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5100
0
      << NewTD << isa<TypeAliasDecl>(NewTD);
5101
5102
0
    if (ChangesLinkage)
5103
0
      return;
5104
0
  }
5105
5106
  // Otherwise, set this as the anon-decl typedef for the tag.
5107
0
  TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5108
0
}
5109
5110
0
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5111
0
  DeclSpec::TST T = DS.getTypeSpecType();
5112
0
  switch (T) {
5113
0
  case DeclSpec::TST_class:
5114
0
    return 0;
5115
0
  case DeclSpec::TST_struct:
5116
0
    return 1;
5117
0
  case DeclSpec::TST_interface:
5118
0
    return 2;
5119
0
  case DeclSpec::TST_union:
5120
0
    return 3;
5121
0
  case DeclSpec::TST_enum:
5122
0
    if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5123
0
      if (ED->isScopedUsingClassTag())
5124
0
        return 5;
5125
0
      if (ED->isScoped())
5126
0
        return 6;
5127
0
    }
5128
0
    return 4;
5129
0
  default:
5130
0
    llvm_unreachable("unexpected type specifier");
5131
0
  }
5132
0
}
5133
/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5134
/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5135
/// parameters to cope with template friend declarations.
5136
Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5137
                                       DeclSpec &DS,
5138
                                       const ParsedAttributesView &DeclAttrs,
5139
                                       MultiTemplateParamsArg TemplateParams,
5140
                                       bool IsExplicitInstantiation,
5141
39
                                       RecordDecl *&AnonRecord) {
5142
39
  Decl *TagD = nullptr;
5143
39
  TagDecl *Tag = nullptr;
5144
39
  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5145
39
      DS.getTypeSpecType() == DeclSpec::TST_struct ||
5146
39
      DS.getTypeSpecType() == DeclSpec::TST_interface ||
5147
39
      DS.getTypeSpecType() == DeclSpec::TST_union ||
5148
39
      DS.getTypeSpecType() == DeclSpec::TST_enum) {
5149
0
    TagD = DS.getRepAsDecl();
5150
5151
0
    if (!TagD) // We probably had an error
5152
0
      return nullptr;
5153
5154
    // Note that the above type specs guarantee that the
5155
    // type rep is a Decl, whereas in many of the others
5156
    // it's a Type.
5157
0
    if (isa<TagDecl>(TagD))
5158
0
      Tag = cast<TagDecl>(TagD);
5159
0
    else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5160
0
      Tag = CTD->getTemplatedDecl();
5161
0
  }
5162
5163
39
  if (Tag) {
5164
0
    handleTagNumbering(Tag, S);
5165
0
    Tag->setFreeStanding();
5166
0
    if (Tag->isInvalidDecl())
5167
0
      return Tag;
5168
0
  }
5169
5170
39
  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5171
    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5172
    // or incomplete types shall not be restrict-qualified."
5173
0
    if (TypeQuals & DeclSpec::TQ_restrict)
5174
0
      Diag(DS.getRestrictSpecLoc(),
5175
0
           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5176
0
           << DS.getSourceRange();
5177
0
  }
5178
5179
39
  if (DS.isInlineSpecified())
5180
0
    Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5181
0
        << getLangOpts().CPlusPlus17;
5182
5183
39
  if (DS.hasConstexprSpecifier()) {
5184
    // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5185
    // and definitions of functions and variables.
5186
    // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5187
    // the declaration of a function or function template
5188
0
    if (Tag)
5189
0
      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5190
0
          << GetDiagnosticTypeSpecifierID(DS)
5191
0
          << static_cast<int>(DS.getConstexprSpecifier());
5192
0
    else
5193
0
      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5194
0
          << static_cast<int>(DS.getConstexprSpecifier());
5195
    // Don't emit warnings after this error.
5196
0
    return TagD;
5197
0
  }
5198
5199
39
  DiagnoseFunctionSpecifiers(DS);
5200
5201
39
  if (DS.isFriendSpecified()) {
5202
    // If we're dealing with a decl but not a TagDecl, assume that
5203
    // whatever routines created it handled the friendship aspect.
5204
0
    if (TagD && !Tag)
5205
0
      return nullptr;
5206
0
    return ActOnFriendTypeDecl(S, DS, TemplateParams);
5207
0
  }
5208
5209
39
  const CXXScopeSpec &SS = DS.getTypeSpecScope();
5210
39
  bool IsExplicitSpecialization =
5211
39
    !TemplateParams.empty() && TemplateParams.back()->size() == 0;
5212
39
  if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
5213
39
      !IsExplicitInstantiation && !IsExplicitSpecialization &&
5214
39
      !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
5215
    // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5216
    // nested-name-specifier unless it is an explicit instantiation
5217
    // or an explicit specialization.
5218
    //
5219
    // FIXME: We allow class template partial specializations here too, per the
5220
    // obvious intent of DR1819.
5221
    //
5222
    // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5223
0
    Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
5224
0
        << GetDiagnosticTypeSpecifierID(DS) << SS.getRange();
5225
0
    return nullptr;
5226
0
  }
5227
5228
  // Track whether this decl-specifier declares anything.
5229
39
  bool DeclaresAnything = true;
5230
5231
  // Handle anonymous struct definitions.
5232
39
  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5233
0
    if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5234
0
        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5235
0
      if (getLangOpts().CPlusPlus ||
5236
0
          Record->getDeclContext()->isRecord()) {
5237
        // If CurContext is a DeclContext that can contain statements,
5238
        // RecursiveASTVisitor won't visit the decls that
5239
        // BuildAnonymousStructOrUnion() will put into CurContext.
5240
        // Also store them here so that they can be part of the
5241
        // DeclStmt that gets created in this case.
5242
        // FIXME: Also return the IndirectFieldDecls created by
5243
        // BuildAnonymousStructOr union, for the same reason?
5244
0
        if (CurContext->isFunctionOrMethod())
5245
0
          AnonRecord = Record;
5246
0
        return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5247
0
                                           Context.getPrintingPolicy());
5248
0
      }
5249
5250
0
      DeclaresAnything = false;
5251
0
    }
5252
0
  }
5253
5254
  // C11 6.7.2.1p2:
5255
  //   A struct-declaration that does not declare an anonymous structure or
5256
  //   anonymous union shall contain a struct-declarator-list.
5257
  //
5258
  // This rule also existed in C89 and C99; the grammar for struct-declaration
5259
  // did not permit a struct-declaration without a struct-declarator-list.
5260
39
  if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5261
39
      DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5262
    // Check for Microsoft C extension: anonymous struct/union member.
5263
    // Handle 2 kinds of anonymous struct/union:
5264
    //   struct STRUCT;
5265
    //   union UNION;
5266
    // and
5267
    //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
5268
    //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
5269
0
    if ((Tag && Tag->getDeclName()) ||
5270
0
        DS.getTypeSpecType() == DeclSpec::TST_typename) {
5271
0
      RecordDecl *Record = nullptr;
5272
0
      if (Tag)
5273
0
        Record = dyn_cast<RecordDecl>(Tag);
5274
0
      else if (const RecordType *RT =
5275
0
                   DS.getRepAsType().get()->getAsStructureType())
5276
0
        Record = RT->getDecl();
5277
0
      else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5278
0
        Record = UT->getDecl();
5279
5280
0
      if (Record && getLangOpts().MicrosoftExt) {
5281
0
        Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5282
0
            << Record->isUnion() << DS.getSourceRange();
5283
0
        return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5284
0
      }
5285
5286
0
      DeclaresAnything = false;
5287
0
    }
5288
0
  }
5289
5290
  // Skip all the checks below if we have a type error.
5291
39
  if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5292
39
      (TagD && TagD->isInvalidDecl()))
5293
31
    return TagD;
5294
5295
8
  if (getLangOpts().CPlusPlus &&
5296
8
      DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5297
0
    if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5298
0
      if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5299
0
          !Enum->getIdentifier() && !Enum->isInvalidDecl())
5300
0
        DeclaresAnything = false;
5301
5302
8
  if (!DS.isMissingDeclaratorOk()) {
5303
    // Customize diagnostic for a typedef missing a name.
5304
8
    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5305
0
      Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5306
0
          << DS.getSourceRange();
5307
8
    else
5308
8
      DeclaresAnything = false;
5309
8
  }
5310
5311
8
  if (DS.isModulePrivateSpecified() &&
5312
8
      Tag && Tag->getDeclContext()->isFunctionOrMethod())
5313
0
    Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5314
0
        << llvm::to_underlying(Tag->getTagKind())
5315
0
        << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5316
5317
8
  ActOnDocumentableDecl(TagD);
5318
5319
  // C 6.7/2:
5320
  //   A declaration [...] shall declare at least a declarator [...], a tag,
5321
  //   or the members of an enumeration.
5322
  // C++ [dcl.dcl]p3:
5323
  //   [If there are no declarators], and except for the declaration of an
5324
  //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5325
  //   names into the program, or shall redeclare a name introduced by a
5326
  //   previous declaration.
5327
8
  if (!DeclaresAnything) {
5328
    // In C, we allow this as a (popular) extension / bug. Don't bother
5329
    // producing further diagnostics for redundant qualifiers after this.
5330
8
    Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5331
8
                               ? diag::err_no_declarators
5332
8
                               : diag::ext_no_declarators)
5333
8
        << DS.getSourceRange();
5334
8
    return TagD;
5335
8
  }
5336
5337
  // C++ [dcl.stc]p1:
5338
  //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5339
  //   init-declarator-list of the declaration shall not be empty.
5340
  // C++ [dcl.fct.spec]p1:
5341
  //   If a cv-qualifier appears in a decl-specifier-seq, the
5342
  //   init-declarator-list of the declaration shall not be empty.
5343
  //
5344
  // Spurious qualifiers here appear to be valid in C.
5345
0
  unsigned DiagID = diag::warn_standalone_specifier;
5346
0
  if (getLangOpts().CPlusPlus)
5347
0
    DiagID = diag::ext_standalone_specifier;
5348
5349
  // Note that a linkage-specification sets a storage class, but
5350
  // 'extern "C" struct foo;' is actually valid and not theoretically
5351
  // useless.
5352
0
  if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5353
0
    if (SCS == DeclSpec::SCS_mutable)
5354
      // Since mutable is not a viable storage class specifier in C, there is
5355
      // no reason to treat it as an extension. Instead, diagnose as an error.
5356
0
      Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5357
0
    else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5358
0
      Diag(DS.getStorageClassSpecLoc(), DiagID)
5359
0
        << DeclSpec::getSpecifierName(SCS);
5360
0
  }
5361
5362
0
  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5363
0
    Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5364
0
      << DeclSpec::getSpecifierName(TSCS);
5365
0
  if (DS.getTypeQualifiers()) {
5366
0
    if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5367
0
      Diag(DS.getConstSpecLoc(), DiagID) << "const";
5368
0
    if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5369
0
      Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5370
    // Restrict is covered above.
5371
0
    if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5372
0
      Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5373
0
    if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5374
0
      Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5375
0
  }
5376
5377
  // Warn about ignored type attributes, for example:
5378
  // __attribute__((aligned)) struct A;
5379
  // Attributes should be placed after tag to apply to type declaration.
5380
0
  if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5381
0
    DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5382
0
    if (TypeSpecType == DeclSpec::TST_class ||
5383
0
        TypeSpecType == DeclSpec::TST_struct ||
5384
0
        TypeSpecType == DeclSpec::TST_interface ||
5385
0
        TypeSpecType == DeclSpec::TST_union ||
5386
0
        TypeSpecType == DeclSpec::TST_enum) {
5387
5388
0
      auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5389
0
        unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5390
0
        if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5391
0
          DiagnosticId = diag::warn_attribute_ignored;
5392
0
        else if (AL.isRegularKeywordAttribute())
5393
0
          DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5394
0
        else
5395
0
          DiagnosticId = diag::warn_declspec_attribute_ignored;
5396
0
        Diag(AL.getLoc(), DiagnosticId)
5397
0
            << AL << GetDiagnosticTypeSpecifierID(DS);
5398
0
      };
5399
5400
0
      llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5401
0
      llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5402
0
    }
5403
0
  }
5404
5405
0
  return TagD;
5406
8
}
5407
5408
/// We are trying to inject an anonymous member into the given scope;
5409
/// check if there's an existing declaration that can't be overloaded.
5410
///
5411
/// \return true if this is a forbidden redeclaration
5412
static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5413
                                         DeclContext *Owner,
5414
                                         DeclarationName Name,
5415
                                         SourceLocation NameLoc, bool IsUnion,
5416
0
                                         StorageClass SC) {
5417
0
  LookupResult R(SemaRef, Name, NameLoc,
5418
0
                 Owner->isRecord() ? Sema::LookupMemberName
5419
0
                                   : Sema::LookupOrdinaryName,
5420
0
                 Sema::ForVisibleRedeclaration);
5421
0
  if (!SemaRef.LookupName(R, S)) return false;
5422
5423
  // Pick a representative declaration.
5424
0
  NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5425
0
  assert(PrevDecl && "Expected a non-null Decl");
5426
5427
0
  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5428
0
    return false;
5429
5430
0
  if (SC == StorageClass::SC_None &&
5431
0
      PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5432
0
      (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5433
0
    if (!Owner->isRecord())
5434
0
      SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5435
0
    return false;
5436
0
  }
5437
5438
0
  SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5439
0
    << IsUnion << Name;
5440
0
  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5441
5442
0
  return true;
5443
0
}
5444
5445
39
void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5446
39
  if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5447
0
    DiagPlaceholderFieldDeclDefinitions(RD);
5448
39
}
5449
5450
/// Emit diagnostic warnings for placeholder members.
5451
/// We can only do that after the class is fully constructed,
5452
/// as anonymous union/structs can insert placeholders
5453
/// in their parent scope (which might be a Record).
5454
0
void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5455
0
  if (!getLangOpts().CPlusPlus)
5456
0
    return;
5457
5458
  // This function can be parsed before we have validated the
5459
  // structure as an anonymous struct
5460
0
  if (Record->isAnonymousStructOrUnion())
5461
0
    return;
5462
5463
0
  const NamedDecl *First = 0;
5464
0
  for (const Decl *D : Record->decls()) {
5465
0
    const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5466
0
    if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5467
0
      continue;
5468
0
    if (!First)
5469
0
      First = ND;
5470
0
    else
5471
0
      DiagPlaceholderVariableDefinition(ND->getLocation());
5472
0
  }
5473
0
}
5474
5475
/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5476
/// anonymous struct or union AnonRecord into the owning context Owner
5477
/// and scope S. This routine will be invoked just after we realize
5478
/// that an unnamed union or struct is actually an anonymous union or
5479
/// struct, e.g.,
5480
///
5481
/// @code
5482
/// union {
5483
///   int i;
5484
///   float f;
5485
/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5486
///    // f into the surrounding scope.x
5487
/// @endcode
5488
///
5489
/// This routine is recursive, injecting the names of nested anonymous
5490
/// structs/unions into the owning context and scope as well.
5491
static bool
5492
InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5493
                                    RecordDecl *AnonRecord, AccessSpecifier AS,
5494
                                    StorageClass SC,
5495
0
                                    SmallVectorImpl<NamedDecl *> &Chaining) {
5496
0
  bool Invalid = false;
5497
5498
  // Look every FieldDecl and IndirectFieldDecl with a name.
5499
0
  for (auto *D : AnonRecord->decls()) {
5500
0
    if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5501
0
        cast<NamedDecl>(D)->getDeclName()) {
5502
0
      ValueDecl *VD = cast<ValueDecl>(D);
5503
0
      if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5504
0
                                       VD->getLocation(), AnonRecord->isUnion(),
5505
0
                                       SC)) {
5506
        // C++ [class.union]p2:
5507
        //   The names of the members of an anonymous union shall be
5508
        //   distinct from the names of any other entity in the
5509
        //   scope in which the anonymous union is declared.
5510
0
        Invalid = true;
5511
0
      } else {
5512
        // C++ [class.union]p2:
5513
        //   For the purpose of name lookup, after the anonymous union
5514
        //   definition, the members of the anonymous union are
5515
        //   considered to have been defined in the scope in which the
5516
        //   anonymous union is declared.
5517
0
        unsigned OldChainingSize = Chaining.size();
5518
0
        if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5519
0
          Chaining.append(IF->chain_begin(), IF->chain_end());
5520
0
        else
5521
0
          Chaining.push_back(VD);
5522
5523
0
        assert(Chaining.size() >= 2);
5524
0
        NamedDecl **NamedChain =
5525
0
          new (SemaRef.Context)NamedDecl*[Chaining.size()];
5526
0
        for (unsigned i = 0; i < Chaining.size(); i++)
5527
0
          NamedChain[i] = Chaining[i];
5528
5529
0
        IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5530
0
            SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5531
0
            VD->getType(), {NamedChain, Chaining.size()});
5532
5533
0
        for (const auto *Attr : VD->attrs())
5534
0
          IndirectField->addAttr(Attr->clone(SemaRef.Context));
5535
5536
0
        IndirectField->setAccess(AS);
5537
0
        IndirectField->setImplicit();
5538
0
        SemaRef.PushOnScopeChains(IndirectField, S);
5539
5540
        // That includes picking up the appropriate access specifier.
5541
0
        if (AS != AS_none) IndirectField->setAccess(AS);
5542
5543
0
        Chaining.resize(OldChainingSize);
5544
0
      }
5545
0
    }
5546
0
  }
5547
5548
0
  return Invalid;
5549
0
}
5550
5551
/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5552
/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5553
/// illegal input values are mapped to SC_None.
5554
static StorageClass
5555
5.07k
StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5556
5.07k
  DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5557
5.07k
  assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5558
5.07k
         "Parser allowed 'typedef' as storage class VarDecl.");
5559
0
  switch (StorageClassSpec) {
5560
5.07k
  case DeclSpec::SCS_unspecified:    return SC_None;
5561
0
  case DeclSpec::SCS_extern:
5562
0
    if (DS.isExternInLinkageSpec())
5563
0
      return SC_None;
5564
0
    return SC_Extern;
5565
0
  case DeclSpec::SCS_static:         return SC_Static;
5566
0
  case DeclSpec::SCS_auto:           return SC_Auto;
5567
0
  case DeclSpec::SCS_register:       return SC_Register;
5568
0
  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5569
    // Illegal SCSs map to None: error reporting is up to the caller.
5570
0
  case DeclSpec::SCS_mutable:        // Fall through.
5571
0
  case DeclSpec::SCS_typedef:        return SC_None;
5572
5.07k
  }
5573
0
  llvm_unreachable("unknown storage class specifier");
5574
0
}
5575
5576
0
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5577
0
  assert(Record->hasInClassInitializer());
5578
5579
0
  for (const auto *I : Record->decls()) {
5580
0
    const auto *FD = dyn_cast<FieldDecl>(I);
5581
0
    if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5582
0
      FD = IFD->getAnonField();
5583
0
    if (FD && FD->hasInClassInitializer())
5584
0
      return FD->getLocation();
5585
0
  }
5586
5587
0
  llvm_unreachable("couldn't find in-class initializer");
5588
0
}
5589
5590
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5591
0
                                      SourceLocation DefaultInitLoc) {
5592
0
  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5593
0
    return;
5594
5595
0
  S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5596
0
  S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5597
0
}
5598
5599
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5600
0
                                      CXXRecordDecl *AnonUnion) {
5601
0
  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5602
0
    return;
5603
5604
0
  checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5605
0
}
5606
5607
/// BuildAnonymousStructOrUnion - Handle the declaration of an
5608
/// anonymous structure or union. Anonymous unions are a C++ feature
5609
/// (C++ [class.union]) and a C11 feature; anonymous structures
5610
/// are a C11 feature and GNU C++ extension.
5611
Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5612
                                        AccessSpecifier AS,
5613
                                        RecordDecl *Record,
5614
0
                                        const PrintingPolicy &Policy) {
5615
0
  DeclContext *Owner = Record->getDeclContext();
5616
5617
  // Diagnose whether this anonymous struct/union is an extension.
5618
0
  if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5619
0
    Diag(Record->getLocation(), diag::ext_anonymous_union);
5620
0
  else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5621
0
    Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5622
0
  else if (!Record->isUnion() && !getLangOpts().C11)
5623
0
    Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5624
5625
  // C and C++ require different kinds of checks for anonymous
5626
  // structs/unions.
5627
0
  bool Invalid = false;
5628
0
  if (getLangOpts().CPlusPlus) {
5629
0
    const char *PrevSpec = nullptr;
5630
0
    if (Record->isUnion()) {
5631
      // C++ [class.union]p6:
5632
      // C++17 [class.union.anon]p2:
5633
      //   Anonymous unions declared in a named namespace or in the
5634
      //   global namespace shall be declared static.
5635
0
      unsigned DiagID;
5636
0
      DeclContext *OwnerScope = Owner->getRedeclContext();
5637
0
      if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5638
0
          (OwnerScope->isTranslationUnit() ||
5639
0
           (OwnerScope->isNamespace() &&
5640
0
            !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5641
0
        Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5642
0
          << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5643
5644
        // Recover by adding 'static'.
5645
0
        DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5646
0
                               PrevSpec, DiagID, Policy);
5647
0
      }
5648
      // C++ [class.union]p6:
5649
      //   A storage class is not allowed in a declaration of an
5650
      //   anonymous union in a class scope.
5651
0
      else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5652
0
               isa<RecordDecl>(Owner)) {
5653
0
        Diag(DS.getStorageClassSpecLoc(),
5654
0
             diag::err_anonymous_union_with_storage_spec)
5655
0
          << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5656
5657
        // Recover by removing the storage specifier.
5658
0
        DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5659
0
                               SourceLocation(),
5660
0
                               PrevSpec, DiagID, Context.getPrintingPolicy());
5661
0
      }
5662
0
    }
5663
5664
    // Ignore const/volatile/restrict qualifiers.
5665
0
    if (DS.getTypeQualifiers()) {
5666
0
      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5667
0
        Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5668
0
          << Record->isUnion() << "const"
5669
0
          << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5670
0
      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5671
0
        Diag(DS.getVolatileSpecLoc(),
5672
0
             diag::ext_anonymous_struct_union_qualified)
5673
0
          << Record->isUnion() << "volatile"
5674
0
          << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5675
0
      if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5676
0
        Diag(DS.getRestrictSpecLoc(),
5677
0
             diag::ext_anonymous_struct_union_qualified)
5678
0
          << Record->isUnion() << "restrict"
5679
0
          << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5680
0
      if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5681
0
        Diag(DS.getAtomicSpecLoc(),
5682
0
             diag::ext_anonymous_struct_union_qualified)
5683
0
          << Record->isUnion() << "_Atomic"
5684
0
          << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5685
0
      if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5686
0
        Diag(DS.getUnalignedSpecLoc(),
5687
0
             diag::ext_anonymous_struct_union_qualified)
5688
0
          << Record->isUnion() << "__unaligned"
5689
0
          << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5690
5691
0
      DS.ClearTypeQualifiers();
5692
0
    }
5693
5694
    // C++ [class.union]p2:
5695
    //   The member-specification of an anonymous union shall only
5696
    //   define non-static data members. [Note: nested types and
5697
    //   functions cannot be declared within an anonymous union. ]
5698
0
    for (auto *Mem : Record->decls()) {
5699
      // Ignore invalid declarations; we already diagnosed them.
5700
0
      if (Mem->isInvalidDecl())
5701
0
        continue;
5702
5703
0
      if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5704
        // C++ [class.union]p3:
5705
        //   An anonymous union shall not have private or protected
5706
        //   members (clause 11).
5707
0
        assert(FD->getAccess() != AS_none);
5708
0
        if (FD->getAccess() != AS_public) {
5709
0
          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5710
0
            << Record->isUnion() << (FD->getAccess() == AS_protected);
5711
0
          Invalid = true;
5712
0
        }
5713
5714
        // C++ [class.union]p1
5715
        //   An object of a class with a non-trivial constructor, a non-trivial
5716
        //   copy constructor, a non-trivial destructor, or a non-trivial copy
5717
        //   assignment operator cannot be a member of a union, nor can an
5718
        //   array of such objects.
5719
0
        if (CheckNontrivialField(FD))
5720
0
          Invalid = true;
5721
0
      } else if (Mem->isImplicit()) {
5722
        // Any implicit members are fine.
5723
0
      } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5724
        // This is a type that showed up in an
5725
        // elaborated-type-specifier inside the anonymous struct or
5726
        // union, but which actually declares a type outside of the
5727
        // anonymous struct or union. It's okay.
5728
0
      } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5729
0
        if (!MemRecord->isAnonymousStructOrUnion() &&
5730
0
            MemRecord->getDeclName()) {
5731
          // Visual C++ allows type definition in anonymous struct or union.
5732
0
          if (getLangOpts().MicrosoftExt)
5733
0
            Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5734
0
              << Record->isUnion();
5735
0
          else {
5736
            // This is a nested type declaration.
5737
0
            Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5738
0
              << Record->isUnion();
5739
0
            Invalid = true;
5740
0
          }
5741
0
        } else {
5742
          // This is an anonymous type definition within another anonymous type.
5743
          // This is a popular extension, provided by Plan9, MSVC and GCC, but
5744
          // not part of standard C++.
5745
0
          Diag(MemRecord->getLocation(),
5746
0
               diag::ext_anonymous_record_with_anonymous_type)
5747
0
            << Record->isUnion();
5748
0
        }
5749
0
      } else if (isa<AccessSpecDecl>(Mem)) {
5750
        // Any access specifier is fine.
5751
0
      } else if (isa<StaticAssertDecl>(Mem)) {
5752
        // In C++1z, static_assert declarations are also fine.
5753
0
      } else {
5754
        // We have something that isn't a non-static data
5755
        // member. Complain about it.
5756
0
        unsigned DK = diag::err_anonymous_record_bad_member;
5757
0
        if (isa<TypeDecl>(Mem))
5758
0
          DK = diag::err_anonymous_record_with_type;
5759
0
        else if (isa<FunctionDecl>(Mem))
5760
0
          DK = diag::err_anonymous_record_with_function;
5761
0
        else if (isa<VarDecl>(Mem))
5762
0
          DK = diag::err_anonymous_record_with_static;
5763
5764
        // Visual C++ allows type definition in anonymous struct or union.
5765
0
        if (getLangOpts().MicrosoftExt &&
5766
0
            DK == diag::err_anonymous_record_with_type)
5767
0
          Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5768
0
            << Record->isUnion();
5769
0
        else {
5770
0
          Diag(Mem->getLocation(), DK) << Record->isUnion();
5771
0
          Invalid = true;
5772
0
        }
5773
0
      }
5774
0
    }
5775
5776
    // C++11 [class.union]p8 (DR1460):
5777
    //   At most one variant member of a union may have a
5778
    //   brace-or-equal-initializer.
5779
0
    if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5780
0
        Owner->isRecord())
5781
0
      checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5782
0
                                cast<CXXRecordDecl>(Record));
5783
0
  }
5784
5785
0
  if (!Record->isUnion() && !Owner->isRecord()) {
5786
0
    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5787
0
      << getLangOpts().CPlusPlus;
5788
0
    Invalid = true;
5789
0
  }
5790
5791
  // C++ [dcl.dcl]p3:
5792
  //   [If there are no declarators], and except for the declaration of an
5793
  //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5794
  //   names into the program
5795
  // C++ [class.mem]p2:
5796
  //   each such member-declaration shall either declare at least one member
5797
  //   name of the class or declare at least one unnamed bit-field
5798
  //
5799
  // For C this is an error even for a named struct, and is diagnosed elsewhere.
5800
0
  if (getLangOpts().CPlusPlus && Record->field_empty())
5801
0
    Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5802
5803
  // Mock up a declarator.
5804
0
  Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5805
0
  StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5806
0
  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5807
0
  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5808
5809
  // Create a declaration for this anonymous struct/union.
5810
0
  NamedDecl *Anon = nullptr;
5811
0
  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5812
0
    Anon = FieldDecl::Create(
5813
0
        Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5814
0
        /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5815
0
        /*BitWidth=*/nullptr, /*Mutable=*/false,
5816
0
        /*InitStyle=*/ICIS_NoInit);
5817
0
    Anon->setAccess(AS);
5818
0
    ProcessDeclAttributes(S, Anon, Dc);
5819
5820
0
    if (getLangOpts().CPlusPlus)
5821
0
      FieldCollector->Add(cast<FieldDecl>(Anon));
5822
0
  } else {
5823
0
    DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5824
0
    if (SCSpec == DeclSpec::SCS_mutable) {
5825
      // mutable can only appear on non-static class members, so it's always
5826
      // an error here
5827
0
      Diag(Record->getLocation(), diag::err_mutable_nonmember);
5828
0
      Invalid = true;
5829
0
      SC = SC_None;
5830
0
    }
5831
5832
0
    Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5833
0
                           Record->getLocation(), /*IdentifierInfo=*/nullptr,
5834
0
                           Context.getTypeDeclType(Record), TInfo, SC);
5835
0
    ProcessDeclAttributes(S, Anon, Dc);
5836
5837
    // Default-initialize the implicit variable. This initialization will be
5838
    // trivial in almost all cases, except if a union member has an in-class
5839
    // initializer:
5840
    //   union { int n = 0; };
5841
0
    ActOnUninitializedDecl(Anon);
5842
0
  }
5843
0
  Anon->setImplicit();
5844
5845
  // Mark this as an anonymous struct/union type.
5846
0
  Record->setAnonymousStructOrUnion(true);
5847
5848
  // Add the anonymous struct/union object to the current
5849
  // context. We'll be referencing this object when we refer to one of
5850
  // its members.
5851
0
  Owner->addDecl(Anon);
5852
5853
  // Inject the members of the anonymous struct/union into the owning
5854
  // context and into the identifier resolver chain for name lookup
5855
  // purposes.
5856
0
  SmallVector<NamedDecl*, 2> Chain;
5857
0
  Chain.push_back(Anon);
5858
5859
0
  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5860
0
                                          Chain))
5861
0
    Invalid = true;
5862
5863
0
  if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5864
0
    if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5865
0
      MangleNumberingContext *MCtx;
5866
0
      Decl *ManglingContextDecl;
5867
0
      std::tie(MCtx, ManglingContextDecl) =
5868
0
          getCurrentMangleNumberContext(NewVD->getDeclContext());
5869
0
      if (MCtx) {
5870
0
        Context.setManglingNumber(
5871
0
            NewVD, MCtx->getManglingNumber(
5872
0
                       NewVD, getMSManglingNumber(getLangOpts(), S)));
5873
0
        Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5874
0
      }
5875
0
    }
5876
0
  }
5877
5878
0
  if (Invalid)
5879
0
    Anon->setInvalidDecl();
5880
5881
0
  return Anon;
5882
0
}
5883
5884
/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5885
/// Microsoft C anonymous structure.
5886
/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5887
/// Example:
5888
///
5889
/// struct A { int a; };
5890
/// struct B { struct A; int b; };
5891
///
5892
/// void foo() {
5893
///   B var;
5894
///   var.a = 3;
5895
/// }
5896
///
5897
Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5898
0
                                           RecordDecl *Record) {
5899
0
  assert(Record && "expected a record!");
5900
5901
  // Mock up a declarator.
5902
0
  Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5903
0
  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5904
0
  assert(TInfo && "couldn't build declarator info for anonymous struct");
5905
5906
0
  auto *ParentDecl = cast<RecordDecl>(CurContext);
5907
0
  QualType RecTy = Context.getTypeDeclType(Record);
5908
5909
  // Create a declaration for this anonymous struct.
5910
0
  NamedDecl *Anon =
5911
0
      FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5912
0
                        /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5913
0
                        /*BitWidth=*/nullptr, /*Mutable=*/false,
5914
0
                        /*InitStyle=*/ICIS_NoInit);
5915
0
  Anon->setImplicit();
5916
5917
  // Add the anonymous struct object to the current context.
5918
0
  CurContext->addDecl(Anon);
5919
5920
  // Inject the members of the anonymous struct into the current
5921
  // context and into the identifier resolver chain for name lookup
5922
  // purposes.
5923
0
  SmallVector<NamedDecl*, 2> Chain;
5924
0
  Chain.push_back(Anon);
5925
5926
0
  RecordDecl *RecordDef = Record->getDefinition();
5927
0
  if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5928
0
                               diag::err_field_incomplete_or_sizeless) ||
5929
0
      InjectAnonymousStructOrUnionMembers(
5930
0
          *this, S, CurContext, RecordDef, AS_none,
5931
0
          StorageClassSpecToVarDeclStorageClass(DS), Chain)) {
5932
0
    Anon->setInvalidDecl();
5933
0
    ParentDecl->setInvalidDecl();
5934
0
  }
5935
5936
0
  return Anon;
5937
0
}
5938
5939
/// GetNameForDeclarator - Determine the full declaration name for the
5940
/// given Declarator.
5941
10.1k
DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5942
10.1k
  return GetNameFromUnqualifiedId(D.getName());
5943
10.1k
}
5944
5945
/// Retrieves the declaration name from a parsed unqualified-id.
5946
DeclarationNameInfo
5947
10.7k
Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5948
10.7k
  DeclarationNameInfo NameInfo;
5949
10.7k
  NameInfo.setLoc(Name.StartLocation);
5950
5951
10.7k
  switch (Name.getKind()) {
5952
5953
0
  case UnqualifiedIdKind::IK_ImplicitSelfParam:
5954
10.7k
  case UnqualifiedIdKind::IK_Identifier:
5955
10.7k
    NameInfo.setName(Name.Identifier);
5956
10.7k
    return NameInfo;
5957
5958
0
  case UnqualifiedIdKind::IK_DeductionGuideName: {
5959
    // C++ [temp.deduct.guide]p3:
5960
    //   The simple-template-id shall name a class template specialization.
5961
    //   The template-name shall be the same identifier as the template-name
5962
    //   of the simple-template-id.
5963
    // These together intend to imply that the template-name shall name a
5964
    // class template.
5965
    // FIXME: template<typename T> struct X {};
5966
    //        template<typename T> using Y = X<T>;
5967
    //        Y(int) -> Y<int>;
5968
    //   satisfies these rules but does not name a class template.
5969
0
    TemplateName TN = Name.TemplateName.get().get();
5970
0
    auto *Template = TN.getAsTemplateDecl();
5971
0
    if (!Template || !isa<ClassTemplateDecl>(Template)) {
5972
0
      Diag(Name.StartLocation,
5973
0
           diag::err_deduction_guide_name_not_class_template)
5974
0
        << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5975
0
      if (Template)
5976
0
        NoteTemplateLocation(*Template);
5977
0
      return DeclarationNameInfo();
5978
0
    }
5979
5980
0
    NameInfo.setName(
5981
0
        Context.DeclarationNames.getCXXDeductionGuideName(Template));
5982
0
    return NameInfo;
5983
0
  }
5984
5985
0
  case UnqualifiedIdKind::IK_OperatorFunctionId:
5986
0
    NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5987
0
                                           Name.OperatorFunctionId.Operator));
5988
0
    NameInfo.setCXXOperatorNameRange(SourceRange(
5989
0
        Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5990
0
    return NameInfo;
5991
5992
0
  case UnqualifiedIdKind::IK_LiteralOperatorId:
5993
0
    NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5994
0
                                                           Name.Identifier));
5995
0
    NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5996
0
    return NameInfo;
5997
5998
0
  case UnqualifiedIdKind::IK_ConversionFunctionId: {
5999
0
    TypeSourceInfo *TInfo;
6000
0
    QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
6001
0
    if (Ty.isNull())
6002
0
      return DeclarationNameInfo();
6003
0
    NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6004
0
                                               Context.getCanonicalType(Ty)));
6005
0
    NameInfo.setNamedTypeInfo(TInfo);
6006
0
    return NameInfo;
6007
0
  }
6008
6009
0
  case UnqualifiedIdKind::IK_ConstructorName: {
6010
0
    TypeSourceInfo *TInfo;
6011
0
    QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6012
0
    if (Ty.isNull())
6013
0
      return DeclarationNameInfo();
6014
0
    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6015
0
                                              Context.getCanonicalType(Ty)));
6016
0
    NameInfo.setNamedTypeInfo(TInfo);
6017
0
    return NameInfo;
6018
0
  }
6019
6020
0
  case UnqualifiedIdKind::IK_ConstructorTemplateId: {
6021
    // In well-formed code, we can only have a constructor
6022
    // template-id that refers to the current context, so go there
6023
    // to find the actual type being constructed.
6024
0
    CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6025
0
    if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6026
0
      return DeclarationNameInfo();
6027
6028
    // Determine the type of the class being constructed.
6029
0
    QualType CurClassType = Context.getTypeDeclType(CurClass);
6030
6031
    // FIXME: Check two things: that the template-id names the same type as
6032
    // CurClassType, and that the template-id does not occur when the name
6033
    // was qualified.
6034
6035
0
    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6036
0
                                    Context.getCanonicalType(CurClassType)));
6037
    // FIXME: should we retrieve TypeSourceInfo?
6038
0
    NameInfo.setNamedTypeInfo(nullptr);
6039
0
    return NameInfo;
6040
0
  }
6041
6042
0
  case UnqualifiedIdKind::IK_DestructorName: {
6043
0
    TypeSourceInfo *TInfo;
6044
0
    QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6045
0
    if (Ty.isNull())
6046
0
      return DeclarationNameInfo();
6047
0
    NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6048
0
                                              Context.getCanonicalType(Ty)));
6049
0
    NameInfo.setNamedTypeInfo(TInfo);
6050
0
    return NameInfo;
6051
0
  }
6052
6053
0
  case UnqualifiedIdKind::IK_TemplateId: {
6054
0
    TemplateName TName = Name.TemplateId->Template.get();
6055
0
    SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6056
0
    return Context.getNameForTemplate(TName, TNameLoc);
6057
0
  }
6058
6059
10.7k
  } // switch (Name.getKind())
6060
6061
0
  llvm_unreachable("Unknown name kind");
6062
0
}
6063
6064
0
static QualType getCoreType(QualType Ty) {
6065
0
  do {
6066
0
    if (Ty->isPointerType() || Ty->isReferenceType())
6067
0
      Ty = Ty->getPointeeType();
6068
0
    else if (Ty->isArrayType())
6069
0
      Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6070
0
    else
6071
0
      return Ty.withoutLocalFastQualifiers();
6072
0
  } while (true);
6073
0
}
6074
6075
/// hasSimilarParameters - Determine whether the C++ functions Declaration
6076
/// and Definition have "nearly" matching parameters. This heuristic is
6077
/// used to improve diagnostics in the case where an out-of-line function
6078
/// definition doesn't match any declaration within the class or namespace.
6079
/// Also sets Params to the list of indices to the parameters that differ
6080
/// between the declaration and the definition. If hasSimilarParameters
6081
/// returns true and Params is empty, then all of the parameters match.
6082
static bool hasSimilarParameters(ASTContext &Context,
6083
                                     FunctionDecl *Declaration,
6084
                                     FunctionDecl *Definition,
6085
0
                                     SmallVectorImpl<unsigned> &Params) {
6086
0
  Params.clear();
6087
0
  if (Declaration->param_size() != Definition->param_size())
6088
0
    return false;
6089
0
  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6090
0
    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6091
0
    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6092
6093
    // The parameter types are identical
6094
0
    if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6095
0
      continue;
6096
6097
0
    QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6098
0
    QualType DefParamBaseTy = getCoreType(DefParamTy);
6099
0
    const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6100
0
    const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6101
6102
0
    if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6103
0
        (DeclTyName && DeclTyName == DefTyName))
6104
0
      Params.push_back(Idx);
6105
0
    else  // The two parameters aren't even close
6106
0
      return false;
6107
0
  }
6108
6109
0
  return true;
6110
0
}
6111
6112
/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6113
/// declarator needs to be rebuilt in the current instantiation.
6114
/// Any bits of declarator which appear before the name are valid for
6115
/// consideration here.  That's specifically the type in the decl spec
6116
/// and the base type in any member-pointer chunks.
6117
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6118
0
                                                    DeclarationName Name) {
6119
  // The types we specifically need to rebuild are:
6120
  //   - typenames, typeofs, and decltypes
6121
  //   - types which will become injected class names
6122
  // Of course, we also need to rebuild any type referencing such a
6123
  // type.  It's safest to just say "dependent", but we call out a
6124
  // few cases here.
6125
6126
0
  DeclSpec &DS = D.getMutableDeclSpec();
6127
0
  switch (DS.getTypeSpecType()) {
6128
0
  case DeclSpec::TST_typename:
6129
0
  case DeclSpec::TST_typeofType:
6130
0
  case DeclSpec::TST_typeof_unqualType:
6131
0
#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6132
0
#include "clang/Basic/TransformTypeTraits.def"
6133
0
  case DeclSpec::TST_atomic: {
6134
    // Grab the type from the parser.
6135
0
    TypeSourceInfo *TSI = nullptr;
6136
0
    QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6137
0
    if (T.isNull() || !T->isInstantiationDependentType()) break;
6138
6139
    // Make sure there's a type source info.  This isn't really much
6140
    // of a waste; most dependent types should have type source info
6141
    // attached already.
6142
0
    if (!TSI)
6143
0
      TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
6144
6145
    // Rebuild the type in the current instantiation.
6146
0
    TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
6147
0
    if (!TSI) return true;
6148
6149
    // Store the new type back in the decl spec.
6150
0
    ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6151
0
    DS.UpdateTypeRep(LocType);
6152
0
    break;
6153
0
  }
6154
6155
0
  case DeclSpec::TST_decltype:
6156
0
  case DeclSpec::TST_typeof_unqualExpr:
6157
0
  case DeclSpec::TST_typeofExpr: {
6158
0
    Expr *E = DS.getRepAsExpr();
6159
0
    ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6160
0
    if (Result.isInvalid()) return true;
6161
0
    DS.UpdateExprRep(Result.get());
6162
0
    break;
6163
0
  }
6164
6165
0
  default:
6166
    // Nothing to do for these decl specs.
6167
0
    break;
6168
0
  }
6169
6170
  // It doesn't matter what order we do this in.
6171
0
  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6172
0
    DeclaratorChunk &Chunk = D.getTypeObject(I);
6173
6174
    // The only type information in the declarator which can come
6175
    // before the declaration name is the base type of a member
6176
    // pointer.
6177
0
    if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6178
0
      continue;
6179
6180
    // Rebuild the scope specifier in-place.
6181
0
    CXXScopeSpec &SS = Chunk.Mem.Scope();
6182
0
    if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6183
0
      return true;
6184
0
  }
6185
6186
0
  return false;
6187
0
}
6188
6189
/// Returns true if the declaration is declared in a system header or from a
6190
/// system macro.
6191
15
static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6192
15
  return SM.isInSystemHeader(D->getLocation()) ||
6193
15
         SM.isInSystemMacro(D->getLocation());
6194
15
}
6195
6196
5.41k
void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6197
  // Avoid warning twice on the same identifier, and don't warn on redeclaration
6198
  // of system decl.
6199
5.41k
  if (D->getPreviousDecl() || D->isImplicit())
6200
505
    return;
6201
4.90k
  ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6202
4.90k
  if (Status != ReservedIdentifierStatus::NotReserved &&
6203
4.90k
      !isFromSystemHeader(Context.getSourceManager(), D)) {
6204
15
    Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6205
15
        << D << static_cast<int>(Status);
6206
15
  }
6207
4.90k
}
6208
6209
5.08k
Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6210
5.08k
  D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6211
6212
  // Check if we are in an `omp begin/end declare variant` scope. Handle this
6213
  // declaration only if the `bind_to_declaration` extension is set.
6214
5.08k
  SmallVector<FunctionDecl *, 4> Bases;
6215
5.08k
  if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
6216
0
    if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
6217
0
              implementation_extension_bind_to_declaration))
6218
0
    ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6219
0
        S, D, MultiTemplateParamsArg(), Bases);
6220
6221
5.08k
  Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
6222
6223
5.08k
  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6224
5.08k
      Dcl && Dcl->getDeclContext()->isFileContext())
6225
0
    Dcl->setTopLevelDeclInObjCContainer();
6226
6227
5.08k
  if (!Bases.empty())
6228
0
    ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
6229
6230
5.08k
  return Dcl;
6231
5.08k
}
6232
6233
/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6234
///   If T is the name of a class, then each of the following shall have a
6235
///   name different from T:
6236
///     - every static data member of class T;
6237
///     - every member function of class T
6238
///     - every member of class T that is itself a type;
6239
/// \returns true if the declaration name violates these rules.
6240
bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6241
5.07k
                                   DeclarationNameInfo NameInfo) {
6242
5.07k
  DeclarationName Name = NameInfo.getName();
6243
6244
5.07k
  CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6245
5.07k
  while (Record && Record->isAnonymousStructOrUnion())
6246
0
    Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6247
5.07k
  if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6248
0
    Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6249
0
    return true;
6250
0
  }
6251
6252
5.07k
  return false;
6253
5.07k
}
6254
6255
/// Diagnose a declaration whose declarator-id has the given
6256
/// nested-name-specifier.
6257
///
6258
/// \param SS The nested-name-specifier of the declarator-id.
6259
///
6260
/// \param DC The declaration context to which the nested-name-specifier
6261
/// resolves.
6262
///
6263
/// \param Name The name of the entity being declared.
6264
///
6265
/// \param Loc The location of the name of the entity being declared.
6266
///
6267
/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
6268
/// we're declaring an explicit / partial specialization / instantiation.
6269
///
6270
/// \returns true if we cannot safely recover from this error, false otherwise.
6271
bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6272
                                        DeclarationName Name,
6273
0
                                        SourceLocation Loc, bool IsTemplateId) {
6274
0
  DeclContext *Cur = CurContext;
6275
0
  while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6276
0
    Cur = Cur->getParent();
6277
6278
  // If the user provided a superfluous scope specifier that refers back to the
6279
  // class in which the entity is already declared, diagnose and ignore it.
6280
  //
6281
  // class X {
6282
  //   void X::f();
6283
  // };
6284
  //
6285
  // Note, it was once ill-formed to give redundant qualification in all
6286
  // contexts, but that rule was removed by DR482.
6287
0
  if (Cur->Equals(DC)) {
6288
0
    if (Cur->isRecord()) {
6289
0
      Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6290
0
                                      : diag::err_member_extra_qualification)
6291
0
        << Name << FixItHint::CreateRemoval(SS.getRange());
6292
0
      SS.clear();
6293
0
    } else {
6294
0
      Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6295
0
    }
6296
0
    return false;
6297
0
  }
6298
6299
  // Check whether the qualifying scope encloses the scope of the original
6300
  // declaration. For a template-id, we perform the checks in
6301
  // CheckTemplateSpecializationScope.
6302
0
  if (!Cur->Encloses(DC) && !IsTemplateId) {
6303
0
    if (Cur->isRecord())
6304
0
      Diag(Loc, diag::err_member_qualification)
6305
0
        << Name << SS.getRange();
6306
0
    else if (isa<TranslationUnitDecl>(DC))
6307
0
      Diag(Loc, diag::err_invalid_declarator_global_scope)
6308
0
        << Name << SS.getRange();
6309
0
    else if (isa<FunctionDecl>(Cur))
6310
0
      Diag(Loc, diag::err_invalid_declarator_in_function)
6311
0
        << Name << SS.getRange();
6312
0
    else if (isa<BlockDecl>(Cur))
6313
0
      Diag(Loc, diag::err_invalid_declarator_in_block)
6314
0
        << Name << SS.getRange();
6315
0
    else if (isa<ExportDecl>(Cur)) {
6316
0
      if (!isa<NamespaceDecl>(DC))
6317
0
        Diag(Loc, diag::err_export_non_namespace_scope_name)
6318
0
            << Name << SS.getRange();
6319
0
      else
6320
        // The cases that DC is not NamespaceDecl should be handled in
6321
        // CheckRedeclarationExported.
6322
0
        return false;
6323
0
    } else
6324
0
      Diag(Loc, diag::err_invalid_declarator_scope)
6325
0
      << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6326
6327
0
    return true;
6328
0
  }
6329
6330
0
  if (Cur->isRecord()) {
6331
    // Cannot qualify members within a class.
6332
0
    Diag(Loc, diag::err_member_qualification)
6333
0
      << Name << SS.getRange();
6334
0
    SS.clear();
6335
6336
    // C++ constructors and destructors with incorrect scopes can break
6337
    // our AST invariants by having the wrong underlying types. If
6338
    // that's the case, then drop this declaration entirely.
6339
0
    if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6340
0
         Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6341
0
        !Context.hasSameType(Name.getCXXNameType(),
6342
0
                             Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6343
0
      return true;
6344
6345
0
    return false;
6346
0
  }
6347
6348
  // C++11 [dcl.meaning]p1:
6349
  //   [...] "The nested-name-specifier of the qualified declarator-id shall
6350
  //   not begin with a decltype-specifer"
6351
0
  NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6352
0
  while (SpecLoc.getPrefix())
6353
0
    SpecLoc = SpecLoc.getPrefix();
6354
0
  if (isa_and_nonnull<DecltypeType>(
6355
0
          SpecLoc.getNestedNameSpecifier()->getAsType()))
6356
0
    Diag(Loc, diag::err_decltype_in_declarator)
6357
0
      << SpecLoc.getTypeLoc().getSourceRange();
6358
6359
0
  return false;
6360
0
}
6361
6362
NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6363
5.08k
                                  MultiTemplateParamsArg TemplateParamLists) {
6364
  // TODO: consider using NameInfo for diagnostic.
6365
5.08k
  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6366
5.08k
  DeclarationName Name = NameInfo.getName();
6367
6368
  // All of these full declarators require an identifier.  If it doesn't have
6369
  // one, the ParsedFreeStandingDeclSpec action should be used.
6370
5.08k
  if (D.isDecompositionDeclarator()) {
6371
0
    return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6372
5.08k
  } else if (!Name) {
6373
0
    if (!D.isInvalidType())  // Reject this if we think it is valid.
6374
0
      Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6375
0
          << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6376
0
    return nullptr;
6377
5.08k
  } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6378
0
    return nullptr;
6379
6380
  // The scope passed in may not be a decl scope.  Zip up the scope tree until
6381
  // we find one that is.
6382
5.08k
  while ((S->getFlags() & Scope::DeclScope) == 0 ||
6383
5.08k
         (S->getFlags() & Scope::TemplateParamScope) != 0)
6384
0
    S = S->getParent();
6385
6386
5.08k
  DeclContext *DC = CurContext;
6387
5.08k
  if (D.getCXXScopeSpec().isInvalid())
6388
0
    D.setInvalidType();
6389
5.08k
  else if (D.getCXXScopeSpec().isSet()) {
6390
0
    if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6391
0
                                        UPPC_DeclarationQualifier))
6392
0
      return nullptr;
6393
6394
0
    bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6395
0
    DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6396
0
    if (!DC || isa<EnumDecl>(DC)) {
6397
      // If we could not compute the declaration context, it's because the
6398
      // declaration context is dependent but does not refer to a class,
6399
      // class template, or class template partial specialization. Complain
6400
      // and return early, to avoid the coming semantic disaster.
6401
0
      Diag(D.getIdentifierLoc(),
6402
0
           diag::err_template_qualified_declarator_no_match)
6403
0
        << D.getCXXScopeSpec().getScopeRep()
6404
0
        << D.getCXXScopeSpec().getRange();
6405
0
      return nullptr;
6406
0
    }
6407
0
    bool IsDependentContext = DC->isDependentContext();
6408
6409
0
    if (!IsDependentContext &&
6410
0
        RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6411
0
      return nullptr;
6412
6413
    // If a class is incomplete, do not parse entities inside it.
6414
0
    if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6415
0
      Diag(D.getIdentifierLoc(),
6416
0
           diag::err_member_def_undefined_record)
6417
0
        << Name << DC << D.getCXXScopeSpec().getRange();
6418
0
      return nullptr;
6419
0
    }
6420
0
    if (!D.getDeclSpec().isFriendSpecified()) {
6421
0
      if (diagnoseQualifiedDeclaration(
6422
0
              D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6423
0
              D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6424
0
        if (DC->isRecord())
6425
0
          return nullptr;
6426
6427
0
        D.setInvalidType();
6428
0
      }
6429
0
    }
6430
6431
    // Check whether we need to rebuild the type of the given
6432
    // declaration in the current instantiation.
6433
0
    if (EnteringContext && IsDependentContext &&
6434
0
        TemplateParamLists.size() != 0) {
6435
0
      ContextRAII SavedContext(*this, DC);
6436
0
      if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6437
0
        D.setInvalidType();
6438
0
    }
6439
0
  }
6440
6441
5.08k
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6442
5.08k
  QualType R = TInfo->getType();
6443
6444
5.08k
  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6445
5.08k
                                      UPPC_DeclarationType))
6446
0
    D.setInvalidType();
6447
6448
5.08k
  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6449
5.08k
                        forRedeclarationInCurContext());
6450
6451
  // See if this is a redefinition of a variable in the same scope.
6452
5.08k
  if (!D.getCXXScopeSpec().isSet()) {
6453
5.08k
    bool IsLinkageLookup = false;
6454
5.08k
    bool CreateBuiltins = false;
6455
6456
    // If the declaration we're planning to build will be a function
6457
    // or object with linkage, then look for another declaration with
6458
    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6459
    //
6460
    // If the declaration we're planning to build will be declared with
6461
    // external linkage in the translation unit, create any builtin with
6462
    // the same name.
6463
5.08k
    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6464
0
      /* Do nothing*/;
6465
5.08k
    else if (CurContext->isFunctionOrMethod() &&
6466
5.08k
             (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6467
0
              R->isFunctionType())) {
6468
0
      IsLinkageLookup = true;
6469
0
      CreateBuiltins =
6470
0
          CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6471
5.08k
    } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6472
5.08k
               D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6473
5.08k
      CreateBuiltins = true;
6474
6475
5.08k
    if (IsLinkageLookup) {
6476
0
      Previous.clear(LookupRedeclarationWithLinkage);
6477
0
      Previous.setRedeclarationKind(ForExternalRedeclaration);
6478
0
    }
6479
6480
5.08k
    LookupName(Previous, S, CreateBuiltins);
6481
5.08k
  } else { // Something like "int foo::x;"
6482
0
    LookupQualifiedName(Previous, DC);
6483
6484
    // C++ [dcl.meaning]p1:
6485
    //   When the declarator-id is qualified, the declaration shall refer to a
6486
    //  previously declared member of the class or namespace to which the
6487
    //  qualifier refers (or, in the case of a namespace, of an element of the
6488
    //  inline namespace set of that namespace (7.3.1)) or to a specialization
6489
    //  thereof; [...]
6490
    //
6491
    // Note that we already checked the context above, and that we do not have
6492
    // enough information to make sure that Previous contains the declaration
6493
    // we want to match. For example, given:
6494
    //
6495
    //   class X {
6496
    //     void f();
6497
    //     void f(float);
6498
    //   };
6499
    //
6500
    //   void X::f(int) { } // ill-formed
6501
    //
6502
    // In this case, Previous will point to the overload set
6503
    // containing the two f's declared in X, but neither of them
6504
    // matches.
6505
6506
0
    RemoveUsingDecls(Previous);
6507
0
  }
6508
6509
5.08k
  if (Previous.isSingleResult() &&
6510
5.08k
      Previous.getFoundDecl()->isTemplateParameter()) {
6511
    // Maybe we will complain about the shadowed template parameter.
6512
0
    if (!D.isInvalidType())
6513
0
      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6514
0
                                      Previous.getFoundDecl());
6515
6516
    // Just pretend that we didn't see the previous declaration.
6517
0
    Previous.clear();
6518
0
  }
6519
6520
5.08k
  if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6521
    // Forget that the previous declaration is the injected-class-name.
6522
0
    Previous.clear();
6523
6524
  // In C++, the previous declaration we find might be a tag type
6525
  // (class or enum). In this case, the new declaration will hide the
6526
  // tag type. Note that this applies to functions, function templates, and
6527
  // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6528
5.08k
  if (Previous.isSingleTagDecl() &&
6529
5.08k
      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6530
5.08k
      (TemplateParamLists.size() == 0 || R->isFunctionType()))
6531
0
    Previous.clear();
6532
6533
  // Check that there are no default arguments other than in the parameters
6534
  // of a function declaration (C++ only).
6535
5.08k
  if (getLangOpts().CPlusPlus)
6536
2.58k
    CheckExtraCXXDefaultArguments(D);
6537
6538
5.08k
  NamedDecl *New;
6539
6540
5.08k
  bool AddToScope = true;
6541
5.08k
  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6542
0
    if (TemplateParamLists.size()) {
6543
0
      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6544
0
      return nullptr;
6545
0
    }
6546
6547
0
    New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6548
5.08k
  } else if (R->isFunctionType()) {
6549
19
    New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6550
19
                                  TemplateParamLists,
6551
19
                                  AddToScope);
6552
5.07k
  } else {
6553
5.07k
    New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6554
5.07k
                                  AddToScope);
6555
5.07k
  }
6556
6557
5.08k
  if (!New)
6558
0
    return nullptr;
6559
6560
  // If this has an identifier and is not a function template specialization,
6561
  // add it to the scope stack.
6562
5.08k
  if (New->getDeclName() && AddToScope)
6563
5.08k
    PushOnScopeChains(New, S);
6564
6565
5.08k
  if (isInOpenMPDeclareTargetContext())
6566
0
    checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6567
6568
5.08k
  return New;
6569
5.08k
}
6570
6571
/// Helper method to turn variable array types into constant array
6572
/// types in certain situations which would otherwise be errors (for
6573
/// GCC compatibility).
6574
static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6575
                                                    ASTContext &Context,
6576
                                                    bool &SizeIsNegative,
6577
2
                                                    llvm::APSInt &Oversized) {
6578
  // This method tries to turn a variable array into a constant
6579
  // array even when the size isn't an ICE.  This is necessary
6580
  // for compatibility with code that depends on gcc's buggy
6581
  // constant expression folding, like struct {char x[(int)(char*)2];}
6582
2
  SizeIsNegative = false;
6583
2
  Oversized = 0;
6584
6585
2
  if (T->isDependentType())
6586
0
    return QualType();
6587
6588
2
  QualifierCollector Qs;
6589
2
  const Type *Ty = Qs.strip(T);
6590
6591
2
  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6592
0
    QualType Pointee = PTy->getPointeeType();
6593
0
    QualType FixedType =
6594
0
        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6595
0
                                            Oversized);
6596
0
    if (FixedType.isNull()) return FixedType;
6597
0
    FixedType = Context.getPointerType(FixedType);
6598
0
    return Qs.apply(Context, FixedType);
6599
0
  }
6600
2
  if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6601
0
    QualType Inner = PTy->getInnerType();
6602
0
    QualType FixedType =
6603
0
        TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6604
0
                                            Oversized);
6605
0
    if (FixedType.isNull()) return FixedType;
6606
0
    FixedType = Context.getParenType(FixedType);
6607
0
    return Qs.apply(Context, FixedType);
6608
0
  }
6609
6610
2
  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6611
2
  if (!VLATy)
6612
0
    return QualType();
6613
6614
2
  QualType ElemTy = VLATy->getElementType();
6615
2
  if (ElemTy->isVariablyModifiedType()) {
6616
0
    ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6617
0
                                                 SizeIsNegative, Oversized);
6618
0
    if (ElemTy.isNull())
6619
0
      return QualType();
6620
0
  }
6621
6622
2
  Expr::EvalResult Result;
6623
2
  if (!VLATy->getSizeExpr() ||
6624
2
      !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6625
2
    return QualType();
6626
6627
0
  llvm::APSInt Res = Result.Val.getInt();
6628
6629
  // Check whether the array size is negative.
6630
0
  if (Res.isSigned() && Res.isNegative()) {
6631
0
    SizeIsNegative = true;
6632
0
    return QualType();
6633
0
  }
6634
6635
  // Check whether the array is too large to be addressed.
6636
0
  unsigned ActiveSizeBits =
6637
0
      (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6638
0
       !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6639
0
          ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6640
0
          : Res.getActiveBits();
6641
0
  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6642
0
    Oversized = Res;
6643
0
    return QualType();
6644
0
  }
6645
6646
0
  QualType FoldedArrayType = Context.getConstantArrayType(
6647
0
      ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6648
0
  return Qs.apply(Context, FoldedArrayType);
6649
0
}
6650
6651
static void
6652
0
FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6653
0
  SrcTL = SrcTL.getUnqualifiedLoc();
6654
0
  DstTL = DstTL.getUnqualifiedLoc();
6655
0
  if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6656
0
    PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6657
0
    FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6658
0
                                      DstPTL.getPointeeLoc());
6659
0
    DstPTL.setStarLoc(SrcPTL.getStarLoc());
6660
0
    return;
6661
0
  }
6662
0
  if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6663
0
    ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6664
0
    FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6665
0
                                      DstPTL.getInnerLoc());
6666
0
    DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6667
0
    DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6668
0
    return;
6669
0
  }
6670
0
  ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6671
0
  ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6672
0
  TypeLoc SrcElemTL = SrcATL.getElementLoc();
6673
0
  TypeLoc DstElemTL = DstATL.getElementLoc();
6674
0
  if (VariableArrayTypeLoc SrcElemATL =
6675
0
          SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6676
0
    ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6677
0
    FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6678
0
  } else {
6679
0
    DstElemTL.initializeFullCopy(SrcElemTL);
6680
0
  }
6681
0
  DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6682
0
  DstATL.setSizeExpr(SrcATL.getSizeExpr());
6683
0
  DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6684
0
}
6685
6686
/// Helper method to turn variable array types into constant array
6687
/// types in certain situations which would otherwise be errors (for
6688
/// GCC compatibility).
6689
static TypeSourceInfo*
6690
TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6691
                                              ASTContext &Context,
6692
                                              bool &SizeIsNegative,
6693
2
                                              llvm::APSInt &Oversized) {
6694
2
  QualType FixedTy
6695
2
    = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6696
2
                                          SizeIsNegative, Oversized);
6697
2
  if (FixedTy.isNull())
6698
2
    return nullptr;
6699
0
  TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6700
0
  FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6701
0
                                    FixedTInfo->getTypeLoc());
6702
0
  return FixedTInfo;
6703
2
}
6704
6705
/// Attempt to fold a variable-sized type to a constant-sized type, returning
6706
/// true if we were successful.
6707
bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6708
                                           QualType &T, SourceLocation Loc,
6709
0
                                           unsigned FailedFoldDiagID) {
6710
0
  bool SizeIsNegative;
6711
0
  llvm::APSInt Oversized;
6712
0
  TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6713
0
      TInfo, Context, SizeIsNegative, Oversized);
6714
0
  if (FixedTInfo) {
6715
0
    Diag(Loc, diag::ext_vla_folded_to_constant);
6716
0
    TInfo = FixedTInfo;
6717
0
    T = FixedTInfo->getType();
6718
0
    return true;
6719
0
  }
6720
6721
0
  if (SizeIsNegative)
6722
0
    Diag(Loc, diag::err_typecheck_negative_array_size);
6723
0
  else if (Oversized.getBoolValue())
6724
0
    Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6725
0
  else if (FailedFoldDiagID)
6726
0
    Diag(Loc, FailedFoldDiagID);
6727
0
  return false;
6728
0
}
6729
6730
/// Register the given locally-scoped extern "C" declaration so
6731
/// that it can be found later for redeclarations. We include any extern "C"
6732
/// declaration that is not visible in the translation unit here, not just
6733
/// function-scope declarations.
6734
void
6735
291
Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6736
291
  if (!getLangOpts().CPlusPlus &&
6737
291
      ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6738
    // Don't need to track declarations in the TU in C.
6739
291
    return;
6740
6741
  // Note that we have a locally-scoped external with this name.
6742
0
  Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6743
0
}
6744
6745
291
NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6746
  // FIXME: We can have multiple results via __attribute__((overloadable)).
6747
291
  auto Result = Context.getExternCContextDecl()->lookup(Name);
6748
291
  return Result.empty() ? nullptr : *Result.begin();
6749
291
}
6750
6751
/// Diagnose function specifiers on a declaration of an identifier that
6752
/// does not identify a function.
6753
5.14k
void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6754
  // FIXME: We should probably indicate the identifier in question to avoid
6755
  // confusion for constructs like "virtual int a(), b;"
6756
5.14k
  if (DS.isVirtualSpecified())
6757
0
    Diag(DS.getVirtualSpecLoc(),
6758
0
         diag::err_virtual_non_function);
6759
6760
5.14k
  if (DS.hasExplicitSpecifier())
6761
0
    Diag(DS.getExplicitSpecLoc(),
6762
0
         diag::err_explicit_non_function);
6763
6764
5.14k
  if (DS.isNoreturnSpecified())
6765
0
    Diag(DS.getNoreturnSpecLoc(),
6766
0
         diag::err_noreturn_non_function);
6767
5.14k
}
6768
6769
NamedDecl*
6770
Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6771
0
                             TypeSourceInfo *TInfo, LookupResult &Previous) {
6772
  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6773
0
  if (D.getCXXScopeSpec().isSet()) {
6774
0
    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6775
0
      << D.getCXXScopeSpec().getRange();
6776
0
    D.setInvalidType();
6777
    // Pretend we didn't see the scope specifier.
6778
0
    DC = CurContext;
6779
0
    Previous.clear();
6780
0
  }
6781
6782
0
  DiagnoseFunctionSpecifiers(D.getDeclSpec());
6783
6784
0
  if (D.getDeclSpec().isInlineSpecified())
6785
0
    Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6786
0
        << getLangOpts().CPlusPlus17;
6787
0
  if (D.getDeclSpec().hasConstexprSpecifier())
6788
0
    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6789
0
        << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6790
6791
0
  if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6792
0
    if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6793
0
      Diag(D.getName().StartLocation,
6794
0
           diag::err_deduction_guide_invalid_specifier)
6795
0
          << "typedef";
6796
0
    else
6797
0
      Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6798
0
          << D.getName().getSourceRange();
6799
0
    return nullptr;
6800
0
  }
6801
6802
0
  TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6803
0
  if (!NewTD) return nullptr;
6804
6805
  // Handle attributes prior to checking for duplicates in MergeVarDecl
6806
0
  ProcessDeclAttributes(S, NewTD, D);
6807
6808
0
  CheckTypedefForVariablyModifiedType(S, NewTD);
6809
6810
0
  bool Redeclaration = D.isRedeclaration();
6811
0
  NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6812
0
  D.setRedeclaration(Redeclaration);
6813
0
  return ND;
6814
0
}
6815
6816
void
6817
0
Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6818
  // C99 6.7.7p2: If a typedef name specifies a variably modified type
6819
  // then it shall have block scope.
6820
  // Note that variably modified types must be fixed before merging the decl so
6821
  // that redeclarations will match.
6822
0
  TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6823
0
  QualType T = TInfo->getType();
6824
0
  if (T->isVariablyModifiedType()) {
6825
0
    setFunctionHasBranchProtectedScope();
6826
6827
0
    if (S->getFnParent() == nullptr) {
6828
0
      bool SizeIsNegative;
6829
0
      llvm::APSInt Oversized;
6830
0
      TypeSourceInfo *FixedTInfo =
6831
0
        TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6832
0
                                                      SizeIsNegative,
6833
0
                                                      Oversized);
6834
0
      if (FixedTInfo) {
6835
0
        Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6836
0
        NewTD->setTypeSourceInfo(FixedTInfo);
6837
0
      } else {
6838
0
        if (SizeIsNegative)
6839
0
          Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6840
0
        else if (T->isVariableArrayType())
6841
0
          Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6842
0
        else if (Oversized.getBoolValue())
6843
0
          Diag(NewTD->getLocation(), diag::err_array_too_large)
6844
0
            << toString(Oversized, 10);
6845
0
        else
6846
0
          Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6847
0
        NewTD->setInvalidDecl();
6848
0
      }
6849
0
    }
6850
0
  }
6851
0
}
6852
6853
/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6854
/// declares a typedef-name, either using the 'typedef' type specifier or via
6855
/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6856
NamedDecl*
6857
Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6858
0
                           LookupResult &Previous, bool &Redeclaration) {
6859
6860
  // Find the shadowed declaration before filtering for scope.
6861
0
  NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6862
6863
  // Merge the decl with the existing one if appropriate. If the decl is
6864
  // in an outer scope, it isn't the same thing.
6865
0
  FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6866
0
                       /*AllowInlineNamespace*/false);
6867
0
  filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6868
0
  if (!Previous.empty()) {
6869
0
    Redeclaration = true;
6870
0
    MergeTypedefNameDecl(S, NewTD, Previous);
6871
0
  } else {
6872
0
    inferGslPointerAttribute(NewTD);
6873
0
  }
6874
6875
0
  if (ShadowedDecl && !Redeclaration)
6876
0
    CheckShadow(NewTD, ShadowedDecl, Previous);
6877
6878
  // If this is the C FILE type, notify the AST context.
6879
0
  if (IdentifierInfo *II = NewTD->getIdentifier())
6880
0
    if (!NewTD->isInvalidDecl() &&
6881
0
        NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6882
0
      switch (II->getInterestingIdentifierID()) {
6883
0
      case tok::InterestingIdentifierKind::FILE:
6884
0
        Context.setFILEDecl(NewTD);
6885
0
        break;
6886
0
      case tok::InterestingIdentifierKind::jmp_buf:
6887
0
        Context.setjmp_bufDecl(NewTD);
6888
0
        break;
6889
0
      case tok::InterestingIdentifierKind::sigjmp_buf:
6890
0
        Context.setsigjmp_bufDecl(NewTD);
6891
0
        break;
6892
0
      case tok::InterestingIdentifierKind::ucontext_t:
6893
0
        Context.setucontext_tDecl(NewTD);
6894
0
        break;
6895
0
      case tok::InterestingIdentifierKind::float_t:
6896
0
      case tok::InterestingIdentifierKind::double_t:
6897
0
        NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6898
0
        break;
6899
0
      default:
6900
0
        break;
6901
0
      }
6902
0
    }
6903
6904
0
  return NewTD;
6905
0
}
6906
6907
/// Determines whether the given declaration is an out-of-scope
6908
/// previous declaration.
6909
///
6910
/// This routine should be invoked when name lookup has found a
6911
/// previous declaration (PrevDecl) that is not in the scope where a
6912
/// new declaration by the same name is being introduced. If the new
6913
/// declaration occurs in a local scope, previous declarations with
6914
/// linkage may still be considered previous declarations (C99
6915
/// 6.2.2p4-5, C++ [basic.link]p6).
6916
///
6917
/// \param PrevDecl the previous declaration found by name
6918
/// lookup
6919
///
6920
/// \param DC the context in which the new declaration is being
6921
/// declared.
6922
///
6923
/// \returns true if PrevDecl is an out-of-scope previous declaration
6924
/// for a new delcaration with the same name.
6925
static bool
6926
isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6927
0
                                ASTContext &Context) {
6928
0
  if (!PrevDecl)
6929
0
    return false;
6930
6931
0
  if (!PrevDecl->hasLinkage())
6932
0
    return false;
6933
6934
0
  if (Context.getLangOpts().CPlusPlus) {
6935
    // C++ [basic.link]p6:
6936
    //   If there is a visible declaration of an entity with linkage
6937
    //   having the same name and type, ignoring entities declared
6938
    //   outside the innermost enclosing namespace scope, the block
6939
    //   scope declaration declares that same entity and receives the
6940
    //   linkage of the previous declaration.
6941
0
    DeclContext *OuterContext = DC->getRedeclContext();
6942
0
    if (!OuterContext->isFunctionOrMethod())
6943
      // This rule only applies to block-scope declarations.
6944
0
      return false;
6945
6946
0
    DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6947
0
    if (PrevOuterContext->isRecord())
6948
      // We found a member function: ignore it.
6949
0
      return false;
6950
6951
    // Find the innermost enclosing namespace for the new and
6952
    // previous declarations.
6953
0
    OuterContext = OuterContext->getEnclosingNamespaceContext();
6954
0
    PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6955
6956
    // The previous declaration is in a different namespace, so it
6957
    // isn't the same function.
6958
0
    if (!OuterContext->Equals(PrevOuterContext))
6959
0
      return false;
6960
0
  }
6961
6962
0
  return true;
6963
0
}
6964
6965
2.58k
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6966
2.58k
  CXXScopeSpec &SS = D.getCXXScopeSpec();
6967
2.58k
  if (!SS.isSet()) return;
6968
0
  DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6969
0
}
6970
6971
0
bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6972
0
  QualType type = decl->getType();
6973
0
  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6974
0
  if (lifetime == Qualifiers::OCL_Autoreleasing) {
6975
    // Various kinds of declaration aren't allowed to be __autoreleasing.
6976
0
    unsigned kind = -1U;
6977
0
    if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6978
0
      if (var->hasAttr<BlocksAttr>())
6979
0
        kind = 0; // __block
6980
0
      else if (!var->hasLocalStorage())
6981
0
        kind = 1; // global
6982
0
    } else if (isa<ObjCIvarDecl>(decl)) {
6983
0
      kind = 3; // ivar
6984
0
    } else if (isa<FieldDecl>(decl)) {
6985
0
      kind = 2; // field
6986
0
    }
6987
6988
0
    if (kind != -1U) {
6989
0
      Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6990
0
        << kind;
6991
0
    }
6992
0
  } else if (lifetime == Qualifiers::OCL_None) {
6993
    // Try to infer lifetime.
6994
0
    if (!type->isObjCLifetimeType())
6995
0
      return false;
6996
6997
0
    lifetime = type->getObjCARCImplicitLifetime();
6998
0
    type = Context.getLifetimeQualifiedType(type, lifetime);
6999
0
    decl->setType(type);
7000
0
  }
7001
7002
0
  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
7003
    // Thread-local variables cannot have lifetime.
7004
0
    if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
7005
0
        var->getTLSKind()) {
7006
0
      Diag(var->getLocation(), diag::err_arc_thread_ownership)
7007
0
        << var->getType();
7008
0
      return true;
7009
0
    }
7010
0
  }
7011
7012
0
  return false;
7013
0
}
7014
7015
0
void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
7016
0
  if (Decl->getType().hasAddressSpace())
7017
0
    return;
7018
0
  if (Decl->getType()->isDependentType())
7019
0
    return;
7020
0
  if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
7021
0
    QualType Type = Var->getType();
7022
0
    if (Type->isSamplerT() || Type->isVoidType())
7023
0
      return;
7024
0
    LangAS ImplAS = LangAS::opencl_private;
7025
    // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7026
    // __opencl_c_program_scope_global_variables feature, the address space
7027
    // for a variable at program scope or a static or extern variable inside
7028
    // a function are inferred to be __global.
7029
0
    if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7030
0
        Var->hasGlobalStorage())
7031
0
      ImplAS = LangAS::opencl_global;
7032
    // If the original type from a decayed type is an array type and that array
7033
    // type has no address space yet, deduce it now.
7034
0
    if (auto DT = dyn_cast<DecayedType>(Type)) {
7035
0
      auto OrigTy = DT->getOriginalType();
7036
0
      if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7037
        // Add the address space to the original array type and then propagate
7038
        // that to the element type through `getAsArrayType`.
7039
0
        OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
7040
0
        OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
7041
        // Re-generate the decayed type.
7042
0
        Type = Context.getDecayedType(OrigTy);
7043
0
      }
7044
0
    }
7045
0
    Type = Context.getAddrSpaceQualType(Type, ImplAS);
7046
    // Apply any qualifiers (including address space) from the array type to
7047
    // the element type. This implements C99 6.7.3p8: "If the specification of
7048
    // an array type includes any type qualifiers, the element type is so
7049
    // qualified, not the array type."
7050
0
    if (Type->isArrayType())
7051
0
      Type = QualType(Context.getAsArrayType(Type), 0);
7052
0
    Decl->setType(Type);
7053
0
  }
7054
0
}
7055
7056
5.08k
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7057
  // Ensure that an auto decl is deduced otherwise the checks below might cache
7058
  // the wrong linkage.
7059
5.08k
  assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7060
7061
  // 'weak' only applies to declarations with external linkage.
7062
5.08k
  if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7063
0
    if (!ND.isExternallyVisible()) {
7064
0
      S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7065
0
      ND.dropAttr<WeakAttr>();
7066
0
    }
7067
0
  }
7068
5.08k
  if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7069
0
    if (ND.isExternallyVisible()) {
7070
0
      S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7071
0
      ND.dropAttr<WeakRefAttr>();
7072
0
      ND.dropAttr<AliasAttr>();
7073
0
    }
7074
0
  }
7075
7076
5.08k
  if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7077
5.07k
    if (VD->hasInit()) {
7078
20
      if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7079
0
        assert(VD->isThisDeclarationADefinition() &&
7080
0
               !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7081
0
        S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7082
0
        VD->dropAttr<AliasAttr>();
7083
0
      }
7084
20
    }
7085
5.07k
  }
7086
7087
  // 'selectany' only applies to externally visible variable declarations.
7088
  // It does not apply to functions.
7089
5.08k
  if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7090
0
    if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7091
0
      S.Diag(Attr->getLocation(),
7092
0
             diag::err_attribute_selectany_non_extern_data);
7093
0
      ND.dropAttr<SelectAnyAttr>();
7094
0
    }
7095
0
  }
7096
7097
5.08k
  if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7098
0
    auto *VD = dyn_cast<VarDecl>(&ND);
7099
0
    bool IsAnonymousNS = false;
7100
0
    bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7101
0
    if (VD) {
7102
0
      const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7103
0
      while (NS && !IsAnonymousNS) {
7104
0
        IsAnonymousNS = NS->isAnonymousNamespace();
7105
0
        NS = dyn_cast<NamespaceDecl>(NS->getParent());
7106
0
      }
7107
0
    }
7108
    // dll attributes require external linkage. Static locals may have external
7109
    // linkage but still cannot be explicitly imported or exported.
7110
    // In Microsoft mode, a variable defined in anonymous namespace must have
7111
    // external linkage in order to be exported.
7112
0
    bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7113
0
    if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7114
0
        (!AnonNSInMicrosoftMode &&
7115
0
         (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7116
0
      S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7117
0
        << &ND << Attr;
7118
0
      ND.setInvalidDecl();
7119
0
    }
7120
0
  }
7121
7122
  // Check the attributes on the function type, if any.
7123
5.08k
  if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7124
    // Don't declare this variable in the second operand of the for-statement;
7125
    // GCC miscompiles that by ending its lifetime before evaluating the
7126
    // third operand. See gcc.gnu.org/PR86769.
7127
19
    AttributedTypeLoc ATL;
7128
19
    for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7129
19
         (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7130
19
         TL = ATL.getModifiedLoc()) {
7131
      // The [[lifetimebound]] attribute can be applied to the implicit object
7132
      // parameter of a non-static member function (other than a ctor or dtor)
7133
      // by applying it to the function type.
7134
0
      if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7135
0
        const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7136
0
        if (!MD || MD->isStatic()) {
7137
0
          S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7138
0
              << !MD << A->getRange();
7139
0
        } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7140
0
          S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7141
0
              << isa<CXXDestructorDecl>(MD) << A->getRange();
7142
0
        }
7143
0
      }
7144
0
    }
7145
19
  }
7146
5.08k
}
7147
7148
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7149
                                           NamedDecl *NewDecl,
7150
                                           bool IsSpecialization,
7151
199
                                           bool IsDefinition) {
7152
199
  if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7153
143
    return;
7154
7155
56
  bool IsTemplate = false;
7156
56
  if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7157
0
    OldDecl = OldTD->getTemplatedDecl();
7158
0
    IsTemplate = true;
7159
0
    if (!IsSpecialization)
7160
0
      IsDefinition = false;
7161
0
  }
7162
56
  if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7163
0
    NewDecl = NewTD->getTemplatedDecl();
7164
0
    IsTemplate = true;
7165
0
  }
7166
7167
56
  if (!OldDecl || !NewDecl)
7168
0
    return;
7169
7170
56
  const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7171
56
  const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7172
56
  const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7173
56
  const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7174
7175
  // dllimport and dllexport are inheritable attributes so we have to exclude
7176
  // inherited attribute instances.
7177
56
  bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7178
56
                    (NewExportAttr && !NewExportAttr->isInherited());
7179
7180
  // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7181
  // the only exception being explicit specializations.
7182
  // Implicitly generated declarations are also excluded for now because there
7183
  // is no other way to switch these to use dllimport or dllexport.
7184
56
  bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7185
7186
56
  if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7187
    // Allow with a warning for free functions and global variables.
7188
0
    bool JustWarn = false;
7189
0
    if (!OldDecl->isCXXClassMember()) {
7190
0
      auto *VD = dyn_cast<VarDecl>(OldDecl);
7191
0
      if (VD && !VD->getDescribedVarTemplate())
7192
0
        JustWarn = true;
7193
0
      auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7194
0
      if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7195
0
        JustWarn = true;
7196
0
    }
7197
7198
    // We cannot change a declaration that's been used because IR has already
7199
    // been emitted. Dllimported functions will still work though (modulo
7200
    // address equality) as they can use the thunk.
7201
0
    if (OldDecl->isUsed())
7202
0
      if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7203
0
        JustWarn = false;
7204
7205
0
    unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7206
0
                               : diag::err_attribute_dll_redeclaration;
7207
0
    S.Diag(NewDecl->getLocation(), DiagID)
7208
0
        << NewDecl
7209
0
        << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7210
0
    S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7211
0
    if (!JustWarn) {
7212
0
      NewDecl->setInvalidDecl();
7213
0
      return;
7214
0
    }
7215
0
  }
7216
7217
  // A redeclaration is not allowed to drop a dllimport attribute, the only
7218
  // exceptions being inline function definitions (except for function
7219
  // templates), local extern declarations, qualified friend declarations or
7220
  // special MSVC extension: in the last case, the declaration is treated as if
7221
  // it were marked dllexport.
7222
56
  bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7223
56
  bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7224
56
  if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7225
    // Ignore static data because out-of-line definitions are diagnosed
7226
    // separately.
7227
56
    IsStaticDataMember = VD->isStaticDataMember();
7228
56
    IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7229
56
                   VarDecl::DeclarationOnly;
7230
56
  } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7231
0
    IsInline = FD->isInlined();
7232
0
    IsQualifiedFriend = FD->getQualifier() &&
7233
0
                        FD->getFriendObjectKind() == Decl::FOK_Declared;
7234
0
  }
7235
7236
56
  if (OldImportAttr && !HasNewAttr &&
7237
56
      (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7238
56
      !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7239
0
    if (IsMicrosoftABI && IsDefinition) {
7240
0
      if (IsSpecialization) {
7241
0
        S.Diag(
7242
0
            NewDecl->getLocation(),
7243
0
            diag::err_attribute_dllimport_function_specialization_definition);
7244
0
        S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7245
0
        NewDecl->dropAttr<DLLImportAttr>();
7246
0
      } else {
7247
0
        S.Diag(NewDecl->getLocation(),
7248
0
               diag::warn_redeclaration_without_import_attribute)
7249
0
            << NewDecl;
7250
0
        S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7251
0
        NewDecl->dropAttr<DLLImportAttr>();
7252
0
        NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7253
0
            S.Context, NewImportAttr->getRange()));
7254
0
      }
7255
0
    } else if (IsMicrosoftABI && IsSpecialization) {
7256
0
      assert(!IsDefinition);
7257
      // MSVC allows this. Keep the inherited attribute.
7258
0
    } else {
7259
0
      S.Diag(NewDecl->getLocation(),
7260
0
             diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7261
0
          << NewDecl << OldImportAttr;
7262
0
      S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7263
0
      S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7264
0
      OldDecl->dropAttr<DLLImportAttr>();
7265
0
      NewDecl->dropAttr<DLLImportAttr>();
7266
0
    }
7267
56
  } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7268
    // In MinGW, seeing a function declared inline drops the dllimport
7269
    // attribute.
7270
0
    OldDecl->dropAttr<DLLImportAttr>();
7271
0
    NewDecl->dropAttr<DLLImportAttr>();
7272
0
    S.Diag(NewDecl->getLocation(),
7273
0
           diag::warn_dllimport_dropped_from_inline_function)
7274
0
        << NewDecl << OldImportAttr;
7275
0
  }
7276
7277
  // A specialization of a class template member function is processed here
7278
  // since it's a redeclaration. If the parent class is dllexport, the
7279
  // specialization inherits that attribute. This doesn't happen automatically
7280
  // since the parent class isn't instantiated until later.
7281
56
  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7282
0
    if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7283
0
        !NewImportAttr && !NewExportAttr) {
7284
0
      if (const DLLExportAttr *ParentExportAttr =
7285
0
              MD->getParent()->getAttr<DLLExportAttr>()) {
7286
0
        DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7287
0
        NewAttr->setInherited(true);
7288
0
        NewDecl->addAttr(NewAttr);
7289
0
      }
7290
0
    }
7291
0
  }
7292
56
}
7293
7294
/// Given that we are within the definition of the given function,
7295
/// will that definition behave like C99's 'inline', where the
7296
/// definition is discarded except for optimization purposes?
7297
0
static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7298
  // Try to avoid calling GetGVALinkageForFunction.
7299
7300
  // All cases of this require the 'inline' keyword.
7301
0
  if (!FD->isInlined()) return false;
7302
7303
  // This is only possible in C++ with the gnu_inline attribute.
7304
0
  if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7305
0
    return false;
7306
7307
  // Okay, go ahead and call the relatively-more-expensive function.
7308
0
  return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7309
0
}
7310
7311
/// Determine whether a variable is extern "C" prior to attaching
7312
/// an initializer. We can't just call isExternC() here, because that
7313
/// will also compute and cache whether the declaration is externally
7314
/// visible, which might change when we attach the initializer.
7315
///
7316
/// This can only be used if the declaration is known to not be a
7317
/// redeclaration of an internal linkage declaration.
7318
///
7319
/// For instance:
7320
///
7321
///   auto x = []{};
7322
///
7323
/// Attaching the initializer here makes this declaration not externally
7324
/// visible, because its type has internal linkage.
7325
///
7326
/// FIXME: This is a hack.
7327
template<typename T>
7328
291
static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7329
291
  if (S.getLangOpts().CPlusPlus) {
7330
    // In C++, the overloadable attribute negates the effects of extern "C".
7331
0
    if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7332
0
      return false;
7333
7334
    // So do CUDA's host/device attributes.
7335
0
    if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7336
0
                                 D->template hasAttr<CUDAHostAttr>()))
7337
0
      return false;
7338
0
  }
7339
291
  return D->isExternC();
7340
291
}
SemaDecl.cpp:bool isIncompleteDeclExternC<clang::VarDecl>(clang::Sema&, clang::VarDecl const*)
Line
Count
Source
7328
285
static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7329
285
  if (S.getLangOpts().CPlusPlus) {
7330
    // In C++, the overloadable attribute negates the effects of extern "C".
7331
0
    if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7332
0
      return false;
7333
7334
    // So do CUDA's host/device attributes.
7335
0
    if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7336
0
                                 D->template hasAttr<CUDAHostAttr>()))
7337
0
      return false;
7338
0
  }
7339
285
  return D->isExternC();
7340
285
}
SemaDecl.cpp:bool isIncompleteDeclExternC<clang::FunctionDecl>(clang::Sema&, clang::FunctionDecl const*)
Line
Count
Source
7328
6
static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7329
6
  if (S.getLangOpts().CPlusPlus) {
7330
    // In C++, the overloadable attribute negates the effects of extern "C".
7331
0
    if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7332
0
      return false;
7333
7334
    // So do CUDA's host/device attributes.
7335
0
    if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7336
0
                                 D->template hasAttr<CUDAHostAttr>()))
7337
0
      return false;
7338
0
  }
7339
6
  return D->isExternC();
7340
6
}
7341
7342
5.07k
static bool shouldConsiderLinkage(const VarDecl *VD) {
7343
5.07k
  const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7344
5.07k
  if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7345
5.07k
      isa<OMPDeclareMapperDecl>(DC))
7346
0
    return VD->hasExternalStorage();
7347
5.07k
  if (DC->isFileContext())
7348
5.07k
    return true;
7349
0
  if (DC->isRecord())
7350
0
    return false;
7351
0
  if (DC->getDeclKind() == Decl::HLSLBuffer)
7352
0
    return false;
7353
7354
0
  if (isa<RequiresExprBodyDecl>(DC))
7355
0
    return false;
7356
0
  llvm_unreachable("Unexpected context");
7357
0
}
7358
7359
19
static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7360
19
  const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7361
19
  if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7362
19
      isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7363
19
    return true;
7364
0
  if (DC->isRecord())
7365
0
    return false;
7366
0
  llvm_unreachable("Unexpected context");
7367
0
}
7368
7369
static bool hasParsedAttr(Scope *S, const Declarator &PD,
7370
5.07k
                          ParsedAttr::Kind Kind) {
7371
  // Check decl attributes on the DeclSpec.
7372
5.07k
  if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7373
0
    return true;
7374
7375
  // Walk the declarator structure, checking decl attributes that were in a type
7376
  // position to the decl itself.
7377
5.55k
  for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7378
485
    if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7379
0
      return true;
7380
485
  }
7381
7382
  // Finally, check attributes on the decl itself.
7383
5.07k
  return PD.getAttributes().hasAttribute(Kind) ||
7384
5.07k
         PD.getDeclarationAttributes().hasAttribute(Kind);
7385
5.07k
}
7386
7387
/// Adjust the \c DeclContext for a function or variable that might be a
7388
/// function-local external declaration.
7389
19
bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7390
19
  if (!DC->isFunctionOrMethod())
7391
19
    return false;
7392
7393
  // If this is a local extern function or variable declared within a function
7394
  // template, don't add it into the enclosing namespace scope until it is
7395
  // instantiated; it might have a dependent type right now.
7396
0
  if (DC->isDependentContext())
7397
0
    return true;
7398
7399
  // C++11 [basic.link]p7:
7400
  //   When a block scope declaration of an entity with linkage is not found to
7401
  //   refer to some other declaration, then that entity is a member of the
7402
  //   innermost enclosing namespace.
7403
  //
7404
  // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7405
  // semantically-enclosing namespace, not a lexically-enclosing one.
7406
0
  while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7407
0
    DC = DC->getParent();
7408
0
  return true;
7409
0
}
7410
7411
/// Returns true if given declaration has external C language linkage.
7412
0
static bool isDeclExternC(const Decl *D) {
7413
0
  if (const auto *FD = dyn_cast<FunctionDecl>(D))
7414
0
    return FD->isExternC();
7415
0
  if (const auto *VD = dyn_cast<VarDecl>(D))
7416
0
    return VD->isExternC();
7417
7418
0
  llvm_unreachable("Unknown type of decl!");
7419
0
}
7420
7421
/// Returns true if there hasn't been any invalid type diagnosed.
7422
0
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7423
0
  DeclContext *DC = NewVD->getDeclContext();
7424
0
  QualType R = NewVD->getType();
7425
7426
  // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7427
  // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7428
  // argument.
7429
0
  if (R->isImageType() || R->isPipeType()) {
7430
0
    Se.Diag(NewVD->getLocation(),
7431
0
            diag::err_opencl_type_can_only_be_used_as_function_parameter)
7432
0
        << R;
7433
0
    NewVD->setInvalidDecl();
7434
0
    return false;
7435
0
  }
7436
7437
  // OpenCL v1.2 s6.9.r:
7438
  // The event type cannot be used to declare a program scope variable.
7439
  // OpenCL v2.0 s6.9.q:
7440
  // The clk_event_t and reserve_id_t types cannot be declared in program
7441
  // scope.
7442
0
  if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7443
0
    if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7444
0
      Se.Diag(NewVD->getLocation(),
7445
0
              diag::err_invalid_type_for_program_scope_var)
7446
0
          << R;
7447
0
      NewVD->setInvalidDecl();
7448
0
      return false;
7449
0
    }
7450
0
  }
7451
7452
  // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7453
0
  if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7454
0
                                               Se.getLangOpts())) {
7455
0
    QualType NR = R.getCanonicalType();
7456
0
    while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7457
0
           NR->isReferenceType()) {
7458
0
      if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7459
0
          NR->isFunctionReferenceType()) {
7460
0
        Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7461
0
            << NR->isReferenceType();
7462
0
        NewVD->setInvalidDecl();
7463
0
        return false;
7464
0
      }
7465
0
      NR = NR->getPointeeType();
7466
0
    }
7467
0
  }
7468
7469
0
  if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7470
0
                                               Se.getLangOpts())) {
7471
    // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7472
    // half array type (unless the cl_khr_fp16 extension is enabled).
7473
0
    if (Se.Context.getBaseElementType(R)->isHalfType()) {
7474
0
      Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7475
0
      NewVD->setInvalidDecl();
7476
0
      return false;
7477
0
    }
7478
0
  }
7479
7480
  // OpenCL v1.2 s6.9.r:
7481
  // The event type cannot be used with the __local, __constant and __global
7482
  // address space qualifiers.
7483
0
  if (R->isEventT()) {
7484
0
    if (R.getAddressSpace() != LangAS::opencl_private) {
7485
0
      Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7486
0
      NewVD->setInvalidDecl();
7487
0
      return false;
7488
0
    }
7489
0
  }
7490
7491
0
  if (R->isSamplerT()) {
7492
    // OpenCL v1.2 s6.9.b p4:
7493
    // The sampler type cannot be used with the __local and __global address
7494
    // space qualifiers.
7495
0
    if (R.getAddressSpace() == LangAS::opencl_local ||
7496
0
        R.getAddressSpace() == LangAS::opencl_global) {
7497
0
      Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7498
0
      NewVD->setInvalidDecl();
7499
0
    }
7500
7501
    // OpenCL v1.2 s6.12.14.1:
7502
    // A global sampler must be declared with either the constant address
7503
    // space qualifier or with the const qualifier.
7504
0
    if (DC->isTranslationUnit() &&
7505
0
        !(R.getAddressSpace() == LangAS::opencl_constant ||
7506
0
          R.isConstQualified())) {
7507
0
      Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7508
0
      NewVD->setInvalidDecl();
7509
0
    }
7510
0
    if (NewVD->isInvalidDecl())
7511
0
      return false;
7512
0
  }
7513
7514
0
  return true;
7515
0
}
7516
7517
template <typename AttrTy>
7518
0
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7519
0
  const TypedefNameDecl *TND = TT->getDecl();
7520
0
  if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7521
0
    AttrTy *Clone = Attribute->clone(S.Context);
7522
0
    Clone->setInherited(true);
7523
0
    D->addAttr(Clone);
7524
0
  }
7525
0
}
7526
7527
// This function emits warning and a corresponding note based on the
7528
// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7529
// declarations of an annotated type must be const qualified.
7530
5.07k
void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7531
5.07k
  QualType VarType = VD->getType().getCanonicalType();
7532
7533
  // Ignore local declarations (for now) and those with const qualification.
7534
  // TODO: Local variables should not be allowed if their type declaration has
7535
  // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7536
5.07k
  if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7537
0
    return;
7538
7539
5.07k
  if (VarType->isArrayType()) {
7540
    // Retrieve element type for array declarations.
7541
43
    VarType = S.getASTContext().getBaseElementType(VarType);
7542
43
  }
7543
7544
5.07k
  const RecordDecl *RD = VarType->getAsRecordDecl();
7545
7546
  // Check if the record declaration is present and if it has any attributes.
7547
5.07k
  if (RD == nullptr)
7548
5.07k
    return;
7549
7550
0
  if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7551
0
    S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7552
0
    S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7553
0
    return;
7554
0
  }
7555
0
}
7556
7557
NamedDecl *Sema::ActOnVariableDeclarator(
7558
    Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7559
    LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7560
5.07k
    bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7561
5.07k
  QualType R = TInfo->getType();
7562
5.07k
  DeclarationName Name = GetNameForDeclarator(D).getName();
7563
7564
5.07k
  IdentifierInfo *II = Name.getAsIdentifierInfo();
7565
5.07k
  bool IsPlaceholderVariable = false;
7566
7567
5.07k
  if (D.isDecompositionDeclarator()) {
7568
    // Take the name of the first declarator as our name for diagnostic
7569
    // purposes.
7570
0
    auto &Decomp = D.getDecompositionDeclarator();
7571
0
    if (!Decomp.bindings().empty()) {
7572
0
      II = Decomp.bindings()[0].Name;
7573
0
      Name = II;
7574
0
    }
7575
5.07k
  } else if (!II) {
7576
0
    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7577
0
    return nullptr;
7578
0
  }
7579
7580
7581
5.07k
  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7582
5.07k
  StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7583
7584
5.07k
  if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7585
5.07k
      SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7586
0
    IsPlaceholderVariable = true;
7587
0
    if (!Previous.empty()) {
7588
0
      NamedDecl *PrevDecl = *Previous.begin();
7589
0
      bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7590
0
          DC->getRedeclContext());
7591
0
      if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))
7592
0
        DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
7593
0
    }
7594
0
  }
7595
7596
  // dllimport globals without explicit storage class are treated as extern. We
7597
  // have to change the storage class this early to get the right DeclContext.
7598
5.07k
  if (SC == SC_None && !DC->isRecord() &&
7599
5.07k
      hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7600
5.07k
      !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7601
0
    SC = SC_Extern;
7602
7603
5.07k
  DeclContext *OriginalDC = DC;
7604
5.07k
  bool IsLocalExternDecl = SC == SC_Extern &&
7605
5.07k
                           adjustContextForLocalExternDecl(DC);
7606
7607
5.07k
  if (SCSpec == DeclSpec::SCS_mutable) {
7608
    // mutable can only appear on non-static class members, so it's always
7609
    // an error here
7610
0
    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7611
0
    D.setInvalidType();
7612
0
    SC = SC_None;
7613
0
  }
7614
7615
5.07k
  if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7616
5.07k
      !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7617
0
                              D.getDeclSpec().getStorageClassSpecLoc())) {
7618
    // In C++11, the 'register' storage class specifier is deprecated.
7619
    // Suppress the warning in system macros, it's used in macros in some
7620
    // popular C system headers, such as in glibc's htonl() macro.
7621
0
    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7622
0
         getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7623
0
                                   : diag::warn_deprecated_register)
7624
0
      << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7625
0
  }
7626
7627
5.07k
  DiagnoseFunctionSpecifiers(D.getDeclSpec());
7628
7629
5.07k
  if (!DC->isRecord() && S->getFnParent() == nullptr) {
7630
    // C99 6.9p2: The storage-class specifiers auto and register shall not
7631
    // appear in the declaration specifiers in an external declaration.
7632
    // Global Register+Asm is a GNU extension we support.
7633
5.07k
    if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7634
0
      Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7635
0
      D.setInvalidType();
7636
0
    }
7637
5.07k
  }
7638
7639
  // If this variable has a VLA type and an initializer, try to
7640
  // fold to a constant-sized type. This is otherwise invalid.
7641
5.07k
  if (D.hasInitializer() && R->isVariableArrayType())
7642
0
    tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7643
0
                                    /*DiagID=*/0);
7644
7645
5.07k
  bool IsMemberSpecialization = false;
7646
5.07k
  bool IsVariableTemplateSpecialization = false;
7647
5.07k
  bool IsPartialSpecialization = false;
7648
5.07k
  bool IsVariableTemplate = false;
7649
5.07k
  VarDecl *NewVD = nullptr;
7650
5.07k
  VarTemplateDecl *NewTemplate = nullptr;
7651
5.07k
  TemplateParameterList *TemplateParams = nullptr;
7652
5.07k
  if (!getLangOpts().CPlusPlus) {
7653
2.48k
    NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7654
2.48k
                            II, R, TInfo, SC);
7655
7656
2.48k
    if (R->getContainedDeducedType())
7657
0
      ParsingInitForAutoVars.insert(NewVD);
7658
7659
2.48k
    if (D.isInvalidType())
7660
2.00k
      NewVD->setInvalidDecl();
7661
7662
2.48k
    if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7663
2.48k
        NewVD->hasLocalStorage())
7664
0
      checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7665
0
                            NTCUC_AutoVar, NTCUK_Destruct);
7666
2.58k
  } else {
7667
2.58k
    bool Invalid = false;
7668
7669
2.58k
    if (DC->isRecord() && !CurContext->isRecord()) {
7670
      // This is an out-of-line definition of a static data member.
7671
0
      switch (SC) {
7672
0
      case SC_None:
7673
0
        break;
7674
0
      case SC_Static:
7675
0
        Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7676
0
             diag::err_static_out_of_line)
7677
0
          << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7678
0
        break;
7679
0
      case SC_Auto:
7680
0
      case SC_Register:
7681
0
      case SC_Extern:
7682
        // [dcl.stc] p2: The auto or register specifiers shall be applied only
7683
        // to names of variables declared in a block or to function parameters.
7684
        // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7685
        // of class members
7686
7687
0
        Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7688
0
             diag::err_storage_class_for_static_member)
7689
0
          << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7690
0
        break;
7691
0
      case SC_PrivateExtern:
7692
0
        llvm_unreachable("C storage class in c++!");
7693
0
      }
7694
0
    }
7695
7696
2.58k
    if (SC == SC_Static && CurContext->isRecord()) {
7697
0
      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7698
        // Walk up the enclosing DeclContexts to check for any that are
7699
        // incompatible with static data members.
7700
0
        const DeclContext *FunctionOrMethod = nullptr;
7701
0
        const CXXRecordDecl *AnonStruct = nullptr;
7702
0
        for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7703
0
          if (Ctxt->isFunctionOrMethod()) {
7704
0
            FunctionOrMethod = Ctxt;
7705
0
            break;
7706
0
          }
7707
0
          const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7708
0
          if (ParentDecl && !ParentDecl->getDeclName()) {
7709
0
            AnonStruct = ParentDecl;
7710
0
            break;
7711
0
          }
7712
0
        }
7713
0
        if (FunctionOrMethod) {
7714
          // C++ [class.static.data]p5: A local class shall not have static data
7715
          // members.
7716
0
          Diag(D.getIdentifierLoc(),
7717
0
               diag::err_static_data_member_not_allowed_in_local_class)
7718
0
              << Name << RD->getDeclName()
7719
0
              << llvm::to_underlying(RD->getTagKind());
7720
0
        } else if (AnonStruct) {
7721
          // C++ [class.static.data]p4: Unnamed classes and classes contained
7722
          // directly or indirectly within unnamed classes shall not contain
7723
          // static data members.
7724
0
          Diag(D.getIdentifierLoc(),
7725
0
               diag::err_static_data_member_not_allowed_in_anon_struct)
7726
0
              << Name << llvm::to_underlying(AnonStruct->getTagKind());
7727
0
          Invalid = true;
7728
0
        } else if (RD->isUnion()) {
7729
          // C++98 [class.union]p1: If a union contains a static data member,
7730
          // the program is ill-formed. C++11 drops this restriction.
7731
0
          Diag(D.getIdentifierLoc(),
7732
0
               getLangOpts().CPlusPlus11
7733
0
                 ? diag::warn_cxx98_compat_static_data_member_in_union
7734
0
                 : diag::ext_static_data_member_in_union) << Name;
7735
0
        }
7736
0
      }
7737
0
    }
7738
7739
    // Match up the template parameter lists with the scope specifier, then
7740
    // determine whether we have a template or a template specialization.
7741
2.58k
    bool InvalidScope = false;
7742
2.58k
    TemplateParams = MatchTemplateParametersToScopeSpecifier(
7743
2.58k
        D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7744
2.58k
        D.getCXXScopeSpec(),
7745
2.58k
        D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7746
2.58k
            ? D.getName().TemplateId
7747
2.58k
            : nullptr,
7748
2.58k
        TemplateParamLists,
7749
2.58k
        /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7750
2.58k
    Invalid |= InvalidScope;
7751
7752
2.58k
    if (TemplateParams) {
7753
0
      if (!TemplateParams->size() &&
7754
0
          D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7755
        // There is an extraneous 'template<>' for this variable. Complain
7756
        // about it, but allow the declaration of the variable.
7757
0
        Diag(TemplateParams->getTemplateLoc(),
7758
0
             diag::err_template_variable_noparams)
7759
0
          << II
7760
0
          << SourceRange(TemplateParams->getTemplateLoc(),
7761
0
                         TemplateParams->getRAngleLoc());
7762
0
        TemplateParams = nullptr;
7763
0
      } else {
7764
        // Check that we can declare a template here.
7765
0
        if (CheckTemplateDeclScope(S, TemplateParams))
7766
0
          return nullptr;
7767
7768
0
        if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7769
          // This is an explicit specialization or a partial specialization.
7770
0
          IsVariableTemplateSpecialization = true;
7771
0
          IsPartialSpecialization = TemplateParams->size() > 0;
7772
0
        } else { // if (TemplateParams->size() > 0)
7773
          // This is a template declaration.
7774
0
          IsVariableTemplate = true;
7775
7776
          // Only C++1y supports variable templates (N3651).
7777
0
          Diag(D.getIdentifierLoc(),
7778
0
               getLangOpts().CPlusPlus14
7779
0
                   ? diag::warn_cxx11_compat_variable_template
7780
0
                   : diag::ext_variable_template);
7781
0
        }
7782
0
      }
7783
2.58k
    } else {
7784
      // Check that we can declare a member specialization here.
7785
2.58k
      if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7786
2.58k
          CheckTemplateDeclScope(S, TemplateParamLists.back()))
7787
0
        return nullptr;
7788
2.58k
      assert((Invalid ||
7789
2.58k
              D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7790
2.58k
             "should have a 'template<>' for this decl");
7791
2.58k
    }
7792
7793
2.58k
    if (IsVariableTemplateSpecialization) {
7794
0
      SourceLocation TemplateKWLoc =
7795
0
          TemplateParamLists.size() > 0
7796
0
              ? TemplateParamLists[0]->getTemplateLoc()
7797
0
              : SourceLocation();
7798
0
      DeclResult Res = ActOnVarTemplateSpecialization(
7799
0
          S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7800
0
          IsPartialSpecialization);
7801
0
      if (Res.isInvalid())
7802
0
        return nullptr;
7803
0
      NewVD = cast<VarDecl>(Res.get());
7804
0
      AddToScope = false;
7805
2.58k
    } else if (D.isDecompositionDeclarator()) {
7806
0
      NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7807
0
                                        D.getIdentifierLoc(), R, TInfo, SC,
7808
0
                                        Bindings);
7809
0
    } else
7810
2.58k
      NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7811
2.58k
                              D.getIdentifierLoc(), II, R, TInfo, SC);
7812
7813
    // If this is supposed to be a variable template, create it as such.
7814
2.58k
    if (IsVariableTemplate) {
7815
0
      NewTemplate =
7816
0
          VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7817
0
                                  TemplateParams, NewVD);
7818
0
      NewVD->setDescribedVarTemplate(NewTemplate);
7819
0
    }
7820
7821
    // If this decl has an auto type in need of deduction, make a note of the
7822
    // Decl so we can diagnose uses of it in its own initializer.
7823
2.58k
    if (R->getContainedDeducedType())
7824
0
      ParsingInitForAutoVars.insert(NewVD);
7825
7826
2.58k
    if (D.isInvalidType() || Invalid) {
7827
2.58k
      NewVD->setInvalidDecl();
7828
2.58k
      if (NewTemplate)
7829
0
        NewTemplate->setInvalidDecl();
7830
2.58k
    }
7831
7832
2.58k
    SetNestedNameSpecifier(*this, NewVD, D);
7833
7834
    // If we have any template parameter lists that don't directly belong to
7835
    // the variable (matching the scope specifier), store them.
7836
    // An explicit variable template specialization does not own any template
7837
    // parameter lists.
7838
2.58k
    bool IsExplicitSpecialization =
7839
2.58k
        IsVariableTemplateSpecialization && !IsPartialSpecialization;
7840
2.58k
    unsigned VDTemplateParamLists =
7841
2.58k
        (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7842
2.58k
    if (TemplateParamLists.size() > VDTemplateParamLists)
7843
0
      NewVD->setTemplateParameterListsInfo(
7844
0
          Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7845
2.58k
  }
7846
7847
5.07k
  if (D.getDeclSpec().isInlineSpecified()) {
7848
0
    if (!getLangOpts().CPlusPlus) {
7849
0
      Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7850
0
          << 0;
7851
0
    } else if (CurContext->isFunctionOrMethod()) {
7852
      // 'inline' is not allowed on block scope variable declaration.
7853
0
      Diag(D.getDeclSpec().getInlineSpecLoc(),
7854
0
           diag::err_inline_declaration_block_scope) << Name
7855
0
        << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7856
0
    } else {
7857
0
      Diag(D.getDeclSpec().getInlineSpecLoc(),
7858
0
           getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7859
0
                                     : diag::ext_inline_variable);
7860
0
      NewVD->setInlineSpecified();
7861
0
    }
7862
0
  }
7863
7864
  // Set the lexical context. If the declarator has a C++ scope specifier, the
7865
  // lexical context will be different from the semantic context.
7866
5.07k
  NewVD->setLexicalDeclContext(CurContext);
7867
5.07k
  if (NewTemplate)
7868
0
    NewTemplate->setLexicalDeclContext(CurContext);
7869
7870
5.07k
  if (IsLocalExternDecl) {
7871
0
    if (D.isDecompositionDeclarator())
7872
0
      for (auto *B : Bindings)
7873
0
        B->setLocalExternDecl();
7874
0
    else
7875
0
      NewVD->setLocalExternDecl();
7876
0
  }
7877
7878
5.07k
  bool EmitTLSUnsupportedError = false;
7879
5.07k
  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7880
    // C++11 [dcl.stc]p4:
7881
    //   When thread_local is applied to a variable of block scope the
7882
    //   storage-class-specifier static is implied if it does not appear
7883
    //   explicitly.
7884
    // Core issue: 'static' is not implied if the variable is declared
7885
    //   'extern'.
7886
0
    if (NewVD->hasLocalStorage() &&
7887
0
        (SCSpec != DeclSpec::SCS_unspecified ||
7888
0
         TSCS != DeclSpec::TSCS_thread_local ||
7889
0
         !DC->isFunctionOrMethod()))
7890
0
      Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7891
0
           diag::err_thread_non_global)
7892
0
        << DeclSpec::getSpecifierName(TSCS);
7893
0
    else if (!Context.getTargetInfo().isTLSSupported()) {
7894
0
      if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7895
0
          getLangOpts().SYCLIsDevice) {
7896
        // Postpone error emission until we've collected attributes required to
7897
        // figure out whether it's a host or device variable and whether the
7898
        // error should be ignored.
7899
0
        EmitTLSUnsupportedError = true;
7900
        // We still need to mark the variable as TLS so it shows up in AST with
7901
        // proper storage class for other tools to use even if we're not going
7902
        // to emit any code for it.
7903
0
        NewVD->setTSCSpec(TSCS);
7904
0
      } else
7905
0
        Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7906
0
             diag::err_thread_unsupported);
7907
0
    } else
7908
0
      NewVD->setTSCSpec(TSCS);
7909
0
  }
7910
7911
5.07k
  switch (D.getDeclSpec().getConstexprSpecifier()) {
7912
5.07k
  case ConstexprSpecKind::Unspecified:
7913
5.07k
    break;
7914
7915
0
  case ConstexprSpecKind::Consteval:
7916
0
    Diag(D.getDeclSpec().getConstexprSpecLoc(),
7917
0
         diag::err_constexpr_wrong_decl_kind)
7918
0
        << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7919
0
    [[fallthrough]];
7920
7921
0
  case ConstexprSpecKind::Constexpr:
7922
0
    NewVD->setConstexpr(true);
7923
    // C++1z [dcl.spec.constexpr]p1:
7924
    //   A static data member declared with the constexpr specifier is
7925
    //   implicitly an inline variable.
7926
0
    if (NewVD->isStaticDataMember() &&
7927
0
        (getLangOpts().CPlusPlus17 ||
7928
0
         Context.getTargetInfo().getCXXABI().isMicrosoft()))
7929
0
      NewVD->setImplicitlyInline();
7930
0
    break;
7931
7932
0
  case ConstexprSpecKind::Constinit:
7933
0
    if (!NewVD->hasGlobalStorage())
7934
0
      Diag(D.getDeclSpec().getConstexprSpecLoc(),
7935
0
           diag::err_constinit_local_variable);
7936
0
    else
7937
0
      NewVD->addAttr(
7938
0
          ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7939
0
                                ConstInitAttr::Keyword_constinit));
7940
0
    break;
7941
5.07k
  }
7942
7943
  // C99 6.7.4p3
7944
  //   An inline definition of a function with external linkage shall
7945
  //   not contain a definition of a modifiable object with static or
7946
  //   thread storage duration...
7947
  // We only apply this when the function is required to be defined
7948
  // elsewhere, i.e. when the function is not 'extern inline'.  Note
7949
  // that a local variable with thread storage duration still has to
7950
  // be marked 'static'.  Also note that it's possible to get these
7951
  // semantics in C++ using __attribute__((gnu_inline)).
7952
5.07k
  if (SC == SC_Static && S->getFnParent() != nullptr &&
7953
5.07k
      !NewVD->getType().isConstQualified()) {
7954
0
    FunctionDecl *CurFD = getCurFunctionDecl();
7955
0
    if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7956
0
      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7957
0
           diag::warn_static_local_in_extern_inline);
7958
0
      MaybeSuggestAddingStaticToDecl(CurFD);
7959
0
    }
7960
0
  }
7961
7962
5.07k
  if (D.getDeclSpec().isModulePrivateSpecified()) {
7963
0
    if (IsVariableTemplateSpecialization)
7964
0
      Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7965
0
          << (IsPartialSpecialization ? 1 : 0)
7966
0
          << FixItHint::CreateRemoval(
7967
0
                 D.getDeclSpec().getModulePrivateSpecLoc());
7968
0
    else if (IsMemberSpecialization)
7969
0
      Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7970
0
        << 2
7971
0
        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7972
0
    else if (NewVD->hasLocalStorage())
7973
0
      Diag(NewVD->getLocation(), diag::err_module_private_local)
7974
0
          << 0 << NewVD
7975
0
          << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7976
0
          << FixItHint::CreateRemoval(
7977
0
                 D.getDeclSpec().getModulePrivateSpecLoc());
7978
0
    else {
7979
0
      NewVD->setModulePrivate();
7980
0
      if (NewTemplate)
7981
0
        NewTemplate->setModulePrivate();
7982
0
      for (auto *B : Bindings)
7983
0
        B->setModulePrivate();
7984
0
    }
7985
0
  }
7986
7987
5.07k
  if (getLangOpts().OpenCL) {
7988
0
    deduceOpenCLAddressSpace(NewVD);
7989
7990
0
    DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7991
0
    if (TSC != TSCS_unspecified) {
7992
0
      Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7993
0
           diag::err_opencl_unknown_type_specifier)
7994
0
          << getLangOpts().getOpenCLVersionString()
7995
0
          << DeclSpec::getSpecifierName(TSC) << 1;
7996
0
      NewVD->setInvalidDecl();
7997
0
    }
7998
0
  }
7999
8000
  // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8001
  // address space if the table has local storage (semantic checks elsewhere
8002
  // will produce an error anyway).
8003
5.07k
  if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8004
43
    if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8005
43
        !NewVD->hasLocalStorage()) {
8006
0
      QualType Type = Context.getAddrSpaceQualType(
8007
0
          NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8008
0
      NewVD->setType(Type);
8009
0
    }
8010
43
  }
8011
8012
  // Handle attributes prior to checking for duplicates in MergeVarDecl
8013
5.07k
  ProcessDeclAttributes(S, NewVD, D);
8014
8015
  // FIXME: This is probably the wrong location to be doing this and we should
8016
  // probably be doing this for more attributes (especially for function
8017
  // pointer attributes such as format, warn_unused_result, etc.). Ideally
8018
  // the code to copy attributes would be generated by TableGen.
8019
5.07k
  if (R->isFunctionPointerType())
8020
0
    if (const auto *TT = R->getAs<TypedefType>())
8021
0
      copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
8022
8023
5.07k
  if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
8024
5.07k
      getLangOpts().SYCLIsDevice) {
8025
0
    if (EmitTLSUnsupportedError &&
8026
0
        ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
8027
0
         (getLangOpts().OpenMPIsTargetDevice &&
8028
0
          OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8029
0
      Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8030
0
           diag::err_thread_unsupported);
8031
8032
0
    if (EmitTLSUnsupportedError &&
8033
0
        (LangOpts.SYCLIsDevice ||
8034
0
         (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8035
0
      targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8036
    // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8037
    // storage [duration]."
8038
0
    if (SC == SC_None && S->getFnParent() != nullptr &&
8039
0
        (NewVD->hasAttr<CUDASharedAttr>() ||
8040
0
         NewVD->hasAttr<CUDAConstantAttr>())) {
8041
0
      NewVD->setStorageClass(SC_Static);
8042
0
    }
8043
0
  }
8044
8045
  // Ensure that dllimport globals without explicit storage class are treated as
8046
  // extern. The storage class is set above using parsed attributes. Now we can
8047
  // check the VarDecl itself.
8048
5.07k
  assert(!NewVD->hasAttr<DLLImportAttr>() ||
8049
5.07k
         NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8050
5.07k
         NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8051
8052
  // In auto-retain/release, infer strong retension for variables of
8053
  // retainable type.
8054
5.07k
  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
8055
0
    NewVD->setInvalidDecl();
8056
8057
  // Handle GNU asm-label extension (encoded as an attribute).
8058
5.07k
  if (Expr *E = (Expr*)D.getAsmLabel()) {
8059
    // The parser guarantees this is a string.
8060
0
    StringLiteral *SE = cast<StringLiteral>(E);
8061
0
    StringRef Label = SE->getString();
8062
0
    if (S->getFnParent() != nullptr) {
8063
0
      switch (SC) {
8064
0
      case SC_None:
8065
0
      case SC_Auto:
8066
0
        Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8067
0
        break;
8068
0
      case SC_Register:
8069
        // Local Named register
8070
0
        if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
8071
0
            DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
8072
0
          Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8073
0
        break;
8074
0
      case SC_Static:
8075
0
      case SC_Extern:
8076
0
      case SC_PrivateExtern:
8077
0
        break;
8078
0
      }
8079
0
    } else if (SC == SC_Register) {
8080
      // Global Named register
8081
0
      if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8082
0
        const auto &TI = Context.getTargetInfo();
8083
0
        bool HasSizeMismatch;
8084
8085
0
        if (!TI.isValidGCCRegisterName(Label))
8086
0
          Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8087
0
        else if (!TI.validateGlobalRegisterVariable(Label,
8088
0
                                                    Context.getTypeSize(R),
8089
0
                                                    HasSizeMismatch))
8090
0
          Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8091
0
        else if (HasSizeMismatch)
8092
0
          Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8093
0
      }
8094
8095
0
      if (!R->isIntegralType(Context) && !R->isPointerType()) {
8096
0
        Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
8097
0
        NewVD->setInvalidDecl(true);
8098
0
      }
8099
0
    }
8100
8101
0
    NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
8102
0
                                        /*IsLiteralLabel=*/true,
8103
0
                                        SE->getStrTokenLoc(0)));
8104
5.07k
  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8105
0
    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8106
0
      ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
8107
0
    if (I != ExtnameUndeclaredIdentifiers.end()) {
8108
0
      if (isDeclExternC(NewVD)) {
8109
0
        NewVD->addAttr(I->second);
8110
0
        ExtnameUndeclaredIdentifiers.erase(I);
8111
0
      } else
8112
0
        Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8113
0
            << /*Variable*/1 << NewVD;
8114
0
    }
8115
0
  }
8116
8117
  // Find the shadowed declaration before filtering for scope.
8118
5.07k
  NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8119
5.07k
                                ? getShadowedDeclaration(NewVD, Previous)
8120
5.07k
                                : nullptr;
8121
8122
  // Don't consider existing declarations that are in a different
8123
  // scope and are out-of-semantic-context declarations (if the new
8124
  // declaration has linkage).
8125
5.07k
  FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
8126
5.07k
                       D.getCXXScopeSpec().isNotEmpty() ||
8127
5.07k
                       IsMemberSpecialization ||
8128
5.07k
                       IsVariableTemplateSpecialization);
8129
8130
  // Check whether the previous declaration is in the same block scope. This
8131
  // affects whether we merge types with it, per C++11 [dcl.array]p3.
8132
5.07k
  if (getLangOpts().CPlusPlus &&
8133
5.07k
      NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8134
0
    NewVD->setPreviousDeclInSameBlockScope(
8135
0
        Previous.isSingleResult() && !Previous.isShadowed() &&
8136
0
        isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8137
8138
5.07k
  if (!getLangOpts().CPlusPlus) {
8139
2.48k
    D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8140
2.58k
  } else {
8141
    // If this is an explicit specialization of a static data member, check it.
8142
2.58k
    if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
8143
2.58k
        CheckMemberSpecialization(NewVD, Previous))
8144
0
      NewVD->setInvalidDecl();
8145
8146
    // Merge the decl with the existing one if appropriate.
8147
2.58k
    if (!Previous.empty()) {
8148
1.05k
      if (Previous.isSingleResult() &&
8149
1.05k
          isa<FieldDecl>(Previous.getFoundDecl()) &&
8150
1.05k
          D.getCXXScopeSpec().isSet()) {
8151
        // The user tried to define a non-static data member
8152
        // out-of-line (C++ [dcl.meaning]p1).
8153
0
        Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8154
0
          << D.getCXXScopeSpec().getRange();
8155
0
        Previous.clear();
8156
0
        NewVD->setInvalidDecl();
8157
0
      }
8158
1.53k
    } else if (D.getCXXScopeSpec().isSet()) {
8159
      // No previous declaration in the qualifying scope.
8160
0
      Diag(D.getIdentifierLoc(), diag::err_no_member)
8161
0
        << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8162
0
        << D.getCXXScopeSpec().getRange();
8163
0
      NewVD->setInvalidDecl();
8164
0
    }
8165
8166
2.58k
    if (!IsVariableTemplateSpecialization && !IsPlaceholderVariable)
8167
2.58k
      D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8168
8169
    // CheckVariableDeclaration will set NewVD as invalid if something is in
8170
    // error like WebAssembly tables being declared as arrays with a non-zero
8171
    // size, but then parsing continues and emits further errors on that line.
8172
    // To avoid that we check here if it happened and return nullptr.
8173
2.58k
    if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8174
0
      return nullptr;
8175
8176
2.58k
    if (NewTemplate) {
8177
0
      VarTemplateDecl *PrevVarTemplate =
8178
0
          NewVD->getPreviousDecl()
8179
0
              ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8180
0
              : nullptr;
8181
8182
      // Check the template parameter list of this declaration, possibly
8183
      // merging in the template parameter list from the previous variable
8184
      // template declaration.
8185
0
      if (CheckTemplateParameterList(
8186
0
              TemplateParams,
8187
0
              PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8188
0
                              : nullptr,
8189
0
              (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8190
0
               DC->isDependentContext())
8191
0
                  ? TPC_ClassTemplateMember
8192
0
                  : TPC_VarTemplate))
8193
0
        NewVD->setInvalidDecl();
8194
8195
      // If we are providing an explicit specialization of a static variable
8196
      // template, make a note of that.
8197
0
      if (PrevVarTemplate &&
8198
0
          PrevVarTemplate->getInstantiatedFromMemberTemplate())
8199
0
        PrevVarTemplate->setMemberSpecialization();
8200
0
    }
8201
2.58k
  }
8202
8203
  // Diagnose shadowed variables iff this isn't a redeclaration.
8204
5.07k
  if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8205
0
    CheckShadow(NewVD, ShadowedDecl, Previous);
8206
8207
5.07k
  ProcessPragmaWeak(S, NewVD);
8208
8209
  // If this is the first declaration of an extern C variable, update
8210
  // the map of such variables.
8211
5.07k
  if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8212
5.07k
      isIncompleteDeclExternC(*this, NewVD))
8213
285
    RegisterLocallyScopedExternCDecl(NewVD, S);
8214
8215
5.07k
  if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8216
0
    MangleNumberingContext *MCtx;
8217
0
    Decl *ManglingContextDecl;
8218
0
    std::tie(MCtx, ManglingContextDecl) =
8219
0
        getCurrentMangleNumberContext(NewVD->getDeclContext());
8220
0
    if (MCtx) {
8221
0
      Context.setManglingNumber(
8222
0
          NewVD, MCtx->getManglingNumber(
8223
0
                     NewVD, getMSManglingNumber(getLangOpts(), S)));
8224
0
      Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8225
0
    }
8226
0
  }
8227
8228
  // Special handling of variable named 'main'.
8229
5.07k
  if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8230
5.07k
      NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8231
5.07k
      !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8232
8233
    // C++ [basic.start.main]p3
8234
    // A program that declares a variable main at global scope is ill-formed.
8235
0
    if (getLangOpts().CPlusPlus)
8236
0
      Diag(D.getBeginLoc(), diag::err_main_global_variable);
8237
8238
    // In C, and external-linkage variable named main results in undefined
8239
    // behavior.
8240
0
    else if (NewVD->hasExternalFormalLinkage())
8241
0
      Diag(D.getBeginLoc(), diag::warn_main_redefined);
8242
0
  }
8243
8244
5.07k
  if (D.isRedeclaration() && !Previous.empty()) {
8245
194
    NamedDecl *Prev = Previous.getRepresentativeDecl();
8246
194
    checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8247
194
                                   D.isFunctionDefinition());
8248
194
  }
8249
8250
5.07k
  if (NewTemplate) {
8251
0
    if (NewVD->isInvalidDecl())
8252
0
      NewTemplate->setInvalidDecl();
8253
0
    ActOnDocumentableDecl(NewTemplate);
8254
0
    return NewTemplate;
8255
0
  }
8256
8257
5.07k
  if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8258
0
    CompleteMemberSpecialization(NewVD, Previous);
8259
8260
5.07k
  emitReadOnlyPlacementAttrWarning(*this, NewVD);
8261
8262
5.07k
  return NewVD;
8263
5.07k
}
8264
8265
/// Enum describing the %select options in diag::warn_decl_shadow.
8266
enum ShadowedDeclKind {
8267
  SDK_Local,
8268
  SDK_Global,
8269
  SDK_StaticMember,
8270
  SDK_Field,
8271
  SDK_Typedef,
8272
  SDK_Using,
8273
  SDK_StructuredBinding
8274
};
8275
8276
/// Determine what kind of declaration we're shadowing.
8277
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8278
0
                                                const DeclContext *OldDC) {
8279
0
  if (isa<TypeAliasDecl>(ShadowedDecl))
8280
0
    return SDK_Using;
8281
0
  else if (isa<TypedefDecl>(ShadowedDecl))
8282
0
    return SDK_Typedef;
8283
0
  else if (isa<BindingDecl>(ShadowedDecl))
8284
0
    return SDK_StructuredBinding;
8285
0
  else if (isa<RecordDecl>(OldDC))
8286
0
    return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8287
8288
0
  return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8289
0
}
8290
8291
/// Return the location of the capture if the given lambda captures the given
8292
/// variable \p VD, or an invalid source location otherwise.
8293
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8294
0
                                         const VarDecl *VD) {
8295
0
  for (const Capture &Capture : LSI->Captures) {
8296
0
    if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8297
0
      return Capture.getLocation();
8298
0
  }
8299
0
  return SourceLocation();
8300
0
}
8301
8302
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8303
5.07k
                                     const LookupResult &R) {
8304
  // Only diagnose if we're shadowing an unambiguous field or variable.
8305
5.07k
  if (R.getResultKind() != LookupResult::Found)
8306
2.87k
    return false;
8307
8308
  // Return false if warning is ignored.
8309
2.19k
  return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8310
5.07k
}
8311
8312
/// Return the declaration shadowed by the given variable \p D, or null
8313
/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8314
NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8315
5.07k
                                        const LookupResult &R) {
8316
5.07k
  if (!shouldWarnIfShadowedDecl(Diags, R))
8317
5.07k
    return nullptr;
8318
8319
  // Don't diagnose declarations at file scope.
8320
0
  if (D->hasGlobalStorage() && !D->isStaticLocal())
8321
0
    return nullptr;
8322
8323
0
  NamedDecl *ShadowedDecl = R.getFoundDecl();
8324
0
  return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8325
0
                                                            : nullptr;
8326
0
}
8327
8328
/// Return the declaration shadowed by the given typedef \p D, or null
8329
/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8330
NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8331
0
                                        const LookupResult &R) {
8332
  // Don't warn if typedef declaration is part of a class
8333
0
  if (D->getDeclContext()->isRecord())
8334
0
    return nullptr;
8335
8336
0
  if (!shouldWarnIfShadowedDecl(Diags, R))
8337
0
    return nullptr;
8338
8339
0
  NamedDecl *ShadowedDecl = R.getFoundDecl();
8340
0
  return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8341
0
}
8342
8343
/// Return the declaration shadowed by the given variable \p D, or null
8344
/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8345
NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8346
0
                                        const LookupResult &R) {
8347
0
  if (!shouldWarnIfShadowedDecl(Diags, R))
8348
0
    return nullptr;
8349
8350
0
  NamedDecl *ShadowedDecl = R.getFoundDecl();
8351
0
  return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8352
0
                                                            : nullptr;
8353
0
}
8354
8355
/// Diagnose variable or built-in function shadowing.  Implements
8356
/// -Wshadow.
8357
///
8358
/// This method is called whenever a VarDecl is added to a "useful"
8359
/// scope.
8360
///
8361
/// \param ShadowedDecl the declaration that is shadowed by the given variable
8362
/// \param R the lookup of the name
8363
///
8364
void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8365
0
                       const LookupResult &R) {
8366
0
  DeclContext *NewDC = D->getDeclContext();
8367
8368
0
  if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8369
    // Fields are not shadowed by variables in C++ static methods.
8370
0
    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8371
0
      if (MD->isStatic())
8372
0
        return;
8373
8374
    // Fields shadowed by constructor parameters are a special case. Usually
8375
    // the constructor initializes the field with the parameter.
8376
0
    if (isa<CXXConstructorDecl>(NewDC))
8377
0
      if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8378
        // Remember that this was shadowed so we can either warn about its
8379
        // modification or its existence depending on warning settings.
8380
0
        ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8381
0
        return;
8382
0
      }
8383
0
  }
8384
8385
0
  if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8386
0
    if (shadowedVar->isExternC()) {
8387
      // For shadowing external vars, make sure that we point to the global
8388
      // declaration, not a locally scoped extern declaration.
8389
0
      for (auto *I : shadowedVar->redecls())
8390
0
        if (I->isFileVarDecl()) {
8391
0
          ShadowedDecl = I;
8392
0
          break;
8393
0
        }
8394
0
    }
8395
8396
0
  DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8397
8398
0
  unsigned WarningDiag = diag::warn_decl_shadow;
8399
0
  SourceLocation CaptureLoc;
8400
0
  if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
8401
0
      isa<CXXMethodDecl>(NewDC)) {
8402
0
    if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8403
0
      if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8404
0
        if (RD->getLambdaCaptureDefault() == LCD_None) {
8405
          // Try to avoid warnings for lambdas with an explicit capture list.
8406
0
          const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8407
          // Warn only when the lambda captures the shadowed decl explicitly.
8408
0
          CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
8409
0
          if (CaptureLoc.isInvalid())
8410
0
            WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8411
0
        } else {
8412
          // Remember that this was shadowed so we can avoid the warning if the
8413
          // shadowed decl isn't captured and the warning settings allow it.
8414
0
          cast<LambdaScopeInfo>(getCurFunction())
8415
0
              ->ShadowingDecls.push_back(
8416
0
                  {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
8417
0
          return;
8418
0
        }
8419
0
      }
8420
8421
0
      if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8422
        // A variable can't shadow a local variable in an enclosing scope, if
8423
        // they are separated by a non-capturing declaration context.
8424
0
        for (DeclContext *ParentDC = NewDC;
8425
0
             ParentDC && !ParentDC->Equals(OldDC);
8426
0
             ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8427
          // Only block literals, captured statements, and lambda expressions
8428
          // can capture; other scopes don't.
8429
0
          if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8430
0
              !isLambdaCallOperator(ParentDC)) {
8431
0
            return;
8432
0
          }
8433
0
        }
8434
0
      }
8435
0
    }
8436
0
  }
8437
8438
  // Never warn about shadowing a placeholder variable.
8439
0
  if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8440
0
    return;
8441
8442
  // Only warn about certain kinds of shadowing for class members.
8443
0
  if (NewDC && NewDC->isRecord()) {
8444
    // In particular, don't warn about shadowing non-class members.
8445
0
    if (!OldDC->isRecord())
8446
0
      return;
8447
8448
    // TODO: should we warn about static data members shadowing
8449
    // static data members from base classes?
8450
8451
    // TODO: don't diagnose for inaccessible shadowed members.
8452
    // This is hard to do perfectly because we might friend the
8453
    // shadowing context, but that's just a false negative.
8454
0
  }
8455
8456
8457
0
  DeclarationName Name = R.getLookupName();
8458
8459
  // Emit warning and note.
8460
0
  ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8461
0
  Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8462
0
  if (!CaptureLoc.isInvalid())
8463
0
    Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8464
0
        << Name << /*explicitly*/ 1;
8465
0
  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8466
0
}
8467
8468
/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8469
/// when these variables are captured by the lambda.
8470
0
void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8471
0
  for (const auto &Shadow : LSI->ShadowingDecls) {
8472
0
    const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8473
    // Try to avoid the warning when the shadowed decl isn't captured.
8474
0
    SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8475
0
    const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8476
0
    Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8477
0
                                       ? diag::warn_decl_shadow_uncaptured_local
8478
0
                                       : diag::warn_decl_shadow)
8479
0
        << Shadow.VD->getDeclName()
8480
0
        << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8481
0
    if (!CaptureLoc.isInvalid())
8482
0
      Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8483
0
          << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8484
0
    Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8485
0
  }
8486
0
}
8487
8488
/// Check -Wshadow without the advantage of a previous lookup.
8489
0
void Sema::CheckShadow(Scope *S, VarDecl *D) {
8490
0
  if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8491
0
    return;
8492
8493
0
  LookupResult R(*this, D->getDeclName(), D->getLocation(),
8494
0
                 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8495
0
  LookupName(R, S);
8496
0
  if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8497
0
    CheckShadow(D, ShadowedDecl, R);
8498
0
}
8499
8500
/// Check if 'E', which is an expression that is about to be modified, refers
8501
/// to a constructor parameter that shadows a field.
8502
0
void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8503
  // Quickly ignore expressions that can't be shadowing ctor parameters.
8504
0
  if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8505
0
    return;
8506
0
  E = E->IgnoreParenImpCasts();
8507
0
  auto *DRE = dyn_cast<DeclRefExpr>(E);
8508
0
  if (!DRE)
8509
0
    return;
8510
0
  const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8511
0
  auto I = ShadowingDecls.find(D);
8512
0
  if (I == ShadowingDecls.end())
8513
0
    return;
8514
0
  const NamedDecl *ShadowedDecl = I->second;
8515
0
  const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8516
0
  Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8517
0
  Diag(D->getLocation(), diag::note_var_declared_here) << D;
8518
0
  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8519
8520
  // Avoid issuing multiple warnings about the same decl.
8521
0
  ShadowingDecls.erase(I);
8522
0
}
8523
8524
/// Check for conflict between this global or extern "C" declaration and
8525
/// previous global or extern "C" declarations. This is only used in C++.
8526
template<typename T>
8527
static bool checkGlobalOrExternCConflict(
8528
0
    Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8529
0
  assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8530
0
  NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8531
8532
0
  if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8533
    // The common case: this global doesn't conflict with any extern "C"
8534
    // declaration.
8535
0
    return false;
8536
0
  }
8537
8538
0
  if (Prev) {
8539
0
    if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8540
      // Both the old and new declarations have C language linkage. This is a
8541
      // redeclaration.
8542
0
      Previous.clear();
8543
0
      Previous.addDecl(Prev);
8544
0
      return true;
8545
0
    }
8546
8547
    // This is a global, non-extern "C" declaration, and there is a previous
8548
    // non-global extern "C" declaration. Diagnose if this is a variable
8549
    // declaration.
8550
0
    if (!isa<VarDecl>(ND))
8551
0
      return false;
8552
0
  } else {
8553
    // The declaration is extern "C". Check for any declaration in the
8554
    // translation unit which might conflict.
8555
0
    if (IsGlobal) {
8556
      // We have already performed the lookup into the translation unit.
8557
0
      IsGlobal = false;
8558
0
      for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8559
0
           I != E; ++I) {
8560
0
        if (isa<VarDecl>(*I)) {
8561
0
          Prev = *I;
8562
0
          break;
8563
0
        }
8564
0
      }
8565
0
    } else {
8566
0
      DeclContext::lookup_result R =
8567
0
          S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8568
0
      for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8569
0
           I != E; ++I) {
8570
0
        if (isa<VarDecl>(*I)) {
8571
0
          Prev = *I;
8572
0
          break;
8573
0
        }
8574
        // FIXME: If we have any other entity with this name in global scope,
8575
        // the declaration is ill-formed, but that is a defect: it breaks the
8576
        // 'stat' hack, for instance. Only variables can have mangled name
8577
        // clashes with extern "C" declarations, so only they deserve a
8578
        // diagnostic.
8579
0
      }
8580
0
    }
8581
8582
0
    if (!Prev)
8583
0
      return false;
8584
0
  }
8585
8586
  // Use the first declaration's location to ensure we point at something which
8587
  // is lexically inside an extern "C" linkage-spec.
8588
0
  assert(Prev && "should have found a previous declaration to diagnose");
8589
0
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8590
0
    Prev = FD->getFirstDecl();
8591
0
  else
8592
0
    Prev = cast<VarDecl>(Prev)->getFirstDecl();
8593
8594
0
  S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8595
0
    << IsGlobal << ND;
8596
0
  S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8597
0
    << IsGlobal;
8598
0
  return false;
8599
0
}
Unexecuted instantiation: SemaDecl.cpp:bool checkGlobalOrExternCConflict<clang::VarDecl>(clang::Sema&, clang::VarDecl const*, bool, clang::LookupResult&)
Unexecuted instantiation: SemaDecl.cpp:bool checkGlobalOrExternCConflict<clang::FunctionDecl>(clang::Sema&, clang::FunctionDecl const*, bool, clang::LookupResult&)
8600
8601
/// Apply special rules for handling extern "C" declarations. Returns \c true
8602
/// if we have found that this is a redeclaration of some prior entity.
8603
///
8604
/// Per C++ [dcl.link]p6:
8605
///   Two declarations [for a function or variable] with C language linkage
8606
///   with the same name that appear in different scopes refer to the same
8607
///   [entity]. An entity with C language linkage shall not be declared with
8608
///   the same name as an entity in global scope.
8609
template<typename T>
8610
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8611
291
                                                  LookupResult &Previous) {
8612
291
  if (!S.getLangOpts().CPlusPlus) {
8613
    // In C, when declaring a global variable, look for a corresponding 'extern'
8614
    // variable declared in function scope. We don't need this in C++, because
8615
    // we find local extern decls in the surrounding file-scope DeclContext.
8616
291
    if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8617
291
      if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8618
0
        Previous.clear();
8619
0
        Previous.addDecl(Prev);
8620
0
        return true;
8621
0
      }
8622
291
    }
8623
291
    return false;
8624
291
  }
8625
8626
  // A declaration in the translation unit can conflict with an extern "C"
8627
  // declaration.
8628
0
  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8629
0
    return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8630
8631
  // An extern "C" declaration can conflict with a declaration in the
8632
  // translation unit or can be a redeclaration of an extern "C" declaration
8633
  // in another scope.
8634
0
  if (isIncompleteDeclExternC(S,ND))
8635
0
    return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8636
8637
  // Neither global nor extern "C": nothing to do.
8638
0
  return false;
8639
0
}
SemaDecl.cpp:bool checkForConflictWithNonVisibleExternC<clang::VarDecl>(clang::Sema&, clang::VarDecl const*, clang::LookupResult&)
Line
Count
Source
8611
285
                                                  LookupResult &Previous) {
8612
285
  if (!S.getLangOpts().CPlusPlus) {
8613
    // In C, when declaring a global variable, look for a corresponding 'extern'
8614
    // variable declared in function scope. We don't need this in C++, because
8615
    // we find local extern decls in the surrounding file-scope DeclContext.
8616
285
    if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8617
285
      if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8618
0
        Previous.clear();
8619
0
        Previous.addDecl(Prev);
8620
0
        return true;
8621
0
      }
8622
285
    }
8623
285
    return false;
8624
285
  }
8625
8626
  // A declaration in the translation unit can conflict with an extern "C"
8627
  // declaration.
8628
0
  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8629
0
    return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8630
8631
  // An extern "C" declaration can conflict with a declaration in the
8632
  // translation unit or can be a redeclaration of an extern "C" declaration
8633
  // in another scope.
8634
0
  if (isIncompleteDeclExternC(S,ND))
8635
0
    return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8636
8637
  // Neither global nor extern "C": nothing to do.
8638
0
  return false;
8639
0
}
SemaDecl.cpp:bool checkForConflictWithNonVisibleExternC<clang::FunctionDecl>(clang::Sema&, clang::FunctionDecl const*, clang::LookupResult&)
Line
Count
Source
8611
6
                                                  LookupResult &Previous) {
8612
6
  if (!S.getLangOpts().CPlusPlus) {
8613
    // In C, when declaring a global variable, look for a corresponding 'extern'
8614
    // variable declared in function scope. We don't need this in C++, because
8615
    // we find local extern decls in the surrounding file-scope DeclContext.
8616
6
    if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8617
6
      if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8618
0
        Previous.clear();
8619
0
        Previous.addDecl(Prev);
8620
0
        return true;
8621
0
      }
8622
6
    }
8623
6
    return false;
8624
6
  }
8625
8626
  // A declaration in the translation unit can conflict with an extern "C"
8627
  // declaration.
8628
0
  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8629
0
    return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8630
8631
  // An extern "C" declaration can conflict with a declaration in the
8632
  // translation unit or can be a redeclaration of an extern "C" declaration
8633
  // in another scope.
8634
0
  if (isIncompleteDeclExternC(S,ND))
8635
0
    return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8636
8637
  // Neither global nor extern "C": nothing to do.
8638
0
  return false;
8639
0
}
8640
8641
5.07k
void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8642
  // If the decl is already known invalid, don't check it.
8643
5.07k
  if (NewVD->isInvalidDecl())
8644
4.58k
    return;
8645
8646
481
  QualType T = NewVD->getType();
8647
8648
  // Defer checking an 'auto' type until its initializer is attached.
8649
481
  if (T->isUndeducedType())
8650
0
    return;
8651
8652
481
  if (NewVD->hasAttrs())
8653
0
    CheckAlignasUnderalignment(NewVD);
8654
8655
481
  if (T->isObjCObjectType()) {
8656
0
    Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8657
0
      << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8658
0
    T = Context.getObjCObjectPointerType(T);
8659
0
    NewVD->setType(T);
8660
0
  }
8661
8662
  // Emit an error if an address space was applied to decl with local storage.
8663
  // This includes arrays of objects with address space qualifiers, but not
8664
  // automatic variables that point to other address spaces.
8665
  // ISO/IEC TR 18037 S5.1.2
8666
481
  if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8667
481
      T.getAddressSpace() != LangAS::Default) {
8668
0
    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8669
0
    NewVD->setInvalidDecl();
8670
0
    return;
8671
0
  }
8672
8673
  // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8674
  // scope.
8675
481
  if (getLangOpts().OpenCLVersion == 120 &&
8676
481
      !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8677
0
                                            getLangOpts()) &&
8678
481
      NewVD->isStaticLocal()) {
8679
0
    Diag(NewVD->getLocation(), diag::err_static_function_scope);
8680
0
    NewVD->setInvalidDecl();
8681
0
    return;
8682
0
  }
8683
8684
481
  if (getLangOpts().OpenCL) {
8685
0
    if (!diagnoseOpenCLTypes(*this, NewVD))
8686
0
      return;
8687
8688
    // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8689
0
    if (NewVD->hasAttr<BlocksAttr>()) {
8690
0
      Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8691
0
      return;
8692
0
    }
8693
8694
0
    if (T->isBlockPointerType()) {
8695
      // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8696
      // can't use 'extern' storage class.
8697
0
      if (!T.isConstQualified()) {
8698
0
        Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8699
0
            << 0 /*const*/;
8700
0
        NewVD->setInvalidDecl();
8701
0
        return;
8702
0
      }
8703
0
      if (NewVD->hasExternalStorage()) {
8704
0
        Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8705
0
        NewVD->setInvalidDecl();
8706
0
        return;
8707
0
      }
8708
0
    }
8709
8710
    // FIXME: Adding local AS in C++ for OpenCL might make sense.
8711
0
    if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8712
0
        NewVD->hasExternalStorage()) {
8713
0
      if (!T->isSamplerT() && !T->isDependentType() &&
8714
0
          !(T.getAddressSpace() == LangAS::opencl_constant ||
8715
0
            (T.getAddressSpace() == LangAS::opencl_global &&
8716
0
             getOpenCLOptions().areProgramScopeVariablesSupported(
8717
0
                 getLangOpts())))) {
8718
0
        int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8719
0
        if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8720
0
          Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8721
0
              << Scope << "global or constant";
8722
0
        else
8723
0
          Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8724
0
              << Scope << "constant";
8725
0
        NewVD->setInvalidDecl();
8726
0
        return;
8727
0
      }
8728
0
    } else {
8729
0
      if (T.getAddressSpace() == LangAS::opencl_global) {
8730
0
        Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8731
0
            << 1 /*is any function*/ << "global";
8732
0
        NewVD->setInvalidDecl();
8733
0
        return;
8734
0
      }
8735
0
      if (T.getAddressSpace() == LangAS::opencl_constant ||
8736
0
          T.getAddressSpace() == LangAS::opencl_local) {
8737
0
        FunctionDecl *FD = getCurFunctionDecl();
8738
        // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8739
        // in functions.
8740
0
        if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8741
0
          if (T.getAddressSpace() == LangAS::opencl_constant)
8742
0
            Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8743
0
                << 0 /*non-kernel only*/ << "constant";
8744
0
          else
8745
0
            Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8746
0
                << 0 /*non-kernel only*/ << "local";
8747
0
          NewVD->setInvalidDecl();
8748
0
          return;
8749
0
        }
8750
        // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8751
        // in the outermost scope of a kernel function.
8752
0
        if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8753
0
          if (!getCurScope()->isFunctionScope()) {
8754
0
            if (T.getAddressSpace() == LangAS::opencl_constant)
8755
0
              Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8756
0
                  << "constant";
8757
0
            else
8758
0
              Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8759
0
                  << "local";
8760
0
            NewVD->setInvalidDecl();
8761
0
            return;
8762
0
          }
8763
0
        }
8764
0
      } else if (T.getAddressSpace() != LangAS::opencl_private &&
8765
                 // If we are parsing a template we didn't deduce an addr
8766
                 // space yet.
8767
0
                 T.getAddressSpace() != LangAS::Default) {
8768
        // Do not allow other address spaces on automatic variable.
8769
0
        Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8770
0
        NewVD->setInvalidDecl();
8771
0
        return;
8772
0
      }
8773
0
    }
8774
0
  }
8775
8776
481
  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8777
481
      && !NewVD->hasAttr<BlocksAttr>()) {
8778
0
    if (getLangOpts().getGC() != LangOptions::NonGC)
8779
0
      Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8780
0
    else {
8781
0
      assert(!getLangOpts().ObjCAutoRefCount);
8782
0
      Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8783
0
    }
8784
0
  }
8785
8786
  // WebAssembly tables must be static with a zero length and can't be
8787
  // declared within functions.
8788
481
  if (T->isWebAssemblyTableType()) {
8789
0
    if (getCurScope()->getParent()) { // Parent is null at top-level
8790
0
      Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8791
0
      NewVD->setInvalidDecl();
8792
0
      return;
8793
0
    }
8794
0
    if (NewVD->getStorageClass() != SC_Static) {
8795
0
      Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8796
0
      NewVD->setInvalidDecl();
8797
0
      return;
8798
0
    }
8799
0
    const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8800
0
    if (!ATy || ATy->getSize().getSExtValue() != 0) {
8801
0
      Diag(NewVD->getLocation(),
8802
0
           diag::err_typecheck_wasm_table_must_have_zero_length);
8803
0
      NewVD->setInvalidDecl();
8804
0
      return;
8805
0
    }
8806
0
  }
8807
8808
481
  bool isVM = T->isVariablyModifiedType();
8809
481
  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8810
481
      NewVD->hasAttr<BlocksAttr>())
8811
2
    setFunctionHasBranchProtectedScope();
8812
8813
481
  if ((isVM && NewVD->hasLinkage()) ||
8814
481
      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8815
2
    bool SizeIsNegative;
8816
2
    llvm::APSInt Oversized;
8817
2
    TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8818
2
        NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8819
2
    QualType FixedT;
8820
2
    if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8821
0
      FixedT = FixedTInfo->getType();
8822
2
    else if (FixedTInfo) {
8823
      // Type and type-as-written are canonically different. We need to fix up
8824
      // both types separately.
8825
0
      FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8826
0
                                                   Oversized);
8827
0
    }
8828
2
    if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8829
2
      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8830
      // FIXME: This won't give the correct result for
8831
      // int a[10][n];
8832
2
      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8833
8834
2
      if (NewVD->isFileVarDecl())
8835
2
        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8836
2
        << SizeRange;
8837
0
      else if (NewVD->isStaticLocal())
8838
0
        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8839
0
        << SizeRange;
8840
0
      else
8841
0
        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8842
0
        << SizeRange;
8843
2
      NewVD->setInvalidDecl();
8844
2
      return;
8845
2
    }
8846
8847
0
    if (!FixedTInfo) {
8848
0
      if (NewVD->isFileVarDecl())
8849
0
        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8850
0
      else
8851
0
        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8852
0
      NewVD->setInvalidDecl();
8853
0
      return;
8854
0
    }
8855
8856
0
    Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8857
0
    NewVD->setType(FixedT);
8858
0
    NewVD->setTypeSourceInfo(FixedTInfo);
8859
0
  }
8860
8861
479
  if (T->isVoidType()) {
8862
    // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8863
    //                    of objects and functions.
8864
0
    if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8865
0
      Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8866
0
        << T;
8867
0
      NewVD->setInvalidDecl();
8868
0
      return;
8869
0
    }
8870
0
  }
8871
8872
479
  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8873
0
    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8874
0
    NewVD->setInvalidDecl();
8875
0
    return;
8876
0
  }
8877
8878
479
  if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8879
479
      !T.isWebAssemblyReferenceType()) {
8880
0
    Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8881
0
    NewVD->setInvalidDecl();
8882
0
    return;
8883
0
  }
8884
8885
479
  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8886
0
    Diag(NewVD->getLocation(), diag::err_block_on_vm);
8887
0
    NewVD->setInvalidDecl();
8888
0
    return;
8889
0
  }
8890
8891
479
  if (NewVD->isConstexpr() && !T->isDependentType() &&
8892
479
      RequireLiteralType(NewVD->getLocation(), T,
8893
0
                         diag::err_constexpr_var_non_literal)) {
8894
0
    NewVD->setInvalidDecl();
8895
0
    return;
8896
0
  }
8897
8898
  // PPC MMA non-pointer types are not allowed as non-local variable types.
8899
479
  if (Context.getTargetInfo().getTriple().isPPC64() &&
8900
479
      !NewVD->isLocalVarDecl() &&
8901
479
      CheckPPCMMAType(T, NewVD->getLocation())) {
8902
0
    NewVD->setInvalidDecl();
8903
0
    return;
8904
0
  }
8905
8906
  // Check that SVE types are only used in functions with SVE available.
8907
479
  if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8908
0
    const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8909
0
    llvm::StringMap<bool> CallerFeatureMap;
8910
0
    Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8911
0
    if (!Builtin::evaluateRequiredTargetFeatures(
8912
0
        "sve", CallerFeatureMap)) {
8913
0
      Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8914
0
      NewVD->setInvalidDecl();
8915
0
      return;
8916
0
    }
8917
0
  }
8918
8919
479
  if (T->isRVVSizelessBuiltinType())
8920
0
    checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext));
8921
479
}
8922
8923
/// Perform semantic checking on a newly-created variable
8924
/// declaration.
8925
///
8926
/// This routine performs all of the type-checking required for a
8927
/// variable declaration once it has been built. It is used both to
8928
/// check variables after they have been parsed and their declarators
8929
/// have been translated into a declaration, and to check variables
8930
/// that have been instantiated from a template.
8931
///
8932
/// Sets NewVD->isInvalidDecl() if an error was encountered.
8933
///
8934
/// Returns true if the variable declaration is a redeclaration.
8935
5.07k
bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8936
5.07k
  CheckVariableDeclarationType(NewVD);
8937
8938
  // If the decl is already known invalid, don't check it.
8939
5.07k
  if (NewVD->isInvalidDecl())
8940
4.59k
    return false;
8941
8942
  // If we did not find anything by this name, look for a non-visible
8943
  // extern "C" declaration with the same name.
8944
479
  if (Previous.empty() &&
8945
479
      checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8946
0
    Previous.setShadowed();
8947
8948
479
  if (!Previous.empty()) {
8949
194
    MergeVarDecl(NewVD, Previous);
8950
194
    return true;
8951
194
  }
8952
285
  return false;
8953
479
}
8954
8955
/// AddOverriddenMethods - See if a method overrides any in the base classes,
8956
/// and if so, check that it's a valid override and remember it.
8957
0
bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8958
0
  llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8959
8960
  // Look for methods in base classes that this method might override.
8961
0
  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8962
0
                     /*DetectVirtual=*/false);
8963
0
  auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8964
0
    CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8965
0
    DeclarationName Name = MD->getDeclName();
8966
8967
0
    if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8968
      // We really want to find the base class destructor here.
8969
0
      QualType T = Context.getTypeDeclType(BaseRecord);
8970
0
      CanQualType CT = Context.getCanonicalType(T);
8971
0
      Name = Context.DeclarationNames.getCXXDestructorName(CT);
8972
0
    }
8973
8974
0
    for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8975
0
      CXXMethodDecl *BaseMD =
8976
0
          dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8977
0
      if (!BaseMD || !BaseMD->isVirtual() ||
8978
0
          IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8979
0
                     /*ConsiderCudaAttrs=*/true))
8980
0
        continue;
8981
0
      if (!CheckExplicitObjectOverride(MD, BaseMD))
8982
0
        continue;
8983
0
      if (Overridden.insert(BaseMD).second) {
8984
0
        MD->addOverriddenMethod(BaseMD);
8985
0
        CheckOverridingFunctionReturnType(MD, BaseMD);
8986
0
        CheckOverridingFunctionAttributes(MD, BaseMD);
8987
0
        CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8988
0
        CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8989
0
      }
8990
8991
      // A method can only override one function from each base class. We
8992
      // don't track indirectly overridden methods from bases of bases.
8993
0
      return true;
8994
0
    }
8995
8996
0
    return false;
8997
0
  };
8998
8999
0
  DC->lookupInBases(VisitBase, Paths);
9000
0
  return !Overridden.empty();
9001
0
}
9002
9003
namespace {
9004
  // Struct for holding all of the extra arguments needed by
9005
  // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9006
  struct ActOnFDArgs {
9007
    Scope *S;
9008
    Declarator &D;
9009
    MultiTemplateParamsArg TemplateParamLists;
9010
    bool AddToScope;
9011
  };
9012
} // end anonymous namespace
9013
9014
namespace {
9015
9016
// Callback to only accept typo corrections that have a non-zero edit distance.
9017
// Also only accept corrections that have the same parent decl.
9018
class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9019
 public:
9020
  DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9021
                            CXXRecordDecl *Parent)
9022
      : Context(Context), OriginalFD(TypoFD),
9023
0
        ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9024
9025
0
  bool ValidateCandidate(const TypoCorrection &candidate) override {
9026
0
    if (candidate.getEditDistance() == 0)
9027
0
      return false;
9028
9029
0
    SmallVector<unsigned, 1> MismatchedParams;
9030
0
    for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9031
0
                                          CDeclEnd = candidate.end();
9032
0
         CDecl != CDeclEnd; ++CDecl) {
9033
0
      FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9034
9035
0
      if (FD && !FD->hasBody() &&
9036
0
          hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9037
0
        if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9038
0
          CXXRecordDecl *Parent = MD->getParent();
9039
0
          if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9040
0
            return true;
9041
0
        } else if (!ExpectedParent) {
9042
0
          return true;
9043
0
        }
9044
0
      }
9045
0
    }
9046
9047
0
    return false;
9048
0
  }
9049
9050
0
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
9051
0
    return std::make_unique<DifferentNameValidatorCCC>(*this);
9052
0
  }
9053
9054
 private:
9055
  ASTContext &Context;
9056
  FunctionDecl *OriginalFD;
9057
  CXXRecordDecl *ExpectedParent;
9058
};
9059
9060
} // end anonymous namespace
9061
9062
0
void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9063
0
  TypoCorrectedFunctionDefinitions.insert(F);
9064
0
}
9065
9066
/// Generate diagnostics for an invalid function redeclaration.
9067
///
9068
/// This routine handles generating the diagnostic messages for an invalid
9069
/// function redeclaration, including finding possible similar declarations
9070
/// or performing typo correction if there are no previous declarations with
9071
/// the same name.
9072
///
9073
/// Returns a NamedDecl iff typo correction was performed and substituting in
9074
/// the new declaration name does not cause new errors.
9075
static NamedDecl *DiagnoseInvalidRedeclaration(
9076
    Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9077
0
    ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9078
0
  DeclarationName Name = NewFD->getDeclName();
9079
0
  DeclContext *NewDC = NewFD->getDeclContext();
9080
0
  SmallVector<unsigned, 1> MismatchedParams;
9081
0
  SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9082
0
  TypoCorrection Correction;
9083
0
  bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9084
0
  unsigned DiagMsg =
9085
0
    IsLocalFriend ? diag::err_no_matching_local_friend :
9086
0
    NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9087
0
    diag::err_member_decl_does_not_match;
9088
0
  LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9089
0
                    IsLocalFriend ? Sema::LookupLocalFriendName
9090
0
                                  : Sema::LookupOrdinaryName,
9091
0
                    Sema::ForVisibleRedeclaration);
9092
9093
0
  NewFD->setInvalidDecl();
9094
0
  if (IsLocalFriend)
9095
0
    SemaRef.LookupName(Prev, S);
9096
0
  else
9097
0
    SemaRef.LookupQualifiedName(Prev, NewDC);
9098
0
  assert(!Prev.isAmbiguous() &&
9099
0
         "Cannot have an ambiguity in previous-declaration lookup");
9100
0
  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9101
0
  DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9102
0
                                MD ? MD->getParent() : nullptr);
9103
0
  if (!Prev.empty()) {
9104
0
    for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9105
0
         Func != FuncEnd; ++Func) {
9106
0
      FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9107
0
      if (FD &&
9108
0
          hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9109
        // Add 1 to the index so that 0 can mean the mismatch didn't
9110
        // involve a parameter
9111
0
        unsigned ParamNum =
9112
0
            MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9113
0
        NearMatches.push_back(std::make_pair(FD, ParamNum));
9114
0
      }
9115
0
    }
9116
  // If the qualified name lookup yielded nothing, try typo correction
9117
0
  } else if ((Correction = SemaRef.CorrectTypo(
9118
0
                  Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9119
0
                  &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
9120
0
                  IsLocalFriend ? nullptr : NewDC))) {
9121
    // Set up everything for the call to ActOnFunctionDeclarator
9122
0
    ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9123
0
                              ExtraArgs.D.getIdentifierLoc());
9124
0
    Previous.clear();
9125
0
    Previous.setLookupName(Correction.getCorrection());
9126
0
    for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9127
0
                                    CDeclEnd = Correction.end();
9128
0
         CDecl != CDeclEnd; ++CDecl) {
9129
0
      FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9130
0
      if (FD && !FD->hasBody() &&
9131
0
          hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9132
0
        Previous.addDecl(FD);
9133
0
      }
9134
0
    }
9135
0
    bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9136
9137
0
    NamedDecl *Result;
9138
    // Retry building the function declaration with the new previous
9139
    // declarations, and with errors suppressed.
9140
0
    {
9141
      // Trap errors.
9142
0
      Sema::SFINAETrap Trap(SemaRef);
9143
9144
      // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9145
      // pieces need to verify the typo-corrected C++ declaration and hopefully
9146
      // eliminate the need for the parameter pack ExtraArgs.
9147
0
      Result = SemaRef.ActOnFunctionDeclarator(
9148
0
          ExtraArgs.S, ExtraArgs.D,
9149
0
          Correction.getCorrectionDecl()->getDeclContext(),
9150
0
          NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9151
0
          ExtraArgs.AddToScope);
9152
9153
0
      if (Trap.hasErrorOccurred())
9154
0
        Result = nullptr;
9155
0
    }
9156
9157
0
    if (Result) {
9158
      // Determine which correction we picked.
9159
0
      Decl *Canonical = Result->getCanonicalDecl();
9160
0
      for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9161
0
           I != E; ++I)
9162
0
        if ((*I)->getCanonicalDecl() == Canonical)
9163
0
          Correction.setCorrectionDecl(*I);
9164
9165
      // Let Sema know about the correction.
9166
0
      SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
9167
0
      SemaRef.diagnoseTypo(
9168
0
          Correction,
9169
0
          SemaRef.PDiag(IsLocalFriend
9170
0
                          ? diag::err_no_matching_local_friend_suggest
9171
0
                          : diag::err_member_decl_does_not_match_suggest)
9172
0
            << Name << NewDC << IsDefinition);
9173
0
      return Result;
9174
0
    }
9175
9176
    // Pretend the typo correction never occurred
9177
0
    ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9178
0
                              ExtraArgs.D.getIdentifierLoc());
9179
0
    ExtraArgs.D.setRedeclaration(wasRedeclaration);
9180
0
    Previous.clear();
9181
0
    Previous.setLookupName(Name);
9182
0
  }
9183
9184
0
  SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9185
0
      << Name << NewDC << IsDefinition << NewFD->getLocation();
9186
9187
0
  bool NewFDisConst = false;
9188
0
  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
9189
0
    NewFDisConst = NewMD->isConst();
9190
9191
0
  for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9192
0
       NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9193
0
       NearMatch != NearMatchEnd; ++NearMatch) {
9194
0
    FunctionDecl *FD = NearMatch->first;
9195
0
    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9196
0
    bool FDisConst = MD && MD->isConst();
9197
0
    bool IsMember = MD || !IsLocalFriend;
9198
9199
    // FIXME: These notes are poorly worded for the local friend case.
9200
0
    if (unsigned Idx = NearMatch->second) {
9201
0
      ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9202
0
      SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9203
0
      if (Loc.isInvalid()) Loc = FD->getLocation();
9204
0
      SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9205
0
                                 : diag::note_local_decl_close_param_match)
9206
0
        << Idx << FDParam->getType()
9207
0
        << NewFD->getParamDecl(Idx - 1)->getType();
9208
0
    } else if (FDisConst != NewFDisConst) {
9209
0
      SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
9210
0
          << NewFDisConst << FD->getSourceRange().getEnd()
9211
0
          << (NewFDisConst
9212
0
                  ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
9213
0
                                                 .getConstQualifierLoc())
9214
0
                  : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
9215
0
                                                   .getRParenLoc()
9216
0
                                                   .getLocWithOffset(1),
9217
0
                                               " const"));
9218
0
    } else
9219
0
      SemaRef.Diag(FD->getLocation(),
9220
0
                   IsMember ? diag::note_member_def_close_match
9221
0
                            : diag::note_local_decl_close_match);
9222
0
  }
9223
0
  return nullptr;
9224
0
}
9225
9226
19
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9227
19
  switch (D.getDeclSpec().getStorageClassSpec()) {
9228
0
  default: llvm_unreachable("Unknown storage class!");
9229
0
  case DeclSpec::SCS_auto:
9230
0
  case DeclSpec::SCS_register:
9231
0
  case DeclSpec::SCS_mutable:
9232
0
    SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9233
0
                 diag::err_typecheck_sclass_func);
9234
0
    D.getMutableDeclSpec().ClearStorageClassSpecs();
9235
0
    D.setInvalidType();
9236
0
    break;
9237
19
  case DeclSpec::SCS_unspecified: break;
9238
0
  case DeclSpec::SCS_extern:
9239
0
    if (D.getDeclSpec().isExternInLinkageSpec())
9240
0
      return SC_None;
9241
0
    return SC_Extern;
9242
0
  case DeclSpec::SCS_static: {
9243
0
    if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9244
      // C99 6.7.1p5:
9245
      //   The declaration of an identifier for a function that has
9246
      //   block scope shall have no explicit storage-class specifier
9247
      //   other than extern
9248
      // See also (C++ [dcl.stc]p4).
9249
0
      SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9250
0
                   diag::err_static_block_func);
9251
0
      break;
9252
0
    } else
9253
0
      return SC_Static;
9254
0
  }
9255
0
  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9256
19
  }
9257
9258
  // No explicit storage class has already been returned
9259
19
  return SC_None;
9260
19
}
9261
9262
static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9263
                                           DeclContext *DC, QualType &R,
9264
                                           TypeSourceInfo *TInfo,
9265
                                           StorageClass SC,
9266
19
                                           bool &IsVirtualOkay) {
9267
19
  DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9268
19
  DeclarationName Name = NameInfo.getName();
9269
9270
19
  FunctionDecl *NewFD = nullptr;
9271
19
  bool isInline = D.getDeclSpec().isInlineSpecified();
9272
9273
19
  if (!SemaRef.getLangOpts().CPlusPlus) {
9274
    // Determine whether the function was written with a prototype. This is
9275
    // true when:
9276
    //   - there is a prototype in the declarator, or
9277
    //   - the type R of the function is some kind of typedef or other non-
9278
    //     attributed reference to a type name (which eventually refers to a
9279
    //     function type). Note, we can't always look at the adjusted type to
9280
    //     check this case because attributes may cause a non-function
9281
    //     declarator to still have a function type. e.g.,
9282
    //       typedef void func(int a);
9283
    //       __attribute__((noreturn)) func other_func; // This has a prototype
9284
18
    bool HasPrototype =
9285
18
        (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9286
18
        (D.getDeclSpec().isTypeRep() &&
9287
10
         SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9288
0
             ->isFunctionProtoType()) ||
9289
18
        (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9290
18
    assert(
9291
18
        (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9292
18
        "Strict prototypes are required");
9293
9294
0
    NewFD = FunctionDecl::Create(
9295
18
        SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9296
18
        SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9297
18
        ConstexprSpecKind::Unspecified,
9298
18
        /*TrailingRequiresClause=*/nullptr);
9299
18
    if (D.isInvalidType())
9300
2
      NewFD->setInvalidDecl();
9301
9302
18
    return NewFD;
9303
18
  }
9304
9305
1
  ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9306
9307
1
  ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9308
1
  if (ConstexprKind == ConstexprSpecKind::Constinit) {
9309
0
    SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9310
0
                 diag::err_constexpr_wrong_decl_kind)
9311
0
        << static_cast<int>(ConstexprKind);
9312
0
    ConstexprKind = ConstexprSpecKind::Unspecified;
9313
0
    D.getMutableDeclSpec().ClearConstexprSpec();
9314
0
  }
9315
1
  Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9316
9317
1
  SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9318
9319
1
  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9320
    // This is a C++ constructor declaration.
9321
0
    assert(DC->isRecord() &&
9322
0
           "Constructors can only be declared in a member context");
9323
9324
0
    R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9325
0
    return CXXConstructorDecl::Create(
9326
0
        SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9327
0
        TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
9328
0
        isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9329
0
        InheritedConstructor(), TrailingRequiresClause);
9330
9331
1
  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9332
    // This is a C++ destructor declaration.
9333
0
    if (DC->isRecord()) {
9334
0
      R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9335
0
      CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9336
0
      CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9337
0
          SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9338
0
          SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9339
0
          /*isImplicitlyDeclared=*/false, ConstexprKind,
9340
0
          TrailingRequiresClause);
9341
      // User defined destructors start as not selected if the class definition is still
9342
      // not done.
9343
0
      if (Record->isBeingDefined())
9344
0
        NewDD->setIneligibleOrNotSelected(true);
9345
9346
      // If the destructor needs an implicit exception specification, set it
9347
      // now. FIXME: It'd be nice to be able to create the right type to start
9348
      // with, but the type needs to reference the destructor declaration.
9349
0
      if (SemaRef.getLangOpts().CPlusPlus11)
9350
0
        SemaRef.AdjustDestructorExceptionSpec(NewDD);
9351
9352
0
      IsVirtualOkay = true;
9353
0
      return NewDD;
9354
9355
0
    } else {
9356
0
      SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9357
0
      D.setInvalidType();
9358
9359
      // Create a FunctionDecl to satisfy the function definition parsing
9360
      // code path.
9361
0
      return FunctionDecl::Create(
9362
0
          SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9363
0
          TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9364
0
          /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9365
0
    }
9366
9367
1
  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9368
0
    if (!DC->isRecord()) {
9369
0
      SemaRef.Diag(D.getIdentifierLoc(),
9370
0
           diag::err_conv_function_not_member);
9371
0
      return nullptr;
9372
0
    }
9373
9374
0
    SemaRef.CheckConversionDeclarator(D, R, SC);
9375
0
    if (D.isInvalidType())
9376
0
      return nullptr;
9377
9378
0
    IsVirtualOkay = true;
9379
0
    return CXXConversionDecl::Create(
9380
0
        SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9381
0
        TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9382
0
        ExplicitSpecifier, ConstexprKind, SourceLocation(),
9383
0
        TrailingRequiresClause);
9384
9385
1
  } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9386
0
    if (TrailingRequiresClause)
9387
0
      SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9388
0
                   diag::err_trailing_requires_clause_on_deduction_guide)
9389
0
          << TrailingRequiresClause->getSourceRange();
9390
0
    if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9391
0
      return nullptr;
9392
0
    return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9393
0
                                         ExplicitSpecifier, NameInfo, R, TInfo,
9394
0
                                         D.getEndLoc());
9395
1
  } else if (DC->isRecord()) {
9396
    // If the name of the function is the same as the name of the record,
9397
    // then this must be an invalid constructor that has a return type.
9398
    // (The parser checks for a return type and makes the declarator a
9399
    // constructor if it has no return type).
9400
0
    if (Name.getAsIdentifierInfo() &&
9401
0
        Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9402
0
      SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9403
0
        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9404
0
        << SourceRange(D.getIdentifierLoc());
9405
0
      return nullptr;
9406
0
    }
9407
9408
    // This is a C++ method declaration.
9409
0
    CXXMethodDecl *Ret = CXXMethodDecl::Create(
9410
0
        SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9411
0
        TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9412
0
        ConstexprKind, SourceLocation(), TrailingRequiresClause);
9413
0
    IsVirtualOkay = !Ret->isStatic();
9414
0
    return Ret;
9415
1
  } else {
9416
1
    bool isFriend =
9417
1
        SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9418
1
    if (!isFriend && SemaRef.CurContext->isRecord())
9419
0
      return nullptr;
9420
9421
    // Determine whether the function was written with a
9422
    // prototype. This true when:
9423
    //   - we're in C++ (where every function has a prototype),
9424
1
    return FunctionDecl::Create(
9425
1
        SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9426
1
        SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9427
1
        true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9428
1
  }
9429
1
}
9430
9431
enum OpenCLParamType {
9432
  ValidKernelParam,
9433
  PtrPtrKernelParam,
9434
  PtrKernelParam,
9435
  InvalidAddrSpacePtrKernelParam,
9436
  InvalidKernelParam,
9437
  RecordKernelParam
9438
};
9439
9440
0
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9441
  // Size dependent types are just typedefs to normal integer types
9442
  // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9443
  // integers other than by their names.
9444
0
  StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9445
9446
  // Remove typedefs one by one until we reach a typedef
9447
  // for a size dependent type.
9448
0
  QualType DesugaredTy = Ty;
9449
0
  do {
9450
0
    ArrayRef<StringRef> Names(SizeTypeNames);
9451
0
    auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9452
0
    if (Names.end() != Match)
9453
0
      return true;
9454
9455
0
    Ty = DesugaredTy;
9456
0
    DesugaredTy = Ty.getSingleStepDesugaredType(C);
9457
0
  } while (DesugaredTy != Ty);
9458
9459
0
  return false;
9460
0
}
9461
9462
0
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9463
0
  if (PT->isDependentType())
9464
0
    return InvalidKernelParam;
9465
9466
0
  if (PT->isPointerType() || PT->isReferenceType()) {
9467
0
    QualType PointeeType = PT->getPointeeType();
9468
0
    if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9469
0
        PointeeType.getAddressSpace() == LangAS::opencl_private ||
9470
0
        PointeeType.getAddressSpace() == LangAS::Default)
9471
0
      return InvalidAddrSpacePtrKernelParam;
9472
9473
0
    if (PointeeType->isPointerType()) {
9474
      // This is a pointer to pointer parameter.
9475
      // Recursively check inner type.
9476
0
      OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9477
0
      if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9478
0
          ParamKind == InvalidKernelParam)
9479
0
        return ParamKind;
9480
9481
      // OpenCL v3.0 s6.11.a:
9482
      // A restriction to pass pointers to pointers only applies to OpenCL C
9483
      // v1.2 or below.
9484
0
      if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9485
0
        return ValidKernelParam;
9486
9487
0
      return PtrPtrKernelParam;
9488
0
    }
9489
9490
    // C++ for OpenCL v1.0 s2.4:
9491
    // Moreover the types used in parameters of the kernel functions must be:
9492
    // Standard layout types for pointer parameters. The same applies to
9493
    // reference if an implementation supports them in kernel parameters.
9494
0
    if (S.getLangOpts().OpenCLCPlusPlus &&
9495
0
        !S.getOpenCLOptions().isAvailableOption(
9496
0
            "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9497
0
     auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9498
0
     bool IsStandardLayoutType = true;
9499
0
     if (CXXRec) {
9500
       // If template type is not ODR-used its definition is only available
9501
       // in the template definition not its instantiation.
9502
       // FIXME: This logic doesn't work for types that depend on template
9503
       // parameter (PR58590).
9504
0
       if (!CXXRec->hasDefinition())
9505
0
         CXXRec = CXXRec->getTemplateInstantiationPattern();
9506
0
       if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9507
0
         IsStandardLayoutType = false;
9508
0
     }
9509
0
     if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9510
0
        !IsStandardLayoutType)
9511
0
      return InvalidKernelParam;
9512
0
    }
9513
9514
    // OpenCL v1.2 s6.9.p:
9515
    // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9516
0
    if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9517
0
      return ValidKernelParam;
9518
9519
0
    return PtrKernelParam;
9520
0
  }
9521
9522
  // OpenCL v1.2 s6.9.k:
9523
  // Arguments to kernel functions in a program cannot be declared with the
9524
  // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9525
  // uintptr_t or a struct and/or union that contain fields declared to be one
9526
  // of these built-in scalar types.
9527
0
  if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9528
0
    return InvalidKernelParam;
9529
9530
0
  if (PT->isImageType())
9531
0
    return PtrKernelParam;
9532
9533
0
  if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9534
0
    return InvalidKernelParam;
9535
9536
  // OpenCL extension spec v1.2 s9.5:
9537
  // This extension adds support for half scalar and vector types as built-in
9538
  // types that can be used for arithmetic operations, conversions etc.
9539
0
  if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9540
0
      PT->isHalfType())
9541
0
    return InvalidKernelParam;
9542
9543
  // Look into an array argument to check if it has a forbidden type.
9544
0
  if (PT->isArrayType()) {
9545
0
    const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9546
    // Call ourself to check an underlying type of an array. Since the
9547
    // getPointeeOrArrayElementType returns an innermost type which is not an
9548
    // array, this recursive call only happens once.
9549
0
    return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9550
0
  }
9551
9552
  // C++ for OpenCL v1.0 s2.4:
9553
  // Moreover the types used in parameters of the kernel functions must be:
9554
  // Trivial and standard-layout types C++17 [basic.types] (plain old data
9555
  // types) for parameters passed by value;
9556
0
  if (S.getLangOpts().OpenCLCPlusPlus &&
9557
0
      !S.getOpenCLOptions().isAvailableOption(
9558
0
          "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9559
0
      !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9560
0
    return InvalidKernelParam;
9561
9562
0
  if (PT->isRecordType())
9563
0
    return RecordKernelParam;
9564
9565
0
  return ValidKernelParam;
9566
0
}
9567
9568
static void checkIsValidOpenCLKernelParameter(
9569
  Sema &S,
9570
  Declarator &D,
9571
  ParmVarDecl *Param,
9572
0
  llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9573
0
  QualType PT = Param->getType();
9574
9575
  // Cache the valid types we encounter to avoid rechecking structs that are
9576
  // used again
9577
0
  if (ValidTypes.count(PT.getTypePtr()))
9578
0
    return;
9579
9580
0
  switch (getOpenCLKernelParameterType(S, PT)) {
9581
0
  case PtrPtrKernelParam:
9582
    // OpenCL v3.0 s6.11.a:
9583
    // A kernel function argument cannot be declared as a pointer to a pointer
9584
    // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9585
0
    S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9586
0
    D.setInvalidType();
9587
0
    return;
9588
9589
0
  case InvalidAddrSpacePtrKernelParam:
9590
    // OpenCL v1.0 s6.5:
9591
    // __kernel function arguments declared to be a pointer of a type can point
9592
    // to one of the following address spaces only : __global, __local or
9593
    // __constant.
9594
0
    S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9595
0
    D.setInvalidType();
9596
0
    return;
9597
9598
    // OpenCL v1.2 s6.9.k:
9599
    // Arguments to kernel functions in a program cannot be declared with the
9600
    // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9601
    // uintptr_t or a struct and/or union that contain fields declared to be
9602
    // one of these built-in scalar types.
9603
9604
0
  case InvalidKernelParam:
9605
    // OpenCL v1.2 s6.8 n:
9606
    // A kernel function argument cannot be declared
9607
    // of event_t type.
9608
    // Do not diagnose half type since it is diagnosed as invalid argument
9609
    // type for any function elsewhere.
9610
0
    if (!PT->isHalfType()) {
9611
0
      S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9612
9613
      // Explain what typedefs are involved.
9614
0
      const TypedefType *Typedef = nullptr;
9615
0
      while ((Typedef = PT->getAs<TypedefType>())) {
9616
0
        SourceLocation Loc = Typedef->getDecl()->getLocation();
9617
        // SourceLocation may be invalid for a built-in type.
9618
0
        if (Loc.isValid())
9619
0
          S.Diag(Loc, diag::note_entity_declared_at) << PT;
9620
0
        PT = Typedef->desugar();
9621
0
      }
9622
0
    }
9623
9624
0
    D.setInvalidType();
9625
0
    return;
9626
9627
0
  case PtrKernelParam:
9628
0
  case ValidKernelParam:
9629
0
    ValidTypes.insert(PT.getTypePtr());
9630
0
    return;
9631
9632
0
  case RecordKernelParam:
9633
0
    break;
9634
0
  }
9635
9636
  // Track nested structs we will inspect
9637
0
  SmallVector<const Decl *, 4> VisitStack;
9638
9639
  // Track where we are in the nested structs. Items will migrate from
9640
  // VisitStack to HistoryStack as we do the DFS for bad field.
9641
0
  SmallVector<const FieldDecl *, 4> HistoryStack;
9642
0
  HistoryStack.push_back(nullptr);
9643
9644
  // At this point we already handled everything except of a RecordType or
9645
  // an ArrayType of a RecordType.
9646
0
  assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9647
0
  const RecordType *RecTy =
9648
0
      PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9649
0
  const RecordDecl *OrigRecDecl = RecTy->getDecl();
9650
9651
0
  VisitStack.push_back(RecTy->getDecl());
9652
0
  assert(VisitStack.back() && "First decl null?");
9653
9654
0
  do {
9655
0
    const Decl *Next = VisitStack.pop_back_val();
9656
0
    if (!Next) {
9657
0
      assert(!HistoryStack.empty());
9658
      // Found a marker, we have gone up a level
9659
0
      if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9660
0
        ValidTypes.insert(Hist->getType().getTypePtr());
9661
9662
0
      continue;
9663
0
    }
9664
9665
    // Adds everything except the original parameter declaration (which is not a
9666
    // field itself) to the history stack.
9667
0
    const RecordDecl *RD;
9668
0
    if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9669
0
      HistoryStack.push_back(Field);
9670
9671
0
      QualType FieldTy = Field->getType();
9672
      // Other field types (known to be valid or invalid) are handled while we
9673
      // walk around RecordDecl::fields().
9674
0
      assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9675
0
             "Unexpected type.");
9676
0
      const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9677
9678
0
      RD = FieldRecTy->castAs<RecordType>()->getDecl();
9679
0
    } else {
9680
0
      RD = cast<RecordDecl>(Next);
9681
0
    }
9682
9683
    // Add a null marker so we know when we've gone back up a level
9684
0
    VisitStack.push_back(nullptr);
9685
9686
0
    for (const auto *FD : RD->fields()) {
9687
0
      QualType QT = FD->getType();
9688
9689
0
      if (ValidTypes.count(QT.getTypePtr()))
9690
0
        continue;
9691
9692
0
      OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9693
0
      if (ParamType == ValidKernelParam)
9694
0
        continue;
9695
9696
0
      if (ParamType == RecordKernelParam) {
9697
0
        VisitStack.push_back(FD);
9698
0
        continue;
9699
0
      }
9700
9701
      // OpenCL v1.2 s6.9.p:
9702
      // Arguments to kernel functions that are declared to be a struct or union
9703
      // do not allow OpenCL objects to be passed as elements of the struct or
9704
      // union. This restriction was lifted in OpenCL v2.0 with the introduction
9705
      // of SVM.
9706
0
      if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9707
0
          ParamType == InvalidAddrSpacePtrKernelParam) {
9708
0
        S.Diag(Param->getLocation(),
9709
0
               diag::err_record_with_pointers_kernel_param)
9710
0
          << PT->isUnionType()
9711
0
          << PT;
9712
0
      } else {
9713
0
        S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9714
0
      }
9715
9716
0
      S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9717
0
          << OrigRecDecl->getDeclName();
9718
9719
      // We have an error, now let's go back up through history and show where
9720
      // the offending field came from
9721
0
      for (ArrayRef<const FieldDecl *>::const_iterator
9722
0
               I = HistoryStack.begin() + 1,
9723
0
               E = HistoryStack.end();
9724
0
           I != E; ++I) {
9725
0
        const FieldDecl *OuterField = *I;
9726
0
        S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9727
0
          << OuterField->getType();
9728
0
      }
9729
9730
0
      S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9731
0
        << QT->isPointerType()
9732
0
        << QT;
9733
0
      D.setInvalidType();
9734
0
      return;
9735
0
    }
9736
0
  } while (!VisitStack.empty());
9737
0
}
9738
9739
/// Find the DeclContext in which a tag is implicitly declared if we see an
9740
/// elaborated type specifier in the specified context, and lookup finds
9741
/// nothing.
9742
18
static DeclContext *getTagInjectionContext(DeclContext *DC) {
9743
18
  while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9744
0
    DC = DC->getParent();
9745
18
  return DC;
9746
18
}
9747
9748
/// Find the Scope in which a tag is implicitly declared if we see an
9749
/// elaborated type specifier in the specified context, and lookup finds
9750
/// nothing.
9751
0
static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9752
0
  while (S->isClassScope() ||
9753
0
         (LangOpts.CPlusPlus &&
9754
0
          S->isFunctionPrototypeScope()) ||
9755
0
         ((S->getFlags() & Scope::DeclScope) == 0) ||
9756
0
         (S->getEntity() && S->getEntity()->isTransparentContext()))
9757
0
    S = S->getParent();
9758
0
  return S;
9759
0
}
9760
9761
/// Determine whether a declaration matches a known function in namespace std.
9762
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9763
0
                         unsigned BuiltinID) {
9764
0
  switch (BuiltinID) {
9765
0
  case Builtin::BI__GetExceptionInfo:
9766
    // No type checking whatsoever.
9767
0
    return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9768
9769
0
  case Builtin::BIaddressof:
9770
0
  case Builtin::BI__addressof:
9771
0
  case Builtin::BIforward:
9772
0
  case Builtin::BIforward_like:
9773
0
  case Builtin::BImove:
9774
0
  case Builtin::BImove_if_noexcept:
9775
0
  case Builtin::BIas_const: {
9776
    // Ensure that we don't treat the algorithm
9777
    //   OutputIt std::move(InputIt, InputIt, OutputIt)
9778
    // as the builtin std::move.
9779
0
    const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9780
0
    return FPT->getNumParams() == 1 && !FPT->isVariadic();
9781
0
  }
9782
9783
0
  default:
9784
0
    return false;
9785
0
  }
9786
0
}
9787
9788
NamedDecl*
9789
Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9790
                              TypeSourceInfo *TInfo, LookupResult &Previous,
9791
                              MultiTemplateParamsArg TemplateParamListsRef,
9792
19
                              bool &AddToScope) {
9793
19
  QualType R = TInfo->getType();
9794
9795
19
  assert(R->isFunctionType());
9796
19
  if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9797
0
    Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9798
9799
19
  SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9800
19
  llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9801
19
  if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9802
0
    if (!TemplateParamLists.empty() &&
9803
0
        Invented->getDepth() == TemplateParamLists.back()->getDepth())
9804
0
      TemplateParamLists.back() = Invented;
9805
0
    else
9806
0
      TemplateParamLists.push_back(Invented);
9807
0
  }
9808
9809
  // TODO: consider using NameInfo for diagnostic.
9810
19
  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9811
19
  DeclarationName Name = NameInfo.getName();
9812
19
  StorageClass SC = getFunctionStorageClass(*this, D);
9813
9814
19
  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9815
0
    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9816
0
         diag::err_invalid_thread)
9817
0
      << DeclSpec::getSpecifierName(TSCS);
9818
9819
19
  if (D.isFirstDeclarationOfMember())
9820
0
    adjustMemberFunctionCC(
9821
0
        R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9822
0
        D.isCtorOrDtor(), D.getIdentifierLoc());
9823
9824
19
  bool isFriend = false;
9825
19
  FunctionTemplateDecl *FunctionTemplate = nullptr;
9826
19
  bool isMemberSpecialization = false;
9827
19
  bool isFunctionTemplateSpecialization = false;
9828
9829
19
  bool HasExplicitTemplateArgs = false;
9830
19
  TemplateArgumentListInfo TemplateArgs;
9831
9832
19
  bool isVirtualOkay = false;
9833
9834
19
  DeclContext *OriginalDC = DC;
9835
19
  bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9836
9837
19
  FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9838
19
                                              isVirtualOkay);
9839
19
  if (!NewFD) return nullptr;
9840
9841
19
  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9842
0
    NewFD->setTopLevelDeclInObjCContainer();
9843
9844
  // Set the lexical context. If this is a function-scope declaration, or has a
9845
  // C++ scope specifier, or is the object of a friend declaration, the lexical
9846
  // context will be different from the semantic context.
9847
19
  NewFD->setLexicalDeclContext(CurContext);
9848
9849
19
  if (IsLocalExternDecl)
9850
0
    NewFD->setLocalExternDecl();
9851
9852
19
  if (getLangOpts().CPlusPlus) {
9853
    // The rules for implicit inlines changed in C++20 for methods and friends
9854
    // with an in-class definition (when such a definition is not attached to
9855
    // the global module).  User-specified 'inline' overrides this (set when
9856
    // the function decl is created above).
9857
    // FIXME: We need a better way to separate C++ standard and clang modules.
9858
1
    bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9859
1
                               !NewFD->getOwningModule() ||
9860
1
                               NewFD->getOwningModule()->isGlobalModule() ||
9861
1
                               NewFD->getOwningModule()->isHeaderLikeModule();
9862
1
    bool isInline = D.getDeclSpec().isInlineSpecified();
9863
1
    bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9864
1
    bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9865
1
    isFriend = D.getDeclSpec().isFriendSpecified();
9866
1
    if (isFriend && !isInline && D.isFunctionDefinition()) {
9867
      // Pre-C++20 [class.friend]p5
9868
      //   A function can be defined in a friend declaration of a
9869
      //   class . . . . Such a function is implicitly inline.
9870
      // Post C++20 [class.friend]p7
9871
      //   Such a function is implicitly an inline function if it is attached
9872
      //   to the global module.
9873
0
      NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9874
0
    }
9875
9876
    // If this is a method defined in an __interface, and is not a constructor
9877
    // or an overloaded operator, then set the pure flag (isVirtual will already
9878
    // return true).
9879
1
    if (const CXXRecordDecl *Parent =
9880
1
          dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9881
0
      if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9882
0
        NewFD->setPure(true);
9883
9884
      // C++ [class.union]p2
9885
      //   A union can have member functions, but not virtual functions.
9886
0
      if (isVirtual && Parent->isUnion()) {
9887
0
        Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9888
0
        NewFD->setInvalidDecl();
9889
0
      }
9890
0
      if ((Parent->isClass() || Parent->isStruct()) &&
9891
0
          Parent->hasAttr<SYCLSpecialClassAttr>() &&
9892
0
          NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9893
0
          NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9894
0
        if (auto *Def = Parent->getDefinition())
9895
0
          Def->setInitMethod(true);
9896
0
      }
9897
0
    }
9898
9899
1
    SetNestedNameSpecifier(*this, NewFD, D);
9900
1
    isMemberSpecialization = false;
9901
1
    isFunctionTemplateSpecialization = false;
9902
1
    if (D.isInvalidType())
9903
1
      NewFD->setInvalidDecl();
9904
9905
    // Match up the template parameter lists with the scope specifier, then
9906
    // determine whether we have a template or a template specialization.
9907
1
    bool Invalid = false;
9908
1
    TemplateIdAnnotation *TemplateId =
9909
1
        D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9910
1
            ? D.getName().TemplateId
9911
1
            : nullptr;
9912
1
    TemplateParameterList *TemplateParams =
9913
1
        MatchTemplateParametersToScopeSpecifier(
9914
1
            D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9915
1
            D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
9916
1
            isMemberSpecialization, Invalid);
9917
1
    if (TemplateParams) {
9918
      // Check that we can declare a template here.
9919
0
      if (CheckTemplateDeclScope(S, TemplateParams))
9920
0
        NewFD->setInvalidDecl();
9921
9922
0
      if (TemplateParams->size() > 0) {
9923
        // This is a function template
9924
9925
        // A destructor cannot be a template.
9926
0
        if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9927
0
          Diag(NewFD->getLocation(), diag::err_destructor_template);
9928
0
          NewFD->setInvalidDecl();
9929
          // Function template with explicit template arguments.
9930
0
        } else if (TemplateId) {
9931
0
          Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9932
0
              << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9933
0
          NewFD->setInvalidDecl();
9934
0
        }
9935
9936
        // If we're adding a template to a dependent context, we may need to
9937
        // rebuilding some of the types used within the template parameter list,
9938
        // now that we know what the current instantiation is.
9939
0
        if (DC->isDependentContext()) {
9940
0
          ContextRAII SavedContext(*this, DC);
9941
0
          if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9942
0
            Invalid = true;
9943
0
        }
9944
9945
0
        FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9946
0
                                                        NewFD->getLocation(),
9947
0
                                                        Name, TemplateParams,
9948
0
                                                        NewFD);
9949
0
        FunctionTemplate->setLexicalDeclContext(CurContext);
9950
0
        NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9951
9952
        // For source fidelity, store the other template param lists.
9953
0
        if (TemplateParamLists.size() > 1) {
9954
0
          NewFD->setTemplateParameterListsInfo(Context,
9955
0
              ArrayRef<TemplateParameterList *>(TemplateParamLists)
9956
0
                  .drop_back(1));
9957
0
        }
9958
0
      } else {
9959
        // This is a function template specialization.
9960
0
        isFunctionTemplateSpecialization = true;
9961
        // For source fidelity, store all the template param lists.
9962
0
        if (TemplateParamLists.size() > 0)
9963
0
          NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9964
9965
        // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9966
0
        if (isFriend) {
9967
          // We want to remove the "template<>", found here.
9968
0
          SourceRange RemoveRange = TemplateParams->getSourceRange();
9969
9970
          // If we remove the template<> and the name is not a
9971
          // template-id, we're actually silently creating a problem:
9972
          // the friend declaration will refer to an untemplated decl,
9973
          // and clearly the user wants a template specialization.  So
9974
          // we need to insert '<>' after the name.
9975
0
          SourceLocation InsertLoc;
9976
0
          if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9977
0
            InsertLoc = D.getName().getSourceRange().getEnd();
9978
0
            InsertLoc = getLocForEndOfToken(InsertLoc);
9979
0
          }
9980
9981
0
          Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9982
0
            << Name << RemoveRange
9983
0
            << FixItHint::CreateRemoval(RemoveRange)
9984
0
            << FixItHint::CreateInsertion(InsertLoc, "<>");
9985
0
          Invalid = true;
9986
9987
          // Recover by faking up an empty template argument list.
9988
0
          HasExplicitTemplateArgs = true;
9989
0
          TemplateArgs.setLAngleLoc(InsertLoc);
9990
0
          TemplateArgs.setRAngleLoc(InsertLoc);
9991
0
        }
9992
0
      }
9993
1
    } else {
9994
      // Check that we can declare a template here.
9995
1
      if (!TemplateParamLists.empty() && isMemberSpecialization &&
9996
1
          CheckTemplateDeclScope(S, TemplateParamLists.back()))
9997
0
        NewFD->setInvalidDecl();
9998
9999
      // All template param lists were matched against the scope specifier:
10000
      // this is NOT (an explicit specialization of) a template.
10001
1
      if (TemplateParamLists.size() > 0)
10002
        // For source fidelity, store all the template param lists.
10003
0
        NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10004
10005
      // "friend void foo<>(int);" is an implicit specialization decl.
10006
1
      if (isFriend && TemplateId)
10007
0
        isFunctionTemplateSpecialization = true;
10008
1
    }
10009
10010
    // If this is a function template specialization and the unqualified-id of
10011
    // the declarator-id is a template-id, convert the template argument list
10012
    // into our AST format and check for unexpanded packs.
10013
1
    if (isFunctionTemplateSpecialization && TemplateId) {
10014
0
      HasExplicitTemplateArgs = true;
10015
10016
0
      TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10017
0
      TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10018
0
      ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10019
0
                                         TemplateId->NumArgs);
10020
0
      translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10021
10022
      // FIXME: Should we check for unexpanded packs if this was an (invalid)
10023
      // declaration of a function template partial specialization? Should we
10024
      // consider the unexpanded pack context to be a partial specialization?
10025
0
      for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10026
0
        if (DiagnoseUnexpandedParameterPack(
10027
0
                ArgLoc, isFriend ? UPPC_FriendDeclaration
10028
0
                                 : UPPC_ExplicitSpecialization))
10029
0
          NewFD->setInvalidDecl();
10030
0
      }
10031
0
    }
10032
10033
1
    if (Invalid) {
10034
0
      NewFD->setInvalidDecl();
10035
0
      if (FunctionTemplate)
10036
0
        FunctionTemplate->setInvalidDecl();
10037
0
    }
10038
10039
    // C++ [dcl.fct.spec]p5:
10040
    //   The virtual specifier shall only be used in declarations of
10041
    //   nonstatic class member functions that appear within a
10042
    //   member-specification of a class declaration; see 10.3.
10043
    //
10044
1
    if (isVirtual && !NewFD->isInvalidDecl()) {
10045
0
      if (!isVirtualOkay) {
10046
0
        Diag(D.getDeclSpec().getVirtualSpecLoc(),
10047
0
             diag::err_virtual_non_function);
10048
0
      } else if (!CurContext->isRecord()) {
10049
        // 'virtual' was specified outside of the class.
10050
0
        Diag(D.getDeclSpec().getVirtualSpecLoc(),
10051
0
             diag::err_virtual_out_of_class)
10052
0
          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10053
0
      } else if (NewFD->getDescribedFunctionTemplate()) {
10054
        // C++ [temp.mem]p3:
10055
        //  A member function template shall not be virtual.
10056
0
        Diag(D.getDeclSpec().getVirtualSpecLoc(),
10057
0
             diag::err_virtual_member_function_template)
10058
0
          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10059
0
      } else {
10060
        // Okay: Add virtual to the method.
10061
0
        NewFD->setVirtualAsWritten(true);
10062
0
      }
10063
10064
0
      if (getLangOpts().CPlusPlus14 &&
10065
0
          NewFD->getReturnType()->isUndeducedType())
10066
0
        Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10067
0
    }
10068
10069
1
    if (getLangOpts().CPlusPlus14 &&
10070
1
        (NewFD->isDependentContext() ||
10071
1
         (isFriend && CurContext->isDependentContext())) &&
10072
1
        NewFD->getReturnType()->isUndeducedType()) {
10073
      // If the function template is referenced directly (for instance, as a
10074
      // member of the current instantiation), pretend it has a dependent type.
10075
      // This is not really justified by the standard, but is the only sane
10076
      // thing to do.
10077
      // FIXME: For a friend function, we have not marked the function as being
10078
      // a friend yet, so 'isDependentContext' on the FD doesn't work.
10079
0
      const FunctionProtoType *FPT =
10080
0
          NewFD->getType()->castAs<FunctionProtoType>();
10081
0
      QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
10082
0
      NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
10083
0
                                             FPT->getExtProtoInfo()));
10084
0
    }
10085
10086
    // C++ [dcl.fct.spec]p3:
10087
    //  The inline specifier shall not appear on a block scope function
10088
    //  declaration.
10089
1
    if (isInline && !NewFD->isInvalidDecl()) {
10090
0
      if (CurContext->isFunctionOrMethod()) {
10091
        // 'inline' is not allowed on block scope function declaration.
10092
0
        Diag(D.getDeclSpec().getInlineSpecLoc(),
10093
0
             diag::err_inline_declaration_block_scope) << Name
10094
0
          << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10095
0
      }
10096
0
    }
10097
10098
    // C++ [dcl.fct.spec]p6:
10099
    //  The explicit specifier shall be used only in the declaration of a
10100
    //  constructor or conversion function within its class definition;
10101
    //  see 12.3.1 and 12.3.2.
10102
1
    if (hasExplicit && !NewFD->isInvalidDecl() &&
10103
1
        !isa<CXXDeductionGuideDecl>(NewFD)) {
10104
0
      if (!CurContext->isRecord()) {
10105
        // 'explicit' was specified outside of the class.
10106
0
        Diag(D.getDeclSpec().getExplicitSpecLoc(),
10107
0
             diag::err_explicit_out_of_class)
10108
0
            << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10109
0
      } else if (!isa<CXXConstructorDecl>(NewFD) &&
10110
0
                 !isa<CXXConversionDecl>(NewFD)) {
10111
        // 'explicit' was specified on a function that wasn't a constructor
10112
        // or conversion function.
10113
0
        Diag(D.getDeclSpec().getExplicitSpecLoc(),
10114
0
             diag::err_explicit_non_ctor_or_conv_function)
10115
0
            << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10116
0
      }
10117
0
    }
10118
10119
1
    ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10120
1
    if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10121
      // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10122
      // are implicitly inline.
10123
0
      NewFD->setImplicitlyInline();
10124
10125
      // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10126
      // be either constructors or to return a literal type. Therefore,
10127
      // destructors cannot be declared constexpr.
10128
0
      if (isa<CXXDestructorDecl>(NewFD) &&
10129
0
          (!getLangOpts().CPlusPlus20 ||
10130
0
           ConstexprKind == ConstexprSpecKind::Consteval)) {
10131
0
        Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10132
0
            << static_cast<int>(ConstexprKind);
10133
0
        NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10134
0
                                    ? ConstexprSpecKind::Unspecified
10135
0
                                    : ConstexprSpecKind::Constexpr);
10136
0
      }
10137
      // C++20 [dcl.constexpr]p2: An allocation function, or a
10138
      // deallocation function shall not be declared with the consteval
10139
      // specifier.
10140
0
      if (ConstexprKind == ConstexprSpecKind::Consteval &&
10141
0
          (NewFD->getOverloadedOperator() == OO_New ||
10142
0
           NewFD->getOverloadedOperator() == OO_Array_New ||
10143
0
           NewFD->getOverloadedOperator() == OO_Delete ||
10144
0
           NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10145
0
        Diag(D.getDeclSpec().getConstexprSpecLoc(),
10146
0
             diag::err_invalid_consteval_decl_kind)
10147
0
            << NewFD;
10148
0
        NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10149
0
      }
10150
0
    }
10151
10152
    // If __module_private__ was specified, mark the function accordingly.
10153
1
    if (D.getDeclSpec().isModulePrivateSpecified()) {
10154
0
      if (isFunctionTemplateSpecialization) {
10155
0
        SourceLocation ModulePrivateLoc
10156
0
          = D.getDeclSpec().getModulePrivateSpecLoc();
10157
0
        Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10158
0
          << 0
10159
0
          << FixItHint::CreateRemoval(ModulePrivateLoc);
10160
0
      } else {
10161
0
        NewFD->setModulePrivate();
10162
0
        if (FunctionTemplate)
10163
0
          FunctionTemplate->setModulePrivate();
10164
0
      }
10165
0
    }
10166
10167
1
    if (isFriend) {
10168
0
      if (FunctionTemplate) {
10169
0
        FunctionTemplate->setObjectOfFriendDecl();
10170
0
        FunctionTemplate->setAccess(AS_public);
10171
0
      }
10172
0
      NewFD->setObjectOfFriendDecl();
10173
0
      NewFD->setAccess(AS_public);
10174
0
    }
10175
10176
    // If a function is defined as defaulted or deleted, mark it as such now.
10177
    // We'll do the relevant checks on defaulted / deleted functions later.
10178
1
    switch (D.getFunctionDefinitionKind()) {
10179
1
    case FunctionDefinitionKind::Declaration:
10180
1
    case FunctionDefinitionKind::Definition:
10181
1
      break;
10182
10183
0
    case FunctionDefinitionKind::Defaulted:
10184
0
      NewFD->setDefaulted();
10185
0
      break;
10186
10187
0
    case FunctionDefinitionKind::Deleted:
10188
0
      NewFD->setDeletedAsWritten();
10189
0
      break;
10190
1
    }
10191
10192
1
    if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10193
1
        D.isFunctionDefinition() && !isInline) {
10194
      // Pre C++20 [class.mfct]p2:
10195
      //   A member function may be defined (8.4) in its class definition, in
10196
      //   which case it is an inline member function (7.1.2)
10197
      // Post C++20 [class.mfct]p1:
10198
      //   If a member function is attached to the global module and is defined
10199
      //   in its class definition, it is inline.
10200
0
      NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10201
0
    }
10202
10203
1
    if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
10204
1
        !CurContext->isRecord()) {
10205
      // C++ [class.static]p1:
10206
      //   A data or function member of a class may be declared static
10207
      //   in a class definition, in which case it is a static member of
10208
      //   the class.
10209
10210
      // Complain about the 'static' specifier if it's on an out-of-line
10211
      // member function definition.
10212
10213
      // MSVC permits the use of a 'static' storage specifier on an out-of-line
10214
      // member function template declaration and class member template
10215
      // declaration (MSVC versions before 2015), warn about this.
10216
0
      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10217
0
           ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10218
0
             cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10219
0
           (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
10220
0
           ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
10221
0
        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10222
0
    }
10223
10224
    // C++11 [except.spec]p15:
10225
    //   A deallocation function with no exception-specification is treated
10226
    //   as if it were specified with noexcept(true).
10227
1
    const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10228
1
    if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10229
1
         Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10230
1
        getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10231
0
      NewFD->setType(Context.getFunctionType(
10232
0
          FPT->getReturnType(), FPT->getParamTypes(),
10233
0
          FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
10234
10235
    // C++20 [dcl.inline]/7
10236
    // If an inline function or variable that is attached to a named module
10237
    // is declared in a definition domain, it shall be defined in that
10238
    // domain.
10239
    // So, if the current declaration does not have a definition, we must
10240
    // check at the end of the TU (or when the PMF starts) to see that we
10241
    // have a definition at that point.
10242
1
    if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10243
1
        NewFD->hasOwningModule() && NewFD->getOwningModule()->isNamedModule()) {
10244
0
      PendingInlineFuncDecls.insert(NewFD);
10245
0
    }
10246
1
  }
10247
10248
  // Filter out previous declarations that don't match the scope.
10249
19
  FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
10250
19
                       D.getCXXScopeSpec().isNotEmpty() ||
10251
19
                       isMemberSpecialization ||
10252
19
                       isFunctionTemplateSpecialization);
10253
10254
  // Handle GNU asm-label extension (encoded as an attribute).
10255
19
  if (Expr *E = (Expr*) D.getAsmLabel()) {
10256
    // The parser guarantees this is a string.
10257
0
    StringLiteral *SE = cast<StringLiteral>(E);
10258
0
    NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10259
0
                                        /*IsLiteralLabel=*/true,
10260
0
                                        SE->getStrTokenLoc(0)));
10261
19
  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10262
0
    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10263
0
      ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10264
0
    if (I != ExtnameUndeclaredIdentifiers.end()) {
10265
0
      if (isDeclExternC(NewFD)) {
10266
0
        NewFD->addAttr(I->second);
10267
0
        ExtnameUndeclaredIdentifiers.erase(I);
10268
0
      } else
10269
0
        Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10270
0
            << /*Variable*/0 << NewFD;
10271
0
    }
10272
0
  }
10273
10274
  // Copy the parameter declarations from the declarator D to the function
10275
  // declaration NewFD, if they are available.  First scavenge them into Params.
10276
19
  SmallVector<ParmVarDecl*, 16> Params;
10277
19
  unsigned FTIIdx;
10278
19
  if (D.isFunctionDeclarator(FTIIdx)) {
10279
19
    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10280
10281
    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10282
    // function that takes no arguments, not a function that takes a
10283
    // single void argument.
10284
    // We let through "const void" here because Sema::GetTypeForDeclarator
10285
    // already checks for that case.
10286
19
    if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10287
18
      for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10288
9
        ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10289
9
        assert(Param->getDeclContext() != NewFD && "Was set before ?");
10290
0
        Param->setDeclContext(NewFD);
10291
9
        Params.push_back(Param);
10292
10293
9
        if (Param->isInvalidDecl())
10294
8
          NewFD->setInvalidDecl();
10295
9
      }
10296
9
    }
10297
10298
19
    if (!getLangOpts().CPlusPlus) {
10299
      // In C, find all the tag declarations from the prototype and move them
10300
      // into the function DeclContext. Remove them from the surrounding tag
10301
      // injection context of the function, which is typically but not always
10302
      // the TU.
10303
18
      DeclContext *PrototypeTagContext =
10304
18
          getTagInjectionContext(NewFD->getLexicalDeclContext());
10305
18
      for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10306
0
        auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10307
10308
        // We don't want to reparent enumerators. Look at their parent enum
10309
        // instead.
10310
0
        if (!TD) {
10311
0
          if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10312
0
            TD = cast<EnumDecl>(ECD->getDeclContext());
10313
0
        }
10314
0
        if (!TD)
10315
0
          continue;
10316
0
        DeclContext *TagDC = TD->getLexicalDeclContext();
10317
0
        if (!TagDC->containsDecl(TD))
10318
0
          continue;
10319
0
        TagDC->removeDecl(TD);
10320
0
        TD->setDeclContext(NewFD);
10321
0
        NewFD->addDecl(TD);
10322
10323
        // Preserve the lexical DeclContext if it is not the surrounding tag
10324
        // injection context of the FD. In this example, the semantic context of
10325
        // E will be f and the lexical context will be S, while both the
10326
        // semantic and lexical contexts of S will be f:
10327
        //   void f(struct S { enum E { a } f; } s);
10328
0
        if (TagDC != PrototypeTagContext)
10329
0
          TD->setLexicalDeclContext(TagDC);
10330
0
      }
10331
18
    }
10332
19
  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10333
    // When we're declaring a function with a typedef, typeof, etc as in the
10334
    // following example, we'll need to synthesize (unnamed)
10335
    // parameters for use in the declaration.
10336
    //
10337
    // @code
10338
    // typedef void fn(int);
10339
    // fn f;
10340
    // @endcode
10341
10342
    // Synthesize a parameter for each argument type.
10343
0
    for (const auto &AI : FT->param_types()) {
10344
0
      ParmVarDecl *Param =
10345
0
          BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10346
0
      Param->setScopeInfo(0, Params.size());
10347
0
      Params.push_back(Param);
10348
0
    }
10349
0
  } else {
10350
0
    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10351
0
           "Should not need args for typedef of non-prototype fn");
10352
0
  }
10353
10354
  // Finally, we know we have the right number of parameters, install them.
10355
0
  NewFD->setParams(Params);
10356
10357
19
  if (D.getDeclSpec().isNoreturnSpecified())
10358
0
    NewFD->addAttr(
10359
0
        C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10360
10361
  // Functions returning a variably modified type violate C99 6.7.5.2p2
10362
  // because all functions have linkage.
10363
19
  if (!NewFD->isInvalidDecl() &&
10364
19
      NewFD->getReturnType()->isVariablyModifiedType()) {
10365
0
    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10366
0
    NewFD->setInvalidDecl();
10367
0
  }
10368
10369
  // Apply an implicit SectionAttr if '#pragma clang section text' is active
10370
19
  if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10371
19
      !NewFD->hasAttr<SectionAttr>())
10372
0
    NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10373
0
        Context, PragmaClangTextSection.SectionName,
10374
0
        PragmaClangTextSection.PragmaLocation));
10375
10376
  // Apply an implicit SectionAttr if #pragma code_seg is active.
10377
19
  if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10378
19
      !NewFD->hasAttr<SectionAttr>()) {
10379
0
    NewFD->addAttr(SectionAttr::CreateImplicit(
10380
0
        Context, CodeSegStack.CurrentValue->getString(),
10381
0
        CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10382
0
    if (UnifySection(CodeSegStack.CurrentValue->getString(),
10383
0
                     ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10384
0
                         ASTContext::PSF_Read,
10385
0
                     NewFD))
10386
0
      NewFD->dropAttr<SectionAttr>();
10387
0
  }
10388
10389
  // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10390
  // active.
10391
19
  if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10392
19
      !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10393
0
    NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10394
0
        Context, PragmaClangTextSection.PragmaLocation));
10395
10396
  // Apply an implicit CodeSegAttr from class declspec or
10397
  // apply an implicit SectionAttr from #pragma code_seg if active.
10398
19
  if (!NewFD->hasAttr<CodeSegAttr>()) {
10399
19
    if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
10400
19
                                                                 D.isFunctionDefinition())) {
10401
0
      NewFD->addAttr(SAttr);
10402
0
    }
10403
19
  }
10404
10405
  // Handle attributes.
10406
19
  ProcessDeclAttributes(S, NewFD, D);
10407
19
  const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10408
19
  if (NewTVA && !NewTVA->isDefaultVersion() &&
10409
19
      !Context.getTargetInfo().hasFeature("fmv")) {
10410
    // Don't add to scope fmv functions declarations if fmv disabled
10411
0
    AddToScope = false;
10412
0
    return NewFD;
10413
0
  }
10414
10415
19
  if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10416
    // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10417
    // type.
10418
    //
10419
    // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10420
    // type declaration will generate a compilation error.
10421
0
    LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10422
0
    if (AddressSpace != LangAS::Default) {
10423
0
      Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10424
0
      NewFD->setInvalidDecl();
10425
0
    }
10426
0
  }
10427
10428
19
  if (!getLangOpts().CPlusPlus) {
10429
    // Perform semantic checking on the function declaration.
10430
18
    if (!NewFD->isInvalidDecl() && NewFD->isMain())
10431
0
      CheckMain(NewFD, D.getDeclSpec());
10432
10433
18
    if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10434
0
      CheckMSVCRTEntryPoint(NewFD);
10435
10436
18
    if (!NewFD->isInvalidDecl())
10437
9
      D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10438
9
                                                  isMemberSpecialization,
10439
9
                                                  D.isFunctionDefinition()));
10440
9
    else if (!Previous.empty())
10441
      // Recover gracefully from an invalid redeclaration.
10442
2
      D.setRedeclaration(true);
10443
18
    assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10444
18
            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10445
18
           "previous declaration set still overloaded");
10446
10447
    // Diagnose no-prototype function declarations with calling conventions that
10448
    // don't support variadic calls. Only do this in C and do it after merging
10449
    // possibly prototyped redeclarations.
10450
0
    const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10451
18
    if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10452
10
      CallingConv CC = FT->getExtInfo().getCC();
10453
10
      if (!supportsVariadicCall(CC)) {
10454
        // Windows system headers sometimes accidentally use stdcall without
10455
        // (void) parameters, so we relax this to a warning.
10456
0
        int DiagID =
10457
0
            CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10458
0
        Diag(NewFD->getLocation(), DiagID)
10459
0
            << FunctionType::getNameForCallConv(CC);
10460
0
      }
10461
10
    }
10462
10463
18
   if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10464
18
       NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10465
0
     checkNonTrivialCUnion(NewFD->getReturnType(),
10466
0
                           NewFD->getReturnTypeSourceRange().getBegin(),
10467
0
                           NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
10468
18
  } else {
10469
    // C++11 [replacement.functions]p3:
10470
    //  The program's definitions shall not be specified as inline.
10471
    //
10472
    // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10473
    //
10474
    // Suppress the diagnostic if the function is __attribute__((used)), since
10475
    // that forces an external definition to be emitted.
10476
1
    if (D.getDeclSpec().isInlineSpecified() &&
10477
1
        NewFD->isReplaceableGlobalAllocationFunction() &&
10478
1
        !NewFD->hasAttr<UsedAttr>())
10479
0
      Diag(D.getDeclSpec().getInlineSpecLoc(),
10480
0
           diag::ext_operator_new_delete_declared_inline)
10481
0
        << NewFD->getDeclName();
10482
10483
    // We do not add HD attributes to specializations here because
10484
    // they may have different constexpr-ness compared to their
10485
    // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10486
    // may end up with different effective targets. Instead, a
10487
    // specialization inherits its target attributes from its template
10488
    // in the CheckFunctionTemplateSpecialization() call below.
10489
1
    if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10490
0
      maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
10491
10492
    // Handle explict specializations of function templates
10493
    // and friend function declarations with an explicit
10494
    // template argument list.
10495
1
    if (isFunctionTemplateSpecialization) {
10496
0
      bool isDependentSpecialization = false;
10497
0
      if (isFriend) {
10498
        // For friend function specializations, this is a dependent
10499
        // specialization if its semantic context is dependent, its
10500
        // type is dependent, or if its template-id is dependent.
10501
0
        isDependentSpecialization =
10502
0
            DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10503
0
            (HasExplicitTemplateArgs &&
10504
0
             TemplateSpecializationType::
10505
0
                 anyInstantiationDependentTemplateArguments(
10506
0
                     TemplateArgs.arguments()));
10507
0
        assert((!isDependentSpecialization ||
10508
0
                (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10509
0
               "dependent friend function specialization without template "
10510
0
               "args");
10511
0
      } else {
10512
        // For class-scope explicit specializations of function templates,
10513
        // if the lexical context is dependent, then the specialization
10514
        // is dependent.
10515
0
        isDependentSpecialization =
10516
0
            CurContext->isRecord() && CurContext->isDependentContext();
10517
0
      }
10518
10519
0
      TemplateArgumentListInfo *ExplicitTemplateArgs =
10520
0
          HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10521
0
      if (isDependentSpecialization) {
10522
        // If it's a dependent specialization, it may not be possible
10523
        // to determine the primary template (for explicit specializations)
10524
        // or befriended declaration (for friends) until the enclosing
10525
        // template is instantiated. In such cases, we store the declarations
10526
        // found by name lookup and defer resolution until instantiation.
10527
0
        if (CheckDependentFunctionTemplateSpecialization(
10528
0
                NewFD, ExplicitTemplateArgs, Previous))
10529
0
          NewFD->setInvalidDecl();
10530
0
      } else if (!NewFD->isInvalidDecl()) {
10531
0
        if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10532
0
                                                Previous))
10533
0
          NewFD->setInvalidDecl();
10534
0
      }
10535
10536
      // C++ [dcl.stc]p1:
10537
      //   A storage-class-specifier shall not be specified in an explicit
10538
      //   specialization (14.7.3)
10539
      // FIXME: We should be checking this for dependent specializations.
10540
0
      FunctionTemplateSpecializationInfo *Info =
10541
0
          NewFD->getTemplateSpecializationInfo();
10542
0
      if (Info && SC != SC_None) {
10543
0
        if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10544
0
          Diag(NewFD->getLocation(),
10545
0
               diag::err_explicit_specialization_inconsistent_storage_class)
10546
0
            << SC
10547
0
            << FixItHint::CreateRemoval(
10548
0
                                      D.getDeclSpec().getStorageClassSpecLoc());
10549
10550
0
        else
10551
0
          Diag(NewFD->getLocation(),
10552
0
               diag::ext_explicit_specialization_storage_class)
10553
0
            << FixItHint::CreateRemoval(
10554
0
                                      D.getDeclSpec().getStorageClassSpecLoc());
10555
0
      }
10556
1
    } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10557
0
      if (CheckMemberSpecialization(NewFD, Previous))
10558
0
          NewFD->setInvalidDecl();
10559
0
    }
10560
10561
    // Perform semantic checking on the function declaration.
10562
1
    if (!NewFD->isInvalidDecl() && NewFD->isMain())
10563
0
      CheckMain(NewFD, D.getDeclSpec());
10564
10565
1
    if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10566
0
      CheckMSVCRTEntryPoint(NewFD);
10567
10568
1
    if (!NewFD->isInvalidDecl())
10569
0
      D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10570
0
                                                  isMemberSpecialization,
10571
0
                                                  D.isFunctionDefinition()));
10572
1
    else if (!Previous.empty())
10573
      // Recover gracefully from an invalid redeclaration.
10574
0
      D.setRedeclaration(true);
10575
10576
1
    assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10577
1
            !D.isRedeclaration() ||
10578
1
            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10579
1
           "previous declaration set still overloaded");
10580
10581
1
    NamedDecl *PrincipalDecl = (FunctionTemplate
10582
1
                                ? cast<NamedDecl>(FunctionTemplate)
10583
1
                                : NewFD);
10584
10585
1
    if (isFriend && NewFD->getPreviousDecl()) {
10586
0
      AccessSpecifier Access = AS_public;
10587
0
      if (!NewFD->isInvalidDecl())
10588
0
        Access = NewFD->getPreviousDecl()->getAccess();
10589
10590
0
      NewFD->setAccess(Access);
10591
0
      if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10592
0
    }
10593
10594
1
    if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10595
1
        PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10596
0
      PrincipalDecl->setNonMemberOperator();
10597
10598
    // If we have a function template, check the template parameter
10599
    // list. This will check and merge default template arguments.
10600
1
    if (FunctionTemplate) {
10601
0
      FunctionTemplateDecl *PrevTemplate =
10602
0
                                     FunctionTemplate->getPreviousDecl();
10603
0
      CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10604
0
                       PrevTemplate ? PrevTemplate->getTemplateParameters()
10605
0
                                    : nullptr,
10606
0
                            D.getDeclSpec().isFriendSpecified()
10607
0
                              ? (D.isFunctionDefinition()
10608
0
                                   ? TPC_FriendFunctionTemplateDefinition
10609
0
                                   : TPC_FriendFunctionTemplate)
10610
0
                              : (D.getCXXScopeSpec().isSet() &&
10611
0
                                 DC && DC->isRecord() &&
10612
0
                                 DC->isDependentContext())
10613
0
                                  ? TPC_ClassTemplateMember
10614
0
                                  : TPC_FunctionTemplate);
10615
0
    }
10616
10617
1
    if (NewFD->isInvalidDecl()) {
10618
      // Ignore all the rest of this.
10619
1
    } else if (!D.isRedeclaration()) {
10620
0
      struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10621
0
                                       AddToScope };
10622
      // Fake up an access specifier if it's supposed to be a class member.
10623
0
      if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10624
0
        NewFD->setAccess(AS_public);
10625
10626
      // Qualified decls generally require a previous declaration.
10627
0
      if (D.getCXXScopeSpec().isSet()) {
10628
        // ...with the major exception of templated-scope or
10629
        // dependent-scope friend declarations.
10630
10631
        // TODO: we currently also suppress this check in dependent
10632
        // contexts because (1) the parameter depth will be off when
10633
        // matching friend templates and (2) we might actually be
10634
        // selecting a friend based on a dependent factor.  But there
10635
        // are situations where these conditions don't apply and we
10636
        // can actually do this check immediately.
10637
        //
10638
        // Unless the scope is dependent, it's always an error if qualified
10639
        // redeclaration lookup found nothing at all. Diagnose that now;
10640
        // nothing will diagnose that error later.
10641
0
        if (isFriend &&
10642
0
            (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10643
0
             (!Previous.empty() && CurContext->isDependentContext()))) {
10644
          // ignore these
10645
0
        } else if (NewFD->isCPUDispatchMultiVersion() ||
10646
0
                   NewFD->isCPUSpecificMultiVersion()) {
10647
          // ignore this, we allow the redeclaration behavior here to create new
10648
          // versions of the function.
10649
0
        } else {
10650
          // The user tried to provide an out-of-line definition for a
10651
          // function that is a member of a class or namespace, but there
10652
          // was no such member function declared (C++ [class.mfct]p2,
10653
          // C++ [namespace.memdef]p2). For example:
10654
          //
10655
          // class X {
10656
          //   void f() const;
10657
          // };
10658
          //
10659
          // void X::f() { } // ill-formed
10660
          //
10661
          // Complain about this problem, and attempt to suggest close
10662
          // matches (e.g., those that differ only in cv-qualifiers and
10663
          // whether the parameter types are references).
10664
10665
0
          if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10666
0
                  *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10667
0
            AddToScope = ExtraArgs.AddToScope;
10668
0
            return Result;
10669
0
          }
10670
0
        }
10671
10672
        // Unqualified local friend declarations are required to resolve
10673
        // to something.
10674
0
      } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10675
0
        if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10676
0
                *this, Previous, NewFD, ExtraArgs, true, S)) {
10677
0
          AddToScope = ExtraArgs.AddToScope;
10678
0
          return Result;
10679
0
        }
10680
0
      }
10681
0
    } else if (!D.isFunctionDefinition() &&
10682
0
               isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10683
0
               !isFriend && !isFunctionTemplateSpecialization &&
10684
0
               !isMemberSpecialization) {
10685
      // An out-of-line member function declaration must also be a
10686
      // definition (C++ [class.mfct]p2).
10687
      // Note that this is not the case for explicit specializations of
10688
      // function templates or member functions of class templates, per
10689
      // C++ [temp.expl.spec]p2. We also allow these declarations as an
10690
      // extension for compatibility with old SWIG code which likes to
10691
      // generate them.
10692
0
      Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10693
0
        << D.getCXXScopeSpec().getRange();
10694
0
    }
10695
1
  }
10696
10697
19
  if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10698
    // Any top level function could potentially be specified as an entry.
10699
0
    if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10700
0
      ActOnHLSLTopLevelFunction(NewFD);
10701
10702
0
    if (NewFD->hasAttr<HLSLShaderAttr>())
10703
0
      CheckHLSLEntryPoint(NewFD);
10704
0
  }
10705
10706
  // If this is the first declaration of a library builtin function, add
10707
  // attributes as appropriate.
10708
19
  if (!D.isRedeclaration()) {
10709
14
    if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10710
14
      if (unsigned BuiltinID = II->getBuiltinID()) {
10711
0
        bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10712
0
        if (!InStdNamespace &&
10713
0
            NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10714
0
          if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10715
            // Validate the type matches unless this builtin is specified as
10716
            // matching regardless of its declared type.
10717
0
            if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10718
0
              NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10719
0
            } else {
10720
0
              ASTContext::GetBuiltinTypeError Error;
10721
0
              LookupNecessaryTypesForBuiltin(S, BuiltinID);
10722
0
              QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10723
10724
0
              if (!Error && !BuiltinType.isNull() &&
10725
0
                  Context.hasSameFunctionTypeIgnoringExceptionSpec(
10726
0
                      NewFD->getType(), BuiltinType))
10727
0
                NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10728
0
            }
10729
0
          }
10730
0
        } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10731
0
                   isStdBuiltin(Context, NewFD, BuiltinID)) {
10732
0
          NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10733
0
        }
10734
0
      }
10735
14
    }
10736
14
  }
10737
10738
19
  ProcessPragmaWeak(S, NewFD);
10739
19
  checkAttributesAfterMerging(*this, *NewFD);
10740
10741
19
  AddKnownFunctionAttributes(NewFD);
10742
10743
19
  if (NewFD->hasAttr<OverloadableAttr>() &&
10744
19
      !NewFD->getType()->getAs<FunctionProtoType>()) {
10745
0
    Diag(NewFD->getLocation(),
10746
0
         diag::err_attribute_overloadable_no_prototype)
10747
0
      << NewFD;
10748
0
    NewFD->dropAttr<OverloadableAttr>();
10749
0
  }
10750
10751
  // If there's a #pragma GCC visibility in scope, and this isn't a class
10752
  // member, set the visibility of this function.
10753
19
  if (!DC->isRecord() && NewFD->isExternallyVisible())
10754
19
    AddPushedVisibilityAttribute(NewFD);
10755
10756
  // If there's a #pragma clang arc_cf_code_audited in scope, consider
10757
  // marking the function.
10758
19
  AddCFAuditedAttribute(NewFD);
10759
10760
  // If this is a function definition, check if we have to apply any
10761
  // attributes (i.e. optnone and no_builtin) due to a pragma.
10762
19
  if (D.isFunctionDefinition()) {
10763
0
    AddRangeBasedOptnone(NewFD);
10764
0
    AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10765
0
    AddSectionMSAllocText(NewFD);
10766
0
    ModifyFnAttributesMSPragmaOptimize(NewFD);
10767
0
  }
10768
10769
  // If this is the first declaration of an extern C variable, update
10770
  // the map of such variables.
10771
19
  if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10772
19
      isIncompleteDeclExternC(*this, NewFD))
10773
6
    RegisterLocallyScopedExternCDecl(NewFD, S);
10774
10775
  // Set this FunctionDecl's range up to the right paren.
10776
19
  NewFD->setRangeEnd(D.getSourceRange().getEnd());
10777
10778
19
  if (D.isRedeclaration() && !Previous.empty()) {
10779
5
    NamedDecl *Prev = Previous.getRepresentativeDecl();
10780
5
    checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10781
5
                                   isMemberSpecialization ||
10782
5
                                       isFunctionTemplateSpecialization,
10783
5
                                   D.isFunctionDefinition());
10784
5
  }
10785
10786
19
  if (getLangOpts().CUDA) {
10787
0
    IdentifierInfo *II = NewFD->getIdentifier();
10788
0
    if (II && II->isStr(getCudaConfigureFuncName()) &&
10789
0
        !NewFD->isInvalidDecl() &&
10790
0
        NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10791
0
      if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10792
0
        Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10793
0
            << getCudaConfigureFuncName();
10794
0
      Context.setcudaConfigureCallDecl(NewFD);
10795
0
    }
10796
10797
    // Variadic functions, other than a *declaration* of printf, are not allowed
10798
    // in device-side CUDA code, unless someone passed
10799
    // -fcuda-allow-variadic-functions.
10800
0
    if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10801
0
        (NewFD->hasAttr<CUDADeviceAttr>() ||
10802
0
         NewFD->hasAttr<CUDAGlobalAttr>()) &&
10803
0
        !(II && II->isStr("printf") && NewFD->isExternC() &&
10804
0
          !D.isFunctionDefinition())) {
10805
0
      Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10806
0
    }
10807
0
  }
10808
10809
19
  MarkUnusedFileScopedDecl(NewFD);
10810
10811
10812
10813
19
  if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10814
    // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10815
0
    if (SC == SC_Static) {
10816
0
      Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10817
0
      D.setInvalidType();
10818
0
    }
10819
10820
    // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10821
0
    if (!NewFD->getReturnType()->isVoidType()) {
10822
0
      SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10823
0
      Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10824
0
          << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10825
0
                                : FixItHint());
10826
0
      D.setInvalidType();
10827
0
    }
10828
10829
0
    llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10830
0
    for (auto *Param : NewFD->parameters())
10831
0
      checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10832
10833
0
    if (getLangOpts().OpenCLCPlusPlus) {
10834
0
      if (DC->isRecord()) {
10835
0
        Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10836
0
        D.setInvalidType();
10837
0
      }
10838
0
      if (FunctionTemplate) {
10839
0
        Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10840
0
        D.setInvalidType();
10841
0
      }
10842
0
    }
10843
0
  }
10844
10845
19
  if (getLangOpts().CPlusPlus) {
10846
    // Precalculate whether this is a friend function template with a constraint
10847
    // that depends on an enclosing template, per [temp.friend]p9.
10848
1
    if (isFriend && FunctionTemplate &&
10849
1
        FriendConstraintsDependOnEnclosingTemplate(NewFD)) {
10850
0
      NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10851
10852
      // C++ [temp.friend]p9:
10853
      //    A friend function template with a constraint that depends on a
10854
      //    template parameter from an enclosing template shall be a definition.
10855
0
      if (!D.isFunctionDefinition()) {
10856
0
        Diag(NewFD->getBeginLoc(),
10857
0
             diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10858
0
        NewFD->setInvalidDecl();
10859
0
      }
10860
0
    }
10861
10862
1
    if (FunctionTemplate) {
10863
0
      if (NewFD->isInvalidDecl())
10864
0
        FunctionTemplate->setInvalidDecl();
10865
0
      return FunctionTemplate;
10866
0
    }
10867
10868
1
    if (isMemberSpecialization && !NewFD->isInvalidDecl())
10869
0
      CompleteMemberSpecialization(NewFD, Previous);
10870
1
  }
10871
10872
19
  for (const ParmVarDecl *Param : NewFD->parameters()) {
10873
9
    QualType PT = Param->getType();
10874
10875
    // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10876
    // types.
10877
9
    if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10878
0
      if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10879
0
        QualType ElemTy = PipeTy->getElementType();
10880
0
          if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10881
0
            Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10882
0
            D.setInvalidType();
10883
0
          }
10884
0
      }
10885
0
    }
10886
    // WebAssembly tables can't be used as function parameters.
10887
9
    if (Context.getTargetInfo().getTriple().isWasm()) {
10888
0
      if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
10889
0
        Diag(Param->getTypeSpecStartLoc(),
10890
0
             diag::err_wasm_table_as_function_parameter);
10891
0
        D.setInvalidType();
10892
0
      }
10893
0
    }
10894
9
  }
10895
10896
  // Diagnose availability attributes. Availability cannot be used on functions
10897
  // that are run during load/unload.
10898
19
  if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10899
0
    if (NewFD->hasAttr<ConstructorAttr>()) {
10900
0
      Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10901
0
          << 1;
10902
0
      NewFD->dropAttr<AvailabilityAttr>();
10903
0
    }
10904
0
    if (NewFD->hasAttr<DestructorAttr>()) {
10905
0
      Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10906
0
          << 2;
10907
0
      NewFD->dropAttr<AvailabilityAttr>();
10908
0
    }
10909
0
  }
10910
10911
  // Diagnose no_builtin attribute on function declaration that are not a
10912
  // definition.
10913
  // FIXME: We should really be doing this in
10914
  // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10915
  // the FunctionDecl and at this point of the code
10916
  // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10917
  // because Sema::ActOnStartOfFunctionDef has not been called yet.
10918
19
  if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10919
0
    switch (D.getFunctionDefinitionKind()) {
10920
0
    case FunctionDefinitionKind::Defaulted:
10921
0
    case FunctionDefinitionKind::Deleted:
10922
0
      Diag(NBA->getLocation(),
10923
0
           diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10924
0
          << NBA->getSpelling();
10925
0
      break;
10926
0
    case FunctionDefinitionKind::Declaration:
10927
0
      Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10928
0
          << NBA->getSpelling();
10929
0
      break;
10930
0
    case FunctionDefinitionKind::Definition:
10931
0
      break;
10932
0
    }
10933
10934
19
  return NewFD;
10935
19
}
10936
10937
/// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10938
/// when __declspec(code_seg) "is applied to a class, all member functions of
10939
/// the class and nested classes -- this includes compiler-generated special
10940
/// member functions -- are put in the specified segment."
10941
/// The actual behavior is a little more complicated. The Microsoft compiler
10942
/// won't check outer classes if there is an active value from #pragma code_seg.
10943
/// The CodeSeg is always applied from the direct parent but only from outer
10944
/// classes when the #pragma code_seg stack is empty. See:
10945
/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10946
/// available since MS has removed the page.
10947
19
static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10948
19
  const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10949
19
  if (!Method)
10950
19
    return nullptr;
10951
0
  const CXXRecordDecl *Parent = Method->getParent();
10952
0
  if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10953
0
    Attr *NewAttr = SAttr->clone(S.getASTContext());
10954
0
    NewAttr->setImplicit(true);
10955
0
    return NewAttr;
10956
0
  }
10957
10958
  // The Microsoft compiler won't check outer classes for the CodeSeg
10959
  // when the #pragma code_seg stack is active.
10960
0
  if (S.CodeSegStack.CurrentValue)
10961
0
   return nullptr;
10962
10963
0
  while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10964
0
    if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10965
0
      Attr *NewAttr = SAttr->clone(S.getASTContext());
10966
0
      NewAttr->setImplicit(true);
10967
0
      return NewAttr;
10968
0
    }
10969
0
  }
10970
0
  return nullptr;
10971
0
}
10972
10973
/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10974
/// containing class. Otherwise it will return implicit SectionAttr if the
10975
/// function is a definition and there is an active value on CodeSegStack
10976
/// (from the current #pragma code-seg value).
10977
///
10978
/// \param FD Function being declared.
10979
/// \param IsDefinition Whether it is a definition or just a declaration.
10980
/// \returns A CodeSegAttr or SectionAttr to apply to the function or
10981
///          nullptr if no attribute should be added.
10982
Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10983
19
                                                       bool IsDefinition) {
10984
19
  if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10985
0
    return A;
10986
19
  if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10987
19
      CodeSegStack.CurrentValue)
10988
0
    return SectionAttr::CreateImplicit(
10989
0
        getASTContext(), CodeSegStack.CurrentValue->getString(),
10990
0
        CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
10991
19
  return nullptr;
10992
19
}
10993
10994
/// Determines if we can perform a correct type check for \p D as a
10995
/// redeclaration of \p PrevDecl. If not, we can generally still perform a
10996
/// best-effort check.
10997
///
10998
/// \param NewD The new declaration.
10999
/// \param OldD The old declaration.
11000
/// \param NewT The portion of the type of the new declaration to check.
11001
/// \param OldT The portion of the type of the old declaration to check.
11002
bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11003
0
                                          QualType NewT, QualType OldT) {
11004
0
  if (!NewD->getLexicalDeclContext()->isDependentContext())
11005
0
    return true;
11006
11007
  // For dependently-typed local extern declarations and friends, we can't
11008
  // perform a correct type check in general until instantiation:
11009
  //
11010
  //   int f();
11011
  //   template<typename T> void g() { T f(); }
11012
  //
11013
  // (valid if g() is only instantiated with T = int).
11014
0
  if (NewT->isDependentType() &&
11015
0
      (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11016
0
    return false;
11017
11018
  // Similarly, if the previous declaration was a dependent local extern
11019
  // declaration, we don't really know its type yet.
11020
0
  if (OldT->isDependentType() && OldD->isLocalExternDecl())
11021
0
    return false;
11022
11023
0
  return true;
11024
0
}
11025
11026
/// Checks if the new declaration declared in dependent context must be
11027
/// put in the same redeclaration chain as the specified declaration.
11028
///
11029
/// \param D Declaration that is checked.
11030
/// \param PrevDecl Previous declaration found with proper lookup method for the
11031
///                 same declaration name.
11032
/// \returns True if D must be added to the redeclaration chain which PrevDecl
11033
///          belongs to.
11034
///
11035
0
bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11036
0
  if (!D->getLexicalDeclContext()->isDependentContext())
11037
0
    return true;
11038
11039
  // Don't chain dependent friend function definitions until instantiation, to
11040
  // permit cases like
11041
  //
11042
  //   void func();
11043
  //   template<typename T> class C1 { friend void func() {} };
11044
  //   template<typename T> class C2 { friend void func() {} };
11045
  //
11046
  // ... which is valid if only one of C1 and C2 is ever instantiated.
11047
  //
11048
  // FIXME: This need only apply to function definitions. For now, we proxy
11049
  // this by checking for a file-scope function. We do not want this to apply
11050
  // to friend declarations nominating member functions, because that gets in
11051
  // the way of access checks.
11052
0
  if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11053
0
    return false;
11054
11055
0
  auto *VD = dyn_cast<ValueDecl>(D);
11056
0
  auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11057
0
  return !VD || !PrevVD ||
11058
0
         canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11059
0
                                        PrevVD->getType());
11060
0
}
11061
11062
/// Check the target or target_version attribute of the function for
11063
/// MultiVersion validity.
11064
///
11065
/// Returns true if there was an error, false otherwise.
11066
0
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11067
0
  const auto *TA = FD->getAttr<TargetAttr>();
11068
0
  const auto *TVA = FD->getAttr<TargetVersionAttr>();
11069
0
  assert(
11070
0
      (TA || TVA) &&
11071
0
      "MultiVersion candidate requires a target or target_version attribute");
11072
0
  const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11073
0
  enum ErrType { Feature = 0, Architecture = 1 };
11074
11075
0
  if (TA) {
11076
0
    ParsedTargetAttr ParseInfo =
11077
0
        S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11078
0
    if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11079
0
      S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11080
0
          << Architecture << ParseInfo.CPU;
11081
0
      return true;
11082
0
    }
11083
0
    for (const auto &Feat : ParseInfo.Features) {
11084
0
      auto BareFeat = StringRef{Feat}.substr(1);
11085
0
      if (Feat[0] == '-') {
11086
0
        S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11087
0
            << Feature << ("no-" + BareFeat).str();
11088
0
        return true;
11089
0
      }
11090
11091
0
      if (!TargetInfo.validateCpuSupports(BareFeat) ||
11092
0
          !TargetInfo.isValidFeatureName(BareFeat)) {
11093
0
        S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11094
0
            << Feature << BareFeat;
11095
0
        return true;
11096
0
      }
11097
0
    }
11098
0
  }
11099
11100
0
  if (TVA) {
11101
0
    llvm::SmallVector<StringRef, 8> Feats;
11102
0
    TVA->getFeatures(Feats);
11103
0
    for (const auto &Feat : Feats) {
11104
0
      if (!TargetInfo.validateCpuSupports(Feat)) {
11105
0
        S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11106
0
            << Feature << Feat;
11107
0
        return true;
11108
0
      }
11109
0
    }
11110
0
  }
11111
0
  return false;
11112
0
}
11113
11114
// Provide a white-list of attributes that are allowed to be combined with
11115
// multiversion functions.
11116
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11117
0
                                           MultiVersionKind MVKind) {
11118
  // Note: this list/diagnosis must match the list in
11119
  // checkMultiversionAttributesAllSame.
11120
0
  switch (Kind) {
11121
0
  default:
11122
0
    return false;
11123
0
  case attr::Used:
11124
0
    return MVKind == MultiVersionKind::Target;
11125
0
  case attr::NonNull:
11126
0
  case attr::NoThrow:
11127
0
    return true;
11128
0
  }
11129
0
}
11130
11131
static bool checkNonMultiVersionCompatAttributes(Sema &S,
11132
                                                 const FunctionDecl *FD,
11133
                                                 const FunctionDecl *CausedFD,
11134
0
                                                 MultiVersionKind MVKind) {
11135
0
  const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11136
0
    S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11137
0
        << static_cast<unsigned>(MVKind) << A;
11138
0
    if (CausedFD)
11139
0
      S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11140
0
    return true;
11141
0
  };
11142
11143
0
  for (const Attr *A : FD->attrs()) {
11144
0
    switch (A->getKind()) {
11145
0
    case attr::CPUDispatch:
11146
0
    case attr::CPUSpecific:
11147
0
      if (MVKind != MultiVersionKind::CPUDispatch &&
11148
0
          MVKind != MultiVersionKind::CPUSpecific)
11149
0
        return Diagnose(S, A);
11150
0
      break;
11151
0
    case attr::Target:
11152
0
      if (MVKind != MultiVersionKind::Target)
11153
0
        return Diagnose(S, A);
11154
0
      break;
11155
0
    case attr::TargetVersion:
11156
0
      if (MVKind != MultiVersionKind::TargetVersion)
11157
0
        return Diagnose(S, A);
11158
0
      break;
11159
0
    case attr::TargetClones:
11160
0
      if (MVKind != MultiVersionKind::TargetClones)
11161
0
        return Diagnose(S, A);
11162
0
      break;
11163
0
    default:
11164
0
      if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11165
0
        return Diagnose(S, A);
11166
0
      break;
11167
0
    }
11168
0
  }
11169
0
  return false;
11170
0
}
11171
11172
bool Sema::areMultiversionVariantFunctionsCompatible(
11173
    const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11174
    const PartialDiagnostic &NoProtoDiagID,
11175
    const PartialDiagnosticAt &NoteCausedDiagIDAt,
11176
    const PartialDiagnosticAt &NoSupportDiagIDAt,
11177
    const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11178
0
    bool ConstexprSupported, bool CLinkageMayDiffer) {
11179
0
  enum DoesntSupport {
11180
0
    FuncTemplates = 0,
11181
0
    VirtFuncs = 1,
11182
0
    DeducedReturn = 2,
11183
0
    Constructors = 3,
11184
0
    Destructors = 4,
11185
0
    DeletedFuncs = 5,
11186
0
    DefaultedFuncs = 6,
11187
0
    ConstexprFuncs = 7,
11188
0
    ConstevalFuncs = 8,
11189
0
    Lambda = 9,
11190
0
  };
11191
0
  enum Different {
11192
0
    CallingConv = 0,
11193
0
    ReturnType = 1,
11194
0
    ConstexprSpec = 2,
11195
0
    InlineSpec = 3,
11196
0
    Linkage = 4,
11197
0
    LanguageLinkage = 5,
11198
0
  };
11199
11200
0
  if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11201
0
      !OldFD->getType()->getAs<FunctionProtoType>()) {
11202
0
    Diag(OldFD->getLocation(), NoProtoDiagID);
11203
0
    Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11204
0
    return true;
11205
0
  }
11206
11207
0
  if (NoProtoDiagID.getDiagID() != 0 &&
11208
0
      !NewFD->getType()->getAs<FunctionProtoType>())
11209
0
    return Diag(NewFD->getLocation(), NoProtoDiagID);
11210
11211
0
  if (!TemplatesSupported &&
11212
0
      NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11213
0
    return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11214
0
           << FuncTemplates;
11215
11216
0
  if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11217
0
    if (NewCXXFD->isVirtual())
11218
0
      return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11219
0
             << VirtFuncs;
11220
11221
0
    if (isa<CXXConstructorDecl>(NewCXXFD))
11222
0
      return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11223
0
             << Constructors;
11224
11225
0
    if (isa<CXXDestructorDecl>(NewCXXFD))
11226
0
      return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11227
0
             << Destructors;
11228
0
  }
11229
11230
0
  if (NewFD->isDeleted())
11231
0
    return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11232
0
           << DeletedFuncs;
11233
11234
0
  if (NewFD->isDefaulted())
11235
0
    return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11236
0
           << DefaultedFuncs;
11237
11238
0
  if (!ConstexprSupported && NewFD->isConstexpr())
11239
0
    return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11240
0
           << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11241
11242
0
  QualType NewQType = Context.getCanonicalType(NewFD->getType());
11243
0
  const auto *NewType = cast<FunctionType>(NewQType);
11244
0
  QualType NewReturnType = NewType->getReturnType();
11245
11246
0
  if (NewReturnType->isUndeducedType())
11247
0
    return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11248
0
           << DeducedReturn;
11249
11250
  // Ensure the return type is identical.
11251
0
  if (OldFD) {
11252
0
    QualType OldQType = Context.getCanonicalType(OldFD->getType());
11253
0
    const auto *OldType = cast<FunctionType>(OldQType);
11254
0
    FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11255
0
    FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11256
11257
0
    if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11258
0
      return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11259
11260
0
    QualType OldReturnType = OldType->getReturnType();
11261
11262
0
    if (OldReturnType != NewReturnType)
11263
0
      return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11264
11265
0
    if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11266
0
      return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11267
11268
0
    if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11269
0
      return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11270
11271
0
    if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11272
0
      return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11273
11274
0
    if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11275
0
      return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11276
11277
0
    if (CheckEquivalentExceptionSpec(
11278
0
            OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11279
0
            NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11280
0
      return true;
11281
0
  }
11282
0
  return false;
11283
0
}
11284
11285
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11286
                                             const FunctionDecl *NewFD,
11287
                                             bool CausesMV,
11288
0
                                             MultiVersionKind MVKind) {
11289
0
  if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11290
0
    S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11291
0
    if (OldFD)
11292
0
      S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11293
0
    return true;
11294
0
  }
11295
11296
0
  bool IsCPUSpecificCPUDispatchMVKind =
11297
0
      MVKind == MultiVersionKind::CPUDispatch ||
11298
0
      MVKind == MultiVersionKind::CPUSpecific;
11299
11300
0
  if (CausesMV && OldFD &&
11301
0
      checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11302
0
    return true;
11303
11304
0
  if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11305
0
    return true;
11306
11307
  // Only allow transition to MultiVersion if it hasn't been used.
11308
0
  if (OldFD && CausesMV && OldFD->isUsed(false))
11309
0
    return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11310
11311
0
  return S.areMultiversionVariantFunctionsCompatible(
11312
0
      OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11313
0
      PartialDiagnosticAt(NewFD->getLocation(),
11314
0
                          S.PDiag(diag::note_multiversioning_caused_here)),
11315
0
      PartialDiagnosticAt(NewFD->getLocation(),
11316
0
                          S.PDiag(diag::err_multiversion_doesnt_support)
11317
0
                              << static_cast<unsigned>(MVKind)),
11318
0
      PartialDiagnosticAt(NewFD->getLocation(),
11319
0
                          S.PDiag(diag::err_multiversion_diff)),
11320
0
      /*TemplatesSupported=*/false,
11321
0
      /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11322
0
      /*CLinkageMayDiffer=*/false);
11323
0
}
11324
11325
/// Check the validity of a multiversion function declaration that is the
11326
/// first of its kind. Also sets the multiversion'ness' of the function itself.
11327
///
11328
/// This sets NewFD->isInvalidDecl() to true if there was an error.
11329
///
11330
/// Returns true if there was an error, false otherwise.
11331
0
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11332
0
  MultiVersionKind MVKind = FD->getMultiVersionKind();
11333
0
  assert(MVKind != MultiVersionKind::None &&
11334
0
         "Function lacks multiversion attribute");
11335
0
  const auto *TA = FD->getAttr<TargetAttr>();
11336
0
  const auto *TVA = FD->getAttr<TargetVersionAttr>();
11337
  // Target and target_version only causes MV if it is default, otherwise this
11338
  // is a normal function.
11339
0
  if ((TA && !TA->isDefaultVersion()) || (TVA && !TVA->isDefaultVersion()))
11340
0
    return false;
11341
11342
0
  if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11343
0
    FD->setInvalidDecl();
11344
0
    return true;
11345
0
  }
11346
11347
0
  if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11348
0
    FD->setInvalidDecl();
11349
0
    return true;
11350
0
  }
11351
11352
0
  FD->setIsMultiVersion();
11353
0
  return false;
11354
0
}
11355
11356
0
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11357
0
  for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11358
0
    if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11359
0
      return true;
11360
0
  }
11361
11362
0
  return false;
11363
0
}
11364
11365
static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11366
                                             FunctionDecl *NewFD,
11367
                                             bool &Redeclaration,
11368
                                             NamedDecl *&OldDecl,
11369
0
                                             LookupResult &Previous) {
11370
0
  const auto *NewTA = NewFD->getAttr<TargetAttr>();
11371
0
  const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11372
0
  const auto *OldTA = OldFD->getAttr<TargetAttr>();
11373
0
  const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11374
  // If the old decl is NOT MultiVersioned yet, and we don't cause that
11375
  // to change, this is a simple redeclaration.
11376
0
  if ((NewTA && !NewTA->isDefaultVersion() &&
11377
0
       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
11378
0
      (NewTVA && !NewTVA->isDefaultVersion() &&
11379
0
       (!OldTVA || OldTVA->getName() == NewTVA->getName())))
11380
0
    return false;
11381
11382
  // Otherwise, this decl causes MultiVersioning.
11383
0
  if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11384
0
                                       NewTVA ? MultiVersionKind::TargetVersion
11385
0
                                              : MultiVersionKind::Target)) {
11386
0
    NewFD->setInvalidDecl();
11387
0
    return true;
11388
0
  }
11389
11390
0
  if (CheckMultiVersionValue(S, NewFD)) {
11391
0
    NewFD->setInvalidDecl();
11392
0
    return true;
11393
0
  }
11394
11395
  // If this is 'default', permit the forward declaration.
11396
0
  if (!OldFD->isMultiVersion() &&
11397
0
      ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11398
0
       (NewTVA && NewTVA->isDefaultVersion() && !OldTVA))) {
11399
0
    Redeclaration = true;
11400
0
    OldDecl = OldFD;
11401
0
    OldFD->setIsMultiVersion();
11402
0
    NewFD->setIsMultiVersion();
11403
0
    return false;
11404
0
  }
11405
11406
0
  if (CheckMultiVersionValue(S, OldFD)) {
11407
0
    S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11408
0
    NewFD->setInvalidDecl();
11409
0
    return true;
11410
0
  }
11411
11412
0
  if (NewTA) {
11413
0
    ParsedTargetAttr OldParsed =
11414
0
        S.getASTContext().getTargetInfo().parseTargetAttr(
11415
0
            OldTA->getFeaturesStr());
11416
0
    llvm::sort(OldParsed.Features);
11417
0
    ParsedTargetAttr NewParsed =
11418
0
        S.getASTContext().getTargetInfo().parseTargetAttr(
11419
0
            NewTA->getFeaturesStr());
11420
    // Sort order doesn't matter, it just needs to be consistent.
11421
0
    llvm::sort(NewParsed.Features);
11422
0
    if (OldParsed == NewParsed) {
11423
0
      S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11424
0
      S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11425
0
      NewFD->setInvalidDecl();
11426
0
      return true;
11427
0
    }
11428
0
  }
11429
11430
0
  if (NewTVA) {
11431
0
    llvm::SmallVector<StringRef, 8> Feats;
11432
0
    OldTVA->getFeatures(Feats);
11433
0
    llvm::sort(Feats);
11434
0
    llvm::SmallVector<StringRef, 8> NewFeats;
11435
0
    NewTVA->getFeatures(NewFeats);
11436
0
    llvm::sort(NewFeats);
11437
11438
0
    if (Feats == NewFeats) {
11439
0
      S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11440
0
      S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11441
0
      NewFD->setInvalidDecl();
11442
0
      return true;
11443
0
    }
11444
0
  }
11445
11446
0
  for (const auto *FD : OldFD->redecls()) {
11447
0
    const auto *CurTA = FD->getAttr<TargetAttr>();
11448
0
    const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11449
    // We allow forward declarations before ANY multiversioning attributes, but
11450
    // nothing after the fact.
11451
0
    if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11452
0
        ((NewTA && (!CurTA || CurTA->isInherited())) ||
11453
0
         (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11454
0
      S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11455
0
          << (NewTA ? 0 : 2);
11456
0
      S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11457
0
      NewFD->setInvalidDecl();
11458
0
      return true;
11459
0
    }
11460
0
  }
11461
11462
0
  OldFD->setIsMultiVersion();
11463
0
  NewFD->setIsMultiVersion();
11464
0
  Redeclaration = false;
11465
0
  OldDecl = nullptr;
11466
0
  Previous.clear();
11467
0
  return false;
11468
0
}
11469
11470
static bool MultiVersionTypesCompatible(MultiVersionKind Old,
11471
0
                                        MultiVersionKind New) {
11472
0
  if (Old == New || Old == MultiVersionKind::None ||
11473
0
      New == MultiVersionKind::None)
11474
0
    return true;
11475
11476
0
  return (Old == MultiVersionKind::CPUDispatch &&
11477
0
          New == MultiVersionKind::CPUSpecific) ||
11478
0
         (Old == MultiVersionKind::CPUSpecific &&
11479
0
          New == MultiVersionKind::CPUDispatch);
11480
0
}
11481
11482
/// Check the validity of a new function declaration being added to an existing
11483
/// multiversioned declaration collection.
11484
static bool CheckMultiVersionAdditionalDecl(
11485
    Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11486
    MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp,
11487
    const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones,
11488
0
    bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
11489
0
  const auto *NewTA = NewFD->getAttr<TargetAttr>();
11490
0
  const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11491
0
  MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11492
  // Disallow mixing of multiversioning types.
11493
0
  if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
11494
0
    S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11495
0
    S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11496
0
    NewFD->setInvalidDecl();
11497
0
    return true;
11498
0
  }
11499
11500
0
  ParsedTargetAttr NewParsed;
11501
0
  if (NewTA) {
11502
0
    NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11503
0
        NewTA->getFeaturesStr());
11504
0
    llvm::sort(NewParsed.Features);
11505
0
  }
11506
0
  llvm::SmallVector<StringRef, 8> NewFeats;
11507
0
  if (NewTVA) {
11508
0
    NewTVA->getFeatures(NewFeats);
11509
0
    llvm::sort(NewFeats);
11510
0
  }
11511
11512
0
  bool UseMemberUsingDeclRules =
11513
0
      S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11514
11515
0
  bool MayNeedOverloadableChecks =
11516
0
      AllowOverloadingOfFunction(Previous, S.Context, NewFD);
11517
11518
  // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11519
  // of a previous member of the MultiVersion set.
11520
0
  for (NamedDecl *ND : Previous) {
11521
0
    FunctionDecl *CurFD = ND->getAsFunction();
11522
0
    if (!CurFD || CurFD->isInvalidDecl())
11523
0
      continue;
11524
0
    if (MayNeedOverloadableChecks &&
11525
0
        S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11526
0
      continue;
11527
11528
0
    if (NewMVKind == MultiVersionKind::None &&
11529
0
        OldMVKind == MultiVersionKind::TargetVersion) {
11530
0
      NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11531
0
          S.Context, "default", NewFD->getSourceRange()));
11532
0
      NewFD->setIsMultiVersion();
11533
0
      NewMVKind = MultiVersionKind::TargetVersion;
11534
0
      if (!NewTVA) {
11535
0
        NewTVA = NewFD->getAttr<TargetVersionAttr>();
11536
0
        NewTVA->getFeatures(NewFeats);
11537
0
        llvm::sort(NewFeats);
11538
0
      }
11539
0
    }
11540
11541
0
    switch (NewMVKind) {
11542
0
    case MultiVersionKind::None:
11543
0
      assert(OldMVKind == MultiVersionKind::TargetClones &&
11544
0
             "Only target_clones can be omitted in subsequent declarations");
11545
0
      break;
11546
0
    case MultiVersionKind::Target: {
11547
0
      const auto *CurTA = CurFD->getAttr<TargetAttr>();
11548
0
      if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11549
0
        NewFD->setIsMultiVersion();
11550
0
        Redeclaration = true;
11551
0
        OldDecl = ND;
11552
0
        return false;
11553
0
      }
11554
11555
0
      ParsedTargetAttr CurParsed =
11556
0
          S.getASTContext().getTargetInfo().parseTargetAttr(
11557
0
              CurTA->getFeaturesStr());
11558
0
      llvm::sort(CurParsed.Features);
11559
0
      if (CurParsed == NewParsed) {
11560
0
        S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11561
0
        S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11562
0
        NewFD->setInvalidDecl();
11563
0
        return true;
11564
0
      }
11565
0
      break;
11566
0
    }
11567
0
    case MultiVersionKind::TargetVersion: {
11568
0
      const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>();
11569
0
      if (CurTVA->getName() == NewTVA->getName()) {
11570
0
        NewFD->setIsMultiVersion();
11571
0
        Redeclaration = true;
11572
0
        OldDecl = ND;
11573
0
        return false;
11574
0
      }
11575
0
      llvm::SmallVector<StringRef, 8> CurFeats;
11576
0
      if (CurTVA) {
11577
0
        CurTVA->getFeatures(CurFeats);
11578
0
        llvm::sort(CurFeats);
11579
0
      }
11580
0
      if (CurFeats == NewFeats) {
11581
0
        S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11582
0
        S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11583
0
        NewFD->setInvalidDecl();
11584
0
        return true;
11585
0
      }
11586
0
      break;
11587
0
    }
11588
0
    case MultiVersionKind::TargetClones: {
11589
0
      const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
11590
0
      Redeclaration = true;
11591
0
      OldDecl = CurFD;
11592
0
      NewFD->setIsMultiVersion();
11593
11594
0
      if (CurClones && NewClones &&
11595
0
          (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11596
0
           !std::equal(CurClones->featuresStrs_begin(),
11597
0
                       CurClones->featuresStrs_end(),
11598
0
                       NewClones->featuresStrs_begin()))) {
11599
0
        S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11600
0
        S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11601
0
        NewFD->setInvalidDecl();
11602
0
        return true;
11603
0
      }
11604
11605
0
      return false;
11606
0
    }
11607
0
    case MultiVersionKind::CPUSpecific:
11608
0
    case MultiVersionKind::CPUDispatch: {
11609
0
      const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11610
0
      const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11611
      // Handle CPUDispatch/CPUSpecific versions.
11612
      // Only 1 CPUDispatch function is allowed, this will make it go through
11613
      // the redeclaration errors.
11614
0
      if (NewMVKind == MultiVersionKind::CPUDispatch &&
11615
0
          CurFD->hasAttr<CPUDispatchAttr>()) {
11616
0
        if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11617
0
            std::equal(
11618
0
                CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11619
0
                NewCPUDisp->cpus_begin(),
11620
0
                [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11621
0
                  return Cur->getName() == New->getName();
11622
0
                })) {
11623
0
          NewFD->setIsMultiVersion();
11624
0
          Redeclaration = true;
11625
0
          OldDecl = ND;
11626
0
          return false;
11627
0
        }
11628
11629
        // If the declarations don't match, this is an error condition.
11630
0
        S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11631
0
        S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11632
0
        NewFD->setInvalidDecl();
11633
0
        return true;
11634
0
      }
11635
0
      if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11636
0
        if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11637
0
            std::equal(
11638
0
                CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11639
0
                NewCPUSpec->cpus_begin(),
11640
0
                [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11641
0
                  return Cur->getName() == New->getName();
11642
0
                })) {
11643
0
          NewFD->setIsMultiVersion();
11644
0
          Redeclaration = true;
11645
0
          OldDecl = ND;
11646
0
          return false;
11647
0
        }
11648
11649
        // Only 1 version of CPUSpecific is allowed for each CPU.
11650
0
        for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11651
0
          for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11652
0
            if (CurII == NewII) {
11653
0
              S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11654
0
                  << NewII;
11655
0
              S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11656
0
              NewFD->setInvalidDecl();
11657
0
              return true;
11658
0
            }
11659
0
          }
11660
0
        }
11661
0
      }
11662
0
      break;
11663
0
    }
11664
0
    }
11665
0
  }
11666
11667
  // Else, this is simply a non-redecl case.  Checking the 'value' is only
11668
  // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11669
  // handled in the attribute adding step.
11670
0
  if ((NewMVKind == MultiVersionKind::TargetVersion ||
11671
0
       NewMVKind == MultiVersionKind::Target) &&
11672
0
      CheckMultiVersionValue(S, NewFD)) {
11673
0
    NewFD->setInvalidDecl();
11674
0
    return true;
11675
0
  }
11676
11677
0
  if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11678
0
                                       !OldFD->isMultiVersion(), NewMVKind)) {
11679
0
    NewFD->setInvalidDecl();
11680
0
    return true;
11681
0
  }
11682
11683
  // Permit forward declarations in the case where these two are compatible.
11684
0
  if (!OldFD->isMultiVersion()) {
11685
0
    OldFD->setIsMultiVersion();
11686
0
    NewFD->setIsMultiVersion();
11687
0
    Redeclaration = true;
11688
0
    OldDecl = OldFD;
11689
0
    return false;
11690
0
  }
11691
11692
0
  NewFD->setIsMultiVersion();
11693
0
  Redeclaration = false;
11694
0
  OldDecl = nullptr;
11695
0
  Previous.clear();
11696
0
  return false;
11697
0
}
11698
11699
/// Check the validity of a mulitversion function declaration.
11700
/// Also sets the multiversion'ness' of the function itself.
11701
///
11702
/// This sets NewFD->isInvalidDecl() to true if there was an error.
11703
///
11704
/// Returns true if there was an error, false otherwise.
11705
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11706
                                      bool &Redeclaration, NamedDecl *&OldDecl,
11707
9
                                      LookupResult &Previous) {
11708
9
  const auto *NewTA = NewFD->getAttr<TargetAttr>();
11709
9
  const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11710
9
  const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11711
9
  const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11712
9
  const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11713
9
  MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11714
11715
  // Main isn't allowed to become a multiversion function, however it IS
11716
  // permitted to have 'main' be marked with the 'target' optimization hint,
11717
  // for 'target_version' only default is allowed.
11718
9
  if (NewFD->isMain()) {
11719
0
    if (MVKind != MultiVersionKind::None &&
11720
0
        !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11721
0
        !(MVKind == MultiVersionKind::TargetVersion &&
11722
0
          NewTVA->isDefaultVersion())) {
11723
0
      S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11724
0
      NewFD->setInvalidDecl();
11725
0
      return true;
11726
0
    }
11727
0
    return false;
11728
0
  }
11729
11730
  // Target attribute on AArch64 is not used for multiversioning
11731
9
  if (NewTA && S.getASTContext().getTargetInfo().getTriple().isAArch64())
11732
0
    return false;
11733
11734
9
  if (!OldDecl || !OldDecl->getAsFunction() ||
11735
9
      OldDecl->getDeclContext()->getRedeclContext() !=
11736
9
          NewFD->getDeclContext()->getRedeclContext()) {
11737
    // If there's no previous declaration, AND this isn't attempting to cause
11738
    // multiversioning, this isn't an error condition.
11739
9
    if (MVKind == MultiVersionKind::None)
11740
9
      return false;
11741
0
    return CheckMultiVersionFirstFunction(S, NewFD);
11742
9
  }
11743
11744
0
  FunctionDecl *OldFD = OldDecl->getAsFunction();
11745
11746
0
  if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
11747
0
    if (NewTVA || !OldFD->getAttr<TargetVersionAttr>())
11748
0
      return false;
11749
0
    if (!NewFD->getType()->getAs<FunctionProtoType>()) {
11750
      // Multiversion declaration doesn't have prototype.
11751
0
      S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
11752
0
      NewFD->setInvalidDecl();
11753
0
    } else {
11754
      // No "target_version" attribute is equivalent to "default" attribute.
11755
0
      NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11756
0
          S.Context, "default", NewFD->getSourceRange()));
11757
0
      NewFD->setIsMultiVersion();
11758
0
      OldFD->setIsMultiVersion();
11759
0
      OldDecl = OldFD;
11760
0
      Redeclaration = true;
11761
0
    }
11762
0
    return true;
11763
0
  }
11764
11765
  // Multiversioned redeclarations aren't allowed to omit the attribute, except
11766
  // for target_clones and target_version.
11767
0
  if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11768
0
      OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
11769
0
      OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
11770
0
    S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11771
0
        << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11772
0
    NewFD->setInvalidDecl();
11773
0
    return true;
11774
0
  }
11775
11776
0
  if (!OldFD->isMultiVersion()) {
11777
0
    switch (MVKind) {
11778
0
    case MultiVersionKind::Target:
11779
0
    case MultiVersionKind::TargetVersion:
11780
0
      return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
11781
0
                                              OldDecl, Previous);
11782
0
    case MultiVersionKind::TargetClones:
11783
0
      if (OldFD->isUsed(false)) {
11784
0
        NewFD->setInvalidDecl();
11785
0
        return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11786
0
      }
11787
0
      OldFD->setIsMultiVersion();
11788
0
      break;
11789
11790
0
    case MultiVersionKind::CPUDispatch:
11791
0
    case MultiVersionKind::CPUSpecific:
11792
0
    case MultiVersionKind::None:
11793
0
      break;
11794
0
    }
11795
0
  }
11796
11797
  // At this point, we have a multiversion function decl (in OldFD) AND an
11798
  // appropriate attribute in the current function decl.  Resolve that these are
11799
  // still compatible with previous declarations.
11800
0
  return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp,
11801
0
                                         NewCPUSpec, NewClones, Redeclaration,
11802
0
                                         OldDecl, Previous);
11803
0
}
11804
11805
/// Perform semantic checking of a new function declaration.
11806
///
11807
/// Performs semantic analysis of the new function declaration
11808
/// NewFD. This routine performs all semantic checking that does not
11809
/// require the actual declarator involved in the declaration, and is
11810
/// used both for the declaration of functions as they are parsed
11811
/// (called via ActOnDeclarator) and for the declaration of functions
11812
/// that have been instantiated via C++ template instantiation (called
11813
/// via InstantiateDecl).
11814
///
11815
/// \param IsMemberSpecialization whether this new function declaration is
11816
/// a member specialization (that replaces any definition provided by the
11817
/// previous declaration).
11818
///
11819
/// This sets NewFD->isInvalidDecl() to true if there was an error.
11820
///
11821
/// \returns true if the function declaration is a redeclaration.
11822
bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11823
                                    LookupResult &Previous,
11824
                                    bool IsMemberSpecialization,
11825
9
                                    bool DeclIsDefn) {
11826
9
  assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11827
9
         "Variably modified return types are not handled here");
11828
11829
  // Determine whether the type of this function should be merged with
11830
  // a previous visible declaration. This never happens for functions in C++,
11831
  // and always happens in C if the previous declaration was visible.
11832
9
  bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11833
9
                               !Previous.isShadowed();
11834
11835
9
  bool Redeclaration = false;
11836
9
  NamedDecl *OldDecl = nullptr;
11837
9
  bool MayNeedOverloadableChecks = false;
11838
11839
  // Merge or overload the declaration with an existing declaration of
11840
  // the same name, if appropriate.
11841
9
  if (!Previous.empty()) {
11842
    // Determine whether NewFD is an overload of PrevDecl or
11843
    // a declaration that requires merging. If it's an overload,
11844
    // there's no more work to do here; we'll just add the new
11845
    // function to the scope.
11846
3
    if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11847
3
      NamedDecl *Candidate = Previous.getRepresentativeDecl();
11848
3
      if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11849
3
        Redeclaration = true;
11850
3
        OldDecl = Candidate;
11851
3
      }
11852
3
    } else {
11853
0
      MayNeedOverloadableChecks = true;
11854
0
      switch (CheckOverload(S, NewFD, Previous, OldDecl,
11855
0
                            /*NewIsUsingDecl*/ false)) {
11856
0
      case Ovl_Match:
11857
0
        Redeclaration = true;
11858
0
        break;
11859
11860
0
      case Ovl_NonFunction:
11861
0
        Redeclaration = true;
11862
0
        break;
11863
11864
0
      case Ovl_Overload:
11865
0
        Redeclaration = false;
11866
0
        break;
11867
0
      }
11868
0
    }
11869
3
  }
11870
11871
  // Check for a previous extern "C" declaration with this name.
11872
9
  if (!Redeclaration &&
11873
9
      checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11874
0
    if (!Previous.empty()) {
11875
      // This is an extern "C" declaration with the same name as a previous
11876
      // declaration, and thus redeclares that entity...
11877
0
      Redeclaration = true;
11878
0
      OldDecl = Previous.getFoundDecl();
11879
0
      MergeTypeWithPrevious = false;
11880
11881
      // ... except in the presence of __attribute__((overloadable)).
11882
0
      if (OldDecl->hasAttr<OverloadableAttr>() ||
11883
0
          NewFD->hasAttr<OverloadableAttr>()) {
11884
0
        if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11885
0
          MayNeedOverloadableChecks = true;
11886
0
          Redeclaration = false;
11887
0
          OldDecl = nullptr;
11888
0
        }
11889
0
      }
11890
0
    }
11891
0
  }
11892
11893
9
  if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11894
0
    return Redeclaration;
11895
11896
  // PPC MMA non-pointer types are not allowed as function return types.
11897
9
  if (Context.getTargetInfo().getTriple().isPPC64() &&
11898
9
      CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11899
0
    NewFD->setInvalidDecl();
11900
0
  }
11901
11902
  // C++11 [dcl.constexpr]p8:
11903
  //   A constexpr specifier for a non-static member function that is not
11904
  //   a constructor declares that member function to be const.
11905
  //
11906
  // This needs to be delayed until we know whether this is an out-of-line
11907
  // definition of a static member function.
11908
  //
11909
  // This rule is not present in C++1y, so we produce a backwards
11910
  // compatibility warning whenever it happens in C++11.
11911
9
  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11912
9
  if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11913
9
      !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11914
9
      !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11915
0
    CXXMethodDecl *OldMD = nullptr;
11916
0
    if (OldDecl)
11917
0
      OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11918
0
    if (!OldMD || !OldMD->isStatic()) {
11919
0
      const FunctionProtoType *FPT =
11920
0
        MD->getType()->castAs<FunctionProtoType>();
11921
0
      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11922
0
      EPI.TypeQuals.addConst();
11923
0
      MD->setType(Context.getFunctionType(FPT->getReturnType(),
11924
0
                                          FPT->getParamTypes(), EPI));
11925
11926
      // Warn that we did this, if we're not performing template instantiation.
11927
      // In that case, we'll have warned already when the template was defined.
11928
0
      if (!inTemplateInstantiation()) {
11929
0
        SourceLocation AddConstLoc;
11930
0
        if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11931
0
                .IgnoreParens().getAs<FunctionTypeLoc>())
11932
0
          AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11933
11934
0
        Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11935
0
          << FixItHint::CreateInsertion(AddConstLoc, " const");
11936
0
      }
11937
0
    }
11938
0
  }
11939
11940
9
  if (Redeclaration) {
11941
    // NewFD and OldDecl represent declarations that need to be
11942
    // merged.
11943
3
    if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11944
3
                          DeclIsDefn)) {
11945
3
      NewFD->setInvalidDecl();
11946
3
      return Redeclaration;
11947
3
    }
11948
11949
0
    Previous.clear();
11950
0
    Previous.addDecl(OldDecl);
11951
11952
0
    if (FunctionTemplateDecl *OldTemplateDecl =
11953
0
            dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11954
0
      auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11955
0
      FunctionTemplateDecl *NewTemplateDecl
11956
0
        = NewFD->getDescribedFunctionTemplate();
11957
0
      assert(NewTemplateDecl && "Template/non-template mismatch");
11958
11959
      // The call to MergeFunctionDecl above may have created some state in
11960
      // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11961
      // can add it as a redeclaration.
11962
0
      NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11963
11964
0
      NewFD->setPreviousDeclaration(OldFD);
11965
0
      if (NewFD->isCXXClassMember()) {
11966
0
        NewFD->setAccess(OldTemplateDecl->getAccess());
11967
0
        NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11968
0
      }
11969
11970
      // If this is an explicit specialization of a member that is a function
11971
      // template, mark it as a member specialization.
11972
0
      if (IsMemberSpecialization &&
11973
0
          NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11974
0
        NewTemplateDecl->setMemberSpecialization();
11975
0
        assert(OldTemplateDecl->isMemberSpecialization());
11976
        // Explicit specializations of a member template do not inherit deleted
11977
        // status from the parent member template that they are specializing.
11978
0
        if (OldFD->isDeleted()) {
11979
          // FIXME: This assert will not hold in the presence of modules.
11980
0
          assert(OldFD->getCanonicalDecl() == OldFD);
11981
          // FIXME: We need an update record for this AST mutation.
11982
0
          OldFD->setDeletedAsWritten(false);
11983
0
        }
11984
0
      }
11985
11986
0
    } else {
11987
0
      if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11988
0
        auto *OldFD = cast<FunctionDecl>(OldDecl);
11989
        // This needs to happen first so that 'inline' propagates.
11990
0
        NewFD->setPreviousDeclaration(OldFD);
11991
0
        if (NewFD->isCXXClassMember())
11992
0
          NewFD->setAccess(OldFD->getAccess());
11993
0
      }
11994
0
    }
11995
6
  } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11996
6
             !NewFD->getAttr<OverloadableAttr>()) {
11997
0
    assert((Previous.empty() ||
11998
0
            llvm::any_of(Previous,
11999
0
                         [](const NamedDecl *ND) {
12000
0
                           return ND->hasAttr<OverloadableAttr>();
12001
0
                         })) &&
12002
0
           "Non-redecls shouldn't happen without overloadable present");
12003
12004
0
    auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12005
0
      const auto *FD = dyn_cast<FunctionDecl>(ND);
12006
0
      return FD && !FD->hasAttr<OverloadableAttr>();
12007
0
    });
12008
12009
0
    if (OtherUnmarkedIter != Previous.end()) {
12010
0
      Diag(NewFD->getLocation(),
12011
0
           diag::err_attribute_overloadable_multiple_unmarked_overloads);
12012
0
      Diag((*OtherUnmarkedIter)->getLocation(),
12013
0
           diag::note_attribute_overloadable_prev_overload)
12014
0
          << false;
12015
12016
0
      NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12017
0
    }
12018
0
  }
12019
12020
6
  if (LangOpts.OpenMP)
12021
0
    ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
12022
12023
  // Semantic checking for this function declaration (in isolation).
12024
12025
6
  if (getLangOpts().CPlusPlus) {
12026
    // C++-specific checks.
12027
0
    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12028
0
      CheckConstructor(Constructor);
12029
0
    } else if (CXXDestructorDecl *Destructor =
12030
0
                   dyn_cast<CXXDestructorDecl>(NewFD)) {
12031
      // We check here for invalid destructor names.
12032
      // If we have a friend destructor declaration that is dependent, we can't
12033
      // diagnose right away because cases like this are still valid:
12034
      // template <class T> struct A { friend T::X::~Y(); };
12035
      // struct B { struct Y { ~Y(); }; using X = Y; };
12036
      // template struct A<B>;
12037
0
      if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12038
0
          !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12039
0
        CXXRecordDecl *Record = Destructor->getParent();
12040
0
        QualType ClassType = Context.getTypeDeclType(Record);
12041
12042
0
        DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
12043
0
            Context.getCanonicalType(ClassType));
12044
0
        if (NewFD->getDeclName() != Name) {
12045
0
          Diag(NewFD->getLocation(), diag::err_destructor_name);
12046
0
          NewFD->setInvalidDecl();
12047
0
          return Redeclaration;
12048
0
        }
12049
0
      }
12050
0
    } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12051
0
      if (auto *TD = Guide->getDescribedFunctionTemplate())
12052
0
        CheckDeductionGuideTemplate(TD);
12053
12054
      // A deduction guide is not on the list of entities that can be
12055
      // explicitly specialized.
12056
0
      if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12057
0
        Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12058
0
            << /*explicit specialization*/ 1;
12059
0
    }
12060
12061
    // Find any virtual functions that this function overrides.
12062
0
    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12063
0
      if (!Method->isFunctionTemplateSpecialization() &&
12064
0
          !Method->getDescribedFunctionTemplate() &&
12065
0
          Method->isCanonicalDecl()) {
12066
0
        AddOverriddenMethods(Method->getParent(), Method);
12067
0
      }
12068
0
      if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12069
        // C++2a [class.virtual]p6
12070
        // A virtual method shall not have a requires-clause.
12071
0
        Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
12072
0
             diag::err_constrained_virtual_method);
12073
12074
0
      if (Method->isStatic())
12075
0
        checkThisInStaticMemberFunctionType(Method);
12076
0
    }
12077
12078
0
    if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
12079
      // C++20: dcl.decl.general p4:
12080
      // The optional requires-clause ([temp.pre]) in an init-declarator or
12081
      // member-declarator shall be present only if the declarator declares a
12082
      // templated function ([dcl.fct]).
12083
      //
12084
      // [temp.pre]/8:
12085
      // An entity is templated if it is
12086
      // - a template,
12087
      // - an entity defined ([basic.def]) or created ([class.temporary]) in a
12088
      // templated entity,
12089
      // - a member of a templated entity,
12090
      // - an enumerator for an enumeration that is a templated entity, or
12091
      // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
12092
      // appearing in the declaration of a templated entity. [Note 6: A local
12093
      // class, a local or block variable, or a friend function defined in a
12094
      // templated entity is a templated entity.  — end note]
12095
      //
12096
      // A templated function is a function template or a function that is
12097
      // templated. A templated class is a class template or a class that is
12098
      // templated. A templated variable is a variable template or a variable
12099
      // that is templated.
12100
12101
0
      bool IsTemplate = NewFD->getDescribedFunctionTemplate();
12102
0
      bool IsFriend = NewFD->getFriendObjectKind();
12103
0
      if (!IsTemplate && // -a template
12104
                         // defined... in a templated entity
12105
0
          !(DeclIsDefn && NewFD->isTemplated()) &&
12106
          // a member of a templated entity
12107
0
          !(isa<CXXMethodDecl>(NewFD) && NewFD->isTemplated()) &&
12108
          // Don't complain about instantiations, they've already had these
12109
          // rules + others enforced.
12110
0
          !NewFD->isTemplateInstantiation() &&
12111
          // If the function violates [temp.friend]p9 because it is missing
12112
          // a definition, and adding a definition would make it templated,
12113
          // then let that error take precedence.
12114
0
          !(!DeclIsDefn && IsFriend && NewFD->isTemplated())) {
12115
0
        Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
12116
0
      } else if (!DeclIsDefn && !IsTemplate && IsFriend &&
12117
0
                 !NewFD->isTemplateInstantiation()) {
12118
        // C++ [temp.friend]p9:
12119
        //   A non-template friend declaration with a requires-clause shall be a
12120
        //   definition.
12121
0
        Diag(NewFD->getBeginLoc(),
12122
0
             diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
12123
0
        NewFD->setInvalidDecl();
12124
0
      }
12125
0
    }
12126
12127
0
    if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12128
0
      ActOnConversionDeclarator(Conversion);
12129
12130
    // Extra checking for C++ overloaded operators (C++ [over.oper]).
12131
0
    if (NewFD->isOverloadedOperator() &&
12132
0
        CheckOverloadedOperatorDeclaration(NewFD)) {
12133
0
      NewFD->setInvalidDecl();
12134
0
      return Redeclaration;
12135
0
    }
12136
12137
    // Extra checking for C++0x literal operators (C++0x [over.literal]).
12138
0
    if (NewFD->getLiteralIdentifier() &&
12139
0
        CheckLiteralOperatorDeclaration(NewFD)) {
12140
0
      NewFD->setInvalidDecl();
12141
0
      return Redeclaration;
12142
0
    }
12143
12144
    // In C++, check default arguments now that we have merged decls. Unless
12145
    // the lexical context is the class, because in this case this is done
12146
    // during delayed parsing anyway.
12147
0
    if (!CurContext->isRecord())
12148
0
      CheckCXXDefaultArguments(NewFD);
12149
12150
    // If this function is declared as being extern "C", then check to see if
12151
    // the function returns a UDT (class, struct, or union type) that is not C
12152
    // compatible, and if it does, warn the user.
12153
    // But, issue any diagnostic on the first declaration only.
12154
0
    if (Previous.empty() && NewFD->isExternC()) {
12155
0
      QualType R = NewFD->getReturnType();
12156
0
      if (R->isIncompleteType() && !R->isVoidType())
12157
0
        Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12158
0
            << NewFD << R;
12159
0
      else if (!R.isPODType(Context) && !R->isVoidType() &&
12160
0
               !R->isObjCObjectPointerType())
12161
0
        Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12162
0
    }
12163
12164
    // C++1z [dcl.fct]p6:
12165
    //   [...] whether the function has a non-throwing exception-specification
12166
    //   [is] part of the function type
12167
    //
12168
    // This results in an ABI break between C++14 and C++17 for functions whose
12169
    // declared type includes an exception-specification in a parameter or
12170
    // return type. (Exception specifications on the function itself are OK in
12171
    // most cases, and exception specifications are not permitted in most other
12172
    // contexts where they could make it into a mangling.)
12173
0
    if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12174
0
      auto HasNoexcept = [&](QualType T) -> bool {
12175
        // Strip off declarator chunks that could be between us and a function
12176
        // type. We don't need to look far, exception specifications are very
12177
        // restricted prior to C++17.
12178
0
        if (auto *RT = T->getAs<ReferenceType>())
12179
0
          T = RT->getPointeeType();
12180
0
        else if (T->isAnyPointerType())
12181
0
          T = T->getPointeeType();
12182
0
        else if (auto *MPT = T->getAs<MemberPointerType>())
12183
0
          T = MPT->getPointeeType();
12184
0
        if (auto *FPT = T->getAs<FunctionProtoType>())
12185
0
          if (FPT->isNothrow())
12186
0
            return true;
12187
0
        return false;
12188
0
      };
12189
12190
0
      auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12191
0
      bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12192
0
      for (QualType T : FPT->param_types())
12193
0
        AnyNoexcept |= HasNoexcept(T);
12194
0
      if (AnyNoexcept)
12195
0
        Diag(NewFD->getLocation(),
12196
0
             diag::warn_cxx17_compat_exception_spec_in_signature)
12197
0
            << NewFD;
12198
0
    }
12199
12200
0
    if (!Redeclaration && LangOpts.CUDA)
12201
0
      checkCUDATargetOverload(NewFD, Previous);
12202
0
  }
12203
12204
  // Check if the function definition uses any AArch64 SME features without
12205
  // having the '+sme' feature enabled.
12206
6
  if (DeclIsDefn) {
12207
0
    const auto *Attr = NewFD->getAttr<ArmNewAttr>();
12208
0
    bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12209
0
    bool UsesZA = Attr && Attr->isNewZA();
12210
0
    if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12211
0
      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12212
0
      UsesSM |=
12213
0
          EPI.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
12214
0
      UsesZA |= FunctionType::getArmZAState(EPI.AArch64SMEAttributes) !=
12215
0
                FunctionType::ARM_None;
12216
0
    }
12217
12218
0
    if (UsesSM || UsesZA) {
12219
0
      llvm::StringMap<bool> FeatureMap;
12220
0
      Context.getFunctionFeatureMap(FeatureMap, NewFD);
12221
0
      if (!FeatureMap.contains("sme")) {
12222
0
        if (UsesSM)
12223
0
          Diag(NewFD->getLocation(),
12224
0
               diag::err_sme_definition_using_sm_in_non_sme_target);
12225
0
        else
12226
0
          Diag(NewFD->getLocation(),
12227
0
               diag::err_sme_definition_using_za_in_non_sme_target);
12228
0
      }
12229
0
    }
12230
0
  }
12231
12232
6
  return Redeclaration;
12233
6
}
12234
12235
0
void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
12236
  // C++11 [basic.start.main]p3:
12237
  //   A program that [...] declares main to be inline, static or
12238
  //   constexpr is ill-formed.
12239
  // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
12240
  //   appear in a declaration of main.
12241
  // static main is not an error under C99, but we should warn about it.
12242
  // We accept _Noreturn main as an extension.
12243
0
  if (FD->getStorageClass() == SC_Static)
12244
0
    Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
12245
0
         ? diag::err_static_main : diag::warn_static_main)
12246
0
      << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12247
0
  if (FD->isInlineSpecified())
12248
0
    Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12249
0
      << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
12250
0
  if (DS.isNoreturnSpecified()) {
12251
0
    SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12252
0
    SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12253
0
    Diag(NoreturnLoc, diag::ext_noreturn_main);
12254
0
    Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12255
0
      << FixItHint::CreateRemoval(NoreturnRange);
12256
0
  }
12257
0
  if (FD->isConstexpr()) {
12258
0
    Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12259
0
        << FD->isConsteval()
12260
0
        << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
12261
0
    FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12262
0
  }
12263
12264
0
  if (getLangOpts().OpenCL) {
12265
0
    Diag(FD->getLocation(), diag::err_opencl_no_main)
12266
0
        << FD->hasAttr<OpenCLKernelAttr>();
12267
0
    FD->setInvalidDecl();
12268
0
    return;
12269
0
  }
12270
12271
  // Functions named main in hlsl are default entries, but don't have specific
12272
  // signatures they are required to conform to.
12273
0
  if (getLangOpts().HLSL)
12274
0
    return;
12275
12276
0
  QualType T = FD->getType();
12277
0
  assert(T->isFunctionType() && "function decl is not of function type");
12278
0
  const FunctionType* FT = T->castAs<FunctionType>();
12279
12280
  // Set default calling convention for main()
12281
0
  if (FT->getCallConv() != CC_C) {
12282
0
    FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12283
0
    FD->setType(QualType(FT, 0));
12284
0
    T = Context.getCanonicalType(FD->getType());
12285
0
  }
12286
12287
0
  if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12288
    // In C with GNU extensions we allow main() to have non-integer return
12289
    // type, but we should warn about the extension, and we disable the
12290
    // implicit-return-zero rule.
12291
12292
    // GCC in C mode accepts qualified 'int'.
12293
0
    if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12294
0
      FD->setHasImplicitReturnZero(true);
12295
0
    else {
12296
0
      Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12297
0
      SourceRange RTRange = FD->getReturnTypeSourceRange();
12298
0
      if (RTRange.isValid())
12299
0
        Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12300
0
            << FixItHint::CreateReplacement(RTRange, "int");
12301
0
    }
12302
0
  } else {
12303
    // In C and C++, main magically returns 0 if you fall off the end;
12304
    // set the flag which tells us that.
12305
    // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12306
12307
    // All the standards say that main() should return 'int'.
12308
0
    if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12309
0
      FD->setHasImplicitReturnZero(true);
12310
0
    else {
12311
      // Otherwise, this is just a flat-out error.
12312
0
      SourceRange RTRange = FD->getReturnTypeSourceRange();
12313
0
      Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12314
0
          << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12315
0
                                : FixItHint());
12316
0
      FD->setInvalidDecl(true);
12317
0
    }
12318
0
  }
12319
12320
  // Treat protoless main() as nullary.
12321
0
  if (isa<FunctionNoProtoType>(FT)) return;
12322
12323
0
  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12324
0
  unsigned nparams = FTP->getNumParams();
12325
0
  assert(FD->getNumParams() == nparams);
12326
12327
0
  bool HasExtraParameters = (nparams > 3);
12328
12329
0
  if (FTP->isVariadic()) {
12330
0
    Diag(FD->getLocation(), diag::ext_variadic_main);
12331
    // FIXME: if we had information about the location of the ellipsis, we
12332
    // could add a FixIt hint to remove it as a parameter.
12333
0
  }
12334
12335
  // Darwin passes an undocumented fourth argument of type char**.  If
12336
  // other platforms start sprouting these, the logic below will start
12337
  // getting shifty.
12338
0
  if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12339
0
    HasExtraParameters = false;
12340
12341
0
  if (HasExtraParameters) {
12342
0
    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12343
0
    FD->setInvalidDecl(true);
12344
0
    nparams = 3;
12345
0
  }
12346
12347
  // FIXME: a lot of the following diagnostics would be improved
12348
  // if we had some location information about types.
12349
12350
0
  QualType CharPP =
12351
0
    Context.getPointerType(Context.getPointerType(Context.CharTy));
12352
0
  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12353
12354
0
  for (unsigned i = 0; i < nparams; ++i) {
12355
0
    QualType AT = FTP->getParamType(i);
12356
12357
0
    bool mismatch = true;
12358
12359
0
    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12360
0
      mismatch = false;
12361
0
    else if (Expected[i] == CharPP) {
12362
      // As an extension, the following forms are okay:
12363
      //   char const **
12364
      //   char const * const *
12365
      //   char * const *
12366
12367
0
      QualifierCollector qs;
12368
0
      const PointerType* PT;
12369
0
      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12370
0
          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12371
0
          Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12372
0
                              Context.CharTy)) {
12373
0
        qs.removeConst();
12374
0
        mismatch = !qs.empty();
12375
0
      }
12376
0
    }
12377
12378
0
    if (mismatch) {
12379
0
      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12380
      // TODO: suggest replacing given type with expected type
12381
0
      FD->setInvalidDecl(true);
12382
0
    }
12383
0
  }
12384
12385
0
  if (nparams == 1 && !FD->isInvalidDecl()) {
12386
0
    Diag(FD->getLocation(), diag::warn_main_one_arg);
12387
0
  }
12388
12389
0
  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12390
0
    Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12391
0
    FD->setInvalidDecl();
12392
0
  }
12393
0
}
12394
12395
0
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12396
12397
  // Default calling convention for main and wmain is __cdecl
12398
0
  if (FD->getName() == "main" || FD->getName() == "wmain")
12399
0
    return false;
12400
12401
  // Default calling convention for MinGW is __cdecl
12402
0
  const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12403
0
  if (T.isWindowsGNUEnvironment())
12404
0
    return false;
12405
12406
  // Default calling convention for WinMain, wWinMain and DllMain
12407
  // is __stdcall on 32 bit Windows
12408
0
  if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12409
0
    return true;
12410
12411
0
  return false;
12412
0
}
12413
12414
0
void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12415
0
  QualType T = FD->getType();
12416
0
  assert(T->isFunctionType() && "function decl is not of function type");
12417
0
  const FunctionType *FT = T->castAs<FunctionType>();
12418
12419
  // Set an implicit return of 'zero' if the function can return some integral,
12420
  // enumeration, pointer or nullptr type.
12421
0
  if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12422
0
      FT->getReturnType()->isAnyPointerType() ||
12423
0
      FT->getReturnType()->isNullPtrType())
12424
    // DllMain is exempt because a return value of zero means it failed.
12425
0
    if (FD->getName() != "DllMain")
12426
0
      FD->setHasImplicitReturnZero(true);
12427
12428
  // Explicity specified calling conventions are applied to MSVC entry points
12429
0
  if (!hasExplicitCallingConv(T)) {
12430
0
    if (isDefaultStdCall(FD, *this)) {
12431
0
      if (FT->getCallConv() != CC_X86StdCall) {
12432
0
        FT = Context.adjustFunctionType(
12433
0
            FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
12434
0
        FD->setType(QualType(FT, 0));
12435
0
      }
12436
0
    } else if (FT->getCallConv() != CC_C) {
12437
0
      FT = Context.adjustFunctionType(FT,
12438
0
                                      FT->getExtInfo().withCallingConv(CC_C));
12439
0
      FD->setType(QualType(FT, 0));
12440
0
    }
12441
0
  }
12442
12443
0
  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12444
0
    Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12445
0
    FD->setInvalidDecl();
12446
0
  }
12447
0
}
12448
12449
0
void Sema::ActOnHLSLTopLevelFunction(FunctionDecl *FD) {
12450
0
  auto &TargetInfo = getASTContext().getTargetInfo();
12451
12452
0
  if (FD->getName() != TargetInfo.getTargetOpts().HLSLEntry)
12453
0
    return;
12454
12455
0
  StringRef Env = TargetInfo.getTriple().getEnvironmentName();
12456
0
  HLSLShaderAttr::ShaderType ShaderType;
12457
0
  if (HLSLShaderAttr::ConvertStrToShaderType(Env, ShaderType)) {
12458
0
    if (const auto *Shader = FD->getAttr<HLSLShaderAttr>()) {
12459
      // The entry point is already annotated - check that it matches the
12460
      // triple.
12461
0
      if (Shader->getType() != ShaderType) {
12462
0
        Diag(Shader->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch)
12463
0
            << Shader;
12464
0
        FD->setInvalidDecl();
12465
0
      }
12466
0
    } else {
12467
      // Implicitly add the shader attribute if the entry function isn't
12468
      // explicitly annotated.
12469
0
      FD->addAttr(HLSLShaderAttr::CreateImplicit(Context, ShaderType,
12470
0
                                                 FD->getBeginLoc()));
12471
0
    }
12472
0
  } else {
12473
0
    switch (TargetInfo.getTriple().getEnvironment()) {
12474
0
    case llvm::Triple::UnknownEnvironment:
12475
0
    case llvm::Triple::Library:
12476
0
      break;
12477
0
    default:
12478
0
      llvm_unreachable("Unhandled environment in triple");
12479
0
    }
12480
0
  }
12481
0
}
12482
12483
0
void Sema::CheckHLSLEntryPoint(FunctionDecl *FD) {
12484
0
  const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>();
12485
0
  assert(ShaderAttr && "Entry point has no shader attribute");
12486
0
  HLSLShaderAttr::ShaderType ST = ShaderAttr->getType();
12487
12488
0
  switch (ST) {
12489
0
  case HLSLShaderAttr::Pixel:
12490
0
  case HLSLShaderAttr::Vertex:
12491
0
  case HLSLShaderAttr::Geometry:
12492
0
  case HLSLShaderAttr::Hull:
12493
0
  case HLSLShaderAttr::Domain:
12494
0
  case HLSLShaderAttr::RayGeneration:
12495
0
  case HLSLShaderAttr::Intersection:
12496
0
  case HLSLShaderAttr::AnyHit:
12497
0
  case HLSLShaderAttr::ClosestHit:
12498
0
  case HLSLShaderAttr::Miss:
12499
0
  case HLSLShaderAttr::Callable:
12500
0
    if (const auto *NT = FD->getAttr<HLSLNumThreadsAttr>()) {
12501
0
      DiagnoseHLSLAttrStageMismatch(NT, ST,
12502
0
                                    {HLSLShaderAttr::Compute,
12503
0
                                     HLSLShaderAttr::Amplification,
12504
0
                                     HLSLShaderAttr::Mesh});
12505
0
      FD->setInvalidDecl();
12506
0
    }
12507
0
    break;
12508
12509
0
  case HLSLShaderAttr::Compute:
12510
0
  case HLSLShaderAttr::Amplification:
12511
0
  case HLSLShaderAttr::Mesh:
12512
0
    if (!FD->hasAttr<HLSLNumThreadsAttr>()) {
12513
0
      Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads)
12514
0
          << HLSLShaderAttr::ConvertShaderTypeToStr(ST);
12515
0
      FD->setInvalidDecl();
12516
0
    }
12517
0
    break;
12518
0
  }
12519
12520
0
  for (ParmVarDecl *Param : FD->parameters()) {
12521
0
    if (const auto *AnnotationAttr = Param->getAttr<HLSLAnnotationAttr>()) {
12522
0
      CheckHLSLSemanticAnnotation(FD, Param, AnnotationAttr);
12523
0
    } else {
12524
      // FIXME: Handle struct parameters where annotations are on struct fields.
12525
      // See: https://github.com/llvm/llvm-project/issues/57875
12526
0
      Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation);
12527
0
      Diag(Param->getLocation(), diag::note_previous_decl) << Param;
12528
0
      FD->setInvalidDecl();
12529
0
    }
12530
0
  }
12531
  // FIXME: Verify return type semantic annotation.
12532
0
}
12533
12534
void Sema::CheckHLSLSemanticAnnotation(
12535
    FunctionDecl *EntryPoint, const Decl *Param,
12536
0
    const HLSLAnnotationAttr *AnnotationAttr) {
12537
0
  auto *ShaderAttr = EntryPoint->getAttr<HLSLShaderAttr>();
12538
0
  assert(ShaderAttr && "Entry point has no shader attribute");
12539
0
  HLSLShaderAttr::ShaderType ST = ShaderAttr->getType();
12540
12541
0
  switch (AnnotationAttr->getKind()) {
12542
0
  case attr::HLSLSV_DispatchThreadID:
12543
0
  case attr::HLSLSV_GroupIndex:
12544
0
    if (ST == HLSLShaderAttr::Compute)
12545
0
      return;
12546
0
    DiagnoseHLSLAttrStageMismatch(AnnotationAttr, ST,
12547
0
                                  {HLSLShaderAttr::Compute});
12548
0
    break;
12549
0
  default:
12550
0
    llvm_unreachable("Unknown HLSLAnnotationAttr");
12551
0
  }
12552
0
}
12553
12554
void Sema::DiagnoseHLSLAttrStageMismatch(
12555
    const Attr *A, HLSLShaderAttr::ShaderType Stage,
12556
0
    std::initializer_list<HLSLShaderAttr::ShaderType> AllowedStages) {
12557
0
  SmallVector<StringRef, 8> StageStrings;
12558
0
  llvm::transform(AllowedStages, std::back_inserter(StageStrings),
12559
0
                  [](HLSLShaderAttr::ShaderType ST) {
12560
0
                    return StringRef(
12561
0
                        HLSLShaderAttr::ConvertShaderTypeToStr(ST));
12562
0
                  });
12563
0
  Diag(A->getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
12564
0
      << A << HLSLShaderAttr::ConvertShaderTypeToStr(Stage)
12565
0
      << (AllowedStages.size() != 1) << join(StageStrings, ", ");
12566
0
}
12567
12568
20
bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
12569
  // FIXME: Need strict checking.  In C89, we need to check for
12570
  // any assignment, increment, decrement, function-calls, or
12571
  // commas outside of a sizeof.  In C99, it's the same list,
12572
  // except that the aforementioned are allowed in unevaluated
12573
  // expressions.  Everything else falls under the
12574
  // "may accept other forms of constant expressions" exception.
12575
  //
12576
  // Regular C++ code will not end up here (exceptions: language extensions,
12577
  // OpenCL C++ etc), so the constant expression rules there don't matter.
12578
20
  if (Init->isValueDependent()) {
12579
12
    assert(Init->containsErrors() &&
12580
12
           "Dependent code should only occur in error-recovery path.");
12581
0
    return true;
12582
12
  }
12583
8
  const Expr *Culprit;
12584
8
  if (Init->isConstantInitializer(Context, false, &Culprit))
12585
3
    return false;
12586
5
  Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
12587
5
    << Culprit->getSourceRange();
12588
5
  return true;
12589
8
}
12590
12591
namespace {
12592
  // Visits an initialization expression to see if OrigDecl is evaluated in
12593
  // its own initialization and throws a warning if it does.
12594
  class SelfReferenceChecker
12595
      : public EvaluatedExprVisitor<SelfReferenceChecker> {
12596
    Sema &S;
12597
    Decl *OrigDecl;
12598
    bool isRecordType;
12599
    bool isPODType;
12600
    bool isReferenceType;
12601
12602
    bool isInitList;
12603
    llvm::SmallVector<unsigned, 4> InitFieldIndex;
12604
12605
  public:
12606
    typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12607
12608
    SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12609
0
                                                    S(S), OrigDecl(OrigDecl) {
12610
0
      isPODType = false;
12611
0
      isRecordType = false;
12612
0
      isReferenceType = false;
12613
0
      isInitList = false;
12614
0
      if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12615
0
        isPODType = VD->getType().isPODType(S.Context);
12616
0
        isRecordType = VD->getType()->isRecordType();
12617
0
        isReferenceType = VD->getType()->isReferenceType();
12618
0
      }
12619
0
    }
12620
12621
    // For most expressions, just call the visitor.  For initializer lists,
12622
    // track the index of the field being initialized since fields are
12623
    // initialized in order allowing use of previously initialized fields.
12624
0
    void CheckExpr(Expr *E) {
12625
0
      InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12626
0
      if (!InitList) {
12627
0
        Visit(E);
12628
0
        return;
12629
0
      }
12630
12631
      // Track and increment the index here.
12632
0
      isInitList = true;
12633
0
      InitFieldIndex.push_back(0);
12634
0
      for (auto *Child : InitList->children()) {
12635
0
        CheckExpr(cast<Expr>(Child));
12636
0
        ++InitFieldIndex.back();
12637
0
      }
12638
0
      InitFieldIndex.pop_back();
12639
0
    }
12640
12641
    // Returns true if MemberExpr is checked and no further checking is needed.
12642
    // Returns false if additional checking is required.
12643
0
    bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12644
0
      llvm::SmallVector<FieldDecl*, 4> Fields;
12645
0
      Expr *Base = E;
12646
0
      bool ReferenceField = false;
12647
12648
      // Get the field members used.
12649
0
      while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12650
0
        FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12651
0
        if (!FD)
12652
0
          return false;
12653
0
        Fields.push_back(FD);
12654
0
        if (FD->getType()->isReferenceType())
12655
0
          ReferenceField = true;
12656
0
        Base = ME->getBase()->IgnoreParenImpCasts();
12657
0
      }
12658
12659
      // Keep checking only if the base Decl is the same.
12660
0
      DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12661
0
      if (!DRE || DRE->getDecl() != OrigDecl)
12662
0
        return false;
12663
12664
      // A reference field can be bound to an unininitialized field.
12665
0
      if (CheckReference && !ReferenceField)
12666
0
        return true;
12667
12668
      // Convert FieldDecls to their index number.
12669
0
      llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12670
0
      for (const FieldDecl *I : llvm::reverse(Fields))
12671
0
        UsedFieldIndex.push_back(I->getFieldIndex());
12672
12673
      // See if a warning is needed by checking the first difference in index
12674
      // numbers.  If field being used has index less than the field being
12675
      // initialized, then the use is safe.
12676
0
      for (auto UsedIter = UsedFieldIndex.begin(),
12677
0
                UsedEnd = UsedFieldIndex.end(),
12678
0
                OrigIter = InitFieldIndex.begin(),
12679
0
                OrigEnd = InitFieldIndex.end();
12680
0
           UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12681
0
        if (*UsedIter < *OrigIter)
12682
0
          return true;
12683
0
        if (*UsedIter > *OrigIter)
12684
0
          break;
12685
0
      }
12686
12687
      // TODO: Add a different warning which will print the field names.
12688
0
      HandleDeclRefExpr(DRE);
12689
0
      return true;
12690
0
    }
12691
12692
    // For most expressions, the cast is directly above the DeclRefExpr.
12693
    // For conditional operators, the cast can be outside the conditional
12694
    // operator if both expressions are DeclRefExpr's.
12695
0
    void HandleValue(Expr *E) {
12696
0
      E = E->IgnoreParens();
12697
0
      if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12698
0
        HandleDeclRefExpr(DRE);
12699
0
        return;
12700
0
      }
12701
12702
0
      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12703
0
        Visit(CO->getCond());
12704
0
        HandleValue(CO->getTrueExpr());
12705
0
        HandleValue(CO->getFalseExpr());
12706
0
        return;
12707
0
      }
12708
12709
0
      if (BinaryConditionalOperator *BCO =
12710
0
              dyn_cast<BinaryConditionalOperator>(E)) {
12711
0
        Visit(BCO->getCond());
12712
0
        HandleValue(BCO->getFalseExpr());
12713
0
        return;
12714
0
      }
12715
12716
0
      if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12717
0
        HandleValue(OVE->getSourceExpr());
12718
0
        return;
12719
0
      }
12720
12721
0
      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12722
0
        if (BO->getOpcode() == BO_Comma) {
12723
0
          Visit(BO->getLHS());
12724
0
          HandleValue(BO->getRHS());
12725
0
          return;
12726
0
        }
12727
0
      }
12728
12729
0
      if (isa<MemberExpr>(E)) {
12730
0
        if (isInitList) {
12731
0
          if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12732
0
                                      false /*CheckReference*/))
12733
0
            return;
12734
0
        }
12735
12736
0
        Expr *Base = E->IgnoreParenImpCasts();
12737
0
        while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12738
          // Check for static member variables and don't warn on them.
12739
0
          if (!isa<FieldDecl>(ME->getMemberDecl()))
12740
0
            return;
12741
0
          Base = ME->getBase()->IgnoreParenImpCasts();
12742
0
        }
12743
0
        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12744
0
          HandleDeclRefExpr(DRE);
12745
0
        return;
12746
0
      }
12747
12748
0
      Visit(E);
12749
0
    }
12750
12751
    // Reference types not handled in HandleValue are handled here since all
12752
    // uses of references are bad, not just r-value uses.
12753
0
    void VisitDeclRefExpr(DeclRefExpr *E) {
12754
0
      if (isReferenceType)
12755
0
        HandleDeclRefExpr(E);
12756
0
    }
12757
12758
0
    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12759
0
      if (E->getCastKind() == CK_LValueToRValue) {
12760
0
        HandleValue(E->getSubExpr());
12761
0
        return;
12762
0
      }
12763
12764
0
      Inherited::VisitImplicitCastExpr(E);
12765
0
    }
12766
12767
0
    void VisitMemberExpr(MemberExpr *E) {
12768
0
      if (isInitList) {
12769
0
        if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12770
0
          return;
12771
0
      }
12772
12773
      // Don't warn on arrays since they can be treated as pointers.
12774
0
      if (E->getType()->canDecayToPointerType()) return;
12775
12776
      // Warn when a non-static method call is followed by non-static member
12777
      // field accesses, which is followed by a DeclRefExpr.
12778
0
      CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12779
0
      bool Warn = (MD && !MD->isStatic());
12780
0
      Expr *Base = E->getBase()->IgnoreParenImpCasts();
12781
0
      while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12782
0
        if (!isa<FieldDecl>(ME->getMemberDecl()))
12783
0
          Warn = false;
12784
0
        Base = ME->getBase()->IgnoreParenImpCasts();
12785
0
      }
12786
12787
0
      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12788
0
        if (Warn)
12789
0
          HandleDeclRefExpr(DRE);
12790
0
        return;
12791
0
      }
12792
12793
      // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12794
      // Visit that expression.
12795
0
      Visit(Base);
12796
0
    }
12797
12798
0
    void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12799
0
      Expr *Callee = E->getCallee();
12800
12801
0
      if (isa<UnresolvedLookupExpr>(Callee))
12802
0
        return Inherited::VisitCXXOperatorCallExpr(E);
12803
12804
0
      Visit(Callee);
12805
0
      for (auto Arg: E->arguments())
12806
0
        HandleValue(Arg->IgnoreParenImpCasts());
12807
0
    }
12808
12809
0
    void VisitUnaryOperator(UnaryOperator *E) {
12810
      // For POD record types, addresses of its own members are well-defined.
12811
0
      if (E->getOpcode() == UO_AddrOf && isRecordType &&
12812
0
          isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12813
0
        if (!isPODType)
12814
0
          HandleValue(E->getSubExpr());
12815
0
        return;
12816
0
      }
12817
12818
0
      if (E->isIncrementDecrementOp()) {
12819
0
        HandleValue(E->getSubExpr());
12820
0
        return;
12821
0
      }
12822
12823
0
      Inherited::VisitUnaryOperator(E);
12824
0
    }
12825
12826
0
    void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12827
12828
0
    void VisitCXXConstructExpr(CXXConstructExpr *E) {
12829
0
      if (E->getConstructor()->isCopyConstructor()) {
12830
0
        Expr *ArgExpr = E->getArg(0);
12831
0
        if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12832
0
          if (ILE->getNumInits() == 1)
12833
0
            ArgExpr = ILE->getInit(0);
12834
0
        if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12835
0
          if (ICE->getCastKind() == CK_NoOp)
12836
0
            ArgExpr = ICE->getSubExpr();
12837
0
        HandleValue(ArgExpr);
12838
0
        return;
12839
0
      }
12840
0
      Inherited::VisitCXXConstructExpr(E);
12841
0
    }
12842
12843
0
    void VisitCallExpr(CallExpr *E) {
12844
      // Treat std::move as a use.
12845
0
      if (E->isCallToStdMove()) {
12846
0
        HandleValue(E->getArg(0));
12847
0
        return;
12848
0
      }
12849
12850
0
      Inherited::VisitCallExpr(E);
12851
0
    }
12852
12853
0
    void VisitBinaryOperator(BinaryOperator *E) {
12854
0
      if (E->isCompoundAssignmentOp()) {
12855
0
        HandleValue(E->getLHS());
12856
0
        Visit(E->getRHS());
12857
0
        return;
12858
0
      }
12859
12860
0
      Inherited::VisitBinaryOperator(E);
12861
0
    }
12862
12863
    // A custom visitor for BinaryConditionalOperator is needed because the
12864
    // regular visitor would check the condition and true expression separately
12865
    // but both point to the same place giving duplicate diagnostics.
12866
0
    void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12867
0
      Visit(E->getCond());
12868
0
      Visit(E->getFalseExpr());
12869
0
    }
12870
12871
0
    void HandleDeclRefExpr(DeclRefExpr *DRE) {
12872
0
      Decl* ReferenceDecl = DRE->getDecl();
12873
0
      if (OrigDecl != ReferenceDecl) return;
12874
0
      unsigned diag;
12875
0
      if (isReferenceType) {
12876
0
        diag = diag::warn_uninit_self_reference_in_reference_init;
12877
0
      } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12878
0
        diag = diag::warn_static_self_reference_in_init;
12879
0
      } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12880
0
                 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12881
0
                 DRE->getDecl()->getType()->isRecordType()) {
12882
0
        diag = diag::warn_uninit_self_reference_in_init;
12883
0
      } else {
12884
        // Local variables will be handled by the CFG analysis.
12885
0
        return;
12886
0
      }
12887
12888
0
      S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12889
0
                            S.PDiag(diag)
12890
0
                                << DRE->getDecl() << OrigDecl->getLocation()
12891
0
                                << DRE->getSourceRange());
12892
0
    }
12893
  };
12894
12895
  /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12896
  static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12897
0
                                 bool DirectInit) {
12898
    // Parameters arguments are occassionially constructed with itself,
12899
    // for instance, in recursive functions.  Skip them.
12900
0
    if (isa<ParmVarDecl>(OrigDecl))
12901
0
      return;
12902
12903
0
    E = E->IgnoreParens();
12904
12905
    // Skip checking T a = a where T is not a record or reference type.
12906
    // Doing so is a way to silence uninitialized warnings.
12907
0
    if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12908
0
      if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12909
0
        if (ICE->getCastKind() == CK_LValueToRValue)
12910
0
          if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12911
0
            if (DRE->getDecl() == OrigDecl)
12912
0
              return;
12913
12914
0
    SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12915
0
  }
12916
} // end anonymous namespace
12917
12918
namespace {
12919
  // Simple wrapper to add the name of a variable or (if no variable is
12920
  // available) a DeclarationName into a diagnostic.
12921
  struct VarDeclOrName {
12922
    VarDecl *VDecl;
12923
    DeclarationName Name;
12924
12925
    friend const Sema::SemaDiagnosticBuilder &
12926
0
    operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12927
0
      return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12928
0
    }
12929
  };
12930
} // end anonymous namespace
12931
12932
QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12933
                                            DeclarationName Name, QualType Type,
12934
                                            TypeSourceInfo *TSI,
12935
                                            SourceRange Range, bool DirectInit,
12936
0
                                            Expr *Init) {
12937
0
  bool IsInitCapture = !VDecl;
12938
0
  assert((!VDecl || !VDecl->isInitCapture()) &&
12939
0
         "init captures are expected to be deduced prior to initialization");
12940
12941
0
  VarDeclOrName VN{VDecl, Name};
12942
12943
0
  DeducedType *Deduced = Type->getContainedDeducedType();
12944
0
  assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12945
12946
  // Diagnose auto array declarations in C23, unless it's a supported extension.
12947
0
  if (getLangOpts().C23 && Type->isArrayType() &&
12948
0
      !isa_and_present<StringLiteral, InitListExpr>(Init)) {
12949
0
      Diag(Range.getBegin(), diag::err_auto_not_allowed)
12950
0
          << (int)Deduced->getContainedAutoType()->getKeyword()
12951
0
          << /*in array decl*/ 23 << Range;
12952
0
    return QualType();
12953
0
  }
12954
12955
  // C++11 [dcl.spec.auto]p3
12956
0
  if (!Init) {
12957
0
    assert(VDecl && "no init for init capture deduction?");
12958
12959
    // Except for class argument deduction, and then for an initializing
12960
    // declaration only, i.e. no static at class scope or extern.
12961
0
    if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12962
0
        VDecl->hasExternalStorage() ||
12963
0
        VDecl->isStaticDataMember()) {
12964
0
      Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12965
0
        << VDecl->getDeclName() << Type;
12966
0
      return QualType();
12967
0
    }
12968
0
  }
12969
12970
0
  ArrayRef<Expr*> DeduceInits;
12971
0
  if (Init)
12972
0
    DeduceInits = Init;
12973
12974
0
  auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12975
0
  if (DirectInit && PL)
12976
0
    DeduceInits = PL->exprs();
12977
12978
0
  if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12979
0
    assert(VDecl && "non-auto type for init capture deduction?");
12980
0
    InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12981
0
    InitializationKind Kind = InitializationKind::CreateForInit(
12982
0
        VDecl->getLocation(), DirectInit, Init);
12983
    // FIXME: Initialization should not be taking a mutable list of inits.
12984
0
    SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12985
0
    return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12986
0
                                                       InitsCopy);
12987
0
  }
12988
12989
0
  if (DirectInit) {
12990
0
    if (auto *IL = dyn_cast<InitListExpr>(Init))
12991
0
      DeduceInits = IL->inits();
12992
0
  }
12993
12994
  // Deduction only works if we have exactly one source expression.
12995
0
  if (DeduceInits.empty()) {
12996
    // It isn't possible to write this directly, but it is possible to
12997
    // end up in this situation with "auto x(some_pack...);"
12998
0
    Diag(Init->getBeginLoc(), IsInitCapture
12999
0
                                  ? diag::err_init_capture_no_expression
13000
0
                                  : diag::err_auto_var_init_no_expression)
13001
0
        << VN << Type << Range;
13002
0
    return QualType();
13003
0
  }
13004
13005
0
  if (DeduceInits.size() > 1) {
13006
0
    Diag(DeduceInits[1]->getBeginLoc(),
13007
0
         IsInitCapture ? diag::err_init_capture_multiple_expressions
13008
0
                       : diag::err_auto_var_init_multiple_expressions)
13009
0
        << VN << Type << Range;
13010
0
    return QualType();
13011
0
  }
13012
13013
0
  Expr *DeduceInit = DeduceInits[0];
13014
0
  if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13015
0
    Diag(Init->getBeginLoc(), IsInitCapture
13016
0
                                  ? diag::err_init_capture_paren_braces
13017
0
                                  : diag::err_auto_var_init_paren_braces)
13018
0
        << isa<InitListExpr>(Init) << VN << Type << Range;
13019
0
    return QualType();
13020
0
  }
13021
13022
  // Expressions default to 'id' when we're in a debugger.
13023
0
  bool DefaultedAnyToId = false;
13024
0
  if (getLangOpts().DebuggerCastResultToId &&
13025
0
      Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13026
0
    ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13027
0
    if (Result.isInvalid()) {
13028
0
      return QualType();
13029
0
    }
13030
0
    Init = Result.get();
13031
0
    DefaultedAnyToId = true;
13032
0
  }
13033
13034
  // C++ [dcl.decomp]p1:
13035
  //   If the assignment-expression [...] has array type A and no ref-qualifier
13036
  //   is present, e has type cv A
13037
0
  if (VDecl && isa<DecompositionDecl>(VDecl) &&
13038
0
      Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13039
0
      DeduceInit->getType()->isConstantArrayType())
13040
0
    return Context.getQualifiedType(DeduceInit->getType(),
13041
0
                                    Type.getQualifiers());
13042
13043
0
  QualType DeducedType;
13044
0
  TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13045
0
  TemplateDeductionResult Result =
13046
0
      DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13047
0
  if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed) {
13048
0
    if (!IsInitCapture)
13049
0
      DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13050
0
    else if (isa<InitListExpr>(Init))
13051
0
      Diag(Range.getBegin(),
13052
0
           diag::err_init_capture_deduction_failure_from_init_list)
13053
0
          << VN
13054
0
          << (DeduceInit->getType().isNull() ? TSI->getType()
13055
0
                                             : DeduceInit->getType())
13056
0
          << DeduceInit->getSourceRange();
13057
0
    else
13058
0
      Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13059
0
          << VN << TSI->getType()
13060
0
          << (DeduceInit->getType().isNull() ? TSI->getType()
13061
0
                                             : DeduceInit->getType())
13062
0
          << DeduceInit->getSourceRange();
13063
0
  }
13064
13065
  // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13066
  // 'id' instead of a specific object type prevents most of our usual
13067
  // checks.
13068
  // We only want to warn outside of template instantiations, though:
13069
  // inside a template, the 'id' could have come from a parameter.
13070
0
  if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13071
0
      !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13072
0
    SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13073
0
    Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13074
0
  }
13075
13076
0
  return DeducedType;
13077
0
}
13078
13079
bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13080
0
                                         Expr *Init) {
13081
0
  assert(!Init || !Init->containsErrors());
13082
0
  QualType DeducedType = deduceVarTypeFromInitializer(
13083
0
      VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13084
0
      VDecl->getSourceRange(), DirectInit, Init);
13085
0
  if (DeducedType.isNull()) {
13086
0
    VDecl->setInvalidDecl();
13087
0
    return true;
13088
0
  }
13089
13090
0
  VDecl->setType(DeducedType);
13091
0
  assert(VDecl->isLinkageValid());
13092
13093
  // In ARC, infer lifetime.
13094
0
  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
13095
0
    VDecl->setInvalidDecl();
13096
13097
0
  if (getLangOpts().OpenCL)
13098
0
    deduceOpenCLAddressSpace(VDecl);
13099
13100
  // If this is a redeclaration, check that the type we just deduced matches
13101
  // the previously declared type.
13102
0
  if (VarDecl *Old = VDecl->getPreviousDecl()) {
13103
    // We never need to merge the type, because we cannot form an incomplete
13104
    // array of auto, nor deduce such a type.
13105
0
    MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13106
0
  }
13107
13108
  // Check the deduced type is valid for a variable declaration.
13109
0
  CheckVariableDeclarationType(VDecl);
13110
0
  return VDecl->isInvalidDecl();
13111
0
}
13112
13113
void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13114
0
                                              SourceLocation Loc) {
13115
0
  if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13116
0
    Init = EWC->getSubExpr();
13117
13118
0
  if (auto *CE = dyn_cast<ConstantExpr>(Init))
13119
0
    Init = CE->getSubExpr();
13120
13121
0
  QualType InitType = Init->getType();
13122
0
  assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13123
0
          InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13124
0
         "shouldn't be called if type doesn't have a non-trivial C struct");
13125
0
  if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13126
0
    for (auto *I : ILE->inits()) {
13127
0
      if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13128
0
          !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13129
0
        continue;
13130
0
      SourceLocation SL = I->getExprLoc();
13131
0
      checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13132
0
    }
13133
0
    return;
13134
0
  }
13135
13136
0
  if (isa<ImplicitValueInitExpr>(Init)) {
13137
0
    if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13138
0
      checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
13139
0
                            NTCUK_Init);
13140
0
  } else {
13141
    // Assume all other explicit initializers involving copying some existing
13142
    // object.
13143
    // TODO: ignore any explicit initializers where we can guarantee
13144
    // copy-elision.
13145
0
    if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13146
0
      checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
13147
0
  }
13148
0
}
13149
13150
namespace {
13151
13152
0
bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13153
  // Ignore unavailable fields. A field can be marked as unavailable explicitly
13154
  // in the source code or implicitly by the compiler if it is in a union
13155
  // defined in a system header and has non-trivial ObjC ownership
13156
  // qualifications. We don't want those fields to participate in determining
13157
  // whether the containing union is non-trivial.
13158
0
  return FD->hasAttr<UnavailableAttr>();
13159
0
}
13160
13161
struct DiagNonTrivalCUnionDefaultInitializeVisitor
13162
    : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13163
                                    void> {
13164
  using Super =
13165
      DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13166
                                    void>;
13167
13168
  DiagNonTrivalCUnionDefaultInitializeVisitor(
13169
      QualType OrigTy, SourceLocation OrigLoc,
13170
      Sema::NonTrivialCUnionContext UseContext, Sema &S)
13171
0
      : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13172
13173
  void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13174
0
                     const FieldDecl *FD, bool InNonTrivialUnion) {
13175
0
    if (const auto *AT = S.Context.getAsArrayType(QT))
13176
0
      return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13177
0
                                     InNonTrivialUnion);
13178
0
    return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13179
0
  }
13180
13181
  void visitARCStrong(QualType QT, const FieldDecl *FD,
13182
0
                      bool InNonTrivialUnion) {
13183
0
    if (InNonTrivialUnion)
13184
0
      S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13185
0
          << 1 << 0 << QT << FD->getName();
13186
0
  }
13187
13188
0
  void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13189
0
    if (InNonTrivialUnion)
13190
0
      S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13191
0
          << 1 << 0 << QT << FD->getName();
13192
0
  }
13193
13194
0
  void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13195
0
    const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13196
0
    if (RD->isUnion()) {
13197
0
      if (OrigLoc.isValid()) {
13198
0
        bool IsUnion = false;
13199
0
        if (auto *OrigRD = OrigTy->getAsRecordDecl())
13200
0
          IsUnion = OrigRD->isUnion();
13201
0
        S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13202
0
            << 0 << OrigTy << IsUnion << UseContext;
13203
        // Reset OrigLoc so that this diagnostic is emitted only once.
13204
0
        OrigLoc = SourceLocation();
13205
0
      }
13206
0
      InNonTrivialUnion = true;
13207
0
    }
13208
13209
0
    if (InNonTrivialUnion)
13210
0
      S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13211
0
          << 0 << 0 << QT.getUnqualifiedType() << "";
13212
13213
0
    for (const FieldDecl *FD : RD->fields())
13214
0
      if (!shouldIgnoreForRecordTriviality(FD))
13215
0
        asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13216
0
  }
13217
13218
0
  void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13219
13220
  // The non-trivial C union type or the struct/union type that contains a
13221
  // non-trivial C union.
13222
  QualType OrigTy;
13223
  SourceLocation OrigLoc;
13224
  Sema::NonTrivialCUnionContext UseContext;
13225
  Sema &S;
13226
};
13227
13228
struct DiagNonTrivalCUnionDestructedTypeVisitor
13229
    : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13230
  using Super =
13231
      DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13232
13233
  DiagNonTrivalCUnionDestructedTypeVisitor(
13234
      QualType OrigTy, SourceLocation OrigLoc,
13235
      Sema::NonTrivialCUnionContext UseContext, Sema &S)
13236
0
      : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13237
13238
  void visitWithKind(QualType::DestructionKind DK, QualType QT,
13239
0
                     const FieldDecl *FD, bool InNonTrivialUnion) {
13240
0
    if (const auto *AT = S.Context.getAsArrayType(QT))
13241
0
      return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13242
0
                                     InNonTrivialUnion);
13243
0
    return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13244
0
  }
13245
13246
  void visitARCStrong(QualType QT, const FieldDecl *FD,
13247
0
                      bool InNonTrivialUnion) {
13248
0
    if (InNonTrivialUnion)
13249
0
      S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13250
0
          << 1 << 1 << QT << FD->getName();
13251
0
  }
13252
13253
0
  void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13254
0
    if (InNonTrivialUnion)
13255
0
      S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13256
0
          << 1 << 1 << QT << FD->getName();
13257
0
  }
13258
13259
0
  void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13260
0
    const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13261
0
    if (RD->isUnion()) {
13262
0
      if (OrigLoc.isValid()) {
13263
0
        bool IsUnion = false;
13264
0
        if (auto *OrigRD = OrigTy->getAsRecordDecl())
13265
0
          IsUnion = OrigRD->isUnion();
13266
0
        S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13267
0
            << 1 << OrigTy << IsUnion << UseContext;
13268
        // Reset OrigLoc so that this diagnostic is emitted only once.
13269
0
        OrigLoc = SourceLocation();
13270
0
      }
13271
0
      InNonTrivialUnion = true;
13272
0
    }
13273
13274
0
    if (InNonTrivialUnion)
13275
0
      S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13276
0
          << 0 << 1 << QT.getUnqualifiedType() << "";
13277
13278
0
    for (const FieldDecl *FD : RD->fields())
13279
0
      if (!shouldIgnoreForRecordTriviality(FD))
13280
0
        asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13281
0
  }
13282
13283
0
  void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13284
  void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13285
0
                          bool InNonTrivialUnion) {}
13286
13287
  // The non-trivial C union type or the struct/union type that contains a
13288
  // non-trivial C union.
13289
  QualType OrigTy;
13290
  SourceLocation OrigLoc;
13291
  Sema::NonTrivialCUnionContext UseContext;
13292
  Sema &S;
13293
};
13294
13295
struct DiagNonTrivalCUnionCopyVisitor
13296
    : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13297
  using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13298
13299
  DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13300
                                 Sema::NonTrivialCUnionContext UseContext,
13301
                                 Sema &S)
13302
0
      : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13303
13304
  void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13305
0
                     const FieldDecl *FD, bool InNonTrivialUnion) {
13306
0
    if (const auto *AT = S.Context.getAsArrayType(QT))
13307
0
      return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13308
0
                                     InNonTrivialUnion);
13309
0
    return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13310
0
  }
13311
13312
  void visitARCStrong(QualType QT, const FieldDecl *FD,
13313
0
                      bool InNonTrivialUnion) {
13314
0
    if (InNonTrivialUnion)
13315
0
      S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13316
0
          << 1 << 2 << QT << FD->getName();
13317
0
  }
13318
13319
0
  void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13320
0
    if (InNonTrivialUnion)
13321
0
      S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13322
0
          << 1 << 2 << QT << FD->getName();
13323
0
  }
13324
13325
0
  void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13326
0
    const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13327
0
    if (RD->isUnion()) {
13328
0
      if (OrigLoc.isValid()) {
13329
0
        bool IsUnion = false;
13330
0
        if (auto *OrigRD = OrigTy->getAsRecordDecl())
13331
0
          IsUnion = OrigRD->isUnion();
13332
0
        S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13333
0
            << 2 << OrigTy << IsUnion << UseContext;
13334
        // Reset OrigLoc so that this diagnostic is emitted only once.
13335
0
        OrigLoc = SourceLocation();
13336
0
      }
13337
0
      InNonTrivialUnion = true;
13338
0
    }
13339
13340
0
    if (InNonTrivialUnion)
13341
0
      S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13342
0
          << 0 << 2 << QT.getUnqualifiedType() << "";
13343
13344
0
    for (const FieldDecl *FD : RD->fields())
13345
0
      if (!shouldIgnoreForRecordTriviality(FD))
13346
0
        asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13347
0
  }
13348
13349
  void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13350
0
                const FieldDecl *FD, bool InNonTrivialUnion) {}
13351
0
  void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13352
  void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13353
0
                            bool InNonTrivialUnion) {}
13354
13355
  // The non-trivial C union type or the struct/union type that contains a
13356
  // non-trivial C union.
13357
  QualType OrigTy;
13358
  SourceLocation OrigLoc;
13359
  Sema::NonTrivialCUnionContext UseContext;
13360
  Sema &S;
13361
};
13362
13363
} // namespace
13364
13365
void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13366
                                 NonTrivialCUnionContext UseContext,
13367
0
                                 unsigned NonTrivialKind) {
13368
0
  assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13369
0
          QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13370
0
          QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13371
0
         "shouldn't be called if type doesn't have a non-trivial C union");
13372
13373
0
  if ((NonTrivialKind & NTCUK_Init) &&
13374
0
      QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13375
0
    DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13376
0
        .visit(QT, nullptr, false);
13377
0
  if ((NonTrivialKind & NTCUK_Destruct) &&
13378
0
      QT.hasNonTrivialToPrimitiveDestructCUnion())
13379
0
    DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13380
0
        .visit(QT, nullptr, false);
13381
0
  if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13382
0
    DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13383
0
        .visit(QT, nullptr, false);
13384
0
}
13385
13386
/// AddInitializerToDecl - Adds the initializer Init to the
13387
/// declaration dcl. If DirectInit is true, this is C++ direct
13388
/// initialization rather than copy initialization.
13389
88
void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13390
  // If there is no declaration, there was an error parsing it.  Just ignore
13391
  // the initializer.
13392
88
  if (!RealDecl || RealDecl->isInvalidDecl()) {
13393
68
    CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13394
68
    return;
13395
68
  }
13396
13397
20
  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13398
    // Pure-specifiers are handled in ActOnPureSpecifier.
13399
0
    Diag(Method->getLocation(), diag::err_member_function_initialization)
13400
0
      << Method->getDeclName() << Init->getSourceRange();
13401
0
    Method->setInvalidDecl();
13402
0
    return;
13403
0
  }
13404
13405
20
  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13406
20
  if (!VDecl) {
13407
0
    assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13408
0
    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13409
0
    RealDecl->setInvalidDecl();
13410
0
    return;
13411
0
  }
13412
13413
  // WebAssembly tables can't be used to initialise a variable.
13414
20
  if (Init && !Init->getType().isNull() &&
13415
20
      Init->getType()->isWebAssemblyTableType()) {
13416
0
    Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13417
0
    VDecl->setInvalidDecl();
13418
0
    return;
13419
0
  }
13420
13421
  // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13422
20
  if (VDecl->getType()->isUndeducedType()) {
13423
    // Attempt typo correction early so that the type of the init expression can
13424
    // be deduced based on the chosen correction if the original init contains a
13425
    // TypoExpr.
13426
0
    ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
13427
0
    if (!Res.isUsable()) {
13428
      // There are unresolved typos in Init, just drop them.
13429
      // FIXME: improve the recovery strategy to preserve the Init.
13430
0
      RealDecl->setInvalidDecl();
13431
0
      return;
13432
0
    }
13433
0
    if (Res.get()->containsErrors()) {
13434
      // Invalidate the decl as we don't know the type for recovery-expr yet.
13435
0
      RealDecl->setInvalidDecl();
13436
0
      VDecl->setInit(Res.get());
13437
0
      return;
13438
0
    }
13439
0
    Init = Res.get();
13440
13441
0
    if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13442
0
      return;
13443
0
  }
13444
13445
  // dllimport cannot be used on variable definitions.
13446
20
  if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13447
0
    Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13448
0
    VDecl->setInvalidDecl();
13449
0
    return;
13450
0
  }
13451
13452
  // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13453
  // the identifier has external or internal linkage, the declaration shall
13454
  // have no initializer for the identifier.
13455
  // C++14 [dcl.init]p5 is the same restriction for C++.
13456
20
  if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13457
0
    Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13458
0
    VDecl->setInvalidDecl();
13459
0
    return;
13460
0
  }
13461
13462
20
  if (!VDecl->getType()->isDependentType()) {
13463
    // A definition must end up with a complete type, which means it must be
13464
    // complete with the restriction that an array type might be completed by
13465
    // the initializer; note that later code assumes this restriction.
13466
19
    QualType BaseDeclType = VDecl->getType();
13467
19
    if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13468
0
      BaseDeclType = Array->getElementType();
13469
19
    if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13470
19
                            diag::err_typecheck_decl_incomplete_type)) {
13471
0
      RealDecl->setInvalidDecl();
13472
0
      return;
13473
0
    }
13474
13475
    // The variable can not have an abstract class type.
13476
19
    if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13477
19
                               diag::err_abstract_type_in_decl,
13478
19
                               AbstractVariableType))
13479
0
      VDecl->setInvalidDecl();
13480
19
  }
13481
13482
  // C++ [module.import/6] external definitions are not permitted in header
13483
  // units.
13484
20
  if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13485
20
      !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13486
20
      VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13487
20
      !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl)) {
13488
0
    Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13489
0
    VDecl->setInvalidDecl();
13490
0
  }
13491
13492
  // If adding the initializer will turn this declaration into a definition,
13493
  // and we already have a definition for this variable, diagnose or otherwise
13494
  // handle the situation.
13495
20
  if (VarDecl *Def = VDecl->getDefinition())
13496
0
    if (Def != VDecl &&
13497
0
        (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13498
0
        !VDecl->isThisDeclarationADemotedDefinition() &&
13499
0
        checkVarDeclRedefinition(Def, VDecl))
13500
0
      return;
13501
13502
20
  if (getLangOpts().CPlusPlus) {
13503
    // C++ [class.static.data]p4
13504
    //   If a static data member is of const integral or const
13505
    //   enumeration type, its declaration in the class definition can
13506
    //   specify a constant-initializer which shall be an integral
13507
    //   constant expression (5.19). In that case, the member can appear
13508
    //   in integral constant expressions. The member shall still be
13509
    //   defined in a namespace scope if it is used in the program and the
13510
    //   namespace scope definition shall not contain an initializer.
13511
    //
13512
    // We already performed a redefinition check above, but for static
13513
    // data members we also need to check whether there was an in-class
13514
    // declaration with an initializer.
13515
0
    if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13516
0
      Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13517
0
          << VDecl->getDeclName();
13518
0
      Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13519
0
           diag::note_previous_initializer)
13520
0
          << 0;
13521
0
      return;
13522
0
    }
13523
13524
0
    if (VDecl->hasLocalStorage())
13525
0
      setFunctionHasBranchProtectedScope();
13526
13527
0
    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
13528
0
      VDecl->setInvalidDecl();
13529
0
      return;
13530
0
    }
13531
0
  }
13532
13533
  // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13534
  // a kernel function cannot be initialized."
13535
20
  if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13536
0
    Diag(VDecl->getLocation(), diag::err_local_cant_init);
13537
0
    VDecl->setInvalidDecl();
13538
0
    return;
13539
0
  }
13540
13541
  // The LoaderUninitialized attribute acts as a definition (of undef).
13542
20
  if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13543
0
    Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13544
0
    VDecl->setInvalidDecl();
13545
0
    return;
13546
0
  }
13547
13548
  // Get the decls type and save a reference for later, since
13549
  // CheckInitializerTypes may change it.
13550
20
  QualType DclT = VDecl->getType(), SavT = DclT;
13551
13552
  // Expressions default to 'id' when we're in a debugger
13553
  // and we are assigning it to a variable of Objective-C pointer type.
13554
20
  if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13555
20
      Init->getType() == Context.UnknownAnyTy) {
13556
0
    ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13557
0
    if (Result.isInvalid()) {
13558
0
      VDecl->setInvalidDecl();
13559
0
      return;
13560
0
    }
13561
0
    Init = Result.get();
13562
0
  }
13563
13564
  // Perform the initialization.
13565
20
  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13566
20
  bool IsParenListInit = false;
13567
20
  if (!VDecl->isInvalidDecl()) {
13568
20
    InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
13569
20
    InitializationKind Kind = InitializationKind::CreateForInit(
13570
20
        VDecl->getLocation(), DirectInit, Init);
13571
13572
20
    MultiExprArg Args = Init;
13573
20
    if (CXXDirectInit)
13574
0
      Args = MultiExprArg(CXXDirectInit->getExprs(),
13575
0
                          CXXDirectInit->getNumExprs());
13576
13577
    // Try to correct any TypoExprs in the initialization arguments.
13578
40
    for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13579
20
      ExprResult Res = CorrectDelayedTyposInExpr(
13580
20
          Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13581
20
          [this, Entity, Kind](Expr *E) {
13582
0
            InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13583
0
            return Init.Failed() ? ExprError() : E;
13584
0
          });
13585
20
      if (Res.isInvalid()) {
13586
0
        VDecl->setInvalidDecl();
13587
20
      } else if (Res.get() != Args[Idx]) {
13588
6
        Args[Idx] = Res.get();
13589
6
      }
13590
20
    }
13591
20
    if (VDecl->isInvalidDecl())
13592
0
      return;
13593
13594
20
    InitializationSequence InitSeq(*this, Entity, Kind, Args,
13595
20
                                   /*TopLevelOfInitList=*/false,
13596
20
                                   /*TreatUnavailableAsInvalid=*/false);
13597
20
    ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13598
20
    if (Result.isInvalid()) {
13599
      // If the provided initializer fails to initialize the var decl,
13600
      // we attach a recovery expr for better recovery.
13601
0
      auto RecoveryExpr =
13602
0
          CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13603
0
      if (RecoveryExpr.get())
13604
0
        VDecl->setInit(RecoveryExpr.get());
13605
0
      return;
13606
0
    }
13607
13608
20
    Init = Result.getAs<Expr>();
13609
20
    IsParenListInit = !InitSeq.steps().empty() &&
13610
20
                      InitSeq.step_begin()->Kind ==
13611
7
                          InitializationSequence::SK_ParenthesizedListInit;
13612
20
    QualType VDeclType = VDecl->getType();
13613
20
    if (Init && !Init->getType().isNull() &&
13614
20
        !Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
13615
20
        Context.getAsIncompleteArrayType(VDeclType) &&
13616
20
        Context.getAsIncompleteArrayType(Init->getType())) {
13617
      // Bail out if it is not possible to deduce array size from the
13618
      // initializer.
13619
0
      Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13620
0
          << VDeclType;
13621
0
      VDecl->setInvalidDecl();
13622
0
      return;
13623
0
    }
13624
20
  }
13625
13626
  // Check for self-references within variable initializers.
13627
  // Variables declared within a function/method body (except for references)
13628
  // are handled by a dataflow analysis.
13629
  // This is undefined behavior in C++, but valid in C.
13630
20
  if (getLangOpts().CPlusPlus)
13631
0
    if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13632
0
        VDecl->getType()->isReferenceType())
13633
0
      CheckSelfReference(*this, RealDecl, Init, DirectInit);
13634
13635
  // If the type changed, it means we had an incomplete type that was
13636
  // completed by the initializer. For example:
13637
  //   int ary[] = { 1, 3, 5 };
13638
  // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13639
20
  if (!VDecl->isInvalidDecl() && (DclT != SavT))
13640
0
    VDecl->setType(DclT);
13641
13642
20
  if (!VDecl->isInvalidDecl()) {
13643
20
    checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13644
13645
20
    if (VDecl->hasAttr<BlocksAttr>())
13646
0
      checkRetainCycles(VDecl, Init);
13647
13648
    // It is safe to assign a weak reference into a strong variable.
13649
    // Although this code can still have problems:
13650
    //   id x = self.weakProp;
13651
    //   id y = self.weakProp;
13652
    // we do not warn to warn spuriously when 'x' and 'y' are on separate
13653
    // paths through the function. This should be revisited if
13654
    // -Wrepeated-use-of-weak is made flow-sensitive.
13655
20
    if (FunctionScopeInfo *FSI = getCurFunction())
13656
0
      if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13657
0
           VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13658
0
          !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13659
0
                           Init->getBeginLoc()))
13660
0
        FSI->markSafeWeakUse(Init);
13661
20
  }
13662
13663
  // The initialization is usually a full-expression.
13664
  //
13665
  // FIXME: If this is a braced initialization of an aggregate, it is not
13666
  // an expression, and each individual field initializer is a separate
13667
  // full-expression. For instance, in:
13668
  //
13669
  //   struct Temp { ~Temp(); };
13670
  //   struct S { S(Temp); };
13671
  //   struct T { S a, b; } t = { Temp(), Temp() }
13672
  //
13673
  // we should destroy the first Temp before constructing the second.
13674
20
  ExprResult Result =
13675
20
      ActOnFinishFullExpr(Init, VDecl->getLocation(),
13676
20
                          /*DiscardedValue*/ false, VDecl->isConstexpr());
13677
20
  if (Result.isInvalid()) {
13678
0
    VDecl->setInvalidDecl();
13679
0
    return;
13680
0
  }
13681
20
  Init = Result.get();
13682
13683
  // Attach the initializer to the decl.
13684
20
  VDecl->setInit(Init);
13685
13686
20
  if (VDecl->isLocalVarDecl()) {
13687
    // Don't check the initializer if the declaration is malformed.
13688
0
    if (VDecl->isInvalidDecl()) {
13689
      // do nothing
13690
13691
    // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13692
    // This is true even in C++ for OpenCL.
13693
0
    } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13694
0
      CheckForConstantInitializer(Init, DclT);
13695
13696
    // Otherwise, C++ does not restrict the initializer.
13697
0
    } else if (getLangOpts().CPlusPlus) {
13698
      // do nothing
13699
13700
    // C99 6.7.8p4: All the expressions in an initializer for an object that has
13701
    // static storage duration shall be constant expressions or string literals.
13702
0
    } else if (VDecl->getStorageClass() == SC_Static) {
13703
0
      CheckForConstantInitializer(Init, DclT);
13704
13705
    // C89 is stricter than C99 for aggregate initializers.
13706
    // C89 6.5.7p3: All the expressions [...] in an initializer list
13707
    // for an object that has aggregate or union type shall be
13708
    // constant expressions.
13709
0
    } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13710
0
               isa<InitListExpr>(Init)) {
13711
0
      const Expr *Culprit;
13712
0
      if (!Init->isConstantInitializer(Context, false, &Culprit)) {
13713
0
        Diag(Culprit->getExprLoc(),
13714
0
             diag::ext_aggregate_init_not_constant)
13715
0
          << Culprit->getSourceRange();
13716
0
      }
13717
0
    }
13718
13719
0
    if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13720
0
      if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13721
0
        if (VDecl->hasLocalStorage())
13722
0
          BE->getBlockDecl()->setCanAvoidCopyToHeap();
13723
20
  } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13724
20
             VDecl->getLexicalDeclContext()->isRecord()) {
13725
    // This is an in-class initialization for a static data member, e.g.,
13726
    //
13727
    // struct S {
13728
    //   static const int value = 17;
13729
    // };
13730
13731
    // C++ [class.mem]p4:
13732
    //   A member-declarator can contain a constant-initializer only
13733
    //   if it declares a static member (9.4) of const integral or
13734
    //   const enumeration type, see 9.4.2.
13735
    //
13736
    // C++11 [class.static.data]p3:
13737
    //   If a non-volatile non-inline const static data member is of integral
13738
    //   or enumeration type, its declaration in the class definition can
13739
    //   specify a brace-or-equal-initializer in which every initializer-clause
13740
    //   that is an assignment-expression is a constant expression. A static
13741
    //   data member of literal type can be declared in the class definition
13742
    //   with the constexpr specifier; if so, its declaration shall specify a
13743
    //   brace-or-equal-initializer in which every initializer-clause that is
13744
    //   an assignment-expression is a constant expression.
13745
13746
    // Do nothing on dependent types.
13747
0
    if (DclT->isDependentType()) {
13748
13749
    // Allow any 'static constexpr' members, whether or not they are of literal
13750
    // type. We separately check that every constexpr variable is of literal
13751
    // type.
13752
0
    } else if (VDecl->isConstexpr()) {
13753
13754
    // Require constness.
13755
0
    } else if (!DclT.isConstQualified()) {
13756
0
      Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13757
0
        << Init->getSourceRange();
13758
0
      VDecl->setInvalidDecl();
13759
13760
    // We allow integer constant expressions in all cases.
13761
0
    } else if (DclT->isIntegralOrEnumerationType()) {
13762
      // Check whether the expression is a constant expression.
13763
0
      SourceLocation Loc;
13764
0
      if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
13765
        // In C++11, a non-constexpr const static data member with an
13766
        // in-class initializer cannot be volatile.
13767
0
        Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13768
0
      else if (Init->isValueDependent())
13769
0
        ; // Nothing to check.
13770
0
      else if (Init->isIntegerConstantExpr(Context, &Loc))
13771
0
        ; // Ok, it's an ICE!
13772
0
      else if (Init->getType()->isScopedEnumeralType() &&
13773
0
               Init->isCXX11ConstantExpr(Context))
13774
0
        ; // Ok, it is a scoped-enum constant expression.
13775
0
      else if (Init->isEvaluatable(Context)) {
13776
        // If we can constant fold the initializer through heroics, accept it,
13777
        // but report this as a use of an extension for -pedantic.
13778
0
        Diag(Loc, diag::ext_in_class_initializer_non_constant)
13779
0
          << Init->getSourceRange();
13780
0
      } else {
13781
        // Otherwise, this is some crazy unknown case.  Report the issue at the
13782
        // location provided by the isIntegerConstantExpr failed check.
13783
0
        Diag(Loc, diag::err_in_class_initializer_non_constant)
13784
0
          << Init->getSourceRange();
13785
0
        VDecl->setInvalidDecl();
13786
0
      }
13787
13788
    // We allow foldable floating-point constants as an extension.
13789
0
    } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13790
      // In C++98, this is a GNU extension. In C++11, it is not, but we support
13791
      // it anyway and provide a fixit to add the 'constexpr'.
13792
0
      if (getLangOpts().CPlusPlus11) {
13793
0
        Diag(VDecl->getLocation(),
13794
0
             diag::ext_in_class_initializer_float_type_cxx11)
13795
0
            << DclT << Init->getSourceRange();
13796
0
        Diag(VDecl->getBeginLoc(),
13797
0
             diag::note_in_class_initializer_float_type_cxx11)
13798
0
            << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13799
0
      } else {
13800
0
        Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13801
0
          << DclT << Init->getSourceRange();
13802
13803
0
        if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13804
0
          Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13805
0
            << Init->getSourceRange();
13806
0
          VDecl->setInvalidDecl();
13807
0
        }
13808
0
      }
13809
13810
    // Suggest adding 'constexpr' in C++11 for literal types.
13811
0
    } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13812
0
      Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13813
0
          << DclT << Init->getSourceRange()
13814
0
          << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13815
0
      VDecl->setConstexpr(true);
13816
13817
0
    } else {
13818
0
      Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13819
0
        << DclT << Init->getSourceRange();
13820
0
      VDecl->setInvalidDecl();
13821
0
    }
13822
20
  } else if (VDecl->isFileVarDecl()) {
13823
    // In C, extern is typically used to avoid tentative definitions when
13824
    // declaring variables in headers, but adding an intializer makes it a
13825
    // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13826
    // In C++, extern is often used to give implictly static const variables
13827
    // external linkage, so don't warn in that case. If selectany is present,
13828
    // this might be header code intended for C and C++ inclusion, so apply the
13829
    // C++ rules.
13830
20
    if (VDecl->getStorageClass() == SC_Extern &&
13831
20
        ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13832
0
         !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
13833
20
        !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13834
20
        !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
13835
0
      Diag(VDecl->getLocation(), diag::warn_extern_init);
13836
13837
    // In Microsoft C++ mode, a const variable defined in namespace scope has
13838
    // external linkage by default if the variable is declared with
13839
    // __declspec(dllexport).
13840
20
    if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13841
20
        getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
13842
20
        VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13843
0
      VDecl->setStorageClass(SC_Extern);
13844
13845
    // C99 6.7.8p4. All file scoped initializers need to be constant.
13846
20
    if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
13847
20
      CheckForConstantInitializer(Init, DclT);
13848
20
  }
13849
13850
20
  QualType InitType = Init->getType();
13851
20
  if (!InitType.isNull() &&
13852
20
      (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13853
20
       InitType.hasNonTrivialToPrimitiveCopyCUnion()))
13854
0
    checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
13855
13856
  // We will represent direct-initialization similarly to copy-initialization:
13857
  //    int x(1);  -as-> int x = 1;
13858
  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13859
  //
13860
  // Clients that want to distinguish between the two forms, can check for
13861
  // direct initializer using VarDecl::getInitStyle().
13862
  // A major benefit is that clients that don't particularly care about which
13863
  // exactly form was it (like the CodeGen) can handle both cases without
13864
  // special case code.
13865
13866
  // C++ 8.5p11:
13867
  // The form of initialization (using parentheses or '=') is generally
13868
  // insignificant, but does matter when the entity being initialized has a
13869
  // class type.
13870
20
  if (CXXDirectInit) {
13871
0
    assert(DirectInit && "Call-style initializer must be direct init.");
13872
0
    VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13873
0
                                        : VarDecl::CallInit);
13874
20
  } else if (DirectInit) {
13875
    // This must be list-initialization. No other way is direct-initialization.
13876
0
    VDecl->setInitStyle(VarDecl::ListInit);
13877
0
  }
13878
13879
20
  if (LangOpts.OpenMP &&
13880
20
      (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13881
20
      VDecl->isFileVarDecl())
13882
0
    DeclsToCheckForDeferredDiags.insert(VDecl);
13883
20
  CheckCompleteVariableDeclaration(VDecl);
13884
20
}
13885
13886
/// ActOnInitializerError - Given that there was an error parsing an
13887
/// initializer for the given declaration, try to at least re-establish
13888
/// invariants such as whether a variable's type is either dependent or
13889
/// complete.
13890
294
void Sema::ActOnInitializerError(Decl *D) {
13891
  // Our main concern here is re-establishing invariants like "a
13892
  // variable's type is either dependent or complete".
13893
294
  if (!D || D->isInvalidDecl()) return;
13894
13895
32
  VarDecl *VD = dyn_cast<VarDecl>(D);
13896
32
  if (!VD) return;
13897
13898
  // Bindings are not usable if we can't make sense of the initializer.
13899
32
  if (auto *DD = dyn_cast<DecompositionDecl>(D))
13900
0
    for (auto *BD : DD->bindings())
13901
0
      BD->setInvalidDecl();
13902
13903
  // Auto types are meaningless if we can't make sense of the initializer.
13904
32
  if (VD->getType()->isUndeducedType()) {
13905
0
    D->setInvalidDecl();
13906
0
    return;
13907
0
  }
13908
13909
32
  QualType Ty = VD->getType();
13910
32
  if (Ty->isDependentType()) return;
13911
13912
  // Require a complete type.
13913
32
  if (RequireCompleteType(VD->getLocation(),
13914
32
                          Context.getBaseElementType(Ty),
13915
32
                          diag::err_typecheck_decl_incomplete_type)) {
13916
0
    VD->setInvalidDecl();
13917
0
    return;
13918
0
  }
13919
13920
  // Require a non-abstract type.
13921
32
  if (RequireNonAbstractType(VD->getLocation(), Ty,
13922
32
                             diag::err_abstract_type_in_decl,
13923
32
                             AbstractVariableType)) {
13924
0
    VD->setInvalidDecl();
13925
0
    return;
13926
0
  }
13927
13928
  // Don't bother complaining about constructors or destructors,
13929
  // though.
13930
32
}
13931
13932
4.70k
void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13933
  // If there is no declaration, there was an error parsing it. Just ignore it.
13934
4.70k
  if (!RealDecl)
13935
0
    return;
13936
13937
4.70k
  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13938
4.68k
    QualType Type = Var->getType();
13939
13940
    // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13941
4.68k
    if (isa<DecompositionDecl>(RealDecl)) {
13942
0
      Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13943
0
      Var->setInvalidDecl();
13944
0
      return;
13945
0
    }
13946
13947
4.68k
    if (Type->isUndeducedType() &&
13948
4.68k
        DeduceVariableDeclarationType(Var, false, nullptr))
13949
0
      return;
13950
13951
    // C++11 [class.static.data]p3: A static data member can be declared with
13952
    // the constexpr specifier; if so, its declaration shall specify
13953
    // a brace-or-equal-initializer.
13954
    // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13955
    // the definition of a variable [...] or the declaration of a static data
13956
    // member.
13957
4.68k
    if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13958
4.68k
        !Var->isThisDeclarationADemotedDefinition()) {
13959
0
      if (Var->isStaticDataMember()) {
13960
        // C++1z removes the relevant rule; the in-class declaration is always
13961
        // a definition there.
13962
0
        if (!getLangOpts().CPlusPlus17 &&
13963
0
            !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13964
0
          Diag(Var->getLocation(),
13965
0
               diag::err_constexpr_static_mem_var_requires_init)
13966
0
              << Var;
13967
0
          Var->setInvalidDecl();
13968
0
          return;
13969
0
        }
13970
0
      } else {
13971
0
        Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13972
0
        Var->setInvalidDecl();
13973
0
        return;
13974
0
      }
13975
0
    }
13976
13977
    // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13978
    // be initialized.
13979
4.68k
    if (!Var->isInvalidDecl() &&
13980
4.68k
        Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13981
4.68k
        Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13982
0
      bool HasConstExprDefaultConstructor = false;
13983
0
      if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13984
0
        for (auto *Ctor : RD->ctors()) {
13985
0
          if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13986
0
              Ctor->getMethodQualifiers().getAddressSpace() ==
13987
0
                  LangAS::opencl_constant) {
13988
0
            HasConstExprDefaultConstructor = true;
13989
0
          }
13990
0
        }
13991
0
      }
13992
0
      if (!HasConstExprDefaultConstructor) {
13993
0
        Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13994
0
        Var->setInvalidDecl();
13995
0
        return;
13996
0
      }
13997
0
    }
13998
13999
4.68k
    if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14000
0
      if (Var->getStorageClass() == SC_Extern) {
14001
0
        Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14002
0
            << Var;
14003
0
        Var->setInvalidDecl();
14004
0
        return;
14005
0
      }
14006
0
      if (RequireCompleteType(Var->getLocation(), Var->getType(),
14007
0
                              diag::err_typecheck_decl_incomplete_type)) {
14008
0
        Var->setInvalidDecl();
14009
0
        return;
14010
0
      }
14011
0
      if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14012
0
        if (!RD->hasTrivialDefaultConstructor()) {
14013
0
          Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14014
0
          Var->setInvalidDecl();
14015
0
          return;
14016
0
        }
14017
0
      }
14018
      // The declaration is unitialized, no need for further checks.
14019
0
      return;
14020
0
    }
14021
14022
4.68k
    VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14023
4.68k
    if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14024
4.68k
        Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14025
0
      checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14026
0
                            NTCUC_DefaultInitializedObject, NTCUK_Init);
14027
14028
14029
4.68k
    switch (DefKind) {
14030
2.27k
    case VarDecl::Definition:
14031
2.27k
      if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14032
2.27k
        break;
14033
14034
      // We have an out-of-line definition of a static data member
14035
      // that has an in-class initializer, so we type-check this like
14036
      // a declaration.
14037
      //
14038
2.27k
      [[fallthrough]];
14039
14040
0
    case VarDecl::DeclarationOnly:
14041
      // It's only a declaration.
14042
14043
      // Block scope. C99 6.7p7: If an identifier for an object is
14044
      // declared with no linkage (C99 6.2.2p6), the type for the
14045
      // object shall be complete.
14046
0
      if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14047
0
          !Var->hasLinkage() && !Var->isInvalidDecl() &&
14048
0
          RequireCompleteType(Var->getLocation(), Type,
14049
0
                              diag::err_typecheck_decl_incomplete_type))
14050
0
        Var->setInvalidDecl();
14051
14052
      // Make sure that the type is not abstract.
14053
0
      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14054
0
          RequireNonAbstractType(Var->getLocation(), Type,
14055
0
                                 diag::err_abstract_type_in_decl,
14056
0
                                 AbstractVariableType))
14057
0
        Var->setInvalidDecl();
14058
0
      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14059
0
          Var->getStorageClass() == SC_PrivateExtern) {
14060
0
        Diag(Var->getLocation(), diag::warn_private_extern);
14061
0
        Diag(Var->getLocation(), diag::note_private_extern);
14062
0
      }
14063
14064
0
      if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14065
0
          !Var->isInvalidDecl())
14066
0
        ExternalDeclarations.push_back(Var);
14067
14068
0
      return;
14069
14070
2.41k
    case VarDecl::TentativeDefinition:
14071
      // File scope. C99 6.9.2p2: A declaration of an identifier for an
14072
      // object that has file scope without an initializer, and without a
14073
      // storage-class specifier or with the storage-class specifier "static",
14074
      // constitutes a tentative definition. Note: A tentative definition with
14075
      // external linkage is valid (C99 6.2.2p5).
14076
2.41k
      if (!Var->isInvalidDecl()) {
14077
416
        if (const IncompleteArrayType *ArrayT
14078
416
                                    = Context.getAsIncompleteArrayType(Type)) {
14079
0
          if (RequireCompleteSizedType(
14080
0
                  Var->getLocation(), ArrayT->getElementType(),
14081
0
                  diag::err_array_incomplete_or_sizeless_type))
14082
0
            Var->setInvalidDecl();
14083
416
        } else if (Var->getStorageClass() == SC_Static) {
14084
          // C99 6.9.2p3: If the declaration of an identifier for an object is
14085
          // a tentative definition and has internal linkage (C99 6.2.2p3), the
14086
          // declared type shall not be an incomplete type.
14087
          // NOTE: code such as the following
14088
          //     static struct s;
14089
          //     struct s { int a; };
14090
          // is accepted by gcc. Hence here we issue a warning instead of
14091
          // an error and we do not invalidate the static declaration.
14092
          // NOTE: to avoid multiple warnings, only check the first declaration.
14093
0
          if (Var->isFirstDecl())
14094
0
            RequireCompleteType(Var->getLocation(), Type,
14095
0
                                diag::ext_typecheck_decl_incomplete_type);
14096
0
        }
14097
416
      }
14098
14099
      // Record the tentative definition; we're done.
14100
2.41k
      if (!Var->isInvalidDecl())
14101
416
        TentativeDefinitions.push_back(Var);
14102
2.41k
      return;
14103
4.68k
    }
14104
14105
    // Provide a specific diagnostic for uninitialized variable
14106
    // definitions with incomplete array type.
14107
2.27k
    if (Type->isIncompleteArrayType()) {
14108
0
      if (Var->isConstexpr())
14109
0
        Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14110
0
            << Var;
14111
0
      else
14112
0
        Diag(Var->getLocation(),
14113
0
             diag::err_typecheck_incomplete_array_needs_initializer);
14114
0
      Var->setInvalidDecl();
14115
0
      return;
14116
0
    }
14117
14118
    // Provide a specific diagnostic for uninitialized variable
14119
    // definitions with reference type.
14120
2.27k
    if (Type->isReferenceType()) {
14121
53
      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14122
53
          << Var << SourceRange(Var->getLocation(), Var->getLocation());
14123
53
      return;
14124
53
    }
14125
14126
    // Do not attempt to type-check the default initializer for a
14127
    // variable with dependent type.
14128
2.22k
    if (Type->isDependentType())
14129
17
      return;
14130
14131
2.20k
    if (Var->isInvalidDecl())
14132
2.20k
      return;
14133
14134
0
    if (!Var->hasAttr<AliasAttr>()) {
14135
0
      if (RequireCompleteType(Var->getLocation(),
14136
0
                              Context.getBaseElementType(Type),
14137
0
                              diag::err_typecheck_decl_incomplete_type)) {
14138
0
        Var->setInvalidDecl();
14139
0
        return;
14140
0
      }
14141
0
    } else {
14142
0
      return;
14143
0
    }
14144
14145
    // The variable can not have an abstract class type.
14146
0
    if (RequireNonAbstractType(Var->getLocation(), Type,
14147
0
                               diag::err_abstract_type_in_decl,
14148
0
                               AbstractVariableType)) {
14149
0
      Var->setInvalidDecl();
14150
0
      return;
14151
0
    }
14152
14153
    // Check for jumps past the implicit initializer.  C++0x
14154
    // clarifies that this applies to a "variable with automatic
14155
    // storage duration", not a "local variable".
14156
    // C++11 [stmt.dcl]p3
14157
    //   A program that jumps from a point where a variable with automatic
14158
    //   storage duration is not in scope to a point where it is in scope is
14159
    //   ill-formed unless the variable has scalar type, class type with a
14160
    //   trivial default constructor and a trivial destructor, a cv-qualified
14161
    //   version of one of these types, or an array of one of the preceding
14162
    //   types and is declared without an initializer.
14163
0
    if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14164
0
      if (const RecordType *Record
14165
0
            = Context.getBaseElementType(Type)->getAs<RecordType>()) {
14166
0
        CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14167
        // Mark the function (if we're in one) for further checking even if the
14168
        // looser rules of C++11 do not require such checks, so that we can
14169
        // diagnose incompatibilities with C++98.
14170
0
        if (!CXXRecord->isPOD())
14171
0
          setFunctionHasBranchProtectedScope();
14172
0
      }
14173
0
    }
14174
    // In OpenCL, we can't initialize objects in the __local address space,
14175
    // even implicitly, so don't synthesize an implicit initializer.
14176
0
    if (getLangOpts().OpenCL &&
14177
0
        Var->getType().getAddressSpace() == LangAS::opencl_local)
14178
0
      return;
14179
    // C++03 [dcl.init]p9:
14180
    //   If no initializer is specified for an object, and the
14181
    //   object is of (possibly cv-qualified) non-POD class type (or
14182
    //   array thereof), the object shall be default-initialized; if
14183
    //   the object is of const-qualified type, the underlying class
14184
    //   type shall have a user-declared default
14185
    //   constructor. Otherwise, if no initializer is specified for
14186
    //   a non- static object, the object and its subobjects, if
14187
    //   any, have an indeterminate initial value); if the object
14188
    //   or any of its subobjects are of const-qualified type, the
14189
    //   program is ill-formed.
14190
    // C++0x [dcl.init]p11:
14191
    //   If no initializer is specified for an object, the object is
14192
    //   default-initialized; [...].
14193
0
    InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14194
0
    InitializationKind Kind
14195
0
      = InitializationKind::CreateDefault(Var->getLocation());
14196
14197
0
    InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
14198
0
    ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
14199
14200
0
    if (Init.get()) {
14201
0
      Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14202
      // This is important for template substitution.
14203
0
      Var->setInitStyle(VarDecl::CallInit);
14204
0
    } else if (Init.isInvalid()) {
14205
      // If default-init fails, attach a recovery-expr initializer to track
14206
      // that initialization was attempted and failed.
14207
0
      auto RecoveryExpr =
14208
0
          CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14209
0
      if (RecoveryExpr.get())
14210
0
        Var->setInit(RecoveryExpr.get());
14211
0
    }
14212
14213
0
    CheckCompleteVariableDeclaration(Var);
14214
0
  }
14215
4.70k
}
14216
14217
0
void Sema::ActOnCXXForRangeDecl(Decl *D) {
14218
  // If there is no declaration, there was an error parsing it. Ignore it.
14219
0
  if (!D)
14220
0
    return;
14221
14222
0
  VarDecl *VD = dyn_cast<VarDecl>(D);
14223
0
  if (!VD) {
14224
0
    Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14225
0
    D->setInvalidDecl();
14226
0
    return;
14227
0
  }
14228
14229
0
  VD->setCXXForRangeDecl(true);
14230
14231
  // for-range-declaration cannot be given a storage class specifier.
14232
0
  int Error = -1;
14233
0
  switch (VD->getStorageClass()) {
14234
0
  case SC_None:
14235
0
    break;
14236
0
  case SC_Extern:
14237
0
    Error = 0;
14238
0
    break;
14239
0
  case SC_Static:
14240
0
    Error = 1;
14241
0
    break;
14242
0
  case SC_PrivateExtern:
14243
0
    Error = 2;
14244
0
    break;
14245
0
  case SC_Auto:
14246
0
    Error = 3;
14247
0
    break;
14248
0
  case SC_Register:
14249
0
    Error = 4;
14250
0
    break;
14251
0
  }
14252
14253
  // for-range-declaration cannot be given a storage class specifier con't.
14254
0
  switch (VD->getTSCSpec()) {
14255
0
  case TSCS_thread_local:
14256
0
    Error = 6;
14257
0
    break;
14258
0
  case TSCS___thread:
14259
0
  case TSCS__Thread_local:
14260
0
  case TSCS_unspecified:
14261
0
    break;
14262
0
  }
14263
14264
0
  if (Error != -1) {
14265
0
    Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14266
0
        << VD << Error;
14267
0
    D->setInvalidDecl();
14268
0
  }
14269
0
}
14270
14271
StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14272
                                            IdentifierInfo *Ident,
14273
0
                                            ParsedAttributes &Attrs) {
14274
  // C++1y [stmt.iter]p1:
14275
  //   A range-based for statement of the form
14276
  //      for ( for-range-identifier : for-range-initializer ) statement
14277
  //   is equivalent to
14278
  //      for ( auto&& for-range-identifier : for-range-initializer ) statement
14279
0
  DeclSpec DS(Attrs.getPool().getFactory());
14280
14281
0
  const char *PrevSpec;
14282
0
  unsigned DiagID;
14283
0
  DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14284
0
                     getPrintingPolicy());
14285
14286
0
  Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14287
0
  D.SetIdentifier(Ident, IdentLoc);
14288
0
  D.takeAttributes(Attrs);
14289
14290
0
  D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14291
0
                IdentLoc);
14292
0
  Decl *Var = ActOnDeclarator(S, D);
14293
0
  cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14294
0
  FinalizeDeclaration(Var);
14295
0
  return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14296
0
                       Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14297
0
                                                      : IdentLoc);
14298
0
}
14299
14300
387
void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14301
387
  if (var->isInvalidDecl()) return;
14302
14303
387
  MaybeAddCUDAConstantAttr(var);
14304
14305
387
  if (getLangOpts().OpenCL) {
14306
    // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14307
    // initialiser
14308
0
    if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14309
0
        !var->hasInit()) {
14310
0
      Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14311
0
          << 1 /*Init*/;
14312
0
      var->setInvalidDecl();
14313
0
      return;
14314
0
    }
14315
0
  }
14316
14317
  // In Objective-C, don't allow jumps past the implicit initialization of a
14318
  // local retaining variable.
14319
387
  if (getLangOpts().ObjC &&
14320
387
      var->hasLocalStorage()) {
14321
0
    switch (var->getType().getObjCLifetime()) {
14322
0
    case Qualifiers::OCL_None:
14323
0
    case Qualifiers::OCL_ExplicitNone:
14324
0
    case Qualifiers::OCL_Autoreleasing:
14325
0
      break;
14326
14327
0
    case Qualifiers::OCL_Weak:
14328
0
    case Qualifiers::OCL_Strong:
14329
0
      setFunctionHasBranchProtectedScope();
14330
0
      break;
14331
0
    }
14332
0
  }
14333
14334
387
  if (var->hasLocalStorage() &&
14335
387
      var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14336
0
    setFunctionHasBranchProtectedScope();
14337
14338
  // Warn about externally-visible variables being defined without a
14339
  // prior declaration.  We only want to do this for global
14340
  // declarations, but we also specifically need to avoid doing it for
14341
  // class members because the linkage of an anonymous class can
14342
  // change if it's later given a typedef name.
14343
387
  if (var->isThisDeclarationADefinition() &&
14344
387
      var->getDeclContext()->getRedeclContext()->isFileContext() &&
14345
387
      var->isExternallyVisible() && var->hasLinkage() &&
14346
387
      !var->isInline() && !var->getDescribedVarTemplate() &&
14347
387
      var->getStorageClass() != SC_Register &&
14348
387
      !isa<VarTemplatePartialSpecializationDecl>(var) &&
14349
387
      !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14350
387
      !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14351
387
                                  var->getLocation())) {
14352
    // Find a previous declaration that's not a definition.
14353
0
    VarDecl *prev = var->getPreviousDecl();
14354
0
    while (prev && prev->isThisDeclarationADefinition())
14355
0
      prev = prev->getPreviousDecl();
14356
14357
0
    if (!prev) {
14358
0
      Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14359
0
      Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14360
0
          << /* variable */ 0;
14361
0
    }
14362
0
  }
14363
14364
  // Cache the result of checking for constant initialization.
14365
387
  std::optional<bool> CacheHasConstInit;
14366
387
  const Expr *CacheCulprit = nullptr;
14367
387
  auto checkConstInit = [&]() mutable {
14368
0
    if (!CacheHasConstInit)
14369
0
      CacheHasConstInit = var->getInit()->isConstantInitializer(
14370
0
            Context, var->getType()->isReferenceType(), &CacheCulprit);
14371
0
    return *CacheHasConstInit;
14372
0
  };
14373
14374
387
  if (var->getTLSKind() == VarDecl::TLS_Static) {
14375
0
    if (var->getType().isDestructedType()) {
14376
      // GNU C++98 edits for __thread, [basic.start.term]p3:
14377
      //   The type of an object with thread storage duration shall not
14378
      //   have a non-trivial destructor.
14379
0
      Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14380
0
      if (getLangOpts().CPlusPlus11)
14381
0
        Diag(var->getLocation(), diag::note_use_thread_local);
14382
0
    } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14383
0
      if (!checkConstInit()) {
14384
        // GNU C++98 edits for __thread, [basic.start.init]p4:
14385
        //   An object of thread storage duration shall not require dynamic
14386
        //   initialization.
14387
        // FIXME: Need strict checking here.
14388
0
        Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14389
0
          << CacheCulprit->getSourceRange();
14390
0
        if (getLangOpts().CPlusPlus11)
14391
0
          Diag(var->getLocation(), diag::note_use_thread_local);
14392
0
      }
14393
0
    }
14394
0
  }
14395
14396
14397
387
  if (!var->getType()->isStructureType() && var->hasInit() &&
14398
387
      isa<InitListExpr>(var->getInit())) {
14399
0
    const auto *ILE = cast<InitListExpr>(var->getInit());
14400
0
    unsigned NumInits = ILE->getNumInits();
14401
0
    if (NumInits > 2)
14402
0
      for (unsigned I = 0; I < NumInits; ++I) {
14403
0
        const auto *Init = ILE->getInit(I);
14404
0
        if (!Init)
14405
0
          break;
14406
0
        const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14407
0
        if (!SL)
14408
0
          break;
14409
14410
0
        unsigned NumConcat = SL->getNumConcatenated();
14411
        // Diagnose missing comma in string array initialization.
14412
        // Do not warn when all the elements in the initializer are concatenated
14413
        // together. Do not warn for macros too.
14414
0
        if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14415
0
          bool OnlyOneMissingComma = true;
14416
0
          for (unsigned J = I + 1; J < NumInits; ++J) {
14417
0
            const auto *Init = ILE->getInit(J);
14418
0
            if (!Init)
14419
0
              break;
14420
0
            const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14421
0
            if (!SLJ || SLJ->getNumConcatenated() > 1) {
14422
0
              OnlyOneMissingComma = false;
14423
0
              break;
14424
0
            }
14425
0
          }
14426
14427
0
          if (OnlyOneMissingComma) {
14428
0
            SmallVector<FixItHint, 1> Hints;
14429
0
            for (unsigned i = 0; i < NumConcat - 1; ++i)
14430
0
              Hints.push_back(FixItHint::CreateInsertion(
14431
0
                  PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14432
14433
0
            Diag(SL->getStrTokenLoc(1),
14434
0
                 diag::warn_concatenated_literal_array_init)
14435
0
                << Hints;
14436
0
            Diag(SL->getBeginLoc(),
14437
0
                 diag::note_concatenated_string_literal_silence);
14438
0
          }
14439
          // In any case, stop now.
14440
0
          break;
14441
0
        }
14442
0
      }
14443
0
  }
14444
14445
14446
387
  QualType type = var->getType();
14447
14448
387
  if (var->hasAttr<BlocksAttr>())
14449
0
    getCurFunction()->addByrefBlockVar(var);
14450
14451
387
  Expr *Init = var->getInit();
14452
387
  bool GlobalStorage = var->hasGlobalStorage();
14453
387
  bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14454
387
  QualType baseType = Context.getBaseElementType(type);
14455
387
  bool HasConstInit = true;
14456
14457
  // Check whether the initializer is sufficiently constant.
14458
387
  if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
14459
387
      !Init->isValueDependent() &&
14460
387
      (GlobalStorage || var->isConstexpr() ||
14461
0
       var->mightBeUsableInConstantExpressions(Context))) {
14462
    // If this variable might have a constant initializer or might be usable in
14463
    // constant expressions, check whether or not it actually is now.  We can't
14464
    // do this lazily, because the result might depend on things that change
14465
    // later, such as which constexpr functions happen to be defined.
14466
0
    SmallVector<PartialDiagnosticAt, 8> Notes;
14467
0
    if (!getLangOpts().CPlusPlus11) {
14468
      // Prior to C++11, in contexts where a constant initializer is required,
14469
      // the set of valid constant initializers is described by syntactic rules
14470
      // in [expr.const]p2-6.
14471
      // FIXME: Stricter checking for these rules would be useful for constinit /
14472
      // -Wglobal-constructors.
14473
0
      HasConstInit = checkConstInit();
14474
14475
      // Compute and cache the constant value, and remember that we have a
14476
      // constant initializer.
14477
0
      if (HasConstInit) {
14478
0
        (void)var->checkForConstantInitialization(Notes);
14479
0
        Notes.clear();
14480
0
      } else if (CacheCulprit) {
14481
0
        Notes.emplace_back(CacheCulprit->getExprLoc(),
14482
0
                           PDiag(diag::note_invalid_subexpr_in_const_expr));
14483
0
        Notes.back().second << CacheCulprit->getSourceRange();
14484
0
      }
14485
0
    } else {
14486
      // Evaluate the initializer to see if it's a constant initializer.
14487
0
      HasConstInit = var->checkForConstantInitialization(Notes);
14488
0
    }
14489
14490
0
    if (HasConstInit) {
14491
      // FIXME: Consider replacing the initializer with a ConstantExpr.
14492
0
    } else if (var->isConstexpr()) {
14493
0
      SourceLocation DiagLoc = var->getLocation();
14494
      // If the note doesn't add any useful information other than a source
14495
      // location, fold it into the primary diagnostic.
14496
0
      if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14497
0
                                   diag::note_invalid_subexpr_in_const_expr) {
14498
0
        DiagLoc = Notes[0].first;
14499
0
        Notes.clear();
14500
0
      }
14501
0
      Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14502
0
          << var << Init->getSourceRange();
14503
0
      for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14504
0
        Diag(Notes[I].first, Notes[I].second);
14505
0
    } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14506
0
      auto *Attr = var->getAttr<ConstInitAttr>();
14507
0
      Diag(var->getLocation(), diag::err_require_constant_init_failed)
14508
0
          << Init->getSourceRange();
14509
0
      Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14510
0
          << Attr->getRange() << Attr->isConstinit();
14511
0
      for (auto &it : Notes)
14512
0
        Diag(it.first, it.second);
14513
0
    } else if (IsGlobal &&
14514
0
               !getDiagnostics().isIgnored(diag::warn_global_constructor,
14515
0
                                           var->getLocation())) {
14516
      // Warn about globals which don't have a constant initializer.  Don't
14517
      // warn about globals with a non-trivial destructor because we already
14518
      // warned about them.
14519
0
      CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14520
0
      if (!(RD && !RD->hasTrivialDestructor())) {
14521
        // checkConstInit() here permits trivial default initialization even in
14522
        // C++11 onwards, where such an initializer is not a constant initializer
14523
        // but nonetheless doesn't require a global constructor.
14524
0
        if (!checkConstInit())
14525
0
          Diag(var->getLocation(), diag::warn_global_constructor)
14526
0
              << Init->getSourceRange();
14527
0
      }
14528
0
    }
14529
0
  }
14530
14531
  // Apply section attributes and pragmas to global variables.
14532
387
  if (GlobalStorage && var->isThisDeclarationADefinition() &&
14533
387
      !inTemplateInstantiation()) {
14534
387
    PragmaStack<StringLiteral *> *Stack = nullptr;
14535
387
    int SectionFlags = ASTContext::PSF_Read;
14536
387
    bool MSVCEnv =
14537
387
        Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14538
387
    std::optional<QualType::NonConstantStorageReason> Reason;
14539
387
    if (HasConstInit &&
14540
387
        !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14541
0
      Stack = &ConstSegStack;
14542
387
    } else {
14543
387
      SectionFlags |= ASTContext::PSF_Write;
14544
387
      Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14545
387
    }
14546
387
    if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14547
0
      if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14548
0
        SectionFlags |= ASTContext::PSF_Implicit;
14549
0
      UnifySection(SA->getName(), SectionFlags, var);
14550
387
    } else if (Stack->CurrentValue) {
14551
0
      if (Stack != &ConstSegStack && MSVCEnv &&
14552
0
          ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14553
0
          var->getType().isConstQualified()) {
14554
0
        assert((!Reason || Reason != QualType::NonConstantStorageReason::
14555
0
                                         NonConstNonReferenceType) &&
14556
0
               "This case should've already been handled elsewhere");
14557
0
        Diag(var->getLocation(), diag::warn_section_msvc_compat)
14558
0
                << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14559
0
            ? QualType::NonConstantStorageReason::NonTrivialCtor
14560
0
            : *Reason);
14561
0
      }
14562
0
      SectionFlags |= ASTContext::PSF_Implicit;
14563
0
      auto SectionName = Stack->CurrentValue->getString();
14564
0
      var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14565
0
                                               Stack->CurrentPragmaLocation,
14566
0
                                               SectionAttr::Declspec_allocate));
14567
0
      if (UnifySection(SectionName, SectionFlags, var))
14568
0
        var->dropAttr<SectionAttr>();
14569
0
    }
14570
14571
    // Apply the init_seg attribute if this has an initializer.  If the
14572
    // initializer turns out to not be dynamic, we'll end up ignoring this
14573
    // attribute.
14574
387
    if (CurInitSeg && var->getInit())
14575
0
      var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14576
0
                                               CurInitSegLoc));
14577
387
  }
14578
14579
  // All the following checks are C++ only.
14580
387
  if (!getLangOpts().CPlusPlus) {
14581
    // If this variable must be emitted, add it as an initializer for the
14582
    // current module.
14583
387
    if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14584
0
      Context.addModuleInitializer(ModuleScopes.back().Module, var);
14585
387
    return;
14586
387
  }
14587
14588
  // Require the destructor.
14589
0
  if (!type->isDependentType())
14590
0
    if (const RecordType *recordType = baseType->getAs<RecordType>())
14591
0
      FinalizeVarWithDestructor(var, recordType);
14592
14593
  // If this variable must be emitted, add it as an initializer for the current
14594
  // module.
14595
0
  if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14596
0
    Context.addModuleInitializer(ModuleScopes.back().Module, var);
14597
14598
  // Build the bindings if this is a structured binding declaration.
14599
0
  if (auto *DD = dyn_cast<DecompositionDecl>(var))
14600
0
    CheckCompleteDecompositionDeclaration(DD);
14601
0
}
14602
14603
/// Check if VD needs to be dllexport/dllimport due to being in a
14604
/// dllexport/import function.
14605
0
void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
14606
0
  assert(VD->isStaticLocal());
14607
14608
0
  auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14609
14610
  // Find outermost function when VD is in lambda function.
14611
0
  while (FD && !getDLLAttr(FD) &&
14612
0
         !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14613
0
         !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14614
0
    FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14615
0
  }
14616
14617
0
  if (!FD)
14618
0
    return;
14619
14620
  // Static locals inherit dll attributes from their function.
14621
0
  if (Attr *A = getDLLAttr(FD)) {
14622
0
    auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14623
0
    NewAttr->setInherited(true);
14624
0
    VD->addAttr(NewAttr);
14625
0
  } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14626
0
    auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14627
0
    NewAttr->setInherited(true);
14628
0
    VD->addAttr(NewAttr);
14629
14630
    // Export this function to enforce exporting this static variable even
14631
    // if it is not used in this compilation unit.
14632
0
    if (!FD->hasAttr<DLLExportAttr>())
14633
0
      FD->addAttr(NewAttr);
14634
14635
0
  } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14636
0
    auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14637
0
    NewAttr->setInherited(true);
14638
0
    VD->addAttr(NewAttr);
14639
0
  }
14640
0
}
14641
14642
0
void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
14643
0
  assert(VD->getTLSKind());
14644
14645
  // Perform TLS alignment check here after attributes attached to the variable
14646
  // which may affect the alignment have been processed. Only perform the check
14647
  // if the target has a maximum TLS alignment (zero means no constraints).
14648
0
  if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14649
    // Protect the check so that it's not performed on dependent types and
14650
    // dependent alignments (we can't determine the alignment in that case).
14651
0
    if (!VD->hasDependentAlignment()) {
14652
0
      CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14653
0
      if (Context.getDeclAlign(VD) > MaxAlignChars) {
14654
0
        Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14655
0
            << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
14656
0
            << (unsigned)MaxAlignChars.getQuantity();
14657
0
      }
14658
0
    }
14659
0
  }
14660
0
}
14661
14662
/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14663
/// any semantic actions necessary after any initializer has been attached.
14664
5.08k
void Sema::FinalizeDeclaration(Decl *ThisDecl) {
14665
  // Note that we are no longer parsing the initializer for this declaration.
14666
5.08k
  ParsingInitForAutoVars.erase(ThisDecl);
14667
14668
5.08k
  VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14669
5.08k
  if (!VD)
14670
19
    return;
14671
14672
  // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14673
5.07k
  if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14674
5.07k
      !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14675
5.07k
    if (PragmaClangBSSSection.Valid)
14676
0
      VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14677
0
          Context, PragmaClangBSSSection.SectionName,
14678
0
          PragmaClangBSSSection.PragmaLocation));
14679
5.07k
    if (PragmaClangDataSection.Valid)
14680
0
      VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14681
0
          Context, PragmaClangDataSection.SectionName,
14682
0
          PragmaClangDataSection.PragmaLocation));
14683
5.07k
    if (PragmaClangRodataSection.Valid)
14684
0
      VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14685
0
          Context, PragmaClangRodataSection.SectionName,
14686
0
          PragmaClangRodataSection.PragmaLocation));
14687
5.07k
    if (PragmaClangRelroSection.Valid)
14688
0
      VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14689
0
          Context, PragmaClangRelroSection.SectionName,
14690
0
          PragmaClangRelroSection.PragmaLocation));
14691
5.07k
  }
14692
14693
5.07k
  if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14694
0
    for (auto *BD : DD->bindings()) {
14695
0
      FinalizeDeclaration(BD);
14696
0
    }
14697
0
  }
14698
14699
5.07k
  checkAttributesAfterMerging(*this, *VD);
14700
14701
5.07k
  if (VD->isStaticLocal())
14702
0
    CheckStaticLocalForDllExport(VD);
14703
14704
5.07k
  if (VD->getTLSKind())
14705
0
    CheckThreadLocalForLargeAlignment(VD);
14706
14707
  // Perform check for initializers of device-side global variables.
14708
  // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14709
  // 7.5). We must also apply the same checks to all __shared__
14710
  // variables whether they are local or not. CUDA also allows
14711
  // constant initializers for __constant__ and __device__ variables.
14712
5.07k
  if (getLangOpts().CUDA)
14713
0
    checkAllowedCUDAInitializer(VD);
14714
14715
  // Grab the dllimport or dllexport attribute off of the VarDecl.
14716
5.07k
  const InheritableAttr *DLLAttr = getDLLAttr(VD);
14717
14718
  // Imported static data members cannot be defined out-of-line.
14719
5.07k
  if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14720
0
    if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14721
0
        VD->isThisDeclarationADefinition()) {
14722
      // We allow definitions of dllimport class template static data members
14723
      // with a warning.
14724
0
      CXXRecordDecl *Context =
14725
0
        cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14726
0
      bool IsClassTemplateMember =
14727
0
          isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14728
0
          Context->getDescribedClassTemplate();
14729
14730
0
      Diag(VD->getLocation(),
14731
0
           IsClassTemplateMember
14732
0
               ? diag::warn_attribute_dllimport_static_field_definition
14733
0
               : diag::err_attribute_dllimport_static_field_definition);
14734
0
      Diag(IA->getLocation(), diag::note_attribute);
14735
0
      if (!IsClassTemplateMember)
14736
0
        VD->setInvalidDecl();
14737
0
    }
14738
0
  }
14739
14740
  // dllimport/dllexport variables cannot be thread local, their TLS index
14741
  // isn't exported with the variable.
14742
5.07k
  if (DLLAttr && VD->getTLSKind()) {
14743
0
    auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14744
0
    if (F && getDLLAttr(F)) {
14745
0
      assert(VD->isStaticLocal());
14746
      // But if this is a static local in a dlimport/dllexport function, the
14747
      // function will never be inlined, which means the var would never be
14748
      // imported, so having it marked import/export is safe.
14749
0
    } else {
14750
0
      Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14751
0
                                                                    << DLLAttr;
14752
0
      VD->setInvalidDecl();
14753
0
    }
14754
0
  }
14755
14756
5.07k
  if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14757
0
    if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14758
0
      Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14759
0
          << Attr;
14760
0
      VD->dropAttr<UsedAttr>();
14761
0
    }
14762
0
  }
14763
5.07k
  if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14764
0
    if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14765
0
      Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14766
0
          << Attr;
14767
0
      VD->dropAttr<RetainAttr>();
14768
0
    }
14769
0
  }
14770
14771
5.07k
  const DeclContext *DC = VD->getDeclContext();
14772
  // If there's a #pragma GCC visibility in scope, and this isn't a class
14773
  // member, set the visibility of this variable.
14774
5.07k
  if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
14775
5.07k
    AddPushedVisibilityAttribute(VD);
14776
14777
  // FIXME: Warn on unused var template partial specializations.
14778
5.07k
  if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14779
5.07k
    MarkUnusedFileScopedDecl(VD);
14780
14781
  // Now we have parsed the initializer and can update the table of magic
14782
  // tag values.
14783
5.07k
  if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14784
5.07k
      !VD->getType()->isIntegralOrEnumerationType())
14785
5.07k
    return;
14786
14787
0
  for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14788
0
    const Expr *MagicValueExpr = VD->getInit();
14789
0
    if (!MagicValueExpr) {
14790
0
      continue;
14791
0
    }
14792
0
    std::optional<llvm::APSInt> MagicValueInt;
14793
0
    if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14794
0
      Diag(I->getRange().getBegin(),
14795
0
           diag::err_type_tag_for_datatype_not_ice)
14796
0
        << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14797
0
      continue;
14798
0
    }
14799
0
    if (MagicValueInt->getActiveBits() > 64) {
14800
0
      Diag(I->getRange().getBegin(),
14801
0
           diag::err_type_tag_for_datatype_too_large)
14802
0
        << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14803
0
      continue;
14804
0
    }
14805
0
    uint64_t MagicValue = MagicValueInt->getZExtValue();
14806
0
    RegisterTypeTagForDatatype(I->getArgumentKind(),
14807
0
                               MagicValue,
14808
0
                               I->getMatchingCType(),
14809
0
                               I->getLayoutCompatible(),
14810
0
                               I->getMustBeNull());
14811
0
  }
14812
0
}
14813
14814
0
static bool hasDeducedAuto(DeclaratorDecl *DD) {
14815
0
  auto *VD = dyn_cast<VarDecl>(DD);
14816
0
  return VD && !VD->getType()->hasAutoForTrailingReturnType();
14817
0
}
14818
14819
Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
14820
5.06k
                                                   ArrayRef<Decl *> Group) {
14821
5.06k
  SmallVector<Decl*, 8> Decls;
14822
14823
5.06k
  if (DS.isTypeSpecOwned())
14824
0
    Decls.push_back(DS.getRepAsDecl());
14825
14826
5.06k
  DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14827
5.06k
  DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14828
5.06k
  bool DiagnosedMultipleDecomps = false;
14829
5.06k
  DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14830
5.06k
  bool DiagnosedNonDeducedAuto = false;
14831
14832
10.1k
  for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14833
5.08k
    if (Decl *D = Group[i]) {
14834
      // Check if the Decl has been declared in '#pragma omp declare target'
14835
      // directive and has static storage duration.
14836
5.08k
      if (auto *VD = dyn_cast<VarDecl>(D);
14837
5.08k
          LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14838
5.08k
          VD->hasGlobalStorage())
14839
0
        ActOnOpenMPDeclareTargetInitializer(D);
14840
      // For declarators, there are some additional syntactic-ish checks we need
14841
      // to perform.
14842
5.08k
      if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14843
5.08k
        if (!FirstDeclaratorInGroup)
14844
5.06k
          FirstDeclaratorInGroup = DD;
14845
5.08k
        if (!FirstDecompDeclaratorInGroup)
14846
5.08k
          FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14847
5.08k
        if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14848
5.08k
            !hasDeducedAuto(DD))
14849
0
          FirstNonDeducedAutoInGroup = DD;
14850
14851
5.08k
        if (FirstDeclaratorInGroup != DD) {
14852
          // A decomposition declaration cannot be combined with any other
14853
          // declaration in the same group.
14854
27
          if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14855
0
            Diag(FirstDecompDeclaratorInGroup->getLocation(),
14856
0
                 diag::err_decomp_decl_not_alone)
14857
0
                << FirstDeclaratorInGroup->getSourceRange()
14858
0
                << DD->getSourceRange();
14859
0
            DiagnosedMultipleDecomps = true;
14860
0
          }
14861
14862
          // A declarator that uses 'auto' in any way other than to declare a
14863
          // variable with a deduced type cannot be combined with any other
14864
          // declarator in the same group.
14865
27
          if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14866
0
            Diag(FirstNonDeducedAutoInGroup->getLocation(),
14867
0
                 diag::err_auto_non_deduced_not_alone)
14868
0
                << FirstNonDeducedAutoInGroup->getType()
14869
0
                       ->hasAutoForTrailingReturnType()
14870
0
                << FirstDeclaratorInGroup->getSourceRange()
14871
0
                << DD->getSourceRange();
14872
0
            DiagnosedNonDeducedAuto = true;
14873
0
          }
14874
27
        }
14875
5.08k
      }
14876
14877
5.08k
      Decls.push_back(D);
14878
5.08k
    }
14879
5.08k
  }
14880
14881
5.06k
  if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
14882
0
    if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14883
0
      handleTagNumbering(Tag, S);
14884
0
      if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14885
0
          getLangOpts().CPlusPlus)
14886
0
        Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14887
0
    }
14888
0
  }
14889
14890
5.06k
  return BuildDeclaratorGroup(Decls);
14891
5.06k
}
14892
14893
/// BuildDeclaratorGroup - convert a list of declarations into a declaration
14894
/// group, performing any necessary semantic checking.
14895
Sema::DeclGroupPtrTy
14896
5.06k
Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14897
  // C++14 [dcl.spec.auto]p7: (DR1347)
14898
  //   If the type that replaces the placeholder type is not the same in each
14899
  //   deduction, the program is ill-formed.
14900
5.06k
  if (Group.size() > 1) {
14901
27
    QualType Deduced;
14902
27
    VarDecl *DeducedDecl = nullptr;
14903
78
    for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14904
53
      VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14905
53
      if (!D || D->isInvalidDecl())
14906
2
        break;
14907
51
      DeducedType *DT = D->getType()->getContainedDeducedType();
14908
51
      if (!DT || DT->getDeducedType().isNull())
14909
51
        continue;
14910
0
      if (Deduced.isNull()) {
14911
0
        Deduced = DT->getDeducedType();
14912
0
        DeducedDecl = D;
14913
0
      } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14914
0
        auto *AT = dyn_cast<AutoType>(DT);
14915
0
        auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14916
0
                        diag::err_auto_different_deductions)
14917
0
                   << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14918
0
                   << DeducedDecl->getDeclName() << DT->getDeducedType()
14919
0
                   << D->getDeclName();
14920
0
        if (DeducedDecl->hasInit())
14921
0
          Dia << DeducedDecl->getInit()->getSourceRange();
14922
0
        if (D->getInit())
14923
0
          Dia << D->getInit()->getSourceRange();
14924
0
        D->setInvalidDecl();
14925
0
        break;
14926
0
      }
14927
0
    }
14928
27
  }
14929
14930
5.06k
  ActOnDocumentableDecls(Group);
14931
14932
5.06k
  return DeclGroupPtrTy::make(
14933
5.06k
      DeclGroupRef::Create(Context, Group.data(), Group.size()));
14934
5.06k
}
14935
14936
8
void Sema::ActOnDocumentableDecl(Decl *D) {
14937
8
  ActOnDocumentableDecls(D);
14938
8
}
14939
14940
5.07k
void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14941
  // Don't parse the comment if Doxygen diagnostics are ignored.
14942
5.07k
  if (Group.empty() || !Group[0])
14943
8
    return;
14944
14945
5.06k
  if (Diags.isIgnored(diag::warn_doc_param_not_found,
14946
5.06k
                      Group[0]->getLocation()) &&
14947
5.06k
      Diags.isIgnored(diag::warn_unknown_comment_command_name,
14948
5.06k
                      Group[0]->getLocation()))
14949
5.06k
    return;
14950
14951
0
  if (Group.size() >= 2) {
14952
    // This is a decl group.  Normally it will contain only declarations
14953
    // produced from declarator list.  But in case we have any definitions or
14954
    // additional declaration references:
14955
    //   'typedef struct S {} S;'
14956
    //   'typedef struct S *S;'
14957
    //   'struct S *pS;'
14958
    // FinalizeDeclaratorGroup adds these as separate declarations.
14959
0
    Decl *MaybeTagDecl = Group[0];
14960
0
    if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14961
0
      Group = Group.slice(1);
14962
0
    }
14963
0
  }
14964
14965
  // FIMXE: We assume every Decl in the group is in the same file.
14966
  // This is false when preprocessor constructs the group from decls in
14967
  // different files (e. g. macros or #include).
14968
0
  Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14969
0
}
14970
14971
/// Common checks for a parameter-declaration that should apply to both function
14972
/// parameters and non-type template parameters.
14973
40
void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14974
  // Check that there are no default arguments inside the type of this
14975
  // parameter.
14976
40
  if (getLangOpts().CPlusPlus)
14977
6
    CheckExtraCXXDefaultArguments(D);
14978
14979
  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14980
40
  if (D.getCXXScopeSpec().isSet()) {
14981
0
    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14982
0
      << D.getCXXScopeSpec().getRange();
14983
0
  }
14984
14985
  // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14986
  // simple identifier except [...irrelevant cases...].
14987
40
  switch (D.getName().getKind()) {
14988
40
  case UnqualifiedIdKind::IK_Identifier:
14989
40
    break;
14990
14991
0
  case UnqualifiedIdKind::IK_OperatorFunctionId:
14992
0
  case UnqualifiedIdKind::IK_ConversionFunctionId:
14993
0
  case UnqualifiedIdKind::IK_LiteralOperatorId:
14994
0
  case UnqualifiedIdKind::IK_ConstructorName:
14995
0
  case UnqualifiedIdKind::IK_DestructorName:
14996
0
  case UnqualifiedIdKind::IK_ImplicitSelfParam:
14997
0
  case UnqualifiedIdKind::IK_DeductionGuideName:
14998
0
    Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14999
0
      << GetNameForDeclarator(D).getName();
15000
0
    break;
15001
15002
0
  case UnqualifiedIdKind::IK_TemplateId:
15003
0
  case UnqualifiedIdKind::IK_ConstructorTemplateId:
15004
    // GetNameForDeclarator would not produce a useful name in this case.
15005
0
    Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15006
0
    break;
15007
40
  }
15008
40
}
15009
15010
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15011
40
                                         SourceLocation ExplicitThisLoc) {
15012
40
  if (!ExplicitThisLoc.isValid())
15013
40
    return;
15014
0
  assert(S.getLangOpts().CPlusPlus &&
15015
0
         "explicit parameter in non-cplusplus mode");
15016
0
  if (!S.getLangOpts().CPlusPlus23)
15017
0
    S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15018
0
        << P->getSourceRange();
15019
15020
  // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15021
  // parameter pack.
15022
0
  if (P->isParameterPack()) {
15023
0
    S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15024
0
        << P->getSourceRange();
15025
0
    return;
15026
0
  }
15027
0
  P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15028
0
  if (LambdaScopeInfo *LSI = S.getCurLambda())
15029
0
    LSI->ExplicitObjectParameter = P;
15030
0
}
15031
15032
/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
15033
/// to introduce parameters into function prototype scope.
15034
Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15035
40
                                 SourceLocation ExplicitThisLoc) {
15036
40
  const DeclSpec &DS = D.getDeclSpec();
15037
15038
  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15039
15040
  // C++03 [dcl.stc]p2 also permits 'auto'.
15041
40
  StorageClass SC = SC_None;
15042
40
  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15043
0
    SC = SC_Register;
15044
    // In C++11, the 'register' storage class specifier is deprecated.
15045
    // In C++17, it is not allowed, but we tolerate it as an extension.
15046
0
    if (getLangOpts().CPlusPlus11) {
15047
0
      Diag(DS.getStorageClassSpecLoc(),
15048
0
           getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
15049
0
                                     : diag::warn_deprecated_register)
15050
0
        << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
15051
0
    }
15052
40
  } else if (getLangOpts().CPlusPlus &&
15053
40
             DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15054
0
    SC = SC_Auto;
15055
40
  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15056
0
    Diag(DS.getStorageClassSpecLoc(),
15057
0
         diag::err_invalid_storage_class_in_func_decl);
15058
0
    D.getMutableDeclSpec().ClearStorageClassSpecs();
15059
0
  }
15060
15061
40
  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15062
0
    Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15063
0
      << DeclSpec::getSpecifierName(TSCS);
15064
40
  if (DS.isInlineSpecified())
15065
0
    Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15066
0
        << getLangOpts().CPlusPlus17;
15067
40
  if (DS.hasConstexprSpecifier())
15068
0
    Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15069
0
        << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15070
15071
40
  DiagnoseFunctionSpecifiers(DS);
15072
15073
40
  CheckFunctionOrTemplateParamDeclarator(S, D);
15074
15075
40
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15076
40
  QualType parmDeclType = TInfo->getType();
15077
15078
  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15079
40
  IdentifierInfo *II = D.getIdentifier();
15080
40
  if (II) {
15081
21
    LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15082
21
                   ForVisibleRedeclaration);
15083
21
    LookupName(R, S);
15084
21
    if (!R.empty()) {
15085
6
      NamedDecl *PrevDecl = *R.begin();
15086
6
      if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15087
        // Maybe we will complain about the shadowed template parameter.
15088
0
        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15089
        // Just pretend that we didn't see the previous declaration.
15090
0
        PrevDecl = nullptr;
15091
0
      }
15092
6
      if (PrevDecl && S->isDeclScope(PrevDecl)) {
15093
0
        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15094
0
        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15095
        // Recover by removing the name
15096
0
        II = nullptr;
15097
0
        D.SetIdentifier(nullptr, D.getIdentifierLoc());
15098
0
        D.setInvalidType(true);
15099
0
      }
15100
6
    }
15101
21
  }
15102
15103
  // Temporarily put parameter variables in the translation unit, not
15104
  // the enclosing context.  This prevents them from accidentally
15105
  // looking like class members in C++.
15106
40
  ParmVarDecl *New =
15107
40
      CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15108
40
                     D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15109
15110
40
  if (D.isInvalidType())
15111
33
    New->setInvalidDecl();
15112
15113
40
  CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15114
15115
40
  assert(S->isFunctionPrototypeScope());
15116
0
  assert(S->getFunctionPrototypeDepth() >= 1);
15117
0
  New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15118
40
                    S->getNextFunctionPrototypeIndex());
15119
15120
  // Add the parameter declaration into this scope.
15121
40
  S->AddDecl(New);
15122
40
  if (II)
15123
21
    IdResolver.AddDecl(New);
15124
15125
40
  ProcessDeclAttributes(S, New, D);
15126
15127
40
  if (D.getDeclSpec().isModulePrivateSpecified())
15128
0
    Diag(New->getLocation(), diag::err_module_private_local)
15129
0
        << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15130
0
        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
15131
15132
40
  if (New->hasAttr<BlocksAttr>()) {
15133
0
    Diag(New->getLocation(), diag::err_block_on_nonlocal);
15134
0
  }
15135
15136
40
  if (getLangOpts().OpenCL)
15137
0
    deduceOpenCLAddressSpace(New);
15138
15139
40
  return New;
15140
40
}
15141
15142
/// Synthesizes a variable for a parameter arising from a
15143
/// typedef.
15144
ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15145
                                              SourceLocation Loc,
15146
0
                                              QualType T) {
15147
  /* FIXME: setting StartLoc == Loc.
15148
     Would it be worth to modify callers so as to provide proper source
15149
     location for the unnamed parameters, embedding the parameter's type? */
15150
0
  ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15151
0
                                T, Context.getTrivialTypeSourceInfo(T, Loc),
15152
0
                                           SC_None, nullptr);
15153
0
  Param->setImplicit();
15154
0
  return Param;
15155
0
}
15156
15157
1
void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15158
  // Don't diagnose unused-parameter errors in template instantiations; we
15159
  // will already have done so in the template itself.
15160
1
  if (inTemplateInstantiation())
15161
0
    return;
15162
15163
1
  for (const ParmVarDecl *Parameter : Parameters) {
15164
0
    if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15165
0
        !Parameter->hasAttr<UnusedAttr>() &&
15166
0
        !Parameter->getIdentifier()->isPlaceholder()) {
15167
0
      Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15168
0
        << Parameter->getDeclName();
15169
0
    }
15170
0
  }
15171
1
}
15172
15173
void Sema::DiagnoseSizeOfParametersAndReturnValue(
15174
0
    ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15175
0
  if (LangOpts.NumLargeByValueCopy == 0) // No check.
15176
0
    return;
15177
15178
  // Warn if the return value is pass-by-value and larger than the specified
15179
  // threshold.
15180
0
  if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15181
0
    unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15182
0
    if (Size > LangOpts.NumLargeByValueCopy)
15183
0
      Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15184
0
  }
15185
15186
  // Warn if any parameter is pass-by-value and larger than the specified
15187
  // threshold.
15188
0
  for (const ParmVarDecl *Parameter : Parameters) {
15189
0
    QualType T = Parameter->getType();
15190
0
    if (T->isDependentType() || !T.isPODType(Context))
15191
0
      continue;
15192
0
    unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15193
0
    if (Size > LangOpts.NumLargeByValueCopy)
15194
0
      Diag(Parameter->getLocation(), diag::warn_parameter_size)
15195
0
          << Parameter << Size;
15196
0
  }
15197
0
}
15198
15199
ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15200
                                  SourceLocation NameLoc, IdentifierInfo *Name,
15201
                                  QualType T, TypeSourceInfo *TSInfo,
15202
40
                                  StorageClass SC) {
15203
  // In ARC, infer a lifetime qualifier for appropriate parameter types.
15204
40
  if (getLangOpts().ObjCAutoRefCount &&
15205
40
      T.getObjCLifetime() == Qualifiers::OCL_None &&
15206
40
      T->isObjCLifetimeType()) {
15207
15208
0
    Qualifiers::ObjCLifetime lifetime;
15209
15210
    // Special cases for arrays:
15211
    //   - if it's const, use __unsafe_unretained
15212
    //   - otherwise, it's an error
15213
0
    if (T->isArrayType()) {
15214
0
      if (!T.isConstQualified()) {
15215
0
        if (DelayedDiagnostics.shouldDelayDiagnostics())
15216
0
          DelayedDiagnostics.add(
15217
0
              sema::DelayedDiagnostic::makeForbiddenType(
15218
0
              NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15219
0
        else
15220
0
          Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15221
0
              << TSInfo->getTypeLoc().getSourceRange();
15222
0
      }
15223
0
      lifetime = Qualifiers::OCL_ExplicitNone;
15224
0
    } else {
15225
0
      lifetime = T->getObjCARCImplicitLifetime();
15226
0
    }
15227
0
    T = Context.getLifetimeQualifiedType(T, lifetime);
15228
0
  }
15229
15230
40
  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15231
40
                                         Context.getAdjustedParameterType(T),
15232
40
                                         TSInfo, SC, nullptr);
15233
15234
  // Make a note if we created a new pack in the scope of a lambda, so that
15235
  // we know that references to that pack must also be expanded within the
15236
  // lambda scope.
15237
40
  if (New->isParameterPack())
15238
0
    if (auto *LSI = getEnclosingLambda())
15239
0
      LSI->LocalPacks.push_back(New);
15240
15241
40
  if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15242
40
      New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15243
0
    checkNonTrivialCUnion(New->getType(), New->getLocation(),
15244
0
                          NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
15245
15246
  // Parameter declarators cannot be interface types. All ObjC objects are
15247
  // passed by reference.
15248
40
  if (T->isObjCObjectType()) {
15249
0
    SourceLocation TypeEndLoc =
15250
0
        getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
15251
0
    Diag(NameLoc,
15252
0
         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15253
0
      << FixItHint::CreateInsertion(TypeEndLoc, "*");
15254
0
    T = Context.getObjCObjectPointerType(T);
15255
0
    New->setType(T);
15256
0
  }
15257
15258
  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15259
  // duration shall not be qualified by an address-space qualifier."
15260
  // Since all parameters have automatic store duration, they can not have
15261
  // an address space.
15262
40
  if (T.getAddressSpace() != LangAS::Default &&
15263
      // OpenCL allows function arguments declared to be an array of a type
15264
      // to be qualified with an address space.
15265
40
      !(getLangOpts().OpenCL &&
15266
0
        (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15267
      // WebAssembly allows reference types as parameters. Funcref in particular
15268
      // lives in a different address space.
15269
40
      !(T->isFunctionPointerType() &&
15270
0
        T.getAddressSpace() == LangAS::wasm_funcref)) {
15271
0
    Diag(NameLoc, diag::err_arg_with_address_space);
15272
0
    New->setInvalidDecl();
15273
0
  }
15274
15275
  // PPC MMA non-pointer types are not allowed as function argument types.
15276
40
  if (Context.getTargetInfo().getTriple().isPPC64() &&
15277
40
      CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15278
0
    New->setInvalidDecl();
15279
0
  }
15280
15281
40
  return New;
15282
40
}
15283
15284
void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15285
0
                                           SourceLocation LocAfterDecls) {
15286
0
  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15287
15288
  // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15289
  // in the declaration list shall have at least one declarator, those
15290
  // declarators shall only declare identifiers from the identifier list, and
15291
  // every identifier in the identifier list shall be declared.
15292
  //
15293
  // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15294
  // identifiers it names shall be declared in the declaration list."
15295
  //
15296
  // This is why we only diagnose in C99 and later. Note, the other conditions
15297
  // listed are checked elsewhere.
15298
0
  if (!FTI.hasPrototype) {
15299
0
    for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15300
0
      --i;
15301
0
      if (FTI.Params[i].Param == nullptr) {
15302
0
        if (getLangOpts().C99) {
15303
0
          SmallString<256> Code;
15304
0
          llvm::raw_svector_ostream(Code)
15305
0
              << "  int " << FTI.Params[i].Ident->getName() << ";\n";
15306
0
          Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15307
0
              << FTI.Params[i].Ident
15308
0
              << FixItHint::CreateInsertion(LocAfterDecls, Code);
15309
0
        }
15310
15311
        // Implicitly declare the argument as type 'int' for lack of a better
15312
        // type.
15313
0
        AttributeFactory attrs;
15314
0
        DeclSpec DS(attrs);
15315
0
        const char* PrevSpec; // unused
15316
0
        unsigned DiagID; // unused
15317
0
        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15318
0
                           DiagID, Context.getPrintingPolicy());
15319
        // Use the identifier location for the type source range.
15320
0
        DS.SetRangeStart(FTI.Params[i].IdentLoc);
15321
0
        DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15322
0
        Declarator ParamD(DS, ParsedAttributesView::none(),
15323
0
                          DeclaratorContext::KNRTypeList);
15324
0
        ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15325
0
        FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15326
0
      }
15327
0
    }
15328
0
  }
15329
0
}
15330
15331
Decl *
15332
Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15333
                              MultiTemplateParamsArg TemplateParameterLists,
15334
0
                              SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15335
0
  assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15336
0
  assert(D.isFunctionDeclarator() && "Not a function declarator!");
15337
0
  Scope *ParentScope = FnBodyScope->getParent();
15338
15339
  // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15340
  // we define a non-templated function definition, we will create a declaration
15341
  // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15342
  // The base function declaration will have the equivalent of an `omp declare
15343
  // variant` annotation which specifies the mangled definition as a
15344
  // specialization function under the OpenMP context defined as part of the
15345
  // `omp begin declare variant`.
15346
0
  SmallVector<FunctionDecl *, 4> Bases;
15347
0
  if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
15348
0
    ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15349
0
        ParentScope, D, TemplateParameterLists, Bases);
15350
15351
0
  D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15352
0
  Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15353
0
  Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15354
15355
0
  if (!Bases.empty())
15356
0
    ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
15357
15358
0
  return Dcl;
15359
0
}
15360
15361
0
void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15362
0
  Consumer.HandleInlineFunctionDefinition(D);
15363
0
}
15364
15365
static bool FindPossiblePrototype(const FunctionDecl *FD,
15366
0
                                  const FunctionDecl *&PossiblePrototype) {
15367
0
  for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15368
0
       Prev = Prev->getPreviousDecl()) {
15369
    // Ignore any declarations that occur in function or method
15370
    // scope, because they aren't visible from the header.
15371
0
    if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15372
0
      continue;
15373
15374
0
    PossiblePrototype = Prev;
15375
0
    return Prev->getType()->isFunctionProtoType();
15376
0
  }
15377
0
  return false;
15378
0
}
15379
15380
static bool
15381
ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15382
0
                                const FunctionDecl *&PossiblePrototype) {
15383
  // Don't warn about invalid declarations.
15384
0
  if (FD->isInvalidDecl())
15385
0
    return false;
15386
15387
  // Or declarations that aren't global.
15388
0
  if (!FD->isGlobal())
15389
0
    return false;
15390
15391
  // Don't warn about C++ member functions.
15392
0
  if (isa<CXXMethodDecl>(FD))
15393
0
    return false;
15394
15395
  // Don't warn about 'main'.
15396
0
  if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15397
0
    if (IdentifierInfo *II = FD->getIdentifier())
15398
0
      if (II->isStr("main") || II->isStr("efi_main"))
15399
0
        return false;
15400
15401
  // Don't warn about inline functions.
15402
0
  if (FD->isInlined())
15403
0
    return false;
15404
15405
  // Don't warn about function templates.
15406
0
  if (FD->getDescribedFunctionTemplate())
15407
0
    return false;
15408
15409
  // Don't warn about function template specializations.
15410
0
  if (FD->isFunctionTemplateSpecialization())
15411
0
    return false;
15412
15413
  // Don't warn for OpenCL kernels.
15414
0
  if (FD->hasAttr<OpenCLKernelAttr>())
15415
0
    return false;
15416
15417
  // Don't warn on explicitly deleted functions.
15418
0
  if (FD->isDeleted())
15419
0
    return false;
15420
15421
  // Don't warn on implicitly local functions (such as having local-typed
15422
  // parameters).
15423
0
  if (!FD->isExternallyVisible())
15424
0
    return false;
15425
15426
  // If we were able to find a potential prototype, don't warn.
15427
0
  if (FindPossiblePrototype(FD, PossiblePrototype))
15428
0
    return false;
15429
15430
0
  return true;
15431
0
}
15432
15433
void
15434
Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
15435
                                   const FunctionDecl *EffectiveDefinition,
15436
0
                                   SkipBodyInfo *SkipBody) {
15437
0
  const FunctionDecl *Definition = EffectiveDefinition;
15438
0
  if (!Definition &&
15439
0
      !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15440
0
    return;
15441
15442
0
  if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15443
0
    if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15444
0
      if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15445
        // A merged copy of the same function, instantiated as a member of
15446
        // the same class, is OK.
15447
0
        if (declaresSameEntity(OrigFD, OrigDef) &&
15448
0
            declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15449
0
                               cast<Decl>(FD->getLexicalDeclContext())))
15450
0
          return;
15451
0
      }
15452
0
    }
15453
0
  }
15454
15455
0
  if (canRedefineFunction(Definition, getLangOpts()))
15456
0
    return;
15457
15458
  // Don't emit an error when this is redefinition of a typo-corrected
15459
  // definition.
15460
0
  if (TypoCorrectedFunctionDefinitions.count(Definition))
15461
0
    return;
15462
15463
  // If we don't have a visible definition of the function, and it's inline or
15464
  // a template, skip the new definition.
15465
0
  if (SkipBody && !hasVisibleDefinition(Definition) &&
15466
0
      (Definition->getFormalLinkage() == Linkage::Internal ||
15467
0
       Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15468
0
       Definition->getNumTemplateParameterLists())) {
15469
0
    SkipBody->ShouldSkip = true;
15470
0
    SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15471
0
    if (auto *TD = Definition->getDescribedFunctionTemplate())
15472
0
      makeMergedDefinitionVisible(TD);
15473
0
    makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
15474
0
    return;
15475
0
  }
15476
15477
0
  if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15478
0
      Definition->getStorageClass() == SC_Extern)
15479
0
    Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15480
0
        << FD << getLangOpts().CPlusPlus;
15481
0
  else
15482
0
    Diag(FD->getLocation(), diag::err_redefinition) << FD;
15483
15484
0
  Diag(Definition->getLocation(), diag::note_previous_definition);
15485
0
  FD->setInvalidDecl();
15486
0
}
15487
15488
0
LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
15489
0
  CXXRecordDecl *LambdaClass = CallOperator->getParent();
15490
15491
0
  LambdaScopeInfo *LSI = PushLambdaScope();
15492
0
  LSI->CallOperator = CallOperator;
15493
0
  LSI->Lambda = LambdaClass;
15494
0
  LSI->ReturnType = CallOperator->getReturnType();
15495
  // This function in calls in situation where the context of the call operator
15496
  // is not entered, so we set AfterParameterList to false, so that
15497
  // `tryCaptureVariable` finds explicit captures in the appropriate context.
15498
0
  LSI->AfterParameterList = false;
15499
0
  const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15500
15501
0
  if (LCD == LCD_None)
15502
0
    LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15503
0
  else if (LCD == LCD_ByCopy)
15504
0
    LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15505
0
  else if (LCD == LCD_ByRef)
15506
0
    LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15507
0
  DeclarationNameInfo DNI = CallOperator->getNameInfo();
15508
15509
0
  LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15510
0
  LSI->Mutable = !CallOperator->isConst();
15511
0
  if (CallOperator->isExplicitObjectMemberFunction())
15512
0
    LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15513
15514
  // Add the captures to the LSI so they can be noted as already
15515
  // captured within tryCaptureVar.
15516
0
  auto I = LambdaClass->field_begin();
15517
0
  for (const auto &C : LambdaClass->captures()) {
15518
0
    if (C.capturesVariable()) {
15519
0
      ValueDecl *VD = C.getCapturedVar();
15520
0
      if (VD->isInitCapture())
15521
0
        CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15522
0
      const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15523
0
      LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15524
0
          /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15525
0
          /*EllipsisLoc*/C.isPackExpansion()
15526
0
                         ? C.getEllipsisLoc() : SourceLocation(),
15527
0
          I->getType(), /*Invalid*/false);
15528
15529
0
    } else if (C.capturesThis()) {
15530
0
      LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15531
0
                          C.getCaptureKind() == LCK_StarThis);
15532
0
    } else {
15533
0
      LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15534
0
                             I->getType());
15535
0
    }
15536
0
    ++I;
15537
0
  }
15538
0
  return LSI;
15539
0
}
15540
15541
Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
15542
                                    SkipBodyInfo *SkipBody,
15543
0
                                    FnBodyKind BodyKind) {
15544
0
  if (!D) {
15545
    // Parsing the function declaration failed in some way. Push on a fake scope
15546
    // anyway so we can try to parse the function body.
15547
0
    PushFunctionScope();
15548
0
    PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15549
0
    return D;
15550
0
  }
15551
15552
0
  FunctionDecl *FD = nullptr;
15553
15554
0
  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15555
0
    FD = FunTmpl->getTemplatedDecl();
15556
0
  else
15557
0
    FD = cast<FunctionDecl>(D);
15558
15559
  // Do not push if it is a lambda because one is already pushed when building
15560
  // the lambda in ActOnStartOfLambdaDefinition().
15561
0
  if (!isLambdaCallOperator(FD))
15562
    // [expr.const]/p14.1
15563
    // An expression or conversion is in an immediate function context if it is
15564
    // potentially evaluated and either: its innermost enclosing non-block scope
15565
    // is a function parameter scope of an immediate function.
15566
0
    PushExpressionEvaluationContext(
15567
0
        FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15568
0
                          : ExprEvalContexts.back().Context);
15569
15570
  // Each ExpressionEvaluationContextRecord also keeps track of whether the
15571
  // context is nested in an immediate function context, so smaller contexts
15572
  // that appear inside immediate functions (like variable initializers) are
15573
  // considered to be inside an immediate function context even though by
15574
  // themselves they are not immediate function contexts. But when a new
15575
  // function is entered, we need to reset this tracking, since the entered
15576
  // function might be not an immediate function.
15577
0
  ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15578
0
  ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15579
0
      getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15580
15581
  // Check for defining attributes before the check for redefinition.
15582
0
  if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15583
0
    Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15584
0
    FD->dropAttr<AliasAttr>();
15585
0
    FD->setInvalidDecl();
15586
0
  }
15587
0
  if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15588
0
    Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15589
0
    FD->dropAttr<IFuncAttr>();
15590
0
    FD->setInvalidDecl();
15591
0
  }
15592
0
  if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15593
0
    if (!Context.getTargetInfo().hasFeature("fmv") &&
15594
0
        !Attr->isDefaultVersion()) {
15595
      // If function multi versioning disabled skip parsing function body
15596
      // defined with non-default target_version attribute
15597
0
      if (SkipBody)
15598
0
        SkipBody->ShouldSkip = true;
15599
0
      return nullptr;
15600
0
    }
15601
0
  }
15602
15603
0
  if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15604
0
    if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15605
0
        Ctor->isDefaultConstructor() &&
15606
0
        Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15607
      // If this is an MS ABI dllexport default constructor, instantiate any
15608
      // default arguments.
15609
0
      InstantiateDefaultCtorDefaultArgs(Ctor);
15610
0
    }
15611
0
  }
15612
15613
  // See if this is a redefinition. If 'will have body' (or similar) is already
15614
  // set, then these checks were already performed when it was set.
15615
0
  if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15616
0
      !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15617
0
    CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15618
15619
    // If we're skipping the body, we're done. Don't enter the scope.
15620
0
    if (SkipBody && SkipBody->ShouldSkip)
15621
0
      return D;
15622
0
  }
15623
15624
  // Mark this function as "will have a body eventually".  This lets users to
15625
  // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15626
  // this function.
15627
0
  FD->setWillHaveBody();
15628
15629
  // If we are instantiating a generic lambda call operator, push
15630
  // a LambdaScopeInfo onto the function stack.  But use the information
15631
  // that's already been calculated (ActOnLambdaExpr) to prime the current
15632
  // LambdaScopeInfo.
15633
  // When the template operator is being specialized, the LambdaScopeInfo,
15634
  // has to be properly restored so that tryCaptureVariable doesn't try
15635
  // and capture any new variables. In addition when calculating potential
15636
  // captures during transformation of nested lambdas, it is necessary to
15637
  // have the LSI properly restored.
15638
0
  if (isGenericLambdaCallOperatorSpecialization(FD)) {
15639
0
    assert(inTemplateInstantiation() &&
15640
0
           "There should be an active template instantiation on the stack "
15641
0
           "when instantiating a generic lambda!");
15642
0
    RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15643
0
  } else {
15644
    // Enter a new function scope
15645
0
    PushFunctionScope();
15646
0
  }
15647
15648
  // Builtin functions cannot be defined.
15649
0
  if (unsigned BuiltinID = FD->getBuiltinID()) {
15650
0
    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
15651
0
        !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
15652
0
      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15653
0
      FD->setInvalidDecl();
15654
0
    }
15655
0
  }
15656
15657
  // The return type of a function definition must be complete (C99 6.9.1p3).
15658
  // C++23 [dcl.fct.def.general]/p2
15659
  // The type of [...] the return for a function definition
15660
  // shall not be a (possibly cv-qualified) class type that is incomplete
15661
  // or abstract within the function body unless the function is deleted.
15662
0
  QualType ResultType = FD->getReturnType();
15663
0
  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15664
0
      !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15665
0
      (RequireCompleteType(FD->getLocation(), ResultType,
15666
0
                           diag::err_func_def_incomplete_result) ||
15667
0
       RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),
15668
0
                              diag::err_abstract_type_in_decl,
15669
0
                              AbstractReturnType)))
15670
0
    FD->setInvalidDecl();
15671
15672
0
  if (FnBodyScope)
15673
0
    PushDeclContext(FnBodyScope, FD);
15674
15675
  // Check the validity of our function parameters
15676
0
  if (BodyKind != FnBodyKind::Delete)
15677
0
    CheckParmsForFunctionDef(FD->parameters(),
15678
0
                             /*CheckParameterNames=*/true);
15679
15680
  // Add non-parameter declarations already in the function to the current
15681
  // scope.
15682
0
  if (FnBodyScope) {
15683
0
    for (Decl *NPD : FD->decls()) {
15684
0
      auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15685
0
      if (!NonParmDecl)
15686
0
        continue;
15687
0
      assert(!isa<ParmVarDecl>(NonParmDecl) &&
15688
0
             "parameters should not be in newly created FD yet");
15689
15690
      // If the decl has a name, make it accessible in the current scope.
15691
0
      if (NonParmDecl->getDeclName())
15692
0
        PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15693
15694
      // Similarly, dive into enums and fish their constants out, making them
15695
      // accessible in this scope.
15696
0
      if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15697
0
        for (auto *EI : ED->enumerators())
15698
0
          PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15699
0
      }
15700
0
    }
15701
0
  }
15702
15703
  // Introduce our parameters into the function scope
15704
0
  for (auto *Param : FD->parameters()) {
15705
0
    Param->setOwningFunction(FD);
15706
15707
    // If this has an identifier, add it to the scope stack.
15708
0
    if (Param->getIdentifier() && FnBodyScope) {
15709
0
      CheckShadow(FnBodyScope, Param);
15710
15711
0
      PushOnScopeChains(Param, FnBodyScope);
15712
0
    }
15713
0
  }
15714
15715
  // C++ [module.import/6] external definitions are not permitted in header
15716
  // units.  Deleted and Defaulted functions are implicitly inline (but the
15717
  // inline state is not set at this point, so check the BodyKind explicitly).
15718
  // FIXME: Consider an alternate location for the test where the inlined()
15719
  // state is complete.
15720
0
  if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15721
0
      !FD->isInvalidDecl() && !FD->isInlined() &&
15722
0
      BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15723
0
      FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15724
0
      !FD->isTemplateInstantiation()) {
15725
0
    assert(FD->isThisDeclarationADefinition());
15726
0
    Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15727
0
    FD->setInvalidDecl();
15728
0
  }
15729
15730
  // Ensure that the function's exception specification is instantiated.
15731
0
  if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15732
0
    ResolveExceptionSpec(D->getLocation(), FPT);
15733
15734
  // dllimport cannot be applied to non-inline function definitions.
15735
0
  if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15736
0
      !FD->isTemplateInstantiation()) {
15737
0
    assert(!FD->hasAttr<DLLExportAttr>());
15738
0
    Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15739
0
    FD->setInvalidDecl();
15740
0
    return D;
15741
0
  }
15742
  // We want to attach documentation to original Decl (which might be
15743
  // a function template).
15744
0
  ActOnDocumentableDecl(D);
15745
0
  if (getCurLexicalContext()->isObjCContainer() &&
15746
0
      getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15747
0
      getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15748
0
    Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15749
15750
0
  return D;
15751
0
}
15752
15753
/// Given the set of return statements within a function body,
15754
/// compute the variables that are subject to the named return value
15755
/// optimization.
15756
///
15757
/// Each of the variables that is subject to the named return value
15758
/// optimization will be marked as NRVO variables in the AST, and any
15759
/// return statement that has a marked NRVO variable as its NRVO candidate can
15760
/// use the named return value optimization.
15761
///
15762
/// This function applies a very simplistic algorithm for NRVO: if every return
15763
/// statement in the scope of a variable has the same NRVO candidate, that
15764
/// candidate is an NRVO variable.
15765
0
void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
15766
0
  ReturnStmt **Returns = Scope->Returns.data();
15767
15768
0
  for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15769
0
    if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15770
0
      if (!NRVOCandidate->isNRVOVariable())
15771
0
        Returns[I]->setNRVOCandidate(nullptr);
15772
0
    }
15773
0
  }
15774
0
}
15775
15776
0
bool Sema::canDelayFunctionBody(const Declarator &D) {
15777
  // We can't delay parsing the body of a constexpr function template (yet).
15778
0
  if (D.getDeclSpec().hasConstexprSpecifier())
15779
0
    return false;
15780
15781
  // We can't delay parsing the body of a function template with a deduced
15782
  // return type (yet).
15783
0
  if (D.getDeclSpec().hasAutoTypeSpec()) {
15784
    // If the placeholder introduces a non-deduced trailing return type,
15785
    // we can still delay parsing it.
15786
0
    if (D.getNumTypeObjects()) {
15787
0
      const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15788
0
      if (Outer.Kind == DeclaratorChunk::Function &&
15789
0
          Outer.Fun.hasTrailingReturnType()) {
15790
0
        QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15791
0
        return Ty.isNull() || !Ty->isUndeducedType();
15792
0
      }
15793
0
    }
15794
0
    return false;
15795
0
  }
15796
15797
0
  return true;
15798
0
}
15799
15800
0
bool Sema::canSkipFunctionBody(Decl *D) {
15801
  // We cannot skip the body of a function (or function template) which is
15802
  // constexpr, since we may need to evaluate its body in order to parse the
15803
  // rest of the file.
15804
  // We cannot skip the body of a function with an undeduced return type,
15805
  // because any callers of that function need to know the type.
15806
0
  if (const FunctionDecl *FD = D->getAsFunction()) {
15807
0
    if (FD->isConstexpr())
15808
0
      return false;
15809
    // We can't simply call Type::isUndeducedType here, because inside template
15810
    // auto can be deduced to a dependent type, which is not considered
15811
    // "undeduced".
15812
0
    if (FD->getReturnType()->getContainedDeducedType())
15813
0
      return false;
15814
0
  }
15815
0
  return Consumer.shouldSkipFunctionBody(D);
15816
0
}
15817
15818
0
Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
15819
0
  if (!Decl)
15820
0
    return nullptr;
15821
0
  if (FunctionDecl *FD = Decl->getAsFunction())
15822
0
    FD->setHasSkippedBody();
15823
0
  else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15824
0
    MD->setHasSkippedBody();
15825
0
  return Decl;
15826
0
}
15827
15828
0
Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
15829
0
  return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false);
15830
0
}
15831
15832
/// RAII object that pops an ExpressionEvaluationContext when exiting a function
15833
/// body.
15834
class ExitFunctionBodyRAII {
15835
public:
15836
0
  ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15837
0
  ~ExitFunctionBodyRAII() {
15838
0
    if (!IsLambda)
15839
0
      S.PopExpressionEvaluationContext();
15840
0
  }
15841
15842
private:
15843
  Sema &S;
15844
  bool IsLambda = false;
15845
};
15846
15847
0
static void diagnoseImplicitlyRetainedSelf(Sema &S) {
15848
0
  llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15849
15850
0
  auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15851
0
    if (EscapeInfo.count(BD))
15852
0
      return EscapeInfo[BD];
15853
15854
0
    bool R = false;
15855
0
    const BlockDecl *CurBD = BD;
15856
15857
0
    do {
15858
0
      R = !CurBD->doesNotEscape();
15859
0
      if (R)
15860
0
        break;
15861
0
      CurBD = CurBD->getParent()->getInnermostBlockDecl();
15862
0
    } while (CurBD);
15863
15864
0
    return EscapeInfo[BD] = R;
15865
0
  };
15866
15867
  // If the location where 'self' is implicitly retained is inside a escaping
15868
  // block, emit a diagnostic.
15869
0
  for (const std::pair<SourceLocation, const BlockDecl *> &P :
15870
0
       S.ImplicitlyRetainedSelfLocs)
15871
0
    if (IsOrNestedInEscapingBlock(P.second))
15872
0
      S.Diag(P.first, diag::warn_implicitly_retains_self)
15873
0
          << FixItHint::CreateInsertion(P.first, "self->");
15874
0
}
15875
15876
0
void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
15877
0
  RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
15878
0
  if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
15879
0
    return;
15880
  // Allow `get_return_object()`.
15881
0
  if (FD->getDeclName().isIdentifier() &&
15882
0
      FD->getName().equals("get_return_object") && FD->param_empty())
15883
0
    return;
15884
0
  if (!FD->hasAttr<CoroWrapperAttr>())
15885
0
    Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
15886
0
}
15887
15888
Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
15889
0
                                    bool IsInstantiation) {
15890
0
  FunctionScopeInfo *FSI = getCurFunction();
15891
0
  FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15892
15893
0
  if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15894
0
    FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15895
15896
0
  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15897
0
  sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15898
15899
  // If we skip function body, we can't tell if a function is a coroutine.
15900
0
  if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
15901
0
    if (FSI->isCoroutine())
15902
0
      CheckCompletedCoroutineBody(FD, Body);
15903
0
    else
15904
0
      CheckCoroutineWrapper(FD);
15905
0
  }
15906
15907
0
  {
15908
    // Do not call PopExpressionEvaluationContext() if it is a lambda because
15909
    // one is already popped when finishing the lambda in BuildLambdaExpr().
15910
    // This is meant to pop the context added in ActOnStartOfFunctionDef().
15911
0
    ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15912
0
    if (FD) {
15913
0
      FD->setBody(Body);
15914
0
      FD->setWillHaveBody(false);
15915
0
      CheckImmediateEscalatingFunctionDefinition(FD, FSI);
15916
15917
0
      if (getLangOpts().CPlusPlus14) {
15918
0
        if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15919
0
            FD->getReturnType()->isUndeducedType()) {
15920
          // For a function with a deduced result type to return void,
15921
          // the result type as written must be 'auto' or 'decltype(auto)',
15922
          // possibly cv-qualified or constrained, but not ref-qualified.
15923
0
          if (!FD->getReturnType()->getAs<AutoType>()) {
15924
0
            Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15925
0
                << FD->getReturnType();
15926
0
            FD->setInvalidDecl();
15927
0
          } else {
15928
            // Falling off the end of the function is the same as 'return;'.
15929
0
            Expr *Dummy = nullptr;
15930
0
            if (DeduceFunctionTypeFromReturnExpr(
15931
0
                    FD, dcl->getLocation(), Dummy,
15932
0
                    FD->getReturnType()->getAs<AutoType>()))
15933
0
              FD->setInvalidDecl();
15934
0
          }
15935
0
        }
15936
0
      } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
15937
        // In C++11, we don't use 'auto' deduction rules for lambda call
15938
        // operators because we don't support return type deduction.
15939
0
        auto *LSI = getCurLambda();
15940
0
        if (LSI->HasImplicitReturnType) {
15941
0
          deduceClosureReturnType(*LSI);
15942
15943
          // C++11 [expr.prim.lambda]p4:
15944
          //   [...] if there are no return statements in the compound-statement
15945
          //   [the deduced type is] the type void
15946
0
          QualType RetType =
15947
0
              LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
15948
15949
          // Update the return type to the deduced type.
15950
0
          const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15951
0
          FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15952
0
                                              Proto->getExtProtoInfo()));
15953
0
        }
15954
0
      }
15955
15956
      // If the function implicitly returns zero (like 'main') or is naked,
15957
      // don't complain about missing return statements.
15958
0
      if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
15959
0
        WP.disableCheckFallThrough();
15960
15961
      // MSVC permits the use of pure specifier (=0) on function definition,
15962
      // defined at class scope, warn about this non-standard construct.
15963
0
      if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
15964
0
        Diag(FD->getLocation(), diag::ext_pure_function_definition);
15965
15966
0
      if (!FD->isInvalidDecl()) {
15967
        // Don't diagnose unused parameters of defaulted, deleted or naked
15968
        // functions.
15969
0
        if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
15970
0
            !FD->hasAttr<NakedAttr>())
15971
0
          DiagnoseUnusedParameters(FD->parameters());
15972
0
        DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
15973
0
                                               FD->getReturnType(), FD);
15974
15975
        // If this is a structor, we need a vtable.
15976
0
        if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15977
0
          MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15978
0
        else if (CXXDestructorDecl *Destructor =
15979
0
                     dyn_cast<CXXDestructorDecl>(FD))
15980
0
          MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15981
15982
        // Try to apply the named return value optimization. We have to check
15983
        // if we can do this here because lambdas keep return statements around
15984
        // to deduce an implicit return type.
15985
0
        if (FD->getReturnType()->isRecordType() &&
15986
0
            (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
15987
0
          computeNRVO(Body, FSI);
15988
0
      }
15989
15990
      // GNU warning -Wmissing-prototypes:
15991
      //   Warn if a global function is defined without a previous
15992
      //   prototype declaration. This warning is issued even if the
15993
      //   definition itself provides a prototype. The aim is to detect
15994
      //   global functions that fail to be declared in header files.
15995
0
      const FunctionDecl *PossiblePrototype = nullptr;
15996
0
      if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15997
0
        Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15998
15999
0
        if (PossiblePrototype) {
16000
          // We found a declaration that is not a prototype,
16001
          // but that could be a zero-parameter prototype
16002
0
          if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16003
0
            TypeLoc TL = TI->getTypeLoc();
16004
0
            if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
16005
0
              Diag(PossiblePrototype->getLocation(),
16006
0
                   diag::note_declaration_not_a_prototype)
16007
0
                  << (FD->getNumParams() != 0)
16008
0
                  << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
16009
0
                                                    FTL.getRParenLoc(), "void")
16010
0
                                              : FixItHint{});
16011
0
          }
16012
0
        } else {
16013
          // Returns true if the token beginning at this Loc is `const`.
16014
0
          auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16015
0
                                  const LangOptions &LangOpts) {
16016
0
            std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
16017
0
            if (LocInfo.first.isInvalid())
16018
0
              return false;
16019
16020
0
            bool Invalid = false;
16021
0
            StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16022
0
            if (Invalid)
16023
0
              return false;
16024
16025
0
            if (LocInfo.second > Buffer.size())
16026
0
              return false;
16027
16028
0
            const char *LexStart = Buffer.data() + LocInfo.second;
16029
0
            StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16030
16031
0
            return StartTok.consume_front("const") &&
16032
0
                   (StartTok.empty() || isWhitespace(StartTok[0]) ||
16033
0
                    StartTok.starts_with("/*") || StartTok.starts_with("//"));
16034
0
          };
16035
16036
0
          auto findBeginLoc = [&]() {
16037
            // If the return type has `const` qualifier, we want to insert
16038
            // `static` before `const` (and not before the typename).
16039
0
            if ((FD->getReturnType()->isAnyPointerType() &&
16040
0
                 FD->getReturnType()->getPointeeType().isConstQualified()) ||
16041
0
                FD->getReturnType().isConstQualified()) {
16042
              // But only do this if we can determine where the `const` is.
16043
16044
0
              if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16045
0
                               getLangOpts()))
16046
16047
0
                return FD->getBeginLoc();
16048
0
            }
16049
0
            return FD->getTypeSpecStartLoc();
16050
0
          };
16051
0
          Diag(FD->getTypeSpecStartLoc(),
16052
0
               diag::note_static_for_internal_linkage)
16053
0
              << /* function */ 1
16054
0
              << (FD->getStorageClass() == SC_None
16055
0
                      ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16056
0
                      : FixItHint{});
16057
0
        }
16058
0
      }
16059
16060
      // We might not have found a prototype because we didn't wish to warn on
16061
      // the lack of a missing prototype. Try again without the checks for
16062
      // whether we want to warn on the missing prototype.
16063
0
      if (!PossiblePrototype)
16064
0
        (void)FindPossiblePrototype(FD, PossiblePrototype);
16065
16066
      // If the function being defined does not have a prototype, then we may
16067
      // need to diagnose it as changing behavior in C23 because we now know
16068
      // whether the function accepts arguments or not. This only handles the
16069
      // case where the definition has no prototype but does have parameters
16070
      // and either there is no previous potential prototype, or the previous
16071
      // potential prototype also has no actual prototype. This handles cases
16072
      // like:
16073
      //   void f(); void f(a) int a; {}
16074
      //   void g(a) int a; {}
16075
      // See MergeFunctionDecl() for other cases of the behavior change
16076
      // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16077
      // type without a prototype.
16078
0
      if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16079
0
          (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16080
0
                                  !PossiblePrototype->isImplicit()))) {
16081
        // The function definition has parameters, so this will change behavior
16082
        // in C23. If there is a possible prototype, it comes before the
16083
        // function definition.
16084
        // FIXME: The declaration may have already been diagnosed as being
16085
        // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16086
        // there's no way to test for the "changes behavior" condition in
16087
        // SemaType.cpp when forming the declaration's function type. So, we do
16088
        // this awkward dance instead.
16089
        //
16090
        // If we have a possible prototype and it declares a function with a
16091
        // prototype, we don't want to diagnose it; if we have a possible
16092
        // prototype and it has no prototype, it may have already been
16093
        // diagnosed in SemaType.cpp as deprecated depending on whether
16094
        // -Wstrict-prototypes is enabled. If we already warned about it being
16095
        // deprecated, add a note that it also changes behavior. If we didn't
16096
        // warn about it being deprecated (because the diagnostic is not
16097
        // enabled), warn now that it is deprecated and changes behavior.
16098
16099
        // This K&R C function definition definitely changes behavior in C23,
16100
        // so diagnose it.
16101
0
        Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16102
0
            << /*definition*/ 1 << /* not supported in C23 */ 0;
16103
16104
        // If we have a possible prototype for the function which is a user-
16105
        // visible declaration, we already tested that it has no prototype.
16106
        // This will change behavior in C23. This gets a warning rather than a
16107
        // note because it's the same behavior-changing problem as with the
16108
        // definition.
16109
0
        if (PossiblePrototype)
16110
0
          Diag(PossiblePrototype->getLocation(),
16111
0
               diag::warn_non_prototype_changes_behavior)
16112
0
              << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16113
0
              << /*definition*/ 1;
16114
0
      }
16115
16116
      // Warn on CPUDispatch with an actual body.
16117
0
      if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16118
0
        if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16119
0
          if (!CmpndBody->body_empty())
16120
0
            Diag(CmpndBody->body_front()->getBeginLoc(),
16121
0
                 diag::warn_dispatch_body_ignored);
16122
16123
0
      if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16124
0
        const CXXMethodDecl *KeyFunction;
16125
0
        if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16126
0
            MD->isVirtual() &&
16127
0
            (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16128
0
            MD == KeyFunction->getCanonicalDecl()) {
16129
          // Update the key-function state if necessary for this ABI.
16130
0
          if (FD->isInlined() &&
16131
0
              !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16132
0
            Context.setNonKeyFunction(MD);
16133
16134
            // If the newly-chosen key function is already defined, then we
16135
            // need to mark the vtable as used retroactively.
16136
0
            KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16137
0
            const FunctionDecl *Definition;
16138
0
            if (KeyFunction && KeyFunction->isDefined(Definition))
16139
0
              MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16140
0
          } else {
16141
            // We just defined they key function; mark the vtable as used.
16142
0
            MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16143
0
          }
16144
0
        }
16145
0
      }
16146
16147
0
      assert(
16148
0
          (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
16149
0
          "Function parsing confused");
16150
0
    } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16151
0
      assert(MD == getCurMethodDecl() && "Method parsing confused");
16152
0
      MD->setBody(Body);
16153
0
      if (!MD->isInvalidDecl()) {
16154
0
        DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
16155
0
                                               MD->getReturnType(), MD);
16156
16157
0
        if (Body)
16158
0
          computeNRVO(Body, FSI);
16159
0
      }
16160
0
      if (FSI->ObjCShouldCallSuper) {
16161
0
        Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16162
0
            << MD->getSelector().getAsString();
16163
0
        FSI->ObjCShouldCallSuper = false;
16164
0
      }
16165
0
      if (FSI->ObjCWarnForNoDesignatedInitChain) {
16166
0
        const ObjCMethodDecl *InitMethod = nullptr;
16167
0
        bool isDesignated =
16168
0
            MD->isDesignatedInitializerForTheInterface(&InitMethod);
16169
0
        assert(isDesignated && InitMethod);
16170
0
        (void)isDesignated;
16171
16172
0
        auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16173
0
          auto IFace = MD->getClassInterface();
16174
0
          if (!IFace)
16175
0
            return false;
16176
0
          auto SuperD = IFace->getSuperClass();
16177
0
          if (!SuperD)
16178
0
            return false;
16179
0
          return SuperD->getIdentifier() ==
16180
0
                 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16181
0
        };
16182
        // Don't issue this warning for unavailable inits or direct subclasses
16183
        // of NSObject.
16184
0
        if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16185
0
          Diag(MD->getLocation(),
16186
0
               diag::warn_objc_designated_init_missing_super_call);
16187
0
          Diag(InitMethod->getLocation(),
16188
0
               diag::note_objc_designated_init_marked_here);
16189
0
        }
16190
0
        FSI->ObjCWarnForNoDesignatedInitChain = false;
16191
0
      }
16192
0
      if (FSI->ObjCWarnForNoInitDelegation) {
16193
        // Don't issue this warning for unavaialable inits.
16194
0
        if (!MD->isUnavailable())
16195
0
          Diag(MD->getLocation(),
16196
0
               diag::warn_objc_secondary_init_missing_init_call);
16197
0
        FSI->ObjCWarnForNoInitDelegation = false;
16198
0
      }
16199
16200
0
      diagnoseImplicitlyRetainedSelf(*this);
16201
0
    } else {
16202
      // Parsing the function declaration failed in some way. Pop the fake scope
16203
      // we pushed on.
16204
0
      PopFunctionScopeInfo(ActivePolicy, dcl);
16205
0
      return nullptr;
16206
0
    }
16207
16208
0
    if (Body && FSI->HasPotentialAvailabilityViolations)
16209
0
      DiagnoseUnguardedAvailabilityViolations(dcl);
16210
16211
0
    assert(!FSI->ObjCShouldCallSuper &&
16212
0
           "This should only be set for ObjC methods, which should have been "
16213
0
           "handled in the block above.");
16214
16215
    // Verify and clean out per-function state.
16216
0
    if (Body && (!FD || !FD->isDefaulted())) {
16217
      // C++ constructors that have function-try-blocks can't have return
16218
      // statements in the handlers of that block. (C++ [except.handle]p14)
16219
      // Verify this.
16220
0
      if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16221
0
        DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16222
16223
      // Verify that gotos and switch cases don't jump into scopes illegally.
16224
0
      if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16225
0
        DiagnoseInvalidJumps(Body);
16226
16227
0
      if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16228
0
        if (!Destructor->getParent()->isDependentType())
16229
0
          CheckDestructor(Destructor);
16230
16231
0
        MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
16232
0
                                               Destructor->getParent());
16233
0
      }
16234
16235
      // If any errors have occurred, clear out any temporaries that may have
16236
      // been leftover. This ensures that these temporaries won't be picked up
16237
      // for deletion in some later function.
16238
0
      if (hasUncompilableErrorOccurred() ||
16239
0
          hasAnyUnrecoverableErrorsInThisFunction() ||
16240
0
          getDiagnostics().getSuppressAllDiagnostics()) {
16241
0
        DiscardCleanupsInEvaluationContext();
16242
0
      }
16243
0
      if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16244
        // Since the body is valid, issue any analysis-based warnings that are
16245
        // enabled.
16246
0
        ActivePolicy = &WP;
16247
0
      }
16248
16249
0
      if (!IsInstantiation && FD &&
16250
0
          (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16251
0
          !FD->isInvalidDecl() &&
16252
0
          !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
16253
0
        FD->setInvalidDecl();
16254
16255
0
      if (FD && FD->hasAttr<NakedAttr>()) {
16256
0
        for (const Stmt *S : Body->children()) {
16257
          // Allow local register variables without initializer as they don't
16258
          // require prologue.
16259
0
          bool RegisterVariables = false;
16260
0
          if (auto *DS = dyn_cast<DeclStmt>(S)) {
16261
0
            for (const auto *Decl : DS->decls()) {
16262
0
              if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16263
0
                RegisterVariables =
16264
0
                    Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16265
0
                if (!RegisterVariables)
16266
0
                  break;
16267
0
              }
16268
0
            }
16269
0
          }
16270
0
          if (RegisterVariables)
16271
0
            continue;
16272
0
          if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16273
0
            Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16274
0
            Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16275
0
            FD->setInvalidDecl();
16276
0
            break;
16277
0
          }
16278
0
        }
16279
0
      }
16280
16281
0
      assert(ExprCleanupObjects.size() ==
16282
0
                 ExprEvalContexts.back().NumCleanupObjects &&
16283
0
             "Leftover temporaries in function");
16284
0
      assert(!Cleanup.exprNeedsCleanups() &&
16285
0
             "Unaccounted cleanups in function");
16286
0
      assert(MaybeODRUseExprs.empty() &&
16287
0
             "Leftover expressions for odr-use checking");
16288
0
    }
16289
0
  } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16290
    // the declaration context below. Otherwise, we're unable to transform
16291
    // 'this' expressions when transforming immediate context functions.
16292
16293
0
  if (!IsInstantiation)
16294
0
    PopDeclContext();
16295
16296
0
  PopFunctionScopeInfo(ActivePolicy, dcl);
16297
  // If any errors have occurred, clear out any temporaries that may have
16298
  // been leftover. This ensures that these temporaries won't be picked up for
16299
  // deletion in some later function.
16300
0
  if (hasUncompilableErrorOccurred()) {
16301
0
    DiscardCleanupsInEvaluationContext();
16302
0
  }
16303
16304
0
  if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16305
0
                                  !LangOpts.OMPTargetTriples.empty())) ||
16306
0
             LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16307
0
    auto ES = getEmissionStatus(FD);
16308
0
    if (ES == Sema::FunctionEmissionStatus::Emitted ||
16309
0
        ES == Sema::FunctionEmissionStatus::Unknown)
16310
0
      DeclsToCheckForDeferredDiags.insert(FD);
16311
0
  }
16312
16313
0
  if (FD && !FD->isDeleted())
16314
0
    checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16315
16316
0
  return dcl;
16317
0
}
16318
16319
/// When we finish delayed parsing of an attribute, we must attach it to the
16320
/// relevant Decl.
16321
void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
16322
0
                                       ParsedAttributes &Attrs) {
16323
  // Always attach attributes to the underlying decl.
16324
0
  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16325
0
    D = TD->getTemplatedDecl();
16326
0
  ProcessDeclAttributeList(S, D, Attrs);
16327
16328
0
  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16329
0
    if (Method->isStatic())
16330
0
      checkThisInStaticMemberFunctionAttributes(Method);
16331
0
}
16332
16333
/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
16334
/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
16335
NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
16336
0
                                          IdentifierInfo &II, Scope *S) {
16337
  // It is not valid to implicitly define a function in C23.
16338
0
  assert(LangOpts.implicitFunctionsAllowed() &&
16339
0
         "Implicit function declarations aren't allowed in this language mode");
16340
16341
  // Find the scope in which the identifier is injected and the corresponding
16342
  // DeclContext.
16343
  // FIXME: C89 does not say what happens if there is no enclosing block scope.
16344
  // In that case, we inject the declaration into the translation unit scope
16345
  // instead.
16346
0
  Scope *BlockScope = S;
16347
0
  while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16348
0
    BlockScope = BlockScope->getParent();
16349
16350
  // Loop until we find a DeclContext that is either a function/method or the
16351
  // translation unit, which are the only two valid places to implicitly define
16352
  // a function. This avoids accidentally defining the function within a tag
16353
  // declaration, for example.
16354
0
  Scope *ContextScope = BlockScope;
16355
0
  while (!ContextScope->getEntity() ||
16356
0
         (!ContextScope->getEntity()->isFunctionOrMethod() &&
16357
0
          !ContextScope->getEntity()->isTranslationUnit()))
16358
0
    ContextScope = ContextScope->getParent();
16359
0
  ContextRAII SavedContext(*this, ContextScope->getEntity());
16360
16361
  // Before we produce a declaration for an implicitly defined
16362
  // function, see whether there was a locally-scoped declaration of
16363
  // this name as a function or variable. If so, use that
16364
  // (non-visible) declaration, and complain about it.
16365
0
  NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16366
0
  if (ExternCPrev) {
16367
    // We still need to inject the function into the enclosing block scope so
16368
    // that later (non-call) uses can see it.
16369
0
    PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16370
16371
    // C89 footnote 38:
16372
    //   If in fact it is not defined as having type "function returning int",
16373
    //   the behavior is undefined.
16374
0
    if (!isa<FunctionDecl>(ExternCPrev) ||
16375
0
        !Context.typesAreCompatible(
16376
0
            cast<FunctionDecl>(ExternCPrev)->getType(),
16377
0
            Context.getFunctionNoProtoType(Context.IntTy))) {
16378
0
      Diag(Loc, diag::ext_use_out_of_scope_declaration)
16379
0
          << ExternCPrev << !getLangOpts().C99;
16380
0
      Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16381
0
      return ExternCPrev;
16382
0
    }
16383
0
  }
16384
16385
  // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16386
0
  unsigned diag_id;
16387
0
  if (II.getName().starts_with("__builtin_"))
16388
0
    diag_id = diag::warn_builtin_unknown;
16389
  // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16390
0
  else if (getLangOpts().C99)
16391
0
    diag_id = diag::ext_implicit_function_decl_c99;
16392
0
  else
16393
0
    diag_id = diag::warn_implicit_function_decl;
16394
16395
0
  TypoCorrection Corrected;
16396
  // Because typo correction is expensive, only do it if the implicit
16397
  // function declaration is going to be treated as an error.
16398
  //
16399
  // Perform the correction before issuing the main diagnostic, as some
16400
  // consumers use typo-correction callbacks to enhance the main diagnostic.
16401
0
  if (S && !ExternCPrev &&
16402
0
      (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
16403
0
    DeclFilterCCC<FunctionDecl> CCC{};
16404
0
    Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
16405
0
                            S, nullptr, CCC, CTK_NonError);
16406
0
  }
16407
16408
0
  Diag(Loc, diag_id) << &II;
16409
0
  if (Corrected) {
16410
    // If the correction is going to suggest an implicitly defined function,
16411
    // skip the correction as not being a particularly good idea.
16412
0
    bool Diagnose = true;
16413
0
    if (const auto *D = Corrected.getCorrectionDecl())
16414
0
      Diagnose = !D->isImplicit();
16415
0
    if (Diagnose)
16416
0
      diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16417
0
                   /*ErrorRecovery*/ false);
16418
0
  }
16419
16420
  // If we found a prior declaration of this function, don't bother building
16421
  // another one. We've already pushed that one into scope, so there's nothing
16422
  // more to do.
16423
0
  if (ExternCPrev)
16424
0
    return ExternCPrev;
16425
16426
  // Set a Declarator for the implicit definition: int foo();
16427
0
  const char *Dummy;
16428
0
  AttributeFactory attrFactory;
16429
0
  DeclSpec DS(attrFactory);
16430
0
  unsigned DiagID;
16431
0
  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16432
0
                                  Context.getPrintingPolicy());
16433
0
  (void)Error; // Silence warning.
16434
0
  assert(!Error && "Error setting up implicit decl!");
16435
0
  SourceLocation NoLoc;
16436
0
  Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
16437
0
  D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16438
0
                                             /*IsAmbiguous=*/false,
16439
0
                                             /*LParenLoc=*/NoLoc,
16440
0
                                             /*Params=*/nullptr,
16441
0
                                             /*NumParams=*/0,
16442
0
                                             /*EllipsisLoc=*/NoLoc,
16443
0
                                             /*RParenLoc=*/NoLoc,
16444
0
                                             /*RefQualifierIsLvalueRef=*/true,
16445
0
                                             /*RefQualifierLoc=*/NoLoc,
16446
0
                                             /*MutableLoc=*/NoLoc, EST_None,
16447
0
                                             /*ESpecRange=*/SourceRange(),
16448
0
                                             /*Exceptions=*/nullptr,
16449
0
                                             /*ExceptionRanges=*/nullptr,
16450
0
                                             /*NumExceptions=*/0,
16451
0
                                             /*NoexceptExpr=*/nullptr,
16452
0
                                             /*ExceptionSpecTokens=*/nullptr,
16453
0
                                             /*DeclsInPrototype=*/std::nullopt,
16454
0
                                             Loc, Loc, D),
16455
0
                std::move(DS.getAttributes()), SourceLocation());
16456
0
  D.SetIdentifier(&II, Loc);
16457
16458
  // Insert this function into the enclosing block scope.
16459
0
  FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16460
0
  FD->setImplicit();
16461
16462
0
  AddKnownFunctionAttributes(FD);
16463
16464
0
  return FD;
16465
0
}
16466
16467
/// If this function is a C++ replaceable global allocation function
16468
/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
16469
/// adds any function attributes that we know a priori based on the standard.
16470
///
16471
/// We need to check for duplicate attributes both here and where user-written
16472
/// attributes are applied to declarations.
16473
void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
16474
6
    FunctionDecl *FD) {
16475
6
  if (FD->isInvalidDecl())
16476
0
    return;
16477
16478
6
  if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16479
6
      FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16480
6
    return;
16481
16482
0
  std::optional<unsigned> AlignmentParam;
16483
0
  bool IsNothrow = false;
16484
0
  if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16485
0
    return;
16486
16487
  // C++2a [basic.stc.dynamic.allocation]p4:
16488
  //   An allocation function that has a non-throwing exception specification
16489
  //   indicates failure by returning a null pointer value. Any other allocation
16490
  //   function never returns a null pointer value and indicates failure only by
16491
  //   throwing an exception [...]
16492
  //
16493
  // However, -fcheck-new invalidates this possible assumption, so don't add
16494
  // NonNull when that is enabled.
16495
0
  if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16496
0
      !getLangOpts().CheckNew)
16497
0
    FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16498
16499
  // C++2a [basic.stc.dynamic.allocation]p2:
16500
  //   An allocation function attempts to allocate the requested amount of
16501
  //   storage. [...] If the request succeeds, the value returned by a
16502
  //   replaceable allocation function is a [...] pointer value p0 different
16503
  //   from any previously returned value p1 [...]
16504
  //
16505
  // However, this particular information is being added in codegen,
16506
  // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16507
16508
  // C++2a [basic.stc.dynamic.allocation]p2:
16509
  //   An allocation function attempts to allocate the requested amount of
16510
  //   storage. If it is successful, it returns the address of the start of a
16511
  //   block of storage whose length in bytes is at least as large as the
16512
  //   requested size.
16513
0
  if (!FD->hasAttr<AllocSizeAttr>()) {
16514
0
    FD->addAttr(AllocSizeAttr::CreateImplicit(
16515
0
        Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16516
0
        /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16517
0
  }
16518
16519
  // C++2a [basic.stc.dynamic.allocation]p3:
16520
  //   For an allocation function [...], the pointer returned on a successful
16521
  //   call shall represent the address of storage that is aligned as follows:
16522
  //   (3.1) If the allocation function takes an argument of type
16523
  //         std​::​align_­val_­t, the storage will have the alignment
16524
  //         specified by the value of this argument.
16525
0
  if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16526
0
    FD->addAttr(AllocAlignAttr::CreateImplicit(
16527
0
        Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16528
0
  }
16529
16530
  // FIXME:
16531
  // C++2a [basic.stc.dynamic.allocation]p3:
16532
  //   For an allocation function [...], the pointer returned on a successful
16533
  //   call shall represent the address of storage that is aligned as follows:
16534
  //   (3.2) Otherwise, if the allocation function is named operator new[],
16535
  //         the storage is aligned for any object that does not have
16536
  //         new-extended alignment ([basic.align]) and is no larger than the
16537
  //         requested size.
16538
  //   (3.3) Otherwise, the storage is aligned for any object that does not
16539
  //         have new-extended alignment and is of the requested size.
16540
0
}
16541
16542
/// Adds any function attributes that we know a priori based on
16543
/// the declaration of this function.
16544
///
16545
/// These attributes can apply both to implicitly-declared builtins
16546
/// (like __builtin___printf_chk) or to library-declared functions
16547
/// like NSLog or printf.
16548
///
16549
/// We need to check for duplicate attributes both here and where user-written
16550
/// attributes are applied to declarations.
16551
19
void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
16552
19
  if (FD->isInvalidDecl())
16553
13
    return;
16554
16555
  // If this is a built-in function, map its builtin attributes to
16556
  // actual attributes.
16557
6
  if (unsigned BuiltinID = FD->getBuiltinID()) {
16558
    // Handle printf-formatting attributes.
16559
0
    unsigned FormatIdx;
16560
0
    bool HasVAListArg;
16561
0
    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16562
0
      if (!FD->hasAttr<FormatAttr>()) {
16563
0
        const char *fmt = "printf";
16564
0
        unsigned int NumParams = FD->getNumParams();
16565
0
        if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16566
0
            FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16567
0
          fmt = "NSString";
16568
0
        FD->addAttr(FormatAttr::CreateImplicit(Context,
16569
0
                                               &Context.Idents.get(fmt),
16570
0
                                               FormatIdx+1,
16571
0
                                               HasVAListArg ? 0 : FormatIdx+2,
16572
0
                                               FD->getLocation()));
16573
0
      }
16574
0
    }
16575
0
    if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16576
0
                                             HasVAListArg)) {
16577
0
     if (!FD->hasAttr<FormatAttr>())
16578
0
       FD->addAttr(FormatAttr::CreateImplicit(Context,
16579
0
                                              &Context.Idents.get("scanf"),
16580
0
                                              FormatIdx+1,
16581
0
                                              HasVAListArg ? 0 : FormatIdx+2,
16582
0
                                              FD->getLocation()));
16583
0
    }
16584
16585
    // Handle automatically recognized callbacks.
16586
0
    SmallVector<int, 4> Encoding;
16587
0
    if (!FD->hasAttr<CallbackAttr>() &&
16588
0
        Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16589
0
      FD->addAttr(CallbackAttr::CreateImplicit(
16590
0
          Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16591
16592
    // Mark const if we don't care about errno and/or floating point exceptions
16593
    // that are the only thing preventing the function from being const. This
16594
    // allows IRgen to use LLVM intrinsics for such functions.
16595
0
    bool NoExceptions =
16596
0
        getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16597
0
    bool ConstWithoutErrnoAndExceptions =
16598
0
        Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
16599
0
    bool ConstWithoutExceptions =
16600
0
        Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
16601
0
    if (!FD->hasAttr<ConstAttr>() &&
16602
0
        (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16603
0
        (!ConstWithoutErrnoAndExceptions ||
16604
0
         (!getLangOpts().MathErrno && NoExceptions)) &&
16605
0
        (!ConstWithoutExceptions || NoExceptions))
16606
0
      FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16607
16608
    // We make "fma" on GNU or Windows const because we know it does not set
16609
    // errno in those environments even though it could set errno based on the
16610
    // C standard.
16611
0
    const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16612
0
    if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16613
0
        !FD->hasAttr<ConstAttr>()) {
16614
0
      switch (BuiltinID) {
16615
0
      case Builtin::BI__builtin_fma:
16616
0
      case Builtin::BI__builtin_fmaf:
16617
0
      case Builtin::BI__builtin_fmal:
16618
0
      case Builtin::BIfma:
16619
0
      case Builtin::BIfmaf:
16620
0
      case Builtin::BIfmal:
16621
0
        FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16622
0
        break;
16623
0
      default:
16624
0
        break;
16625
0
      }
16626
0
    }
16627
16628
0
    if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16629
0
        !FD->hasAttr<ReturnsTwiceAttr>())
16630
0
      FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16631
0
                                         FD->getLocation()));
16632
0
    if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16633
0
      FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16634
0
    if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16635
0
      FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16636
0
    if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16637
0
      FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16638
0
    if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16639
0
        !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16640
      // Add the appropriate attribute, depending on the CUDA compilation mode
16641
      // and which target the builtin belongs to. For example, during host
16642
      // compilation, aux builtins are __device__, while the rest are __host__.
16643
0
      if (getLangOpts().CUDAIsDevice !=
16644
0
          Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
16645
0
        FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16646
0
      else
16647
0
        FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16648
0
    }
16649
16650
    // Add known guaranteed alignment for allocation functions.
16651
0
    switch (BuiltinID) {
16652
0
    case Builtin::BImemalign:
16653
0
    case Builtin::BIaligned_alloc:
16654
0
      if (!FD->hasAttr<AllocAlignAttr>())
16655
0
        FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16656
0
                                                   FD->getLocation()));
16657
0
      break;
16658
0
    default:
16659
0
      break;
16660
0
    }
16661
16662
    // Add allocsize attribute for allocation functions.
16663
0
    switch (BuiltinID) {
16664
0
    case Builtin::BIcalloc:
16665
0
      FD->addAttr(AllocSizeAttr::CreateImplicit(
16666
0
          Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16667
0
      break;
16668
0
    case Builtin::BImemalign:
16669
0
    case Builtin::BIaligned_alloc:
16670
0
    case Builtin::BIrealloc:
16671
0
      FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16672
0
                                                ParamIdx(), FD->getLocation()));
16673
0
      break;
16674
0
    case Builtin::BImalloc:
16675
0
      FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16676
0
                                                ParamIdx(), FD->getLocation()));
16677
0
      break;
16678
0
    default:
16679
0
      break;
16680
0
    }
16681
16682
    // Add lifetime attribute to std::move, std::fowrard et al.
16683
0
    switch (BuiltinID) {
16684
0
    case Builtin::BIaddressof:
16685
0
    case Builtin::BI__addressof:
16686
0
    case Builtin::BI__builtin_addressof:
16687
0
    case Builtin::BIas_const:
16688
0
    case Builtin::BIforward:
16689
0
    case Builtin::BIforward_like:
16690
0
    case Builtin::BImove:
16691
0
    case Builtin::BImove_if_noexcept:
16692
0
      if (ParmVarDecl *P = FD->getParamDecl(0u);
16693
0
          !P->hasAttr<LifetimeBoundAttr>())
16694
0
        P->addAttr(
16695
0
            LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16696
0
      break;
16697
0
    default:
16698
0
      break;
16699
0
    }
16700
0
  }
16701
16702
6
  AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
16703
16704
  // If C++ exceptions are enabled but we are told extern "C" functions cannot
16705
  // throw, add an implicit nothrow attribute to any extern "C" function we come
16706
  // across.
16707
6
  if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16708
6
      FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16709
0
    const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16710
0
    if (!FPT || FPT->getExceptionSpecType() == EST_None)
16711
0
      FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16712
0
  }
16713
16714
6
  IdentifierInfo *Name = FD->getIdentifier();
16715
6
  if (!Name)
16716
0
    return;
16717
6
  if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
16718
6
      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16719
0
       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16720
6
           LinkageSpecLanguageIDs::C)) {
16721
    // Okay: this could be a libc/libm/Objective-C function we know
16722
    // about.
16723
6
  } else
16724
0
    return;
16725
16726
6
  if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16727
    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16728
    // target-specific builtins, perhaps?
16729
0
    if (!FD->hasAttr<FormatAttr>())
16730
0
      FD->addAttr(FormatAttr::CreateImplicit(Context,
16731
0
                                             &Context.Idents.get("printf"), 2,
16732
0
                                             Name->isStr("vasprintf") ? 0 : 3,
16733
0
                                             FD->getLocation()));
16734
0
  }
16735
16736
6
  if (Name->isStr("__CFStringMakeConstantString")) {
16737
    // We already have a __builtin___CFStringMakeConstantString,
16738
    // but builds that use -fno-constant-cfstrings don't go through that.
16739
0
    if (!FD->hasAttr<FormatArgAttr>())
16740
0
      FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16741
0
                                                FD->getLocation()));
16742
0
  }
16743
6
}
16744
16745
TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
16746
0
                                    TypeSourceInfo *TInfo) {
16747
0
  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16748
0
  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16749
16750
0
  if (!TInfo) {
16751
0
    assert(D.isInvalidType() && "no declarator info for valid type");
16752
0
    TInfo = Context.getTrivialTypeSourceInfo(T);
16753
0
  }
16754
16755
  // Scope manipulation handled by caller.
16756
0
  TypedefDecl *NewTD =
16757
0
      TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
16758
0
                          D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16759
16760
  // Bail out immediately if we have an invalid declaration.
16761
0
  if (D.isInvalidType()) {
16762
0
    NewTD->setInvalidDecl();
16763
0
    return NewTD;
16764
0
  }
16765
16766
0
  if (D.getDeclSpec().isModulePrivateSpecified()) {
16767
0
    if (CurContext->isFunctionOrMethod())
16768
0
      Diag(NewTD->getLocation(), diag::err_module_private_local)
16769
0
          << 2 << NewTD
16770
0
          << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16771
0
          << FixItHint::CreateRemoval(
16772
0
                 D.getDeclSpec().getModulePrivateSpecLoc());
16773
0
    else
16774
0
      NewTD->setModulePrivate();
16775
0
  }
16776
16777
  // C++ [dcl.typedef]p8:
16778
  //   If the typedef declaration defines an unnamed class (or
16779
  //   enum), the first typedef-name declared by the declaration
16780
  //   to be that class type (or enum type) is used to denote the
16781
  //   class type (or enum type) for linkage purposes only.
16782
  // We need to check whether the type was declared in the declaration.
16783
0
  switch (D.getDeclSpec().getTypeSpecType()) {
16784
0
  case TST_enum:
16785
0
  case TST_struct:
16786
0
  case TST_interface:
16787
0
  case TST_union:
16788
0
  case TST_class: {
16789
0
    TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16790
0
    setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16791
0
    break;
16792
0
  }
16793
16794
0
  default:
16795
0
    break;
16796
0
  }
16797
16798
0
  return NewTD;
16799
0
}
16800
16801
/// Check that this is a valid underlying type for an enum declaration.
16802
0
bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
16803
0
  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16804
0
  QualType T = TI->getType();
16805
16806
0
  if (T->isDependentType())
16807
0
    return false;
16808
16809
  // This doesn't use 'isIntegralType' despite the error message mentioning
16810
  // integral type because isIntegralType would also allow enum types in C.
16811
0
  if (const BuiltinType *BT = T->getAs<BuiltinType>())
16812
0
    if (BT->isInteger())
16813
0
      return false;
16814
16815
0
  return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
16816
0
         << T << T->isBitIntType();
16817
0
}
16818
16819
/// Check whether this is a valid redeclaration of a previous enumeration.
16820
/// \return true if the redeclaration was invalid.
16821
bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
16822
                                  QualType EnumUnderlyingTy, bool IsFixed,
16823
0
                                  const EnumDecl *Prev) {
16824
0
  if (IsScoped != Prev->isScoped()) {
16825
0
    Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16826
0
      << Prev->isScoped();
16827
0
    Diag(Prev->getLocation(), diag::note_previous_declaration);
16828
0
    return true;
16829
0
  }
16830
16831
0
  if (IsFixed && Prev->isFixed()) {
16832
0
    if (!EnumUnderlyingTy->isDependentType() &&
16833
0
        !Prev->getIntegerType()->isDependentType() &&
16834
0
        !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16835
0
                                        Prev->getIntegerType())) {
16836
      // TODO: Highlight the underlying type of the redeclaration.
16837
0
      Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16838
0
        << EnumUnderlyingTy << Prev->getIntegerType();
16839
0
      Diag(Prev->getLocation(), diag::note_previous_declaration)
16840
0
          << Prev->getIntegerTypeRange();
16841
0
      return true;
16842
0
    }
16843
0
  } else if (IsFixed != Prev->isFixed()) {
16844
0
    Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16845
0
      << Prev->isFixed();
16846
0
    Diag(Prev->getLocation(), diag::note_previous_declaration);
16847
0
    return true;
16848
0
  }
16849
16850
0
  return false;
16851
0
}
16852
16853
/// Get diagnostic %select index for tag kind for
16854
/// redeclaration diagnostic message.
16855
/// WARNING: Indexes apply to particular diagnostics only!
16856
///
16857
/// \returns diagnostic %select index.
16858
0
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
16859
0
  switch (Tag) {
16860
0
  case TagTypeKind::Struct:
16861
0
    return 0;
16862
0
  case TagTypeKind::Interface:
16863
0
    return 1;
16864
0
  case TagTypeKind::Class:
16865
0
    return 2;
16866
0
  default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16867
0
  }
16868
0
}
16869
16870
/// Determine if tag kind is a class-key compatible with
16871
/// class for redeclaration (class, struct, or __interface).
16872
///
16873
/// \returns true iff the tag kind is compatible.
16874
static bool isClassCompatTagKind(TagTypeKind Tag)
16875
0
{
16876
0
  return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
16877
0
         Tag == TagTypeKind::Interface;
16878
0
}
16879
16880
Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
16881
0
                                             TagTypeKind TTK) {
16882
0
  if (isa<TypedefDecl>(PrevDecl))
16883
0
    return NTK_Typedef;
16884
0
  else if (isa<TypeAliasDecl>(PrevDecl))
16885
0
    return NTK_TypeAlias;
16886
0
  else if (isa<ClassTemplateDecl>(PrevDecl))
16887
0
    return NTK_Template;
16888
0
  else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16889
0
    return NTK_TypeAliasTemplate;
16890
0
  else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16891
0
    return NTK_TemplateTemplateArgument;
16892
0
  switch (TTK) {
16893
0
  case TagTypeKind::Struct:
16894
0
  case TagTypeKind::Interface:
16895
0
  case TagTypeKind::Class:
16896
0
    return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16897
0
  case TagTypeKind::Union:
16898
0
    return NTK_NonUnion;
16899
0
  case TagTypeKind::Enum:
16900
0
    return NTK_NonEnum;
16901
0
  }
16902
0
  llvm_unreachable("invalid TTK");
16903
0
}
16904
16905
/// Determine whether a tag with a given kind is acceptable
16906
/// as a redeclaration of the given tag declaration.
16907
///
16908
/// \returns true if the new tag kind is acceptable, false otherwise.
16909
bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
16910
                                        TagTypeKind NewTag, bool isDefinition,
16911
                                        SourceLocation NewTagLoc,
16912
0
                                        const IdentifierInfo *Name) {
16913
  // C++ [dcl.type.elab]p3:
16914
  //   The class-key or enum keyword present in the
16915
  //   elaborated-type-specifier shall agree in kind with the
16916
  //   declaration to which the name in the elaborated-type-specifier
16917
  //   refers. This rule also applies to the form of
16918
  //   elaborated-type-specifier that declares a class-name or
16919
  //   friend class since it can be construed as referring to the
16920
  //   definition of the class. Thus, in any
16921
  //   elaborated-type-specifier, the enum keyword shall be used to
16922
  //   refer to an enumeration (7.2), the union class-key shall be
16923
  //   used to refer to a union (clause 9), and either the class or
16924
  //   struct class-key shall be used to refer to a class (clause 9)
16925
  //   declared using the class or struct class-key.
16926
0
  TagTypeKind OldTag = Previous->getTagKind();
16927
0
  if (OldTag != NewTag &&
16928
0
      !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
16929
0
    return false;
16930
16931
  // Tags are compatible, but we might still want to warn on mismatched tags.
16932
  // Non-class tags can't be mismatched at this point.
16933
0
  if (!isClassCompatTagKind(NewTag))
16934
0
    return true;
16935
16936
  // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16937
  // by our warning analysis. We don't want to warn about mismatches with (eg)
16938
  // declarations in system headers that are designed to be specialized, but if
16939
  // a user asks us to warn, we should warn if their code contains mismatched
16940
  // declarations.
16941
0
  auto IsIgnoredLoc = [&](SourceLocation Loc) {
16942
0
    return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16943
0
                                      Loc);
16944
0
  };
16945
0
  if (IsIgnoredLoc(NewTagLoc))
16946
0
    return true;
16947
16948
0
  auto IsIgnored = [&](const TagDecl *Tag) {
16949
0
    return IsIgnoredLoc(Tag->getLocation());
16950
0
  };
16951
0
  while (IsIgnored(Previous)) {
16952
0
    Previous = Previous->getPreviousDecl();
16953
0
    if (!Previous)
16954
0
      return true;
16955
0
    OldTag = Previous->getTagKind();
16956
0
  }
16957
16958
0
  bool isTemplate = false;
16959
0
  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16960
0
    isTemplate = Record->getDescribedClassTemplate();
16961
16962
0
  if (inTemplateInstantiation()) {
16963
0
    if (OldTag != NewTag) {
16964
      // In a template instantiation, do not offer fix-its for tag mismatches
16965
      // since they usually mess up the template instead of fixing the problem.
16966
0
      Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16967
0
        << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16968
0
        << getRedeclDiagFromTagKind(OldTag);
16969
      // FIXME: Note previous location?
16970
0
    }
16971
0
    return true;
16972
0
  }
16973
16974
0
  if (isDefinition) {
16975
    // On definitions, check all previous tags and issue a fix-it for each
16976
    // one that doesn't match the current tag.
16977
0
    if (Previous->getDefinition()) {
16978
      // Don't suggest fix-its for redefinitions.
16979
0
      return true;
16980
0
    }
16981
16982
0
    bool previousMismatch = false;
16983
0
    for (const TagDecl *I : Previous->redecls()) {
16984
0
      if (I->getTagKind() != NewTag) {
16985
        // Ignore previous declarations for which the warning was disabled.
16986
0
        if (IsIgnored(I))
16987
0
          continue;
16988
16989
0
        if (!previousMismatch) {
16990
0
          previousMismatch = true;
16991
0
          Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
16992
0
            << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16993
0
            << getRedeclDiagFromTagKind(I->getTagKind());
16994
0
        }
16995
0
        Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16996
0
          << getRedeclDiagFromTagKind(NewTag)
16997
0
          << FixItHint::CreateReplacement(I->getInnerLocStart(),
16998
0
               TypeWithKeyword::getTagTypeKindName(NewTag));
16999
0
      }
17000
0
    }
17001
0
    return true;
17002
0
  }
17003
17004
  // Identify the prevailing tag kind: this is the kind of the definition (if
17005
  // there is a non-ignored definition), or otherwise the kind of the prior
17006
  // (non-ignored) declaration.
17007
0
  const TagDecl *PrevDef = Previous->getDefinition();
17008
0
  if (PrevDef && IsIgnored(PrevDef))
17009
0
    PrevDef = nullptr;
17010
0
  const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17011
0
  if (Redecl->getTagKind() != NewTag) {
17012
0
    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17013
0
      << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17014
0
      << getRedeclDiagFromTagKind(OldTag);
17015
0
    Diag(Redecl->getLocation(), diag::note_previous_use);
17016
17017
    // If there is a previous definition, suggest a fix-it.
17018
0
    if (PrevDef) {
17019
0
      Diag(NewTagLoc, diag::note_struct_class_suggestion)
17020
0
        << getRedeclDiagFromTagKind(Redecl->getTagKind())
17021
0
        << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
17022
0
             TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
17023
0
    }
17024
0
  }
17025
17026
0
  return true;
17027
0
}
17028
17029
/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17030
/// from an outer enclosing namespace or file scope inside a friend declaration.
17031
/// This should provide the commented out code in the following snippet:
17032
///   namespace N {
17033
///     struct X;
17034
///     namespace M {
17035
///       struct Y { friend struct /*N::*/ X; };
17036
///     }
17037
///   }
17038
static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
17039
0
                                         SourceLocation NameLoc) {
17040
  // While the decl is in a namespace, do repeated lookup of that name and see
17041
  // if we get the same namespace back.  If we do not, continue until
17042
  // translation unit scope, at which point we have a fully qualified NNS.
17043
0
  SmallVector<IdentifierInfo *, 4> Namespaces;
17044
0
  DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17045
0
  for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17046
    // This tag should be declared in a namespace, which can only be enclosed by
17047
    // other namespaces.  Bail if there's an anonymous namespace in the chain.
17048
0
    NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17049
0
    if (!Namespace || Namespace->isAnonymousNamespace())
17050
0
      return FixItHint();
17051
0
    IdentifierInfo *II = Namespace->getIdentifier();
17052
0
    Namespaces.push_back(II);
17053
0
    NamedDecl *Lookup = SemaRef.LookupSingleName(
17054
0
        S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17055
0
    if (Lookup == Namespace)
17056
0
      break;
17057
0
  }
17058
17059
  // Once we have all the namespaces, reverse them to go outermost first, and
17060
  // build an NNS.
17061
0
  SmallString<64> Insertion;
17062
0
  llvm::raw_svector_ostream OS(Insertion);
17063
0
  if (DC->isTranslationUnit())
17064
0
    OS << "::";
17065
0
  std::reverse(Namespaces.begin(), Namespaces.end());
17066
0
  for (auto *II : Namespaces)
17067
0
    OS << II->getName() << "::";
17068
0
  return FixItHint::CreateInsertion(NameLoc, Insertion);
17069
0
}
17070
17071
/// Determine whether a tag originally declared in context \p OldDC can
17072
/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17073
/// found a declaration in \p OldDC as a previous decl, perhaps through a
17074
/// using-declaration).
17075
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
17076
0
                                         DeclContext *NewDC) {
17077
0
  OldDC = OldDC->getRedeclContext();
17078
0
  NewDC = NewDC->getRedeclContext();
17079
17080
0
  if (OldDC->Equals(NewDC))
17081
0
    return true;
17082
17083
  // In MSVC mode, we allow a redeclaration if the contexts are related (either
17084
  // encloses the other).
17085
0
  if (S.getLangOpts().MSVCCompat &&
17086
0
      (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17087
0
    return true;
17088
17089
0
  return false;
17090
0
}
17091
17092
/// This is invoked when we see 'struct foo' or 'struct {'.  In the
17093
/// former case, Name will be non-null.  In the later case, Name will be null.
17094
/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
17095
/// reference/declaration/definition of a tag.
17096
///
17097
/// \param IsTypeSpecifier \c true if this is a type-specifier (or
17098
/// trailing-type-specifier) other than one in an alias-declaration.
17099
///
17100
/// \param SkipBody If non-null, will be set to indicate if the caller should
17101
/// skip the definition of this tag and treat it as if it were a declaration.
17102
DeclResult
17103
Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17104
               CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17105
               const ParsedAttributesView &Attrs, AccessSpecifier AS,
17106
               SourceLocation ModulePrivateLoc,
17107
               MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17108
               bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17109
               bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17110
               bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17111
0
               OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17112
  // If this is not a definition, it must have a name.
17113
0
  IdentifierInfo *OrigName = Name;
17114
0
  assert((Name != nullptr || TUK == TUK_Definition) &&
17115
0
         "Nameless record must be a definition!");
17116
0
  assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
17117
17118
0
  OwnedDecl = false;
17119
0
  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
17120
0
  bool ScopedEnum = ScopedEnumKWLoc.isValid();
17121
17122
  // FIXME: Check member specializations more carefully.
17123
0
  bool isMemberSpecialization = false;
17124
0
  bool Invalid = false;
17125
17126
  // We only need to do this matching if we have template parameters
17127
  // or a scope specifier, which also conveniently avoids this work
17128
  // for non-C++ cases.
17129
0
  if (TemplateParameterLists.size() > 0 ||
17130
0
      (SS.isNotEmpty() && TUK != TUK_Reference)) {
17131
0
    if (TemplateParameterList *TemplateParams =
17132
0
            MatchTemplateParametersToScopeSpecifier(
17133
0
                KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17134
0
                TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
17135
0
      if (Kind == TagTypeKind::Enum) {
17136
0
        Diag(KWLoc, diag::err_enum_template);
17137
0
        return true;
17138
0
      }
17139
17140
0
      if (TemplateParams->size() > 0) {
17141
        // This is a declaration or definition of a class template (which may
17142
        // be a member of another template).
17143
17144
0
        if (Invalid)
17145
0
          return true;
17146
17147
0
        OwnedDecl = false;
17148
0
        DeclResult Result = CheckClassTemplate(
17149
0
            S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17150
0
            AS, ModulePrivateLoc,
17151
0
            /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17152
0
            TemplateParameterLists.data(), SkipBody);
17153
0
        return Result.get();
17154
0
      } else {
17155
        // The "template<>" header is extraneous.
17156
0
        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17157
0
          << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17158
0
        isMemberSpecialization = true;
17159
0
      }
17160
0
    }
17161
17162
0
    if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17163
0
        CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17164
0
      return true;
17165
0
  }
17166
17167
  // Figure out the underlying type if this a enum declaration. We need to do
17168
  // this early, because it's needed to detect if this is an incompatible
17169
  // redeclaration.
17170
0
  llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17171
0
  bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17172
17173
0
  if (Kind == TagTypeKind::Enum) {
17174
0
    if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17175
      // No underlying type explicitly specified, or we failed to parse the
17176
      // type, default to int.
17177
0
      EnumUnderlying = Context.IntTy.getTypePtr();
17178
0
    } else if (UnderlyingType.get()) {
17179
      // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17180
      // integral type; any cv-qualification is ignored.
17181
0
      TypeSourceInfo *TI = nullptr;
17182
0
      GetTypeFromParser(UnderlyingType.get(), &TI);
17183
0
      EnumUnderlying = TI;
17184
17185
0
      if (CheckEnumUnderlyingType(TI))
17186
        // Recover by falling back to int.
17187
0
        EnumUnderlying = Context.IntTy.getTypePtr();
17188
17189
0
      if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
17190
0
                                          UPPC_FixedUnderlyingType))
17191
0
        EnumUnderlying = Context.IntTy.getTypePtr();
17192
17193
0
    } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17194
      // For MSVC ABI compatibility, unfixed enums must use an underlying type
17195
      // of 'int'. However, if this is an unfixed forward declaration, don't set
17196
      // the underlying type unless the user enables -fms-compatibility. This
17197
      // makes unfixed forward declared enums incomplete and is more conforming.
17198
0
      if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
17199
0
        EnumUnderlying = Context.IntTy.getTypePtr();
17200
0
    }
17201
0
  }
17202
17203
0
  DeclContext *SearchDC = CurContext;
17204
0
  DeclContext *DC = CurContext;
17205
0
  bool isStdBadAlloc = false;
17206
0
  bool isStdAlignValT = false;
17207
17208
0
  RedeclarationKind Redecl = forRedeclarationInCurContext();
17209
0
  if (TUK == TUK_Friend || TUK == TUK_Reference)
17210
0
    Redecl = NotForRedeclaration;
17211
17212
  /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17213
  /// implemented asks for structural equivalence checking, the returned decl
17214
  /// here is passed back to the parser, allowing the tag body to be parsed.
17215
0
  auto createTagFromNewDecl = [&]() -> TagDecl * {
17216
0
    assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17217
    // If there is an identifier, use the location of the identifier as the
17218
    // location of the decl, otherwise use the location of the struct/union
17219
    // keyword.
17220
0
    SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17221
0
    TagDecl *New = nullptr;
17222
17223
0
    if (Kind == TagTypeKind::Enum) {
17224
0
      New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17225
0
                             ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17226
      // If this is an undefined enum, bail.
17227
0
      if (TUK != TUK_Definition && !Invalid)
17228
0
        return nullptr;
17229
0
      if (EnumUnderlying) {
17230
0
        EnumDecl *ED = cast<EnumDecl>(New);
17231
0
        if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17232
0
          ED->setIntegerTypeSourceInfo(TI);
17233
0
        else
17234
0
          ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17235
0
        QualType EnumTy = ED->getIntegerType();
17236
0
        ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17237
0
                                 ? Context.getPromotedIntegerType(EnumTy)
17238
0
                                 : EnumTy);
17239
0
      }
17240
0
    } else { // struct/union
17241
0
      New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17242
0
                               nullptr);
17243
0
    }
17244
17245
0
    if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17246
      // Add alignment attributes if necessary; these attributes are checked
17247
      // when the ASTContext lays out the structure.
17248
      //
17249
      // It is important for implementing the correct semantics that this
17250
      // happen here (in ActOnTag). The #pragma pack stack is
17251
      // maintained as a result of parser callbacks which can occur at
17252
      // many points during the parsing of a struct declaration (because
17253
      // the #pragma tokens are effectively skipped over during the
17254
      // parsing of the struct).
17255
0
      if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17256
0
        AddAlignmentAttributesForRecord(RD);
17257
0
        AddMsStructLayoutForRecord(RD);
17258
0
      }
17259
0
    }
17260
0
    New->setLexicalDeclContext(CurContext);
17261
0
    return New;
17262
0
  };
17263
17264
0
  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17265
0
  if (Name && SS.isNotEmpty()) {
17266
    // We have a nested-name tag ('struct foo::bar').
17267
17268
    // Check for invalid 'foo::'.
17269
0
    if (SS.isInvalid()) {
17270
0
      Name = nullptr;
17271
0
      goto CreateNewDecl;
17272
0
    }
17273
17274
    // If this is a friend or a reference to a class in a dependent
17275
    // context, don't try to make a decl for it.
17276
0
    if (TUK == TUK_Friend || TUK == TUK_Reference) {
17277
0
      DC = computeDeclContext(SS, false);
17278
0
      if (!DC) {
17279
0
        IsDependent = true;
17280
0
        return true;
17281
0
      }
17282
0
    } else {
17283
0
      DC = computeDeclContext(SS, true);
17284
0
      if (!DC) {
17285
0
        Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17286
0
          << SS.getRange();
17287
0
        return true;
17288
0
      }
17289
0
    }
17290
17291
0
    if (RequireCompleteDeclContext(SS, DC))
17292
0
      return true;
17293
17294
0
    SearchDC = DC;
17295
    // Look-up name inside 'foo::'.
17296
0
    LookupQualifiedName(Previous, DC);
17297
17298
0
    if (Previous.isAmbiguous())
17299
0
      return true;
17300
17301
0
    if (Previous.empty()) {
17302
      // Name lookup did not find anything. However, if the
17303
      // nested-name-specifier refers to the current instantiation,
17304
      // and that current instantiation has any dependent base
17305
      // classes, we might find something at instantiation time: treat
17306
      // this as a dependent elaborated-type-specifier.
17307
      // But this only makes any sense for reference-like lookups.
17308
0
      if (Previous.wasNotFoundInCurrentInstantiation() &&
17309
0
          (TUK == TUK_Reference || TUK == TUK_Friend)) {
17310
0
        IsDependent = true;
17311
0
        return true;
17312
0
      }
17313
17314
      // A tag 'foo::bar' must already exist.
17315
0
      Diag(NameLoc, diag::err_not_tag_in_scope)
17316
0
          << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17317
0
      Name = nullptr;
17318
0
      Invalid = true;
17319
0
      goto CreateNewDecl;
17320
0
    }
17321
0
  } else if (Name) {
17322
    // C++14 [class.mem]p14:
17323
    //   If T is the name of a class, then each of the following shall have a
17324
    //   name different from T:
17325
    //    -- every member of class T that is itself a type
17326
0
    if (TUK != TUK_Reference && TUK != TUK_Friend &&
17327
0
        DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17328
0
      return true;
17329
17330
    // If this is a named struct, check to see if there was a previous forward
17331
    // declaration or definition.
17332
    // FIXME: We're looking into outer scopes here, even when we
17333
    // shouldn't be. Doing so can result in ambiguities that we
17334
    // shouldn't be diagnosing.
17335
0
    LookupName(Previous, S);
17336
17337
    // When declaring or defining a tag, ignore ambiguities introduced
17338
    // by types using'ed into this scope.
17339
0
    if (Previous.isAmbiguous() &&
17340
0
        (TUK == TUK_Definition || TUK == TUK_Declaration)) {
17341
0
      LookupResult::Filter F = Previous.makeFilter();
17342
0
      while (F.hasNext()) {
17343
0
        NamedDecl *ND = F.next();
17344
0
        if (!ND->getDeclContext()->getRedeclContext()->Equals(
17345
0
                SearchDC->getRedeclContext()))
17346
0
          F.erase();
17347
0
      }
17348
0
      F.done();
17349
0
    }
17350
17351
    // C++11 [namespace.memdef]p3:
17352
    //   If the name in a friend declaration is neither qualified nor
17353
    //   a template-id and the declaration is a function or an
17354
    //   elaborated-type-specifier, the lookup to determine whether
17355
    //   the entity has been previously declared shall not consider
17356
    //   any scopes outside the innermost enclosing namespace.
17357
    //
17358
    // MSVC doesn't implement the above rule for types, so a friend tag
17359
    // declaration may be a redeclaration of a type declared in an enclosing
17360
    // scope.  They do implement this rule for friend functions.
17361
    //
17362
    // Does it matter that this should be by scope instead of by
17363
    // semantic context?
17364
0
    if (!Previous.empty() && TUK == TUK_Friend) {
17365
0
      DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17366
0
      LookupResult::Filter F = Previous.makeFilter();
17367
0
      bool FriendSawTagOutsideEnclosingNamespace = false;
17368
0
      while (F.hasNext()) {
17369
0
        NamedDecl *ND = F.next();
17370
0
        DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17371
0
        if (DC->isFileContext() &&
17372
0
            !EnclosingNS->Encloses(ND->getDeclContext())) {
17373
0
          if (getLangOpts().MSVCCompat)
17374
0
            FriendSawTagOutsideEnclosingNamespace = true;
17375
0
          else
17376
0
            F.erase();
17377
0
        }
17378
0
      }
17379
0
      F.done();
17380
17381
      // Diagnose this MSVC extension in the easy case where lookup would have
17382
      // unambiguously found something outside the enclosing namespace.
17383
0
      if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17384
0
        NamedDecl *ND = Previous.getFoundDecl();
17385
0
        Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17386
0
            << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17387
0
      }
17388
0
    }
17389
17390
    // Note:  there used to be some attempt at recovery here.
17391
0
    if (Previous.isAmbiguous())
17392
0
      return true;
17393
17394
0
    if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
17395
      // FIXME: This makes sure that we ignore the contexts associated
17396
      // with C structs, unions, and enums when looking for a matching
17397
      // tag declaration or definition. See the similar lookup tweak
17398
      // in Sema::LookupName; is there a better way to deal with this?
17399
0
      while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17400
0
        SearchDC = SearchDC->getParent();
17401
0
    } else if (getLangOpts().CPlusPlus) {
17402
      // Inside ObjCContainer want to keep it as a lexical decl context but go
17403
      // past it (most often to TranslationUnit) to find the semantic decl
17404
      // context.
17405
0
      while (isa<ObjCContainerDecl>(SearchDC))
17406
0
        SearchDC = SearchDC->getParent();
17407
0
    }
17408
0
  } else if (getLangOpts().CPlusPlus) {
17409
    // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17410
    // TagDecl the same way as we skip it for named TagDecl.
17411
0
    while (isa<ObjCContainerDecl>(SearchDC))
17412
0
      SearchDC = SearchDC->getParent();
17413
0
  }
17414
17415
0
  if (Previous.isSingleResult() &&
17416
0
      Previous.getFoundDecl()->isTemplateParameter()) {
17417
    // Maybe we will complain about the shadowed template parameter.
17418
0
    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17419
    // Just pretend that we didn't see the previous declaration.
17420
0
    Previous.clear();
17421
0
  }
17422
17423
0
  if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17424
0
      DC->Equals(getStdNamespace())) {
17425
0
    if (Name->isStr("bad_alloc")) {
17426
      // This is a declaration of or a reference to "std::bad_alloc".
17427
0
      isStdBadAlloc = true;
17428
17429
      // If std::bad_alloc has been implicitly declared (but made invisible to
17430
      // name lookup), fill in this implicit declaration as the previous
17431
      // declaration, so that the declarations get chained appropriately.
17432
0
      if (Previous.empty() && StdBadAlloc)
17433
0
        Previous.addDecl(getStdBadAlloc());
17434
0
    } else if (Name->isStr("align_val_t")) {
17435
0
      isStdAlignValT = true;
17436
0
      if (Previous.empty() && StdAlignValT)
17437
0
        Previous.addDecl(getStdAlignValT());
17438
0
    }
17439
0
  }
17440
17441
  // If we didn't find a previous declaration, and this is a reference
17442
  // (or friend reference), move to the correct scope.  In C++, we
17443
  // also need to do a redeclaration lookup there, just in case
17444
  // there's a shadow friend decl.
17445
0
  if (Name && Previous.empty() &&
17446
0
      (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
17447
0
    if (Invalid) goto CreateNewDecl;
17448
0
    assert(SS.isEmpty());
17449
17450
0
    if (TUK == TUK_Reference || IsTemplateParamOrArg) {
17451
      // C++ [basic.scope.pdecl]p5:
17452
      //   -- for an elaborated-type-specifier of the form
17453
      //
17454
      //          class-key identifier
17455
      //
17456
      //      if the elaborated-type-specifier is used in the
17457
      //      decl-specifier-seq or parameter-declaration-clause of a
17458
      //      function defined in namespace scope, the identifier is
17459
      //      declared as a class-name in the namespace that contains
17460
      //      the declaration; otherwise, except as a friend
17461
      //      declaration, the identifier is declared in the smallest
17462
      //      non-class, non-function-prototype scope that contains the
17463
      //      declaration.
17464
      //
17465
      // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17466
      // C structs and unions.
17467
      //
17468
      // It is an error in C++ to declare (rather than define) an enum
17469
      // type, including via an elaborated type specifier.  We'll
17470
      // diagnose that later; for now, declare the enum in the same
17471
      // scope as we would have picked for any other tag type.
17472
      //
17473
      // GNU C also supports this behavior as part of its incomplete
17474
      // enum types extension, while GNU C++ does not.
17475
      //
17476
      // Find the context where we'll be declaring the tag.
17477
      // FIXME: We would like to maintain the current DeclContext as the
17478
      // lexical context,
17479
0
      SearchDC = getTagInjectionContext(SearchDC);
17480
17481
      // Find the scope where we'll be declaring the tag.
17482
0
      S = getTagInjectionScope(S, getLangOpts());
17483
0
    } else {
17484
0
      assert(TUK == TUK_Friend);
17485
0
      CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17486
17487
      // C++ [namespace.memdef]p3:
17488
      //   If a friend declaration in a non-local class first declares a
17489
      //   class or function, the friend class or function is a member of
17490
      //   the innermost enclosing namespace.
17491
0
      SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17492
0
                                    : SearchDC->getEnclosingNamespaceContext();
17493
0
    }
17494
17495
    // In C++, we need to do a redeclaration lookup to properly
17496
    // diagnose some problems.
17497
    // FIXME: redeclaration lookup is also used (with and without C++) to find a
17498
    // hidden declaration so that we don't get ambiguity errors when using a
17499
    // type declared by an elaborated-type-specifier.  In C that is not correct
17500
    // and we should instead merge compatible types found by lookup.
17501
0
    if (getLangOpts().CPlusPlus) {
17502
      // FIXME: This can perform qualified lookups into function contexts,
17503
      // which are meaningless.
17504
0
      Previous.setRedeclarationKind(forRedeclarationInCurContext());
17505
0
      LookupQualifiedName(Previous, SearchDC);
17506
0
    } else {
17507
0
      Previous.setRedeclarationKind(forRedeclarationInCurContext());
17508
0
      LookupName(Previous, S);
17509
0
    }
17510
0
  }
17511
17512
  // If we have a known previous declaration to use, then use it.
17513
0
  if (Previous.empty() && SkipBody && SkipBody->Previous)
17514
0
    Previous.addDecl(SkipBody->Previous);
17515
17516
0
  if (!Previous.empty()) {
17517
0
    NamedDecl *PrevDecl = Previous.getFoundDecl();
17518
0
    NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17519
17520
    // It's okay to have a tag decl in the same scope as a typedef
17521
    // which hides a tag decl in the same scope.  Finding this
17522
    // with a redeclaration lookup can only actually happen in C++.
17523
    //
17524
    // This is also okay for elaborated-type-specifiers, which is
17525
    // technically forbidden by the current standard but which is
17526
    // okay according to the likely resolution of an open issue;
17527
    // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17528
0
    if (getLangOpts().CPlusPlus) {
17529
0
      if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17530
0
        if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17531
0
          TagDecl *Tag = TT->getDecl();
17532
0
          if (Tag->getDeclName() == Name &&
17533
0
              Tag->getDeclContext()->getRedeclContext()
17534
0
                          ->Equals(TD->getDeclContext()->getRedeclContext())) {
17535
0
            PrevDecl = Tag;
17536
0
            Previous.clear();
17537
0
            Previous.addDecl(Tag);
17538
0
            Previous.resolveKind();
17539
0
          }
17540
0
        }
17541
0
      }
17542
0
    }
17543
17544
    // If this is a redeclaration of a using shadow declaration, it must
17545
    // declare a tag in the same context. In MSVC mode, we allow a
17546
    // redefinition if either context is within the other.
17547
0
    if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17548
0
      auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17549
0
      if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
17550
0
          isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17551
0
          !(OldTag && isAcceptableTagRedeclContext(
17552
0
                          *this, OldTag->getDeclContext(), SearchDC))) {
17553
0
        Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17554
0
        Diag(Shadow->getTargetDecl()->getLocation(),
17555
0
             diag::note_using_decl_target);
17556
0
        Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17557
0
            << 0;
17558
        // Recover by ignoring the old declaration.
17559
0
        Previous.clear();
17560
0
        goto CreateNewDecl;
17561
0
      }
17562
0
    }
17563
17564
0
    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17565
      // If this is a use of a previous tag, or if the tag is already declared
17566
      // in the same scope (so that the definition/declaration completes or
17567
      // rementions the tag), reuse the decl.
17568
0
      if (TUK == TUK_Reference || TUK == TUK_Friend ||
17569
0
          isDeclInScope(DirectPrevDecl, SearchDC, S,
17570
0
                        SS.isNotEmpty() || isMemberSpecialization)) {
17571
        // Make sure that this wasn't declared as an enum and now used as a
17572
        // struct or something similar.
17573
0
        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17574
0
                                          TUK == TUK_Definition, KWLoc,
17575
0
                                          Name)) {
17576
0
          bool SafeToContinue =
17577
0
              (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17578
0
               Kind != TagTypeKind::Enum);
17579
0
          if (SafeToContinue)
17580
0
            Diag(KWLoc, diag::err_use_with_wrong_tag)
17581
0
              << Name
17582
0
              << FixItHint::CreateReplacement(SourceRange(KWLoc),
17583
0
                                              PrevTagDecl->getKindName());
17584
0
          else
17585
0
            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17586
0
          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17587
17588
0
          if (SafeToContinue)
17589
0
            Kind = PrevTagDecl->getTagKind();
17590
0
          else {
17591
            // Recover by making this an anonymous redefinition.
17592
0
            Name = nullptr;
17593
0
            Previous.clear();
17594
0
            Invalid = true;
17595
0
          }
17596
0
        }
17597
17598
0
        if (Kind == TagTypeKind::Enum &&
17599
0
            PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17600
0
          const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17601
0
          if (TUK == TUK_Reference || TUK == TUK_Friend)
17602
0
            return PrevTagDecl;
17603
17604
0
          QualType EnumUnderlyingTy;
17605
0
          if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17606
0
            EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17607
0
          else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17608
0
            EnumUnderlyingTy = QualType(T, 0);
17609
17610
          // All conflicts with previous declarations are recovered by
17611
          // returning the previous declaration, unless this is a definition,
17612
          // in which case we want the caller to bail out.
17613
0
          if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17614
0
                                     ScopedEnum, EnumUnderlyingTy,
17615
0
                                     IsFixed, PrevEnum))
17616
0
            return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
17617
0
        }
17618
17619
        // C++11 [class.mem]p1:
17620
        //   A member shall not be declared twice in the member-specification,
17621
        //   except that a nested class or member class template can be declared
17622
        //   and then later defined.
17623
0
        if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
17624
0
            S->isDeclScope(PrevDecl)) {
17625
0
          Diag(NameLoc, diag::ext_member_redeclared);
17626
0
          Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17627
0
        }
17628
17629
0
        if (!Invalid) {
17630
          // If this is a use, just return the declaration we found, unless
17631
          // we have attributes.
17632
0
          if (TUK == TUK_Reference || TUK == TUK_Friend) {
17633
0
            if (!Attrs.empty()) {
17634
              // FIXME: Diagnose these attributes. For now, we create a new
17635
              // declaration to hold them.
17636
0
            } else if (TUK == TUK_Reference &&
17637
0
                       (PrevTagDecl->getFriendObjectKind() ==
17638
0
                            Decl::FOK_Undeclared ||
17639
0
                        PrevDecl->getOwningModule() != getCurrentModule()) &&
17640
0
                       SS.isEmpty()) {
17641
              // This declaration is a reference to an existing entity, but
17642
              // has different visibility from that entity: it either makes
17643
              // a friend visible or it makes a type visible in a new module.
17644
              // In either case, create a new declaration. We only do this if
17645
              // the declaration would have meant the same thing if no prior
17646
              // declaration were found, that is, if it was found in the same
17647
              // scope where we would have injected a declaration.
17648
0
              if (!getTagInjectionContext(CurContext)->getRedeclContext()
17649
0
                       ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17650
0
                return PrevTagDecl;
17651
              // This is in the injected scope, create a new declaration in
17652
              // that scope.
17653
0
              S = getTagInjectionScope(S, getLangOpts());
17654
0
            } else {
17655
0
              return PrevTagDecl;
17656
0
            }
17657
0
          }
17658
17659
          // Diagnose attempts to redefine a tag.
17660
0
          if (TUK == TUK_Definition) {
17661
0
            if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17662
              // If we're defining a specialization and the previous definition
17663
              // is from an implicit instantiation, don't emit an error
17664
              // here; we'll catch this in the general case below.
17665
0
              bool IsExplicitSpecializationAfterInstantiation = false;
17666
0
              if (isMemberSpecialization) {
17667
0
                if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17668
0
                  IsExplicitSpecializationAfterInstantiation =
17669
0
                    RD->getTemplateSpecializationKind() !=
17670
0
                    TSK_ExplicitSpecialization;
17671
0
                else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17672
0
                  IsExplicitSpecializationAfterInstantiation =
17673
0
                    ED->getTemplateSpecializationKind() !=
17674
0
                    TSK_ExplicitSpecialization;
17675
0
              }
17676
17677
              // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17678
              // not keep more that one definition around (merge them). However,
17679
              // ensure the decl passes the structural compatibility check in
17680
              // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17681
0
              NamedDecl *Hidden = nullptr;
17682
0
              if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17683
                // There is a definition of this tag, but it is not visible. We
17684
                // explicitly make use of C++'s one definition rule here, and
17685
                // assume that this definition is identical to the hidden one
17686
                // we already have. Make the existing definition visible and
17687
                // use it in place of this one.
17688
0
                if (!getLangOpts().CPlusPlus) {
17689
                  // Postpone making the old definition visible until after we
17690
                  // complete parsing the new one and do the structural
17691
                  // comparison.
17692
0
                  SkipBody->CheckSameAsPrevious = true;
17693
0
                  SkipBody->New = createTagFromNewDecl();
17694
0
                  SkipBody->Previous = Def;
17695
0
                  return Def;
17696
0
                } else {
17697
0
                  SkipBody->ShouldSkip = true;
17698
0
                  SkipBody->Previous = Def;
17699
0
                  makeMergedDefinitionVisible(Hidden);
17700
                  // Carry on and handle it like a normal definition. We'll
17701
                  // skip starting the definitiion later.
17702
0
                }
17703
0
              } else if (!IsExplicitSpecializationAfterInstantiation) {
17704
                // A redeclaration in function prototype scope in C isn't
17705
                // visible elsewhere, so merely issue a warning.
17706
0
                if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17707
0
                  Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17708
0
                else
17709
0
                  Diag(NameLoc, diag::err_redefinition) << Name;
17710
0
                notePreviousDefinition(Def,
17711
0
                                       NameLoc.isValid() ? NameLoc : KWLoc);
17712
                // If this is a redefinition, recover by making this
17713
                // struct be anonymous, which will make any later
17714
                // references get the previous definition.
17715
0
                Name = nullptr;
17716
0
                Previous.clear();
17717
0
                Invalid = true;
17718
0
              }
17719
0
            } else {
17720
              // If the type is currently being defined, complain
17721
              // about a nested redefinition.
17722
0
              auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17723
0
              if (TD->isBeingDefined()) {
17724
0
                Diag(NameLoc, diag::err_nested_redefinition) << Name;
17725
0
                Diag(PrevTagDecl->getLocation(),
17726
0
                     diag::note_previous_definition);
17727
0
                Name = nullptr;
17728
0
                Previous.clear();
17729
0
                Invalid = true;
17730
0
              }
17731
0
            }
17732
17733
            // Okay, this is definition of a previously declared or referenced
17734
            // tag. We're going to create a new Decl for it.
17735
0
          }
17736
17737
          // Okay, we're going to make a redeclaration.  If this is some kind
17738
          // of reference, make sure we build the redeclaration in the same DC
17739
          // as the original, and ignore the current access specifier.
17740
0
          if (TUK == TUK_Friend || TUK == TUK_Reference) {
17741
0
            SearchDC = PrevTagDecl->getDeclContext();
17742
0
            AS = AS_none;
17743
0
          }
17744
0
        }
17745
        // If we get here we have (another) forward declaration or we
17746
        // have a definition.  Just create a new decl.
17747
17748
0
      } else {
17749
        // If we get here, this is a definition of a new tag type in a nested
17750
        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17751
        // new decl/type.  We set PrevDecl to NULL so that the entities
17752
        // have distinct types.
17753
0
        Previous.clear();
17754
0
      }
17755
      // If we get here, we're going to create a new Decl. If PrevDecl
17756
      // is non-NULL, it's a definition of the tag declared by
17757
      // PrevDecl. If it's NULL, we have a new definition.
17758
17759
    // Otherwise, PrevDecl is not a tag, but was found with tag
17760
    // lookup.  This is only actually possible in C++, where a few
17761
    // things like templates still live in the tag namespace.
17762
0
    } else {
17763
      // Use a better diagnostic if an elaborated-type-specifier
17764
      // found the wrong kind of type on the first
17765
      // (non-redeclaration) lookup.
17766
0
      if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
17767
0
          !Previous.isForRedeclaration()) {
17768
0
        NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17769
0
        Diag(NameLoc, diag::err_tag_reference_non_tag)
17770
0
            << PrevDecl << NTK << llvm::to_underlying(Kind);
17771
0
        Diag(PrevDecl->getLocation(), diag::note_declared_at);
17772
0
        Invalid = true;
17773
17774
      // Otherwise, only diagnose if the declaration is in scope.
17775
0
      } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17776
0
                                SS.isNotEmpty() || isMemberSpecialization)) {
17777
        // do nothing
17778
17779
      // Diagnose implicit declarations introduced by elaborated types.
17780
0
      } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
17781
0
        NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17782
0
        Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17783
0
        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17784
0
        Invalid = true;
17785
17786
      // Otherwise it's a declaration.  Call out a particularly common
17787
      // case here.
17788
0
      } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17789
0
        unsigned Kind = 0;
17790
0
        if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17791
0
        Diag(NameLoc, diag::err_tag_definition_of_typedef)
17792
0
          << Name << Kind << TND->getUnderlyingType();
17793
0
        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17794
0
        Invalid = true;
17795
17796
      // Otherwise, diagnose.
17797
0
      } else {
17798
        // The tag name clashes with something else in the target scope,
17799
        // issue an error and recover by making this tag be anonymous.
17800
0
        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17801
0
        notePreviousDefinition(PrevDecl, NameLoc);
17802
0
        Name = nullptr;
17803
0
        Invalid = true;
17804
0
      }
17805
17806
      // The existing declaration isn't relevant to us; we're in a
17807
      // new scope, so clear out the previous declaration.
17808
0
      Previous.clear();
17809
0
    }
17810
0
  }
17811
17812
0
CreateNewDecl:
17813
17814
0
  TagDecl *PrevDecl = nullptr;
17815
0
  if (Previous.isSingleResult())
17816
0
    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17817
17818
  // If there is an identifier, use the location of the identifier as the
17819
  // location of the decl, otherwise use the location of the struct/union
17820
  // keyword.
17821
0
  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17822
17823
  // Otherwise, create a new declaration. If there is a previous
17824
  // declaration of the same entity, the two will be linked via
17825
  // PrevDecl.
17826
0
  TagDecl *New;
17827
17828
0
  if (Kind == TagTypeKind::Enum) {
17829
    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17830
    // enum X { A, B, C } D;    D should chain to X.
17831
0
    New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17832
0
                           cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17833
0
                           ScopedEnumUsesClassTag, IsFixed);
17834
17835
0
    if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17836
0
      StdAlignValT = cast<EnumDecl>(New);
17837
17838
    // If this is an undefined enum, warn.
17839
0
    if (TUK != TUK_Definition && !Invalid) {
17840
0
      TagDecl *Def;
17841
0
      if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17842
        // C++0x: 7.2p2: opaque-enum-declaration.
17843
        // Conflicts are diagnosed above. Do nothing.
17844
0
      }
17845
0
      else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17846
0
        Diag(Loc, diag::ext_forward_ref_enum_def)
17847
0
          << New;
17848
0
        Diag(Def->getLocation(), diag::note_previous_definition);
17849
0
      } else {
17850
0
        unsigned DiagID = diag::ext_forward_ref_enum;
17851
0
        if (getLangOpts().MSVCCompat)
17852
0
          DiagID = diag::ext_ms_forward_ref_enum;
17853
0
        else if (getLangOpts().CPlusPlus)
17854
0
          DiagID = diag::err_forward_ref_enum;
17855
0
        Diag(Loc, DiagID);
17856
0
      }
17857
0
    }
17858
17859
0
    if (EnumUnderlying) {
17860
0
      EnumDecl *ED = cast<EnumDecl>(New);
17861
0
      if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17862
0
        ED->setIntegerTypeSourceInfo(TI);
17863
0
      else
17864
0
        ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17865
0
      QualType EnumTy = ED->getIntegerType();
17866
0
      ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17867
0
                               ? Context.getPromotedIntegerType(EnumTy)
17868
0
                               : EnumTy);
17869
0
      assert(ED->isComplete() && "enum with type should be complete");
17870
0
    }
17871
0
  } else {
17872
    // struct/union/class
17873
17874
    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17875
    // struct X { int A; } D;    D should chain to X.
17876
0
    if (getLangOpts().CPlusPlus) {
17877
      // FIXME: Look for a way to use RecordDecl for simple structs.
17878
0
      New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17879
0
                                  cast_or_null<CXXRecordDecl>(PrevDecl));
17880
17881
0
      if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17882
0
        StdBadAlloc = cast<CXXRecordDecl>(New);
17883
0
    } else
17884
0
      New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17885
0
                               cast_or_null<RecordDecl>(PrevDecl));
17886
0
  }
17887
17888
0
  if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus)
17889
0
    Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17890
0
        << (OOK == OOK_Macro) << New->getSourceRange();
17891
17892
  // C++11 [dcl.type]p3:
17893
  //   A type-specifier-seq shall not define a class or enumeration [...].
17894
0
  if (!Invalid && getLangOpts().CPlusPlus &&
17895
0
      (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
17896
0
    Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17897
0
      << Context.getTagDeclType(New);
17898
0
    Invalid = true;
17899
0
  }
17900
17901
0
  if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
17902
0
      DC->getDeclKind() == Decl::Enum) {
17903
0
    Diag(New->getLocation(), diag::err_type_defined_in_enum)
17904
0
      << Context.getTagDeclType(New);
17905
0
    Invalid = true;
17906
0
  }
17907
17908
  // Maybe add qualifier info.
17909
0
  if (SS.isNotEmpty()) {
17910
0
    if (SS.isSet()) {
17911
      // If this is either a declaration or a definition, check the
17912
      // nested-name-specifier against the current context.
17913
0
      if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
17914
0
          diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17915
0
                                       isMemberSpecialization))
17916
0
        Invalid = true;
17917
17918
0
      New->setQualifierInfo(SS.getWithLocInContext(Context));
17919
0
      if (TemplateParameterLists.size() > 0) {
17920
0
        New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17921
0
      }
17922
0
    }
17923
0
    else
17924
0
      Invalid = true;
17925
0
  }
17926
17927
0
  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17928
    // Add alignment attributes if necessary; these attributes are checked when
17929
    // the ASTContext lays out the structure.
17930
    //
17931
    // It is important for implementing the correct semantics that this
17932
    // happen here (in ActOnTag). The #pragma pack stack is
17933
    // maintained as a result of parser callbacks which can occur at
17934
    // many points during the parsing of a struct declaration (because
17935
    // the #pragma tokens are effectively skipped over during the
17936
    // parsing of the struct).
17937
0
    if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17938
0
      AddAlignmentAttributesForRecord(RD);
17939
0
      AddMsStructLayoutForRecord(RD);
17940
0
    }
17941
0
  }
17942
17943
0
  if (ModulePrivateLoc.isValid()) {
17944
0
    if (isMemberSpecialization)
17945
0
      Diag(New->getLocation(), diag::err_module_private_specialization)
17946
0
        << 2
17947
0
        << FixItHint::CreateRemoval(ModulePrivateLoc);
17948
    // __module_private__ does not apply to local classes. However, we only
17949
    // diagnose this as an error when the declaration specifiers are
17950
    // freestanding. Here, we just ignore the __module_private__.
17951
0
    else if (!SearchDC->isFunctionOrMethod())
17952
0
      New->setModulePrivate();
17953
0
  }
17954
17955
  // If this is a specialization of a member class (of a class template),
17956
  // check the specialization.
17957
0
  if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
17958
0
    Invalid = true;
17959
17960
  // If we're declaring or defining a tag in function prototype scope in C,
17961
  // note that this type can only be used within the function and add it to
17962
  // the list of decls to inject into the function definition scope.
17963
0
  if ((Name || Kind == TagTypeKind::Enum) &&
17964
0
      getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
17965
0
    if (getLangOpts().CPlusPlus) {
17966
      // C++ [dcl.fct]p6:
17967
      //   Types shall not be defined in return or parameter types.
17968
0
      if (TUK == TUK_Definition && !IsTypeSpecifier) {
17969
0
        Diag(Loc, diag::err_type_defined_in_param_type)
17970
0
            << Name;
17971
0
        Invalid = true;
17972
0
      }
17973
0
    } else if (!PrevDecl) {
17974
0
      Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
17975
0
    }
17976
0
  }
17977
17978
0
  if (Invalid)
17979
0
    New->setInvalidDecl();
17980
17981
  // Set the lexical context. If the tag has a C++ scope specifier, the
17982
  // lexical context will be different from the semantic context.
17983
0
  New->setLexicalDeclContext(CurContext);
17984
17985
  // Mark this as a friend decl if applicable.
17986
  // In Microsoft mode, a friend declaration also acts as a forward
17987
  // declaration so we always pass true to setObjectOfFriendDecl to make
17988
  // the tag name visible.
17989
0
  if (TUK == TUK_Friend)
17990
0
    New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17991
17992
  // Set the access specifier.
17993
0
  if (!Invalid && SearchDC->isRecord())
17994
0
    SetMemberAccessSpecifier(New, PrevDecl, AS);
17995
17996
0
  if (PrevDecl)
17997
0
    CheckRedeclarationInModule(New, PrevDecl);
17998
17999
0
  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
18000
0
    New->startDefinition();
18001
18002
0
  ProcessDeclAttributeList(S, New, Attrs);
18003
0
  AddPragmaAttributes(S, New);
18004
18005
  // If this has an identifier, add it to the scope stack.
18006
0
  if (TUK == TUK_Friend) {
18007
    // We might be replacing an existing declaration in the lookup tables;
18008
    // if so, borrow its access specifier.
18009
0
    if (PrevDecl)
18010
0
      New->setAccess(PrevDecl->getAccess());
18011
18012
0
    DeclContext *DC = New->getDeclContext()->getRedeclContext();
18013
0
    DC->makeDeclVisibleInContext(New);
18014
0
    if (Name) // can be null along some error paths
18015
0
      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18016
0
        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18017
0
  } else if (Name) {
18018
0
    S = getNonFieldDeclScope(S);
18019
0
    PushOnScopeChains(New, S, true);
18020
0
  } else {
18021
0
    CurContext->addDecl(New);
18022
0
  }
18023
18024
  // If this is the C FILE type, notify the AST context.
18025
0
  if (IdentifierInfo *II = New->getIdentifier())
18026
0
    if (!New->isInvalidDecl() &&
18027
0
        New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18028
0
        II->isStr("FILE"))
18029
0
      Context.setFILEDecl(New);
18030
18031
0
  if (PrevDecl)
18032
0
    mergeDeclAttributes(New, PrevDecl);
18033
18034
0
  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
18035
0
    inferGslOwnerPointerAttribute(CXXRD);
18036
18037
  // If there's a #pragma GCC visibility in scope, set the visibility of this
18038
  // record.
18039
0
  AddPushedVisibilityAttribute(New);
18040
18041
0
  if (isMemberSpecialization && !New->isInvalidDecl())
18042
0
    CompleteMemberSpecialization(New, Previous);
18043
18044
0
  OwnedDecl = true;
18045
  // In C++, don't return an invalid declaration. We can't recover well from
18046
  // the cases where we make the type anonymous.
18047
0
  if (Invalid && getLangOpts().CPlusPlus) {
18048
0
    if (New->isBeingDefined())
18049
0
      if (auto RD = dyn_cast<RecordDecl>(New))
18050
0
        RD->completeDefinition();
18051
0
    return true;
18052
0
  } else if (SkipBody && SkipBody->ShouldSkip) {
18053
0
    return SkipBody->Previous;
18054
0
  } else {
18055
0
    return New;
18056
0
  }
18057
0
}
18058
18059
0
void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
18060
0
  AdjustDeclIfTemplate(TagD);
18061
0
  TagDecl *Tag = cast<TagDecl>(TagD);
18062
18063
  // Enter the tag context.
18064
0
  PushDeclContext(S, Tag);
18065
18066
0
  ActOnDocumentableDecl(TagD);
18067
18068
  // If there's a #pragma GCC visibility in scope, set the visibility of this
18069
  // record.
18070
0
  AddPushedVisibilityAttribute(Tag);
18071
0
}
18072
18073
0
bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
18074
0
  if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18075
0
    return false;
18076
18077
  // Make the previous decl visible.
18078
0
  makeMergedDefinitionVisible(SkipBody.Previous);
18079
0
  return true;
18080
0
}
18081
18082
0
void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
18083
0
  assert(IDecl->getLexicalParent() == CurContext &&
18084
0
      "The next DeclContext should be lexically contained in the current one.");
18085
0
  CurContext = IDecl;
18086
0
}
18087
18088
void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
18089
                                           SourceLocation FinalLoc,
18090
                                           bool IsFinalSpelledSealed,
18091
                                           bool IsAbstract,
18092
0
                                           SourceLocation LBraceLoc) {
18093
0
  AdjustDeclIfTemplate(TagD);
18094
0
  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18095
18096
0
  FieldCollector->StartClass();
18097
18098
0
  if (!Record->getIdentifier())
18099
0
    return;
18100
18101
0
  if (IsAbstract)
18102
0
    Record->markAbstract();
18103
18104
0
  if (FinalLoc.isValid()) {
18105
0
    Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18106
0
                                      IsFinalSpelledSealed
18107
0
                                          ? FinalAttr::Keyword_sealed
18108
0
                                          : FinalAttr::Keyword_final));
18109
0
  }
18110
  // C++ [class]p2:
18111
  //   [...] The class-name is also inserted into the scope of the
18112
  //   class itself; this is known as the injected-class-name. For
18113
  //   purposes of access checking, the injected-class-name is treated
18114
  //   as if it were a public member name.
18115
0
  CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18116
0
      Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18117
0
      Record->getLocation(), Record->getIdentifier(),
18118
0
      /*PrevDecl=*/nullptr,
18119
0
      /*DelayTypeCreation=*/true);
18120
0
  Context.getTypeDeclType(InjectedClassName, Record);
18121
0
  InjectedClassName->setImplicit();
18122
0
  InjectedClassName->setAccess(AS_public);
18123
0
  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18124
0
      InjectedClassName->setDescribedClassTemplate(Template);
18125
0
  PushOnScopeChains(InjectedClassName, S);
18126
0
  assert(InjectedClassName->isInjectedClassName() &&
18127
0
         "Broken injected-class-name");
18128
0
}
18129
18130
void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
18131
0
                                    SourceRange BraceRange) {
18132
0
  AdjustDeclIfTemplate(TagD);
18133
0
  TagDecl *Tag = cast<TagDecl>(TagD);
18134
0
  Tag->setBraceRange(BraceRange);
18135
18136
  // Make sure we "complete" the definition even it is invalid.
18137
0
  if (Tag->isBeingDefined()) {
18138
0
    assert(Tag->isInvalidDecl() && "We should already have completed it");
18139
0
    if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18140
0
      RD->completeDefinition();
18141
0
  }
18142
18143
0
  if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18144
0
    FieldCollector->FinishClass();
18145
0
    if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18146
0
      auto *Def = RD->getDefinition();
18147
0
      assert(Def && "The record is expected to have a completed definition");
18148
0
      unsigned NumInitMethods = 0;
18149
0
      for (auto *Method : Def->methods()) {
18150
0
        if (!Method->getIdentifier())
18151
0
            continue;
18152
0
        if (Method->getName() == "__init")
18153
0
          NumInitMethods++;
18154
0
      }
18155
0
      if (NumInitMethods > 1 || !Def->hasInitMethod())
18156
0
        Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18157
0
    }
18158
0
  }
18159
18160
  // Exit this scope of this tag's definition.
18161
0
  PopDeclContext();
18162
18163
0
  if (getCurLexicalContext()->isObjCContainer() &&
18164
0
      Tag->getDeclContext()->isFileContext())
18165
0
    Tag->setTopLevelDeclInObjCContainer();
18166
18167
  // Notify the consumer that we've defined a tag.
18168
0
  if (!Tag->isInvalidDecl())
18169
0
    Consumer.HandleTagDeclDefinition(Tag);
18170
18171
  // Clangs implementation of #pragma align(packed) differs in bitfield layout
18172
  // from XLs and instead matches the XL #pragma pack(1) behavior.
18173
0
  if (Context.getTargetInfo().getTriple().isOSAIX() &&
18174
0
      AlignPackStack.hasValue()) {
18175
0
    AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18176
    // Only diagnose #pragma align(packed).
18177
0
    if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18178
0
      return;
18179
0
    const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18180
0
    if (!RD)
18181
0
      return;
18182
    // Only warn if there is at least 1 bitfield member.
18183
0
    if (llvm::any_of(RD->fields(),
18184
0
                     [](const FieldDecl *FD) { return FD->isBitField(); }))
18185
0
      Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18186
0
  }
18187
0
}
18188
18189
0
void Sema::ActOnObjCContainerFinishDefinition() {
18190
  // Exit this scope of this interface definition.
18191
0
  PopDeclContext();
18192
0
}
18193
18194
0
void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
18195
0
  assert(ObjCCtx == CurContext && "Mismatch of container contexts");
18196
0
  OriginalLexicalContext = ObjCCtx;
18197
0
  ActOnObjCContainerFinishDefinition();
18198
0
}
18199
18200
0
void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
18201
0
  ActOnObjCContainerStartDefinition(ObjCCtx);
18202
0
  OriginalLexicalContext = nullptr;
18203
0
}
18204
18205
0
void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
18206
0
  AdjustDeclIfTemplate(TagD);
18207
0
  TagDecl *Tag = cast<TagDecl>(TagD);
18208
0
  Tag->setInvalidDecl();
18209
18210
  // Make sure we "complete" the definition even it is invalid.
18211
0
  if (Tag->isBeingDefined()) {
18212
0
    if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18213
0
      RD->completeDefinition();
18214
0
  }
18215
18216
  // We're undoing ActOnTagStartDefinition here, not
18217
  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18218
  // the FieldCollector.
18219
18220
0
  PopDeclContext();
18221
0
}
18222
18223
// Note that FieldName may be null for anonymous bitfields.
18224
ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
18225
                                IdentifierInfo *FieldName, QualType FieldTy,
18226
0
                                bool IsMsStruct, Expr *BitWidth) {
18227
0
  assert(BitWidth);
18228
0
  if (BitWidth->containsErrors())
18229
0
    return ExprError();
18230
18231
  // C99 6.7.2.1p4 - verify the field type.
18232
  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18233
0
  if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18234
    // Handle incomplete and sizeless types with a specific error.
18235
0
    if (RequireCompleteSizedType(FieldLoc, FieldTy,
18236
0
                                 diag::err_field_incomplete_or_sizeless))
18237
0
      return ExprError();
18238
0
    if (FieldName)
18239
0
      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18240
0
        << FieldName << FieldTy << BitWidth->getSourceRange();
18241
0
    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18242
0
      << FieldTy << BitWidth->getSourceRange();
18243
0
  } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18244
0
                                             UPPC_BitFieldWidth))
18245
0
    return ExprError();
18246
18247
  // If the bit-width is type- or value-dependent, don't try to check
18248
  // it now.
18249
0
  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18250
0
    return BitWidth;
18251
18252
0
  llvm::APSInt Value;
18253
0
  ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
18254
0
  if (ICE.isInvalid())
18255
0
    return ICE;
18256
0
  BitWidth = ICE.get();
18257
18258
  // Zero-width bitfield is ok for anonymous field.
18259
0
  if (Value == 0 && FieldName)
18260
0
    return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18261
0
           << FieldName << BitWidth->getSourceRange();
18262
18263
0
  if (Value.isSigned() && Value.isNegative()) {
18264
0
    if (FieldName)
18265
0
      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18266
0
               << FieldName << toString(Value, 10);
18267
0
    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18268
0
      << toString(Value, 10);
18269
0
  }
18270
18271
  // The size of the bit-field must not exceed our maximum permitted object
18272
  // size.
18273
0
  if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18274
0
    return Diag(FieldLoc, diag::err_bitfield_too_wide)
18275
0
           << !FieldName << FieldName << toString(Value, 10);
18276
0
  }
18277
18278
0
  if (!FieldTy->isDependentType()) {
18279
0
    uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18280
0
    uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18281
0
    bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18282
18283
    // Over-wide bitfields are an error in C or when using the MSVC bitfield
18284
    // ABI.
18285
0
    bool CStdConstraintViolation =
18286
0
        BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18287
0
    bool MSBitfieldViolation =
18288
0
        Value.ugt(TypeStorageSize) &&
18289
0
        (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18290
0
    if (CStdConstraintViolation || MSBitfieldViolation) {
18291
0
      unsigned DiagWidth =
18292
0
          CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18293
0
      return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18294
0
             << (bool)FieldName << FieldName << toString(Value, 10)
18295
0
             << !CStdConstraintViolation << DiagWidth;
18296
0
    }
18297
18298
    // Warn on types where the user might conceivably expect to get all
18299
    // specified bits as value bits: that's all integral types other than
18300
    // 'bool'.
18301
0
    if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18302
0
      Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18303
0
          << FieldName << toString(Value, 10)
18304
0
          << (unsigned)TypeWidth;
18305
0
    }
18306
0
  }
18307
18308
0
  return BitWidth;
18309
0
}
18310
18311
/// ActOnField - Each field of a C struct/union is passed into this in order
18312
/// to create a FieldDecl object for it.
18313
Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
18314
0
                       Declarator &D, Expr *BitfieldWidth) {
18315
0
  FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18316
0
                               D, BitfieldWidth,
18317
0
                               /*InitStyle=*/ICIS_NoInit, AS_public);
18318
0
  return Res;
18319
0
}
18320
18321
/// HandleField - Analyze a field of a C struct or a C++ data member.
18322
///
18323
FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
18324
                             SourceLocation DeclStart,
18325
                             Declarator &D, Expr *BitWidth,
18326
                             InClassInitStyle InitStyle,
18327
0
                             AccessSpecifier AS) {
18328
0
  if (D.isDecompositionDeclarator()) {
18329
0
    const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18330
0
    Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18331
0
      << Decomp.getSourceRange();
18332
0
    return nullptr;
18333
0
  }
18334
18335
0
  IdentifierInfo *II = D.getIdentifier();
18336
0
  SourceLocation Loc = DeclStart;
18337
0
  if (II) Loc = D.getIdentifierLoc();
18338
18339
0
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18340
0
  QualType T = TInfo->getType();
18341
0
  if (getLangOpts().CPlusPlus) {
18342
0
    CheckExtraCXXDefaultArguments(D);
18343
18344
0
    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18345
0
                                        UPPC_DataMemberType)) {
18346
0
      D.setInvalidType();
18347
0
      T = Context.IntTy;
18348
0
      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18349
0
    }
18350
0
  }
18351
18352
0
  DiagnoseFunctionSpecifiers(D.getDeclSpec());
18353
18354
0
  if (D.getDeclSpec().isInlineSpecified())
18355
0
    Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18356
0
        << getLangOpts().CPlusPlus17;
18357
0
  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18358
0
    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18359
0
         diag::err_invalid_thread)
18360
0
      << DeclSpec::getSpecifierName(TSCS);
18361
18362
  // Check to see if this name was declared as a member previously
18363
0
  NamedDecl *PrevDecl = nullptr;
18364
0
  LookupResult Previous(*this, II, Loc, LookupMemberName,
18365
0
                        ForVisibleRedeclaration);
18366
0
  LookupName(Previous, S);
18367
0
  switch (Previous.getResultKind()) {
18368
0
    case LookupResult::Found:
18369
0
    case LookupResult::FoundUnresolvedValue:
18370
0
      PrevDecl = Previous.getAsSingle<NamedDecl>();
18371
0
      break;
18372
18373
0
    case LookupResult::FoundOverloaded:
18374
0
      PrevDecl = Previous.getRepresentativeDecl();
18375
0
      break;
18376
18377
0
    case LookupResult::NotFound:
18378
0
    case LookupResult::NotFoundInCurrentInstantiation:
18379
0
    case LookupResult::Ambiguous:
18380
0
      break;
18381
0
  }
18382
0
  Previous.suppressDiagnostics();
18383
18384
0
  if (PrevDecl && PrevDecl->isTemplateParameter()) {
18385
    // Maybe we will complain about the shadowed template parameter.
18386
0
    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18387
    // Just pretend that we didn't see the previous declaration.
18388
0
    PrevDecl = nullptr;
18389
0
  }
18390
18391
0
  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18392
0
    PrevDecl = nullptr;
18393
18394
0
  bool Mutable
18395
0
    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18396
0
  SourceLocation TSSL = D.getBeginLoc();
18397
0
  FieldDecl *NewFD
18398
0
    = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18399
0
                     TSSL, AS, PrevDecl, &D);
18400
18401
0
  if (NewFD->isInvalidDecl())
18402
0
    Record->setInvalidDecl();
18403
18404
0
  if (D.getDeclSpec().isModulePrivateSpecified())
18405
0
    NewFD->setModulePrivate();
18406
18407
0
  if (NewFD->isInvalidDecl() && PrevDecl) {
18408
    // Don't introduce NewFD into scope; there's already something
18409
    // with the same name in the same scope.
18410
0
  } else if (II) {
18411
0
    PushOnScopeChains(NewFD, S);
18412
0
  } else
18413
0
    Record->addDecl(NewFD);
18414
18415
0
  return NewFD;
18416
0
}
18417
18418
/// Build a new FieldDecl and check its well-formedness.
18419
///
18420
/// This routine builds a new FieldDecl given the fields name, type,
18421
/// record, etc. \p PrevDecl should refer to any previous declaration
18422
/// with the same name and in the same scope as the field to be
18423
/// created.
18424
///
18425
/// \returns a new FieldDecl.
18426
///
18427
/// \todo The Declarator argument is a hack. It will be removed once
18428
FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
18429
                                TypeSourceInfo *TInfo,
18430
                                RecordDecl *Record, SourceLocation Loc,
18431
                                bool Mutable, Expr *BitWidth,
18432
                                InClassInitStyle InitStyle,
18433
                                SourceLocation TSSL,
18434
                                AccessSpecifier AS, NamedDecl *PrevDecl,
18435
0
                                Declarator *D) {
18436
0
  IdentifierInfo *II = Name.getAsIdentifierInfo();
18437
0
  bool InvalidDecl = false;
18438
0
  if (D) InvalidDecl = D->isInvalidType();
18439
18440
  // If we receive a broken type, recover by assuming 'int' and
18441
  // marking this declaration as invalid.
18442
0
  if (T.isNull() || T->containsErrors()) {
18443
0
    InvalidDecl = true;
18444
0
    T = Context.IntTy;
18445
0
  }
18446
18447
0
  QualType EltTy = Context.getBaseElementType(T);
18448
0
  if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18449
0
    if (RequireCompleteSizedType(Loc, EltTy,
18450
0
                                 diag::err_field_incomplete_or_sizeless)) {
18451
      // Fields of incomplete type force their record to be invalid.
18452
0
      Record->setInvalidDecl();
18453
0
      InvalidDecl = true;
18454
0
    } else {
18455
0
      NamedDecl *Def;
18456
0
      EltTy->isIncompleteType(&Def);
18457
0
      if (Def && Def->isInvalidDecl()) {
18458
0
        Record->setInvalidDecl();
18459
0
        InvalidDecl = true;
18460
0
      }
18461
0
    }
18462
0
  }
18463
18464
  // TR 18037 does not allow fields to be declared with address space
18465
0
  if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18466
0
      T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18467
0
    Diag(Loc, diag::err_field_with_address_space);
18468
0
    Record->setInvalidDecl();
18469
0
    InvalidDecl = true;
18470
0
  }
18471
18472
0
  if (LangOpts.OpenCL) {
18473
    // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18474
    // used as structure or union field: image, sampler, event or block types.
18475
0
    if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18476
0
        T->isBlockPointerType()) {
18477
0
      Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18478
0
      Record->setInvalidDecl();
18479
0
      InvalidDecl = true;
18480
0
    }
18481
    // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18482
    // is enabled.
18483
0
    if (BitWidth && !getOpenCLOptions().isAvailableOption(
18484
0
                        "__cl_clang_bitfields", LangOpts)) {
18485
0
      Diag(Loc, diag::err_opencl_bitfields);
18486
0
      InvalidDecl = true;
18487
0
    }
18488
0
  }
18489
18490
  // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18491
0
  if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18492
0
      T.hasQualifiers()) {
18493
0
    InvalidDecl = true;
18494
0
    Diag(Loc, diag::err_anon_bitfield_qualifiers);
18495
0
  }
18496
18497
  // C99 6.7.2.1p8: A member of a structure or union may have any type other
18498
  // than a variably modified type.
18499
0
  if (!InvalidDecl && T->isVariablyModifiedType()) {
18500
0
    if (!tryToFixVariablyModifiedVarType(
18501
0
            TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18502
0
      InvalidDecl = true;
18503
0
  }
18504
18505
  // Fields can not have abstract class types
18506
0
  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18507
0
                                             diag::err_abstract_type_in_decl,
18508
0
                                             AbstractFieldType))
18509
0
    InvalidDecl = true;
18510
18511
0
  if (InvalidDecl)
18512
0
    BitWidth = nullptr;
18513
  // If this is declared as a bit-field, check the bit-field.
18514
0
  if (BitWidth) {
18515
0
    BitWidth =
18516
0
        VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18517
0
    if (!BitWidth) {
18518
0
      InvalidDecl = true;
18519
0
      BitWidth = nullptr;
18520
0
    }
18521
0
  }
18522
18523
  // Check that 'mutable' is consistent with the type of the declaration.
18524
0
  if (!InvalidDecl && Mutable) {
18525
0
    unsigned DiagID = 0;
18526
0
    if (T->isReferenceType())
18527
0
      DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18528
0
                                        : diag::err_mutable_reference;
18529
0
    else if (T.isConstQualified())
18530
0
      DiagID = diag::err_mutable_const;
18531
18532
0
    if (DiagID) {
18533
0
      SourceLocation ErrLoc = Loc;
18534
0
      if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18535
0
        ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18536
0
      Diag(ErrLoc, DiagID);
18537
0
      if (DiagID != diag::ext_mutable_reference) {
18538
0
        Mutable = false;
18539
0
        InvalidDecl = true;
18540
0
      }
18541
0
    }
18542
0
  }
18543
18544
  // C++11 [class.union]p8 (DR1460):
18545
  //   At most one variant member of a union may have a
18546
  //   brace-or-equal-initializer.
18547
0
  if (InitStyle != ICIS_NoInit)
18548
0
    checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18549
18550
0
  FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18551
0
                                       BitWidth, Mutable, InitStyle);
18552
0
  if (InvalidDecl)
18553
0
    NewFD->setInvalidDecl();
18554
18555
0
  if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18556
0
      !PrevDecl->isPlaceholderVar(getLangOpts())) {
18557
0
    Diag(Loc, diag::err_duplicate_member) << II;
18558
0
    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18559
0
    NewFD->setInvalidDecl();
18560
0
  }
18561
18562
0
  if (!InvalidDecl && getLangOpts().CPlusPlus) {
18563
0
    if (Record->isUnion()) {
18564
0
      if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18565
0
        CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18566
0
        if (RDecl->getDefinition()) {
18567
          // C++ [class.union]p1: An object of a class with a non-trivial
18568
          // constructor, a non-trivial copy constructor, a non-trivial
18569
          // destructor, or a non-trivial copy assignment operator
18570
          // cannot be a member of a union, nor can an array of such
18571
          // objects.
18572
0
          if (CheckNontrivialField(NewFD))
18573
0
            NewFD->setInvalidDecl();
18574
0
        }
18575
0
      }
18576
18577
      // C++ [class.union]p1: If a union contains a member of reference type,
18578
      // the program is ill-formed, except when compiling with MSVC extensions
18579
      // enabled.
18580
0
      if (EltTy->isReferenceType()) {
18581
0
        Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18582
0
                                    diag::ext_union_member_of_reference_type :
18583
0
                                    diag::err_union_member_of_reference_type)
18584
0
          << NewFD->getDeclName() << EltTy;
18585
0
        if (!getLangOpts().MicrosoftExt)
18586
0
          NewFD->setInvalidDecl();
18587
0
      }
18588
0
    }
18589
0
  }
18590
18591
  // FIXME: We need to pass in the attributes given an AST
18592
  // representation, not a parser representation.
18593
0
  if (D) {
18594
    // FIXME: The current scope is almost... but not entirely... correct here.
18595
0
    ProcessDeclAttributes(getCurScope(), NewFD, *D);
18596
18597
0
    if (NewFD->hasAttrs())
18598
0
      CheckAlignasUnderalignment(NewFD);
18599
0
  }
18600
18601
  // In auto-retain/release, infer strong retension for fields of
18602
  // retainable type.
18603
0
  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
18604
0
    NewFD->setInvalidDecl();
18605
18606
0
  if (T.isObjCGCWeak())
18607
0
    Diag(Loc, diag::warn_attribute_weak_on_field);
18608
18609
  // PPC MMA non-pointer types are not allowed as field types.
18610
0
  if (Context.getTargetInfo().getTriple().isPPC64() &&
18611
0
      CheckPPCMMAType(T, NewFD->getLocation()))
18612
0
    NewFD->setInvalidDecl();
18613
18614
0
  NewFD->setAccess(AS);
18615
0
  return NewFD;
18616
0
}
18617
18618
0
bool Sema::CheckNontrivialField(FieldDecl *FD) {
18619
0
  assert(FD);
18620
0
  assert(getLangOpts().CPlusPlus && "valid check only for C++");
18621
18622
0
  if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18623
0
    return false;
18624
18625
0
  QualType EltTy = Context.getBaseElementType(FD->getType());
18626
0
  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18627
0
    CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18628
0
    if (RDecl->getDefinition()) {
18629
      // We check for copy constructors before constructors
18630
      // because otherwise we'll never get complaints about
18631
      // copy constructors.
18632
18633
0
      CXXSpecialMember member = CXXInvalid;
18634
      // We're required to check for any non-trivial constructors. Since the
18635
      // implicit default constructor is suppressed if there are any
18636
      // user-declared constructors, we just need to check that there is a
18637
      // trivial default constructor and a trivial copy constructor. (We don't
18638
      // worry about move constructors here, since this is a C++98 check.)
18639
0
      if (RDecl->hasNonTrivialCopyConstructor())
18640
0
        member = CXXCopyConstructor;
18641
0
      else if (!RDecl->hasTrivialDefaultConstructor())
18642
0
        member = CXXDefaultConstructor;
18643
0
      else if (RDecl->hasNonTrivialCopyAssignment())
18644
0
        member = CXXCopyAssignment;
18645
0
      else if (RDecl->hasNonTrivialDestructor())
18646
0
        member = CXXDestructor;
18647
18648
0
      if (member != CXXInvalid) {
18649
0
        if (!getLangOpts().CPlusPlus11 &&
18650
0
            getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18651
          // Objective-C++ ARC: it is an error to have a non-trivial field of
18652
          // a union. However, system headers in Objective-C programs
18653
          // occasionally have Objective-C lifetime objects within unions,
18654
          // and rather than cause the program to fail, we make those
18655
          // members unavailable.
18656
0
          SourceLocation Loc = FD->getLocation();
18657
0
          if (getSourceManager().isInSystemHeader(Loc)) {
18658
0
            if (!FD->hasAttr<UnavailableAttr>())
18659
0
              FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18660
0
                            UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18661
0
            return false;
18662
0
          }
18663
0
        }
18664
18665
0
        Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
18666
0
               diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
18667
0
               diag::err_illegal_union_or_anon_struct_member)
18668
0
          << FD->getParent()->isUnion() << FD->getDeclName() << member;
18669
0
        DiagnoseNontrivial(RDecl, member);
18670
0
        return !getLangOpts().CPlusPlus11;
18671
0
      }
18672
0
    }
18673
0
  }
18674
18675
0
  return false;
18676
0
}
18677
18678
/// TranslateIvarVisibility - Translate visibility from a token ID to an
18679
///  AST enum value.
18680
static ObjCIvarDecl::AccessControl
18681
0
TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
18682
0
  switch (ivarVisibility) {
18683
0
  default: llvm_unreachable("Unknown visitibility kind");
18684
0
  case tok::objc_private: return ObjCIvarDecl::Private;
18685
0
  case tok::objc_public: return ObjCIvarDecl::Public;
18686
0
  case tok::objc_protected: return ObjCIvarDecl::Protected;
18687
0
  case tok::objc_package: return ObjCIvarDecl::Package;
18688
0
  }
18689
0
}
18690
18691
/// ActOnIvar - Each ivar field of an objective-c class is passed into this
18692
/// in order to create an IvarDecl object for it.
18693
Decl *Sema::ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D,
18694
0
                      Expr *BitWidth, tok::ObjCKeywordKind Visibility) {
18695
18696
0
  IdentifierInfo *II = D.getIdentifier();
18697
0
  SourceLocation Loc = DeclStart;
18698
0
  if (II) Loc = D.getIdentifierLoc();
18699
18700
  // FIXME: Unnamed fields can be handled in various different ways, for
18701
  // example, unnamed unions inject all members into the struct namespace!
18702
18703
0
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18704
0
  QualType T = TInfo->getType();
18705
18706
0
  if (BitWidth) {
18707
    // 6.7.2.1p3, 6.7.2.1p4
18708
0
    BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
18709
0
    if (!BitWidth)
18710
0
      D.setInvalidType();
18711
0
  } else {
18712
    // Not a bitfield.
18713
18714
    // validate II.
18715
18716
0
  }
18717
0
  if (T->isReferenceType()) {
18718
0
    Diag(Loc, diag::err_ivar_reference_type);
18719
0
    D.setInvalidType();
18720
0
  }
18721
  // C99 6.7.2.1p8: A member of a structure or union may have any type other
18722
  // than a variably modified type.
18723
0
  else if (T->isVariablyModifiedType()) {
18724
0
    if (!tryToFixVariablyModifiedVarType(
18725
0
            TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
18726
0
      D.setInvalidType();
18727
0
  }
18728
18729
  // Get the visibility (access control) for this ivar.
18730
0
  ObjCIvarDecl::AccessControl ac =
18731
0
    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
18732
0
                                        : ObjCIvarDecl::None;
18733
  // Must set ivar's DeclContext to its enclosing interface.
18734
0
  ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
18735
0
  if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
18736
0
    return nullptr;
18737
0
  ObjCContainerDecl *EnclosingContext;
18738
0
  if (ObjCImplementationDecl *IMPDecl =
18739
0
      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18740
0
    if (LangOpts.ObjCRuntime.isFragile()) {
18741
    // Case of ivar declared in an implementation. Context is that of its class.
18742
0
      EnclosingContext = IMPDecl->getClassInterface();
18743
0
      assert(EnclosingContext && "Implementation has no class interface!");
18744
0
    }
18745
0
    else
18746
0
      EnclosingContext = EnclosingDecl;
18747
0
  } else {
18748
0
    if (ObjCCategoryDecl *CDecl =
18749
0
        dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18750
0
      if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
18751
0
        Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
18752
0
        return nullptr;
18753
0
      }
18754
0
    }
18755
0
    EnclosingContext = EnclosingDecl;
18756
0
  }
18757
18758
  // Construct the decl.
18759
0
  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(
18760
0
      Context, EnclosingContext, DeclStart, Loc, II, T, TInfo, ac, BitWidth);
18761
18762
0
  if (T->containsErrors())
18763
0
    NewID->setInvalidDecl();
18764
18765
0
  if (II) {
18766
0
    NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
18767
0
                                           ForVisibleRedeclaration);
18768
0
    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
18769
0
        && !isa<TagDecl>(PrevDecl)) {
18770
0
      Diag(Loc, diag::err_duplicate_member) << II;
18771
0
      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18772
0
      NewID->setInvalidDecl();
18773
0
    }
18774
0
  }
18775
18776
  // Process attributes attached to the ivar.
18777
0
  ProcessDeclAttributes(S, NewID, D);
18778
18779
0
  if (D.isInvalidType())
18780
0
    NewID->setInvalidDecl();
18781
18782
  // In ARC, infer 'retaining' for ivars of retainable type.
18783
0
  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
18784
0
    NewID->setInvalidDecl();
18785
18786
0
  if (D.getDeclSpec().isModulePrivateSpecified())
18787
0
    NewID->setModulePrivate();
18788
18789
0
  if (II) {
18790
    // FIXME: When interfaces are DeclContexts, we'll need to add
18791
    // these to the interface.
18792
0
    S->AddDecl(NewID);
18793
0
    IdResolver.AddDecl(NewID);
18794
0
  }
18795
18796
0
  if (LangOpts.ObjCRuntime.isNonFragile() &&
18797
0
      !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
18798
0
    Diag(Loc, diag::warn_ivars_in_interface);
18799
18800
0
  return NewID;
18801
0
}
18802
18803
/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
18804
/// class and class extensions. For every class \@interface and class
18805
/// extension \@interface, if the last ivar is a bitfield of any type,
18806
/// then add an implicit `char :0` ivar to the end of that interface.
18807
void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
18808
0
                             SmallVectorImpl<Decl *> &AllIvarDecls) {
18809
0
  if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18810
0
    return;
18811
18812
0
  Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18813
0
  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18814
18815
0
  if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18816
0
    return;
18817
0
  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18818
0
  if (!ID) {
18819
0
    if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18820
0
      if (!CD->IsClassExtension())
18821
0
        return;
18822
0
    }
18823
    // No need to add this to end of @implementation.
18824
0
    else
18825
0
      return;
18826
0
  }
18827
  // All conditions are met. Add a new bitfield to the tail end of ivars.
18828
0
  llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18829
0
  Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18830
18831
0
  Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18832
0
                              DeclLoc, DeclLoc, nullptr,
18833
0
                              Context.CharTy,
18834
0
                              Context.getTrivialTypeSourceInfo(Context.CharTy,
18835
0
                                                               DeclLoc),
18836
0
                              ObjCIvarDecl::Private, BW,
18837
0
                              true);
18838
0
  AllIvarDecls.push_back(Ivar);
18839
0
}
18840
18841
/// [class.dtor]p4:
18842
///   At the end of the definition of a class, overload resolution is
18843
///   performed among the prospective destructors declared in that class with
18844
///   an empty argument list to select the destructor for the class, also
18845
///   known as the selected destructor.
18846
///
18847
/// We do the overload resolution here, then mark the selected constructor in the AST.
18848
/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18849
0
static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
18850
0
  if (!Record->hasUserDeclaredDestructor()) {
18851
0
    return;
18852
0
  }
18853
18854
0
  SourceLocation Loc = Record->getLocation();
18855
0
  OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
18856
18857
0
  for (auto *Decl : Record->decls()) {
18858
0
    if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18859
0
      if (DD->isInvalidDecl())
18860
0
        continue;
18861
0
      S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18862
0
                             OCS);
18863
0
      assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18864
0
    }
18865
0
  }
18866
18867
0
  if (OCS.empty()) {
18868
0
    return;
18869
0
  }
18870
0
  OverloadCandidateSet::iterator Best;
18871
0
  unsigned Msg = 0;
18872
0
  OverloadCandidateDisplayKind DisplayKind;
18873
18874
0
  switch (OCS.BestViableFunction(S, Loc, Best)) {
18875
0
  case OR_Success:
18876
0
  case OR_Deleted:
18877
0
    Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18878
0
    break;
18879
18880
0
  case OR_Ambiguous:
18881
0
    Msg = diag::err_ambiguous_destructor;
18882
0
    DisplayKind = OCD_AmbiguousCandidates;
18883
0
    break;
18884
18885
0
  case OR_No_Viable_Function:
18886
0
    Msg = diag::err_no_viable_destructor;
18887
0
    DisplayKind = OCD_AllCandidates;
18888
0
    break;
18889
0
  }
18890
18891
0
  if (Msg) {
18892
    // OpenCL have got their own thing going with destructors. It's slightly broken,
18893
    // but we allow it.
18894
0
    if (!S.LangOpts.OpenCL) {
18895
0
      PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18896
0
      OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18897
0
      Record->setInvalidDecl();
18898
0
    }
18899
    // It's a bit hacky: At this point we've raised an error but we want the
18900
    // rest of the compiler to continue somehow working. However almost
18901
    // everything we'll try to do with the class will depend on there being a
18902
    // destructor. So let's pretend the first one is selected and hope for the
18903
    // best.
18904
0
    Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18905
0
  }
18906
0
}
18907
18908
/// [class.mem.special]p5
18909
/// Two special member functions are of the same kind if:
18910
/// - they are both default constructors,
18911
/// - they are both copy or move constructors with the same first parameter
18912
///   type, or
18913
/// - they are both copy or move assignment operators with the same first
18914
///   parameter type and the same cv-qualifiers and ref-qualifier, if any.
18915
static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
18916
                                              CXXMethodDecl *M1,
18917
                                              CXXMethodDecl *M2,
18918
0
                                              Sema::CXXSpecialMember CSM) {
18919
  // We don't want to compare templates to non-templates: See
18920
  // https://github.com/llvm/llvm-project/issues/59206
18921
0
  if (CSM == Sema::CXXDefaultConstructor)
18922
0
    return bool(M1->getDescribedFunctionTemplate()) ==
18923
0
           bool(M2->getDescribedFunctionTemplate());
18924
  // FIXME: better resolve CWG
18925
  // https://cplusplus.github.io/CWG/issues/2787.html
18926
0
  if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
18927
0
                           M2->getNonObjectParameter(0)->getType()))
18928
0
    return false;
18929
0
  if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
18930
0
                           M2->getFunctionObjectParameterReferenceType()))
18931
0
    return false;
18932
18933
0
  return true;
18934
0
}
18935
18936
/// [class.mem.special]p6:
18937
/// An eligible special member function is a special member function for which:
18938
/// - the function is not deleted,
18939
/// - the associated constraints, if any, are satisfied, and
18940
/// - no special member function of the same kind whose associated constraints
18941
///   [CWG2595], if any, are satisfied is more constrained.
18942
static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
18943
                               ArrayRef<CXXMethodDecl *> Methods,
18944
0
                               Sema::CXXSpecialMember CSM) {
18945
0
  SmallVector<bool, 4> SatisfactionStatus;
18946
18947
0
  for (CXXMethodDecl *Method : Methods) {
18948
0
    const Expr *Constraints = Method->getTrailingRequiresClause();
18949
0
    if (!Constraints)
18950
0
      SatisfactionStatus.push_back(true);
18951
0
    else {
18952
0
      ConstraintSatisfaction Satisfaction;
18953
0
      if (S.CheckFunctionConstraints(Method, Satisfaction))
18954
0
        SatisfactionStatus.push_back(false);
18955
0
      else
18956
0
        SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18957
0
    }
18958
0
  }
18959
18960
0
  for (size_t i = 0; i < Methods.size(); i++) {
18961
0
    if (!SatisfactionStatus[i])
18962
0
      continue;
18963
0
    CXXMethodDecl *Method = Methods[i];
18964
0
    CXXMethodDecl *OrigMethod = Method;
18965
0
    if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18966
0
      OrigMethod = cast<CXXMethodDecl>(MF);
18967
18968
0
    const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18969
0
    bool AnotherMethodIsMoreConstrained = false;
18970
0
    for (size_t j = 0; j < Methods.size(); j++) {
18971
0
      if (i == j || !SatisfactionStatus[j])
18972
0
        continue;
18973
0
      CXXMethodDecl *OtherMethod = Methods[j];
18974
0
      if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18975
0
        OtherMethod = cast<CXXMethodDecl>(MF);
18976
18977
0
      if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18978
0
                                             CSM))
18979
0
        continue;
18980
18981
0
      const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18982
0
      if (!OtherConstraints)
18983
0
        continue;
18984
0
      if (!Constraints) {
18985
0
        AnotherMethodIsMoreConstrained = true;
18986
0
        break;
18987
0
      }
18988
0
      if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18989
0
                                   {Constraints},
18990
0
                                   AnotherMethodIsMoreConstrained)) {
18991
        // There was an error with the constraints comparison. Exit the loop
18992
        // and don't consider this function eligible.
18993
0
        AnotherMethodIsMoreConstrained = true;
18994
0
      }
18995
0
      if (AnotherMethodIsMoreConstrained)
18996
0
        break;
18997
0
    }
18998
    // FIXME: Do not consider deleted methods as eligible after implementing
18999
    // DR1734 and DR1496.
19000
0
    if (!AnotherMethodIsMoreConstrained) {
19001
0
      Method->setIneligibleOrNotSelected(false);
19002
0
      Record->addedEligibleSpecialMemberFunction(Method, 1 << CSM);
19003
0
    }
19004
0
  }
19005
0
}
19006
19007
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
19008
0
                                                    CXXRecordDecl *Record) {
19009
0
  SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19010
0
  SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19011
0
  SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19012
0
  SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19013
0
  SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19014
19015
0
  for (auto *Decl : Record->decls()) {
19016
0
    auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19017
0
    if (!MD) {
19018
0
      auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19019
0
      if (FTD)
19020
0
        MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19021
0
    }
19022
0
    if (!MD)
19023
0
      continue;
19024
0
    if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19025
0
      if (CD->isInvalidDecl())
19026
0
        continue;
19027
0
      if (CD->isDefaultConstructor())
19028
0
        DefaultConstructors.push_back(MD);
19029
0
      else if (CD->isCopyConstructor())
19030
0
        CopyConstructors.push_back(MD);
19031
0
      else if (CD->isMoveConstructor())
19032
0
        MoveConstructors.push_back(MD);
19033
0
    } else if (MD->isCopyAssignmentOperator()) {
19034
0
      CopyAssignmentOperators.push_back(MD);
19035
0
    } else if (MD->isMoveAssignmentOperator()) {
19036
0
      MoveAssignmentOperators.push_back(MD);
19037
0
    }
19038
0
  }
19039
19040
0
  SetEligibleMethods(S, Record, DefaultConstructors,
19041
0
                     Sema::CXXDefaultConstructor);
19042
0
  SetEligibleMethods(S, Record, CopyConstructors, Sema::CXXCopyConstructor);
19043
0
  SetEligibleMethods(S, Record, MoveConstructors, Sema::CXXMoveConstructor);
19044
0
  SetEligibleMethods(S, Record, CopyAssignmentOperators,
19045
0
                     Sema::CXXCopyAssignment);
19046
0
  SetEligibleMethods(S, Record, MoveAssignmentOperators,
19047
0
                     Sema::CXXMoveAssignment);
19048
0
}
19049
19050
void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19051
                       ArrayRef<Decl *> Fields, SourceLocation LBrac,
19052
                       SourceLocation RBrac,
19053
0
                       const ParsedAttributesView &Attrs) {
19054
0
  assert(EnclosingDecl && "missing record or interface decl");
19055
19056
  // If this is an Objective-C @implementation or category and we have
19057
  // new fields here we should reset the layout of the interface since
19058
  // it will now change.
19059
0
  if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19060
0
    ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19061
0
    switch (DC->getKind()) {
19062
0
    default: break;
19063
0
    case Decl::ObjCCategory:
19064
0
      Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19065
0
      break;
19066
0
    case Decl::ObjCImplementation:
19067
0
      Context.
19068
0
        ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19069
0
      break;
19070
0
    }
19071
0
  }
19072
19073
0
  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19074
0
  CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19075
19076
  // Start counting up the number of named members; make sure to include
19077
  // members of anonymous structs and unions in the total.
19078
0
  unsigned NumNamedMembers = 0;
19079
0
  if (Record) {
19080
0
    for (const auto *I : Record->decls()) {
19081
0
      if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19082
0
        if (IFD->getDeclName())
19083
0
          ++NumNamedMembers;
19084
0
    }
19085
0
  }
19086
19087
  // Verify that all the fields are okay.
19088
0
  SmallVector<FieldDecl*, 32> RecFields;
19089
19090
0
  for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19091
0
       i != end; ++i) {
19092
0
    FieldDecl *FD = cast<FieldDecl>(*i);
19093
19094
    // Get the type for the field.
19095
0
    const Type *FDTy = FD->getType().getTypePtr();
19096
19097
0
    if (!FD->isAnonymousStructOrUnion()) {
19098
      // Remember all fields written by the user.
19099
0
      RecFields.push_back(FD);
19100
0
    }
19101
19102
    // If the field is already invalid for some reason, don't emit more
19103
    // diagnostics about it.
19104
0
    if (FD->isInvalidDecl()) {
19105
0
      EnclosingDecl->setInvalidDecl();
19106
0
      continue;
19107
0
    }
19108
19109
    // C99 6.7.2.1p2:
19110
    //   A structure or union shall not contain a member with
19111
    //   incomplete or function type (hence, a structure shall not
19112
    //   contain an instance of itself, but may contain a pointer to
19113
    //   an instance of itself), except that the last member of a
19114
    //   structure with more than one named member may have incomplete
19115
    //   array type; such a structure (and any union containing,
19116
    //   possibly recursively, a member that is such a structure)
19117
    //   shall not be a member of a structure or an element of an
19118
    //   array.
19119
0
    bool IsLastField = (i + 1 == Fields.end());
19120
0
    if (FDTy->isFunctionType()) {
19121
      // Field declared as a function.
19122
0
      Diag(FD->getLocation(), diag::err_field_declared_as_function)
19123
0
        << FD->getDeclName();
19124
0
      FD->setInvalidDecl();
19125
0
      EnclosingDecl->setInvalidDecl();
19126
0
      continue;
19127
0
    } else if (FDTy->isIncompleteArrayType() &&
19128
0
               (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19129
0
      if (Record) {
19130
        // Flexible array member.
19131
        // Microsoft and g++ is more permissive regarding flexible array.
19132
        // It will accept flexible array in union and also
19133
        // as the sole element of a struct/class.
19134
0
        unsigned DiagID = 0;
19135
0
        if (!Record->isUnion() && !IsLastField) {
19136
0
          Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19137
0
              << FD->getDeclName() << FD->getType()
19138
0
              << llvm::to_underlying(Record->getTagKind());
19139
0
          Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19140
0
          FD->setInvalidDecl();
19141
0
          EnclosingDecl->setInvalidDecl();
19142
0
          continue;
19143
0
        } else if (Record->isUnion())
19144
0
          DiagID = getLangOpts().MicrosoftExt
19145
0
                       ? diag::ext_flexible_array_union_ms
19146
0
                       : getLangOpts().CPlusPlus
19147
0
                             ? diag::ext_flexible_array_union_gnu
19148
0
                             : diag::err_flexible_array_union;
19149
0
        else if (NumNamedMembers < 1)
19150
0
          DiagID = getLangOpts().MicrosoftExt
19151
0
                       ? diag::ext_flexible_array_empty_aggregate_ms
19152
0
                       : getLangOpts().CPlusPlus
19153
0
                             ? diag::ext_flexible_array_empty_aggregate_gnu
19154
0
                             : diag::err_flexible_array_empty_aggregate;
19155
19156
0
        if (DiagID)
19157
0
          Diag(FD->getLocation(), DiagID)
19158
0
              << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19159
        // While the layout of types that contain virtual bases is not specified
19160
        // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19161
        // virtual bases after the derived members.  This would make a flexible
19162
        // array member declared at the end of an object not adjacent to the end
19163
        // of the type.
19164
0
        if (CXXRecord && CXXRecord->getNumVBases() != 0)
19165
0
          Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19166
0
              << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19167
0
        if (!getLangOpts().C99)
19168
0
          Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19169
0
              << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19170
19171
        // If the element type has a non-trivial destructor, we would not
19172
        // implicitly destroy the elements, so disallow it for now.
19173
        //
19174
        // FIXME: GCC allows this. We should probably either implicitly delete
19175
        // the destructor of the containing class, or just allow this.
19176
0
        QualType BaseElem = Context.getBaseElementType(FD->getType());
19177
0
        if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19178
0
          Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19179
0
            << FD->getDeclName() << FD->getType();
19180
0
          FD->setInvalidDecl();
19181
0
          EnclosingDecl->setInvalidDecl();
19182
0
          continue;
19183
0
        }
19184
        // Okay, we have a legal flexible array member at the end of the struct.
19185
0
        Record->setHasFlexibleArrayMember(true);
19186
0
      } else {
19187
        // In ObjCContainerDecl ivars with incomplete array type are accepted,
19188
        // unless they are followed by another ivar. That check is done
19189
        // elsewhere, after synthesized ivars are known.
19190
0
      }
19191
0
    } else if (!FDTy->isDependentType() &&
19192
0
               RequireCompleteSizedType(
19193
0
                   FD->getLocation(), FD->getType(),
19194
0
                   diag::err_field_incomplete_or_sizeless)) {
19195
      // Incomplete type
19196
0
      FD->setInvalidDecl();
19197
0
      EnclosingDecl->setInvalidDecl();
19198
0
      continue;
19199
0
    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19200
0
      if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19201
        // A type which contains a flexible array member is considered to be a
19202
        // flexible array member.
19203
0
        Record->setHasFlexibleArrayMember(true);
19204
0
        if (!Record->isUnion()) {
19205
          // If this is a struct/class and this is not the last element, reject
19206
          // it.  Note that GCC supports variable sized arrays in the middle of
19207
          // structures.
19208
0
          if (!IsLastField)
19209
0
            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19210
0
              << FD->getDeclName() << FD->getType();
19211
0
          else {
19212
            // We support flexible arrays at the end of structs in
19213
            // other structs as an extension.
19214
0
            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19215
0
              << FD->getDeclName();
19216
0
          }
19217
0
        }
19218
0
      }
19219
0
      if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19220
0
          RequireNonAbstractType(FD->getLocation(), FD->getType(),
19221
0
                                 diag::err_abstract_type_in_decl,
19222
0
                                 AbstractIvarType)) {
19223
        // Ivars can not have abstract class types
19224
0
        FD->setInvalidDecl();
19225
0
      }
19226
0
      if (Record && FDTTy->getDecl()->hasObjectMember())
19227
0
        Record->setHasObjectMember(true);
19228
0
      if (Record && FDTTy->getDecl()->hasVolatileMember())
19229
0
        Record->setHasVolatileMember(true);
19230
0
    } else if (FDTy->isObjCObjectType()) {
19231
      /// A field cannot be an Objective-c object
19232
0
      Diag(FD->getLocation(), diag::err_statically_allocated_object)
19233
0
        << FixItHint::CreateInsertion(FD->getLocation(), "*");
19234
0
      QualType T = Context.getObjCObjectPointerType(FD->getType());
19235
0
      FD->setType(T);
19236
0
    } else if (Record && Record->isUnion() &&
19237
0
               FD->getType().hasNonTrivialObjCLifetime() &&
19238
0
               getSourceManager().isInSystemHeader(FD->getLocation()) &&
19239
0
               !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19240
0
               (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
19241
0
                !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19242
      // For backward compatibility, fields of C unions declared in system
19243
      // headers that have non-trivial ObjC ownership qualifications are marked
19244
      // as unavailable unless the qualifier is explicit and __strong. This can
19245
      // break ABI compatibility between programs compiled with ARC and MRR, but
19246
      // is a better option than rejecting programs using those unions under
19247
      // ARC.
19248
0
      FD->addAttr(UnavailableAttr::CreateImplicit(
19249
0
          Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19250
0
          FD->getLocation()));
19251
0
    } else if (getLangOpts().ObjC &&
19252
0
               getLangOpts().getGC() != LangOptions::NonGC && Record &&
19253
0
               !Record->hasObjectMember()) {
19254
0
      if (FD->getType()->isObjCObjectPointerType() ||
19255
0
          FD->getType().isObjCGCStrong())
19256
0
        Record->setHasObjectMember(true);
19257
0
      else if (Context.getAsArrayType(FD->getType())) {
19258
0
        QualType BaseType = Context.getBaseElementType(FD->getType());
19259
0
        if (BaseType->isRecordType() &&
19260
0
            BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19261
0
          Record->setHasObjectMember(true);
19262
0
        else if (BaseType->isObjCObjectPointerType() ||
19263
0
                 BaseType.isObjCGCStrong())
19264
0
               Record->setHasObjectMember(true);
19265
0
      }
19266
0
    }
19267
19268
0
    if (Record && !getLangOpts().CPlusPlus &&
19269
0
        !shouldIgnoreForRecordTriviality(FD)) {
19270
0
      QualType FT = FD->getType();
19271
0
      if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
19272
0
        Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19273
0
        if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
19274
0
            Record->isUnion())
19275
0
          Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19276
0
      }
19277
0
      QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
19278
0
      if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
19279
0
        Record->setNonTrivialToPrimitiveCopy(true);
19280
0
        if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19281
0
          Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19282
0
      }
19283
0
      if (FT.isDestructedType()) {
19284
0
        Record->setNonTrivialToPrimitiveDestroy(true);
19285
0
        Record->setParamDestroyedInCallee(true);
19286
0
        if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19287
0
          Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19288
0
      }
19289
19290
0
      if (const auto *RT = FT->getAs<RecordType>()) {
19291
0
        if (RT->getDecl()->getArgPassingRestrictions() ==
19292
0
            RecordArgPassingKind::CanNeverPassInRegs)
19293
0
          Record->setArgPassingRestrictions(
19294
0
              RecordArgPassingKind::CanNeverPassInRegs);
19295
0
      } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
19296
0
        Record->setArgPassingRestrictions(
19297
0
            RecordArgPassingKind::CanNeverPassInRegs);
19298
0
    }
19299
19300
0
    if (Record && FD->getType().isVolatileQualified())
19301
0
      Record->setHasVolatileMember(true);
19302
    // Keep track of the number of named members.
19303
0
    if (FD->getIdentifier())
19304
0
      ++NumNamedMembers;
19305
0
  }
19306
19307
  // Okay, we successfully defined 'Record'.
19308
0
  if (Record) {
19309
0
    bool Completed = false;
19310
0
    if (CXXRecord) {
19311
0
      if (!CXXRecord->isInvalidDecl()) {
19312
        // Set access bits correctly on the directly-declared conversions.
19313
0
        for (CXXRecordDecl::conversion_iterator
19314
0
               I = CXXRecord->conversion_begin(),
19315
0
               E = CXXRecord->conversion_end(); I != E; ++I)
19316
0
          I.setAccess((*I)->getAccess());
19317
0
      }
19318
19319
      // Add any implicitly-declared members to this class.
19320
0
      AddImplicitlyDeclaredMembersToClass(CXXRecord);
19321
19322
0
      if (!CXXRecord->isDependentType()) {
19323
0
        if (!CXXRecord->isInvalidDecl()) {
19324
          // If we have virtual base classes, we may end up finding multiple
19325
          // final overriders for a given virtual function. Check for this
19326
          // problem now.
19327
0
          if (CXXRecord->getNumVBases()) {
19328
0
            CXXFinalOverriderMap FinalOverriders;
19329
0
            CXXRecord->getFinalOverriders(FinalOverriders);
19330
19331
0
            for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19332
0
                                             MEnd = FinalOverriders.end();
19333
0
                 M != MEnd; ++M) {
19334
0
              for (OverridingMethods::iterator SO = M->second.begin(),
19335
0
                                            SOEnd = M->second.end();
19336
0
                   SO != SOEnd; ++SO) {
19337
0
                assert(SO->second.size() > 0 &&
19338
0
                       "Virtual function without overriding functions?");
19339
0
                if (SO->second.size() == 1)
19340
0
                  continue;
19341
19342
                // C++ [class.virtual]p2:
19343
                //   In a derived class, if a virtual member function of a base
19344
                //   class subobject has more than one final overrider the
19345
                //   program is ill-formed.
19346
0
                Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19347
0
                  << (const NamedDecl *)M->first << Record;
19348
0
                Diag(M->first->getLocation(),
19349
0
                     diag::note_overridden_virtual_function);
19350
0
                for (OverridingMethods::overriding_iterator
19351
0
                          OM = SO->second.begin(),
19352
0
                       OMEnd = SO->second.end();
19353
0
                     OM != OMEnd; ++OM)
19354
0
                  Diag(OM->Method->getLocation(), diag::note_final_overrider)
19355
0
                    << (const NamedDecl *)M->first << OM->Method->getParent();
19356
19357
0
                Record->setInvalidDecl();
19358
0
              }
19359
0
            }
19360
0
            CXXRecord->completeDefinition(&FinalOverriders);
19361
0
            Completed = true;
19362
0
          }
19363
0
        }
19364
0
        ComputeSelectedDestructor(*this, CXXRecord);
19365
0
        ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);
19366
0
      }
19367
0
    }
19368
19369
0
    if (!Completed)
19370
0
      Record->completeDefinition();
19371
19372
    // Handle attributes before checking the layout.
19373
0
    ProcessDeclAttributeList(S, Record, Attrs);
19374
19375
    // Check to see if a FieldDecl is a pointer to a function.
19376
0
    auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19377
0
      const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19378
0
      if (!FD) {
19379
        // Check whether this is a forward declaration that was inserted by
19380
        // Clang. This happens when a non-forward declared / defined type is
19381
        // used, e.g.:
19382
        //
19383
        //   struct foo {
19384
        //     struct bar *(*f)();
19385
        //     struct bar *(*g)();
19386
        //   };
19387
        //
19388
        // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19389
        // incomplete definition.
19390
0
        if (const auto *TD = dyn_cast<TagDecl>(D))
19391
0
          return !TD->isCompleteDefinition();
19392
0
        return false;
19393
0
      }
19394
0
      QualType FieldType = FD->getType().getDesugaredType(Context);
19395
0
      if (isa<PointerType>(FieldType)) {
19396
0
        QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19397
0
        return PointeeType.getDesugaredType(Context)->isFunctionType();
19398
0
      }
19399
0
      return false;
19400
0
    };
19401
19402
    // Maybe randomize the record's decls. We automatically randomize a record
19403
    // of function pointers, unless it has the "no_randomize_layout" attribute.
19404
0
    if (!getLangOpts().CPlusPlus &&
19405
0
        (Record->hasAttr<RandomizeLayoutAttr>() ||
19406
0
         (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19407
0
          llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19408
0
        !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19409
0
        !Record->isRandomized()) {
19410
0
      SmallVector<Decl *, 32> NewDeclOrdering;
19411
0
      if (randstruct::randomizeStructureLayout(Context, Record,
19412
0
                                               NewDeclOrdering))
19413
0
        Record->reorderDecls(NewDeclOrdering);
19414
0
    }
19415
19416
    // We may have deferred checking for a deleted destructor. Check now.
19417
0
    if (CXXRecord) {
19418
0
      auto *Dtor = CXXRecord->getDestructor();
19419
0
      if (Dtor && Dtor->isImplicit() &&
19420
0
          ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
19421
0
        CXXRecord->setImplicitDestructorIsDeleted();
19422
0
        SetDeclDeleted(Dtor, CXXRecord->getLocation());
19423
0
      }
19424
0
    }
19425
19426
0
    if (Record->hasAttrs()) {
19427
0
      CheckAlignasUnderalignment(Record);
19428
19429
0
      if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19430
0
        checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19431
0
                                           IA->getRange(), IA->getBestCase(),
19432
0
                                           IA->getInheritanceModel());
19433
0
    }
19434
19435
    // Check if the structure/union declaration is a type that can have zero
19436
    // size in C. For C this is a language extension, for C++ it may cause
19437
    // compatibility problems.
19438
0
    bool CheckForZeroSize;
19439
0
    if (!getLangOpts().CPlusPlus) {
19440
0
      CheckForZeroSize = true;
19441
0
    } else {
19442
      // For C++ filter out types that cannot be referenced in C code.
19443
0
      CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19444
0
      CheckForZeroSize =
19445
0
          CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19446
0
          !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19447
0
          CXXRecord->isCLike();
19448
0
    }
19449
0
    if (CheckForZeroSize) {
19450
0
      bool ZeroSize = true;
19451
0
      bool IsEmpty = true;
19452
0
      unsigned NonBitFields = 0;
19453
0
      for (RecordDecl::field_iterator I = Record->field_begin(),
19454
0
                                      E = Record->field_end();
19455
0
           (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19456
0
        IsEmpty = false;
19457
0
        if (I->isUnnamedBitfield()) {
19458
0
          if (!I->isZeroLengthBitField(Context))
19459
0
            ZeroSize = false;
19460
0
        } else {
19461
0
          ++NonBitFields;
19462
0
          QualType FieldType = I->getType();
19463
0
          if (FieldType->isIncompleteType() ||
19464
0
              !Context.getTypeSizeInChars(FieldType).isZero())
19465
0
            ZeroSize = false;
19466
0
        }
19467
0
      }
19468
19469
      // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19470
      // allowed in C++, but warn if its declaration is inside
19471
      // extern "C" block.
19472
0
      if (ZeroSize) {
19473
0
        Diag(RecLoc, getLangOpts().CPlusPlus ?
19474
0
                         diag::warn_zero_size_struct_union_in_extern_c :
19475
0
                         diag::warn_zero_size_struct_union_compat)
19476
0
          << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19477
0
      }
19478
19479
      // Structs without named members are extension in C (C99 6.7.2.1p7),
19480
      // but are accepted by GCC.
19481
0
      if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19482
0
        Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19483
0
                               diag::ext_no_named_members_in_struct_union)
19484
0
          << Record->isUnion();
19485
0
      }
19486
0
    }
19487
0
  } else {
19488
0
    ObjCIvarDecl **ClsFields =
19489
0
      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19490
0
    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19491
0
      ID->setEndOfDefinitionLoc(RBrac);
19492
      // Add ivar's to class's DeclContext.
19493
0
      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19494
0
        ClsFields[i]->setLexicalDeclContext(ID);
19495
0
        ID->addDecl(ClsFields[i]);
19496
0
      }
19497
      // Must enforce the rule that ivars in the base classes may not be
19498
      // duplicates.
19499
0
      if (ID->getSuperClass())
19500
0
        DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19501
0
    } else if (ObjCImplementationDecl *IMPDecl =
19502
0
                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19503
0
      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19504
0
      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19505
        // Ivar declared in @implementation never belongs to the implementation.
19506
        // Only it is in implementation's lexical context.
19507
0
        ClsFields[I]->setLexicalDeclContext(IMPDecl);
19508
0
      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
19509
0
      IMPDecl->setIvarLBraceLoc(LBrac);
19510
0
      IMPDecl->setIvarRBraceLoc(RBrac);
19511
0
    } else if (ObjCCategoryDecl *CDecl =
19512
0
                dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19513
      // case of ivars in class extension; all other cases have been
19514
      // reported as errors elsewhere.
19515
      // FIXME. Class extension does not have a LocEnd field.
19516
      // CDecl->setLocEnd(RBrac);
19517
      // Add ivar's to class extension's DeclContext.
19518
      // Diagnose redeclaration of private ivars.
19519
0
      ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19520
0
      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19521
0
        if (IDecl) {
19522
0
          if (const ObjCIvarDecl *ClsIvar =
19523
0
              IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19524
0
            Diag(ClsFields[i]->getLocation(),
19525
0
                 diag::err_duplicate_ivar_declaration);
19526
0
            Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19527
0
            continue;
19528
0
          }
19529
0
          for (const auto *Ext : IDecl->known_extensions()) {
19530
0
            if (const ObjCIvarDecl *ClsExtIvar
19531
0
                  = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19532
0
              Diag(ClsFields[i]->getLocation(),
19533
0
                   diag::err_duplicate_ivar_declaration);
19534
0
              Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19535
0
              continue;
19536
0
            }
19537
0
          }
19538
0
        }
19539
0
        ClsFields[i]->setLexicalDeclContext(CDecl);
19540
0
        CDecl->addDecl(ClsFields[i]);
19541
0
      }
19542
0
      CDecl->setIvarLBraceLoc(LBrac);
19543
0
      CDecl->setIvarRBraceLoc(RBrac);
19544
0
    }
19545
0
  }
19546
0
}
19547
19548
/// Determine whether the given integral value is representable within
19549
/// the given type T.
19550
static bool isRepresentableIntegerValue(ASTContext &Context,
19551
                                        llvm::APSInt &Value,
19552
0
                                        QualType T) {
19553
0
  assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19554
0
         "Integral type required!");
19555
0
  unsigned BitWidth = Context.getIntWidth(T);
19556
19557
0
  if (Value.isUnsigned() || Value.isNonNegative()) {
19558
0
    if (T->isSignedIntegerOrEnumerationType())
19559
0
      --BitWidth;
19560
0
    return Value.getActiveBits() <= BitWidth;
19561
0
  }
19562
0
  return Value.getSignificantBits() <= BitWidth;
19563
0
}
19564
19565
// Given an integral type, return the next larger integral type
19566
// (or a NULL type of no such type exists).
19567
0
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
19568
  // FIXME: Int128/UInt128 support, which also needs to be introduced into
19569
  // enum checking below.
19570
0
  assert((T->isIntegralType(Context) ||
19571
0
         T->isEnumeralType()) && "Integral type required!");
19572
0
  const unsigned NumTypes = 4;
19573
0
  QualType SignedIntegralTypes[NumTypes] = {
19574
0
    Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19575
0
  };
19576
0
  QualType UnsignedIntegralTypes[NumTypes] = {
19577
0
    Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19578
0
    Context.UnsignedLongLongTy
19579
0
  };
19580
19581
0
  unsigned BitWidth = Context.getTypeSize(T);
19582
0
  QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19583
0
                                                        : UnsignedIntegralTypes;
19584
0
  for (unsigned I = 0; I != NumTypes; ++I)
19585
0
    if (Context.getTypeSize(Types[I]) > BitWidth)
19586
0
      return Types[I];
19587
19588
0
  return QualType();
19589
0
}
19590
19591
EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
19592
                                          EnumConstantDecl *LastEnumConst,
19593
                                          SourceLocation IdLoc,
19594
                                          IdentifierInfo *Id,
19595
0
                                          Expr *Val) {
19596
0
  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19597
0
  llvm::APSInt EnumVal(IntWidth);
19598
0
  QualType EltTy;
19599
19600
0
  if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
19601
0
    Val = nullptr;
19602
19603
0
  if (Val)
19604
0
    Val = DefaultLvalueConversion(Val).get();
19605
19606
0
  if (Val) {
19607
0
    if (Enum->isDependentType() || Val->isTypeDependent() ||
19608
0
        Val->containsErrors())
19609
0
      EltTy = Context.DependentTy;
19610
0
    else {
19611
      // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19612
      // underlying type, but do allow it in all other contexts.
19613
0
      if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19614
        // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19615
        // constant-expression in the enumerator-definition shall be a converted
19616
        // constant expression of the underlying type.
19617
0
        EltTy = Enum->getIntegerType();
19618
0
        ExprResult Converted =
19619
0
          CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19620
0
                                           CCEK_Enumerator);
19621
0
        if (Converted.isInvalid())
19622
0
          Val = nullptr;
19623
0
        else
19624
0
          Val = Converted.get();
19625
0
      } else if (!Val->isValueDependent() &&
19626
0
                 !(Val =
19627
0
                       VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
19628
0
                           .get())) {
19629
        // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19630
0
      } else {
19631
0
        if (Enum->isComplete()) {
19632
0
          EltTy = Enum->getIntegerType();
19633
19634
          // In Obj-C and Microsoft mode, require the enumeration value to be
19635
          // representable in the underlying type of the enumeration. In C++11,
19636
          // we perform a non-narrowing conversion as part of converted constant
19637
          // expression checking.
19638
0
          if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19639
0
            if (Context.getTargetInfo()
19640
0
                    .getTriple()
19641
0
                    .isWindowsMSVCEnvironment()) {
19642
0
              Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19643
0
            } else {
19644
0
              Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19645
0
            }
19646
0
          }
19647
19648
          // Cast to the underlying type.
19649
0
          Val = ImpCastExprToType(Val, EltTy,
19650
0
                                  EltTy->isBooleanType() ? CK_IntegralToBoolean
19651
0
                                                         : CK_IntegralCast)
19652
0
                    .get();
19653
0
        } else if (getLangOpts().CPlusPlus) {
19654
          // C++11 [dcl.enum]p5:
19655
          //   If the underlying type is not fixed, the type of each enumerator
19656
          //   is the type of its initializing value:
19657
          //     - If an initializer is specified for an enumerator, the
19658
          //       initializing value has the same type as the expression.
19659
0
          EltTy = Val->getType();
19660
0
        } else {
19661
          // C99 6.7.2.2p2:
19662
          //   The expression that defines the value of an enumeration constant
19663
          //   shall be an integer constant expression that has a value
19664
          //   representable as an int.
19665
19666
          // Complain if the value is not representable in an int.
19667
0
          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
19668
0
            Diag(IdLoc, diag::ext_enum_value_not_int)
19669
0
              << toString(EnumVal, 10) << Val->getSourceRange()
19670
0
              << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19671
0
          else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19672
            // Force the type of the expression to 'int'.
19673
0
            Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19674
0
          }
19675
0
          EltTy = Val->getType();
19676
0
        }
19677
0
      }
19678
0
    }
19679
0
  }
19680
19681
0
  if (!Val) {
19682
0
    if (Enum->isDependentType())
19683
0
      EltTy = Context.DependentTy;
19684
0
    else if (!LastEnumConst) {
19685
      // C++0x [dcl.enum]p5:
19686
      //   If the underlying type is not fixed, the type of each enumerator
19687
      //   is the type of its initializing value:
19688
      //     - If no initializer is specified for the first enumerator, the
19689
      //       initializing value has an unspecified integral type.
19690
      //
19691
      // GCC uses 'int' for its unspecified integral type, as does
19692
      // C99 6.7.2.2p3.
19693
0
      if (Enum->isFixed()) {
19694
0
        EltTy = Enum->getIntegerType();
19695
0
      }
19696
0
      else {
19697
0
        EltTy = Context.IntTy;
19698
0
      }
19699
0
    } else {
19700
      // Assign the last value + 1.
19701
0
      EnumVal = LastEnumConst->getInitVal();
19702
0
      ++EnumVal;
19703
0
      EltTy = LastEnumConst->getType();
19704
19705
      // Check for overflow on increment.
19706
0
      if (EnumVal < LastEnumConst->getInitVal()) {
19707
        // C++0x [dcl.enum]p5:
19708
        //   If the underlying type is not fixed, the type of each enumerator
19709
        //   is the type of its initializing value:
19710
        //
19711
        //     - Otherwise the type of the initializing value is the same as
19712
        //       the type of the initializing value of the preceding enumerator
19713
        //       unless the incremented value is not representable in that type,
19714
        //       in which case the type is an unspecified integral type
19715
        //       sufficient to contain the incremented value. If no such type
19716
        //       exists, the program is ill-formed.
19717
0
        QualType T = getNextLargerIntegralType(Context, EltTy);
19718
0
        if (T.isNull() || Enum->isFixed()) {
19719
          // There is no integral type larger enough to represent this
19720
          // value. Complain, then allow the value to wrap around.
19721
0
          EnumVal = LastEnumConst->getInitVal();
19722
0
          EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19723
0
          ++EnumVal;
19724
0
          if (Enum->isFixed())
19725
            // When the underlying type is fixed, this is ill-formed.
19726
0
            Diag(IdLoc, diag::err_enumerator_wrapped)
19727
0
              << toString(EnumVal, 10)
19728
0
              << EltTy;
19729
0
          else
19730
0
            Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19731
0
              << toString(EnumVal, 10);
19732
0
        } else {
19733
0
          EltTy = T;
19734
0
        }
19735
19736
        // Retrieve the last enumerator's value, extent that type to the
19737
        // type that is supposed to be large enough to represent the incremented
19738
        // value, then increment.
19739
0
        EnumVal = LastEnumConst->getInitVal();
19740
0
        EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19741
0
        EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19742
0
        ++EnumVal;
19743
19744
        // If we're not in C++, diagnose the overflow of enumerator values,
19745
        // which in C99 means that the enumerator value is not representable in
19746
        // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19747
        // permits enumerator values that are representable in some larger
19748
        // integral type.
19749
0
        if (!getLangOpts().CPlusPlus && !T.isNull())
19750
0
          Diag(IdLoc, diag::warn_enum_value_overflow);
19751
0
      } else if (!getLangOpts().CPlusPlus &&
19752
0
                 !EltTy->isDependentType() &&
19753
0
                 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19754
        // Enforce C99 6.7.2.2p2 even when we compute the next value.
19755
0
        Diag(IdLoc, diag::ext_enum_value_not_int)
19756
0
          << toString(EnumVal, 10) << 1;
19757
0
      }
19758
0
    }
19759
0
  }
19760
19761
0
  if (!EltTy->isDependentType()) {
19762
    // Make the enumerator value match the signedness and size of the
19763
    // enumerator's type.
19764
0
    EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19765
0
    EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19766
0
  }
19767
19768
0
  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19769
0
                                  Val, EnumVal);
19770
0
}
19771
19772
Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
19773
0
                                                SourceLocation IILoc) {
19774
0
  if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19775
0
      !getLangOpts().CPlusPlus)
19776
0
    return SkipBodyInfo();
19777
19778
  // We have an anonymous enum definition. Look up the first enumerator to
19779
  // determine if we should merge the definition with an existing one and
19780
  // skip the body.
19781
0
  NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19782
0
                                         forRedeclarationInCurContext());
19783
0
  auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19784
0
  if (!PrevECD)
19785
0
    return SkipBodyInfo();
19786
19787
0
  EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19788
0
  NamedDecl *Hidden;
19789
0
  if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19790
0
    SkipBodyInfo Skip;
19791
0
    Skip.Previous = Hidden;
19792
0
    return Skip;
19793
0
  }
19794
19795
0
  return SkipBodyInfo();
19796
0
}
19797
19798
Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19799
                              SourceLocation IdLoc, IdentifierInfo *Id,
19800
                              const ParsedAttributesView &Attrs,
19801
0
                              SourceLocation EqualLoc, Expr *Val) {
19802
0
  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19803
0
  EnumConstantDecl *LastEnumConst =
19804
0
    cast_or_null<EnumConstantDecl>(lastEnumConst);
19805
19806
  // The scope passed in may not be a decl scope.  Zip up the scope tree until
19807
  // we find one that is.
19808
0
  S = getNonFieldDeclScope(S);
19809
19810
  // Verify that there isn't already something declared with this name in this
19811
  // scope.
19812
0
  LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
19813
0
  LookupName(R, S);
19814
0
  NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19815
19816
0
  if (PrevDecl && PrevDecl->isTemplateParameter()) {
19817
    // Maybe we will complain about the shadowed template parameter.
19818
0
    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19819
    // Just pretend that we didn't see the previous declaration.
19820
0
    PrevDecl = nullptr;
19821
0
  }
19822
19823
  // C++ [class.mem]p15:
19824
  // If T is the name of a class, then each of the following shall have a name
19825
  // different from T:
19826
  // - every enumerator of every member of class T that is an unscoped
19827
  // enumerated type
19828
0
  if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19829
0
    DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
19830
0
                            DeclarationNameInfo(Id, IdLoc));
19831
19832
0
  EnumConstantDecl *New =
19833
0
    CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19834
0
  if (!New)
19835
0
    return nullptr;
19836
19837
0
  if (PrevDecl) {
19838
0
    if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19839
      // Check for other kinds of shadowing not already handled.
19840
0
      CheckShadow(New, PrevDecl, R);
19841
0
    }
19842
19843
    // When in C++, we may get a TagDecl with the same name; in this case the
19844
    // enum constant will 'hide' the tag.
19845
0
    assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19846
0
           "Received TagDecl when not in C++!");
19847
0
    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19848
0
      if (isa<EnumConstantDecl>(PrevDecl))
19849
0
        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19850
0
      else
19851
0
        Diag(IdLoc, diag::err_redefinition) << Id;
19852
0
      notePreviousDefinition(PrevDecl, IdLoc);
19853
0
      return nullptr;
19854
0
    }
19855
0
  }
19856
19857
  // Process attributes.
19858
0
  ProcessDeclAttributeList(S, New, Attrs);
19859
0
  AddPragmaAttributes(S, New);
19860
19861
  // Register this decl in the current scope stack.
19862
0
  New->setAccess(TheEnumDecl->getAccess());
19863
0
  PushOnScopeChains(New, S);
19864
19865
0
  ActOnDocumentableDecl(New);
19866
19867
0
  return New;
19868
0
}
19869
19870
// Returns true when the enum initial expression does not trigger the
19871
// duplicate enum warning.  A few common cases are exempted as follows:
19872
// Element2 = Element1
19873
// Element2 = Element1 + 1
19874
// Element2 = Element1 - 1
19875
// Where Element2 and Element1 are from the same enum.
19876
0
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
19877
0
  Expr *InitExpr = ECD->getInitExpr();
19878
0
  if (!InitExpr)
19879
0
    return true;
19880
0
  InitExpr = InitExpr->IgnoreImpCasts();
19881
19882
0
  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19883
0
    if (!BO->isAdditiveOp())
19884
0
      return true;
19885
0
    IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19886
0
    if (!IL)
19887
0
      return true;
19888
0
    if (IL->getValue() != 1)
19889
0
      return true;
19890
19891
0
    InitExpr = BO->getLHS();
19892
0
  }
19893
19894
  // This checks if the elements are from the same enum.
19895
0
  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19896
0
  if (!DRE)
19897
0
    return true;
19898
19899
0
  EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19900
0
  if (!EnumConstant)
19901
0
    return true;
19902
19903
0
  if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19904
0
      Enum)
19905
0
    return true;
19906
19907
0
  return false;
19908
0
}
19909
19910
// Emits a warning when an element is implicitly set a value that
19911
// a previous element has already been set to.
19912
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
19913
0
                                        EnumDecl *Enum, QualType EnumType) {
19914
  // Avoid anonymous enums
19915
0
  if (!Enum->getIdentifier())
19916
0
    return;
19917
19918
  // Only check for small enums.
19919
0
  if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19920
0
    return;
19921
19922
0
  if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19923
0
    return;
19924
19925
0
  typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19926
0
  typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19927
19928
0
  typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19929
19930
  // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19931
0
  typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19932
19933
  // Use int64_t as a key to avoid needing special handling for map keys.
19934
0
  auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19935
0
    llvm::APSInt Val = D->getInitVal();
19936
0
    return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19937
0
  };
19938
19939
0
  DuplicatesVector DupVector;
19940
0
  ValueToVectorMap EnumMap;
19941
19942
  // Populate the EnumMap with all values represented by enum constants without
19943
  // an initializer.
19944
0
  for (auto *Element : Elements) {
19945
0
    EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19946
19947
    // Null EnumConstantDecl means a previous diagnostic has been emitted for
19948
    // this constant.  Skip this enum since it may be ill-formed.
19949
0
    if (!ECD) {
19950
0
      return;
19951
0
    }
19952
19953
    // Constants with initializers are handled in the next loop.
19954
0
    if (ECD->getInitExpr())
19955
0
      continue;
19956
19957
    // Duplicate values are handled in the next loop.
19958
0
    EnumMap.insert({EnumConstantToKey(ECD), ECD});
19959
0
  }
19960
19961
0
  if (EnumMap.size() == 0)
19962
0
    return;
19963
19964
  // Create vectors for any values that has duplicates.
19965
0
  for (auto *Element : Elements) {
19966
    // The last loop returned if any constant was null.
19967
0
    EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19968
0
    if (!ValidDuplicateEnum(ECD, Enum))
19969
0
      continue;
19970
19971
0
    auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19972
0
    if (Iter == EnumMap.end())
19973
0
      continue;
19974
19975
0
    DeclOrVector& Entry = Iter->second;
19976
0
    if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19977
      // Ensure constants are different.
19978
0
      if (D == ECD)
19979
0
        continue;
19980
19981
      // Create new vector and push values onto it.
19982
0
      auto Vec = std::make_unique<ECDVector>();
19983
0
      Vec->push_back(D);
19984
0
      Vec->push_back(ECD);
19985
19986
      // Update entry to point to the duplicates vector.
19987
0
      Entry = Vec.get();
19988
19989
      // Store the vector somewhere we can consult later for quick emission of
19990
      // diagnostics.
19991
0
      DupVector.emplace_back(std::move(Vec));
19992
0
      continue;
19993
0
    }
19994
19995
0
    ECDVector *Vec = Entry.get<ECDVector*>();
19996
    // Make sure constants are not added more than once.
19997
0
    if (*Vec->begin() == ECD)
19998
0
      continue;
19999
20000
0
    Vec->push_back(ECD);
20001
0
  }
20002
20003
  // Emit diagnostics.
20004
0
  for (const auto &Vec : DupVector) {
20005
0
    assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20006
20007
    // Emit warning for one enum constant.
20008
0
    auto *FirstECD = Vec->front();
20009
0
    S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20010
0
      << FirstECD << toString(FirstECD->getInitVal(), 10)
20011
0
      << FirstECD->getSourceRange();
20012
20013
    // Emit one note for each of the remaining enum constants with
20014
    // the same value.
20015
0
    for (auto *ECD : llvm::drop_begin(*Vec))
20016
0
      S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20017
0
        << ECD << toString(ECD->getInitVal(), 10)
20018
0
        << ECD->getSourceRange();
20019
0
  }
20020
0
}
20021
20022
bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20023
0
                             bool AllowMask) const {
20024
0
  assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20025
0
  assert(ED->isCompleteDefinition() && "expected enum definition");
20026
20027
0
  auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
20028
0
  llvm::APInt &FlagBits = R.first->second;
20029
20030
0
  if (R.second) {
20031
0
    for (auto *E : ED->enumerators()) {
20032
0
      const auto &EVal = E->getInitVal();
20033
      // Only single-bit enumerators introduce new flag values.
20034
0
      if (EVal.isPowerOf2())
20035
0
        FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20036
0
    }
20037
0
  }
20038
20039
  // A value is in a flag enum if either its bits are a subset of the enum's
20040
  // flag bits (the first condition) or we are allowing masks and the same is
20041
  // true of its complement (the second condition). When masks are allowed, we
20042
  // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20043
  //
20044
  // While it's true that any value could be used as a mask, the assumption is
20045
  // that a mask will have all of the insignificant bits set. Anything else is
20046
  // likely a logic error.
20047
0
  llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20048
0
  return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20049
0
}
20050
20051
void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
20052
                         Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20053
0
                         const ParsedAttributesView &Attrs) {
20054
0
  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20055
0
  QualType EnumType = Context.getTypeDeclType(Enum);
20056
20057
0
  ProcessDeclAttributeList(S, Enum, Attrs);
20058
20059
0
  if (Enum->isDependentType()) {
20060
0
    for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20061
0
      EnumConstantDecl *ECD =
20062
0
        cast_or_null<EnumConstantDecl>(Elements[i]);
20063
0
      if (!ECD) continue;
20064
20065
0
      ECD->setType(EnumType);
20066
0
    }
20067
20068
0
    Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20069
0
    return;
20070
0
  }
20071
20072
  // TODO: If the result value doesn't fit in an int, it must be a long or long
20073
  // long value.  ISO C does not support this, but GCC does as an extension,
20074
  // emit a warning.
20075
0
  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20076
0
  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
20077
0
  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
20078
20079
  // Verify that all the values are okay, compute the size of the values, and
20080
  // reverse the list.
20081
0
  unsigned NumNegativeBits = 0;
20082
0
  unsigned NumPositiveBits = 0;
20083
20084
0
  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20085
0
    EnumConstantDecl *ECD =
20086
0
      cast_or_null<EnumConstantDecl>(Elements[i]);
20087
0
    if (!ECD) continue;  // Already issued a diagnostic.
20088
20089
0
    const llvm::APSInt &InitVal = ECD->getInitVal();
20090
20091
    // Keep track of the size of positive and negative values.
20092
0
    if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
20093
      // If the enumerator is zero that should still be counted as a positive
20094
      // bit since we need a bit to store the value zero.
20095
0
      unsigned ActiveBits = InitVal.getActiveBits();
20096
0
      NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
20097
0
    } else {
20098
0
      NumNegativeBits =
20099
0
          std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
20100
0
    }
20101
0
  }
20102
20103
  // If we have an empty set of enumerators we still need one bit.
20104
  // From [dcl.enum]p8
20105
  // If the enumerator-list is empty, the values of the enumeration are as if
20106
  // the enumeration had a single enumerator with value 0
20107
0
  if (!NumPositiveBits && !NumNegativeBits)
20108
0
    NumPositiveBits = 1;
20109
20110
  // Figure out the type that should be used for this enum.
20111
0
  QualType BestType;
20112
0
  unsigned BestWidth;
20113
20114
  // C++0x N3000 [conv.prom]p3:
20115
  //   An rvalue of an unscoped enumeration type whose underlying
20116
  //   type is not fixed can be converted to an rvalue of the first
20117
  //   of the following types that can represent all the values of
20118
  //   the enumeration: int, unsigned int, long int, unsigned long
20119
  //   int, long long int, or unsigned long long int.
20120
  // C99 6.4.4.3p2:
20121
  //   An identifier declared as an enumeration constant has type int.
20122
  // The C99 rule is modified by a gcc extension
20123
0
  QualType BestPromotionType;
20124
20125
0
  bool Packed = Enum->hasAttr<PackedAttr>();
20126
  // -fshort-enums is the equivalent to specifying the packed attribute on all
20127
  // enum definitions.
20128
0
  if (LangOpts.ShortEnums)
20129
0
    Packed = true;
20130
20131
  // If the enum already has a type because it is fixed or dictated by the
20132
  // target, promote that type instead of analyzing the enumerators.
20133
0
  if (Enum->isComplete()) {
20134
0
    BestType = Enum->getIntegerType();
20135
0
    if (Context.isPromotableIntegerType(BestType))
20136
0
      BestPromotionType = Context.getPromotedIntegerType(BestType);
20137
0
    else
20138
0
      BestPromotionType = BestType;
20139
20140
0
    BestWidth = Context.getIntWidth(BestType);
20141
0
  }
20142
0
  else if (NumNegativeBits) {
20143
    // If there is a negative value, figure out the smallest integer type (of
20144
    // int/long/longlong) that fits.
20145
    // If it's packed, check also if it fits a char or a short.
20146
0
    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
20147
0
      BestType = Context.SignedCharTy;
20148
0
      BestWidth = CharWidth;
20149
0
    } else if (Packed && NumNegativeBits <= ShortWidth &&
20150
0
               NumPositiveBits < ShortWidth) {
20151
0
      BestType = Context.ShortTy;
20152
0
      BestWidth = ShortWidth;
20153
0
    } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
20154
0
      BestType = Context.IntTy;
20155
0
      BestWidth = IntWidth;
20156
0
    } else {
20157
0
      BestWidth = Context.getTargetInfo().getLongWidth();
20158
20159
0
      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
20160
0
        BestType = Context.LongTy;
20161
0
      } else {
20162
0
        BestWidth = Context.getTargetInfo().getLongLongWidth();
20163
20164
0
        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
20165
0
          Diag(Enum->getLocation(), diag::ext_enum_too_large);
20166
0
        BestType = Context.LongLongTy;
20167
0
      }
20168
0
    }
20169
0
    BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
20170
0
  } else {
20171
    // If there is no negative value, figure out the smallest type that fits
20172
    // all of the enumerator values.
20173
    // If it's packed, check also if it fits a char or a short.
20174
0
    if (Packed && NumPositiveBits <= CharWidth) {
20175
0
      BestType = Context.UnsignedCharTy;
20176
0
      BestPromotionType = Context.IntTy;
20177
0
      BestWidth = CharWidth;
20178
0
    } else if (Packed && NumPositiveBits <= ShortWidth) {
20179
0
      BestType = Context.UnsignedShortTy;
20180
0
      BestPromotionType = Context.IntTy;
20181
0
      BestWidth = ShortWidth;
20182
0
    } else if (NumPositiveBits <= IntWidth) {
20183
0
      BestType = Context.UnsignedIntTy;
20184
0
      BestWidth = IntWidth;
20185
0
      BestPromotionType
20186
0
        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20187
0
                           ? Context.UnsignedIntTy : Context.IntTy;
20188
0
    } else if (NumPositiveBits <=
20189
0
               (BestWidth = Context.getTargetInfo().getLongWidth())) {
20190
0
      BestType = Context.UnsignedLongTy;
20191
0
      BestPromotionType
20192
0
        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20193
0
                           ? Context.UnsignedLongTy : Context.LongTy;
20194
0
    } else {
20195
0
      BestWidth = Context.getTargetInfo().getLongLongWidth();
20196
0
      assert(NumPositiveBits <= BestWidth &&
20197
0
             "How could an initializer get larger than ULL?");
20198
0
      BestType = Context.UnsignedLongLongTy;
20199
0
      BestPromotionType
20200
0
        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20201
0
                           ? Context.UnsignedLongLongTy : Context.LongLongTy;
20202
0
    }
20203
0
  }
20204
20205
  // Loop over all of the enumerator constants, changing their types to match
20206
  // the type of the enum if needed.
20207
0
  for (auto *D : Elements) {
20208
0
    auto *ECD = cast_or_null<EnumConstantDecl>(D);
20209
0
    if (!ECD) continue;  // Already issued a diagnostic.
20210
20211
    // Standard C says the enumerators have int type, but we allow, as an
20212
    // extension, the enumerators to be larger than int size.  If each
20213
    // enumerator value fits in an int, type it as an int, otherwise type it the
20214
    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
20215
    // that X has type 'int', not 'unsigned'.
20216
20217
    // Determine whether the value fits into an int.
20218
0
    llvm::APSInt InitVal = ECD->getInitVal();
20219
20220
    // If it fits into an integer type, force it.  Otherwise force it to match
20221
    // the enum decl type.
20222
0
    QualType NewTy;
20223
0
    unsigned NewWidth;
20224
0
    bool NewSign;
20225
0
    if (!getLangOpts().CPlusPlus &&
20226
0
        !Enum->isFixed() &&
20227
0
        isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
20228
0
      NewTy = Context.IntTy;
20229
0
      NewWidth = IntWidth;
20230
0
      NewSign = true;
20231
0
    } else if (ECD->getType() == BestType) {
20232
      // Already the right type!
20233
0
      if (getLangOpts().CPlusPlus)
20234
        // C++ [dcl.enum]p4: Following the closing brace of an
20235
        // enum-specifier, each enumerator has the type of its
20236
        // enumeration.
20237
0
        ECD->setType(EnumType);
20238
0
      continue;
20239
0
    } else {
20240
0
      NewTy = BestType;
20241
0
      NewWidth = BestWidth;
20242
0
      NewSign = BestType->isSignedIntegerOrEnumerationType();
20243
0
    }
20244
20245
    // Adjust the APSInt value.
20246
0
    InitVal = InitVal.extOrTrunc(NewWidth);
20247
0
    InitVal.setIsSigned(NewSign);
20248
0
    ECD->setInitVal(Context, InitVal);
20249
20250
    // Adjust the Expr initializer and type.
20251
0
    if (ECD->getInitExpr() &&
20252
0
        !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20253
0
      ECD->setInitExpr(ImplicitCastExpr::Create(
20254
0
          Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20255
0
          /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20256
0
    if (getLangOpts().CPlusPlus)
20257
      // C++ [dcl.enum]p4: Following the closing brace of an
20258
      // enum-specifier, each enumerator has the type of its
20259
      // enumeration.
20260
0
      ECD->setType(EnumType);
20261
0
    else
20262
0
      ECD->setType(NewTy);
20263
0
  }
20264
20265
0
  Enum->completeDefinition(BestType, BestPromotionType,
20266
0
                           NumPositiveBits, NumNegativeBits);
20267
20268
0
  CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20269
20270
0
  if (Enum->isClosedFlag()) {
20271
0
    for (Decl *D : Elements) {
20272
0
      EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20273
0
      if (!ECD) continue;  // Already issued a diagnostic.
20274
20275
0
      llvm::APSInt InitVal = ECD->getInitVal();
20276
0
      if (InitVal != 0 && !InitVal.isPowerOf2() &&
20277
0
          !IsValueInFlagEnum(Enum, InitVal, true))
20278
0
        Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20279
0
          << ECD << Enum;
20280
0
    }
20281
0
  }
20282
20283
  // Now that the enum type is defined, ensure it's not been underaligned.
20284
0
  if (Enum->hasAttrs())
20285
0
    CheckAlignasUnderalignment(Enum);
20286
0
}
20287
20288
Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
20289
                                  SourceLocation StartLoc,
20290
0
                                  SourceLocation EndLoc) {
20291
0
  StringLiteral *AsmString = cast<StringLiteral>(expr);
20292
20293
0
  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
20294
0
                                                   AsmString, StartLoc,
20295
0
                                                   EndLoc);
20296
0
  CurContext->addDecl(New);
20297
0
  return New;
20298
0
}
20299
20300
0
Decl *Sema::ActOnTopLevelStmtDecl(Stmt *Statement) {
20301
0
  auto *New = TopLevelStmtDecl::Create(Context, Statement);
20302
0
  Context.getTranslationUnitDecl()->addDecl(New);
20303
0
  return New;
20304
0
}
20305
20306
void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
20307
                                      IdentifierInfo* AliasName,
20308
                                      SourceLocation PragmaLoc,
20309
                                      SourceLocation NameLoc,
20310
0
                                      SourceLocation AliasNameLoc) {
20311
0
  NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20312
0
                                         LookupOrdinaryName);
20313
0
  AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20314
0
                           AttributeCommonInfo::Form::Pragma());
20315
0
  AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20316
0
      Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20317
20318
  // If a declaration that:
20319
  // 1) declares a function or a variable
20320
  // 2) has external linkage
20321
  // already exists, add a label attribute to it.
20322
0
  if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20323
0
    if (isDeclExternC(PrevDecl))
20324
0
      PrevDecl->addAttr(Attr);
20325
0
    else
20326
0
      Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20327
0
          << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20328
    // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20329
0
  } else
20330
0
    (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20331
0
}
20332
20333
void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
20334
                             SourceLocation PragmaLoc,
20335
0
                             SourceLocation NameLoc) {
20336
0
  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20337
20338
0
  if (PrevDecl) {
20339
0
    PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20340
0
  } else {
20341
0
    (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20342
0
  }
20343
0
}
20344
20345
void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
20346
                                IdentifierInfo* AliasName,
20347
                                SourceLocation PragmaLoc,
20348
                                SourceLocation NameLoc,
20349
0
                                SourceLocation AliasNameLoc) {
20350
0
  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20351
0
                                    LookupOrdinaryName);
20352
0
  WeakInfo W = WeakInfo(Name, NameLoc);
20353
20354
0
  if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20355
0
    if (!PrevDecl->hasAttr<AliasAttr>())
20356
0
      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20357
0
        DeclApplyPragmaWeak(TUScope, ND, W);
20358
0
  } else {
20359
0
    (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20360
0
  }
20361
0
}
20362
20363
23.9k
ObjCContainerDecl *Sema::getObjCDeclContext() const {
20364
23.9k
  return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
20365
23.9k
}
20366
20367
Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
20368
0
                                                     bool Final) {
20369
0
  assert(FD && "Expected non-null FunctionDecl");
20370
20371
  // SYCL functions can be template, so we check if they have appropriate
20372
  // attribute prior to checking if it is a template.
20373
0
  if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20374
0
    return FunctionEmissionStatus::Emitted;
20375
20376
  // Templates are emitted when they're instantiated.
20377
0
  if (FD->isDependentContext())
20378
0
    return FunctionEmissionStatus::TemplateDiscarded;
20379
20380
  // Check whether this function is an externally visible definition.
20381
0
  auto IsEmittedForExternalSymbol = [this, FD]() {
20382
    // We have to check the GVA linkage of the function's *definition* -- if we
20383
    // only have a declaration, we don't know whether or not the function will
20384
    // be emitted, because (say) the definition could include "inline".
20385
0
    const FunctionDecl *Def = FD->getDefinition();
20386
20387
0
    return Def && !isDiscardableGVALinkage(
20388
0
                      getASTContext().GetGVALinkageForFunction(Def));
20389
0
  };
20390
20391
0
  if (LangOpts.OpenMPIsTargetDevice) {
20392
    // In OpenMP device mode we will not emit host only functions, or functions
20393
    // we don't need due to their linkage.
20394
0
    std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20395
0
        OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20396
    // DevTy may be changed later by
20397
    //  #pragma omp declare target to(*) device_type(*).
20398
    // Therefore DevTy having no value does not imply host. The emission status
20399
    // will be checked again at the end of compilation unit with Final = true.
20400
0
    if (DevTy)
20401
0
      if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20402
0
        return FunctionEmissionStatus::OMPDiscarded;
20403
    // If we have an explicit value for the device type, or we are in a target
20404
    // declare context, we need to emit all extern and used symbols.
20405
0
    if (isInOpenMPDeclareTargetContext() || DevTy)
20406
0
      if (IsEmittedForExternalSymbol())
20407
0
        return FunctionEmissionStatus::Emitted;
20408
    // Device mode only emits what it must, if it wasn't tagged yet and needed,
20409
    // we'll omit it.
20410
0
    if (Final)
20411
0
      return FunctionEmissionStatus::OMPDiscarded;
20412
0
  } else if (LangOpts.OpenMP > 45) {
20413
    // In OpenMP host compilation prior to 5.0 everything was an emitted host
20414
    // function. In 5.0, no_host was introduced which might cause a function to
20415
    // be ommitted.
20416
0
    std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20417
0
        OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20418
0
    if (DevTy)
20419
0
      if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20420
0
        return FunctionEmissionStatus::OMPDiscarded;
20421
0
  }
20422
20423
0
  if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20424
0
    return FunctionEmissionStatus::Emitted;
20425
20426
0
  if (LangOpts.CUDA) {
20427
    // When compiling for device, host functions are never emitted.  Similarly,
20428
    // when compiling for host, device and global functions are never emitted.
20429
    // (Technically, we do emit a host-side stub for global functions, but this
20430
    // doesn't count for our purposes here.)
20431
0
    Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
20432
0
    if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
20433
0
      return FunctionEmissionStatus::CUDADiscarded;
20434
0
    if (!LangOpts.CUDAIsDevice &&
20435
0
        (T == Sema::CFT_Device || T == Sema::CFT_Global))
20436
0
      return FunctionEmissionStatus::CUDADiscarded;
20437
20438
0
    if (IsEmittedForExternalSymbol())
20439
0
      return FunctionEmissionStatus::Emitted;
20440
0
  }
20441
20442
  // Otherwise, the function is known-emitted if it's in our set of
20443
  // known-emitted functions.
20444
0
  return FunctionEmissionStatus::Unknown;
20445
0
}
20446
20447
0
bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
20448
  // Host-side references to a __global__ function refer to the stub, so the
20449
  // function itself is never emitted and therefore should not be marked.
20450
  // If we have host fn calls kernel fn calls host+device, the HD function
20451
  // does not get instantiated on the host. We model this by omitting at the
20452
  // call to the kernel from the callgraph. This ensures that, when compiling
20453
  // for host, only HD functions actually called from the host get marked as
20454
  // known-emitted.
20455
0
  return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20456
0
         IdentifyCUDATarget(Callee) == CFT_Global;
20457
0
}