Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/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/DeclCXX.h"
21
#include "clang/AST/DeclObjC.h"
22
#include "clang/AST/DeclTemplate.h"
23
#include "clang/AST/EvaluatedExprVisitor.h"
24
#include "clang/AST/Expr.h"
25
#include "clang/AST/ExprCXX.h"
26
#include "clang/AST/NonTrivialTypeVisitor.h"
27
#include "clang/AST/StmtCXX.h"
28
#include "clang/Basic/Builtins.h"
29
#include "clang/Basic/PartialDiagnostic.h"
30
#include "clang/Basic/SourceManager.h"
31
#include "clang/Basic/TargetInfo.h"
32
#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33
#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34
#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35
#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36
#include "clang/Sema/CXXFieldCollector.h"
37
#include "clang/Sema/DeclSpec.h"
38
#include "clang/Sema/DelayedDiagnostic.h"
39
#include "clang/Sema/Initialization.h"
40
#include "clang/Sema/Lookup.h"
41
#include "clang/Sema/ParsedTemplate.h"
42
#include "clang/Sema/Scope.h"
43
#include "clang/Sema/ScopeInfo.h"
44
#include "clang/Sema/SemaInternal.h"
45
#include "clang/Sema/Template.h"
46
#include "llvm/ADT/SmallString.h"
47
#include "llvm/ADT/Triple.h"
48
#include <algorithm>
49
#include <cstring>
50
#include <functional>
51
#include <unordered_map>
52
53
using namespace clang;
54
using namespace sema;
55
56
5.03M
Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57
5.03M
  if (OwnedType) {
58
1.79k
    Decl *Group[2] = { OwnedType, Ptr };
59
1.79k
    return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60
1.79k
  }
61
62
5.03M
  return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63
5.03M
}
64
65
namespace {
66
67
class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68
 public:
69
   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70
                        bool AllowTemplates = false,
71
                        bool AllowNonTemplates = true)
72
       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73
1.32k
         AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74
1.32k
     WantExpressionKeywords = false;
75
1.32k
     WantCXXNamedCasts = false;
76
1.32k
     WantRemainingKeywords = false;
77
1.32k
  }
78
79
819
  bool ValidateCandidate(const TypoCorrection &candidate) override {
80
819
    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81
778
      if (!AllowInvalidDecl && 
ND->isInvalidDecl()772
)
82
11
        return false;
83
84
767
      if (getAsTypeTemplateDecl(ND))
85
100
        return AllowTemplates;
86
87
667
      bool IsType = isa<TypeDecl>(ND) || 
isa<ObjCInterfaceDecl>(ND)110
;
88
667
      if (!IsType)
89
107
        return false;
90
91
560
      if (AllowNonTemplates)
92
560
        return true;
93
94
      // An injected-class-name of a class template (specialization) is valid
95
      // as a template or as a non-template.
96
0
      if (AllowTemplates) {
97
0
        auto *RD = dyn_cast<CXXRecordDecl>(ND);
98
0
        if (!RD || !RD->isInjectedClassName())
99
0
          return false;
100
0
        RD = cast<CXXRecordDecl>(RD->getDeclContext());
101
0
        return RD->getDescribedClassTemplate() ||
102
0
               isa<ClassTemplateSpecializationDecl>(RD);
103
0
      }
104
105
0
      return false;
106
0
    }
107
108
41
    return !WantClassName && 
candidate.isKeyword()39
;
109
819
  }
110
111
956
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
112
956
    return std::make_unique<TypeNameValidatorCCC>(*this);
113
956
  }
114
115
 private:
116
  bool AllowInvalidDecl;
117
  bool WantClassName;
118
  bool AllowTemplates;
119
  bool AllowNonTemplates;
120
};
121
122
} // end anonymous namespace
123
124
/// Determine whether the token kind starts a simple-type-specifier.
125
29.6k
bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126
29.6k
  switch (Kind) {
127
  // FIXME: Take into account the current language when deciding whether a
128
  // token kind is a valid type specifier
129
0
  case tok::kw_short:
130
0
  case tok::kw_long:
131
0
  case tok::kw___int64:
132
0
  case tok::kw___int128:
133
0
  case tok::kw_signed:
134
0
  case tok::kw_unsigned:
135
0
  case tok::kw_void:
136
0
  case tok::kw_char:
137
1
  case tok::kw_int:
138
1
  case tok::kw_half:
139
1
  case tok::kw_float:
140
1
  case tok::kw_double:
141
1
  case tok::kw___bf16:
142
1
  case tok::kw__Float16:
143
1
  case tok::kw___float128:
144
1
  case tok::kw___ibm128:
145
1
  case tok::kw_wchar_t:
146
1
  case tok::kw_bool:
147
1
  case tok::kw___underlying_type:
148
1
  case tok::kw___auto_type:
149
1
    return true;
150
151
27.6k
  case tok::annot_typename:
152
27.6k
  case tok::kw_char16_t:
153
27.6k
  case tok::kw_char32_t:
154
27.6k
  case tok::kw_typeof:
155
27.6k
  case tok::annot_decltype:
156
27.6k
  case tok::kw_decltype:
157
27.6k
    return getLangOpts().CPlusPlus;
158
159
0
  case tok::kw_char8_t:
160
0
    return getLangOpts().Char8;
161
162
1.95k
  default:
163
1.95k
    break;
164
29.6k
  }
165
166
1.95k
  return false;
167
29.6k
}
168
169
namespace {
170
enum class UnqualifiedTypeNameLookupResult {
171
  NotFound,
172
  FoundNonType,
173
  FoundType
174
};
175
} // end anonymous namespace
176
177
/// Tries to perform unqualified lookup of the type decls in bases for
178
/// dependent class.
179
/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
180
/// type decl, \a FoundType if only type decls are found.
181
static UnqualifiedTypeNameLookupResult
182
lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
183
                                SourceLocation NameLoc,
184
128
                                const CXXRecordDecl *RD) {
185
128
  if (!RD->hasDefinition())
186
2
    return UnqualifiedTypeNameLookupResult::NotFound;
187
  // Look for type decls in base classes.
188
126
  UnqualifiedTypeNameLookupResult FoundTypeDecl =
189
126
      UnqualifiedTypeNameLookupResult::NotFound;
190
126
  for (const auto &Base : RD->bases()) {
191
124
    const CXXRecordDecl *BaseRD = nullptr;
192
124
    if (auto *BaseTT = Base.getType()->getAs<TagType>())
193
10
      BaseRD = BaseTT->getAsCXXRecordDecl();
194
114
    else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
195
      // Look for type decls in dependent base classes that have known primary
196
      // templates.
197
88
      if (!TST || !TST->isDependentType())
198
0
        continue;
199
88
      auto *TD = TST->getTemplateName().getAsTemplateDecl();
200
88
      if (!TD)
201
0
        continue;
202
88
      if (auto *BasePrimaryTemplate =
203
88
          dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
204
84
        if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
205
82
          BaseRD = BasePrimaryTemplate;
206
2
        else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
207
2
          if (const ClassTemplatePartialSpecializationDecl *PS =
208
2
                  CTD->findPartialSpecialization(Base.getType()))
209
2
            if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
210
2
              BaseRD = PS;
211
2
        }
212
84
      }
213
88
    }
214
124
    if (BaseRD) {
215
94
      for (NamedDecl *ND : BaseRD->lookup(&II)) {
216
76
        if (!isa<TypeDecl>(ND))
217
24
          return UnqualifiedTypeNameLookupResult::FoundNonType;
218
52
        FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
219
52
      }
220
70
      if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
221
18
        switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
222
0
        case UnqualifiedTypeNameLookupResult::FoundNonType:
223
0
          return UnqualifiedTypeNameLookupResult::FoundNonType;
224
10
        case UnqualifiedTypeNameLookupResult::FoundType:
225
10
          FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
226
10
          break;
227
8
        case UnqualifiedTypeNameLookupResult::NotFound:
228
8
          break;
229
18
        }
230
18
      }
231
70
    }
232
124
  }
233
234
102
  return FoundTypeDecl;
235
126
}
236
237
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
238
                                                      const IdentifierInfo &II,
239
185
                                                      SourceLocation NameLoc) {
240
  // Lookup in the parent class template context, if any.
241
185
  const CXXRecordDecl *RD = nullptr;
242
185
  UnqualifiedTypeNameLookupResult FoundTypeDecl =
243
185
      UnqualifiedTypeNameLookupResult::NotFound;
244
185
  for (DeclContext *DC = S.CurContext;
245
585
       DC && 
FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound468
;
246
400
       DC = DC->getParent()) {
247
    // Look for type decls in dependent base classes that have known primary
248
    // templates.
249
400
    RD = dyn_cast<CXXRecordDecl>(DC);
250
400
    if (RD && 
RD->getDescribedClassTemplate()127
)
251
110
      FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
252
400
  }
253
185
  if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
254
141
    return nullptr;
255
256
  // We found some types in dependent base classes.  Recover as if the user
257
  // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
258
  // lookup during template instantiation.
259
44
  S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
260
261
44
  ASTContext &Context = S.Context;
262
44
  auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
263
44
                                          cast<Type>(Context.getRecordType(RD)));
264
44
  QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
265
266
44
  CXXScopeSpec SS;
267
44
  SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
268
269
44
  TypeLocBuilder Builder;
270
44
  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
271
44
  DepTL.setNameLoc(NameLoc);
272
44
  DepTL.setElaboratedKeywordLoc(SourceLocation());
273
44
  DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
274
44
  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
275
185
}
276
277
/// If the identifier refers to a type name within this scope,
278
/// return the declaration of that type.
279
///
280
/// This routine performs ordinary name lookup of the identifier II
281
/// within the given scope, with optional C++ scope specifier SS, to
282
/// determine whether the name refers to a type. If so, returns an
283
/// opaque pointer (actually a QualType) corresponding to that
284
/// type. Otherwise, returns NULL.
285
ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
286
                             Scope *S, CXXScopeSpec *SS,
287
                             bool isClassName, bool HasTrailingDot,
288
                             ParsedType ObjectTypePtr,
289
                             bool IsCtorOrDtorName,
290
                             bool WantNontrivialTypeSourceInfo,
291
                             bool IsClassTemplateDeductionContext,
292
100M
                             IdentifierInfo **CorrectedII) {
293
  // FIXME: Consider allowing this outside C++1z mode as an extension.
294
100M
  bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
295
100M
                              
getLangOpts().CPlusPlus17100M
&&
!IsCtorOrDtorName306k
&&
296
100M
                              
!isClassName305k
&&
!HasTrailingDot305k
;
297
298
  // Determine where we will perform name lookup.
299
100M
  DeclContext *LookupCtx = nullptr;
300
100M
  if (ObjectTypePtr) {
301
5.89k
    QualType ObjectType = ObjectTypePtr.get();
302
5.89k
    if (ObjectType->isRecordType())
303
425
      LookupCtx = computeDeclContext(ObjectType);
304
100M
  } else if (SS && 
SS->isNotEmpty()26.2M
) {
305
2.56M
    LookupCtx = computeDeclContext(*SS, false);
306
307
2.56M
    if (!LookupCtx) {
308
1.58M
      if (isDependentScopeSpecifier(*SS)) {
309
        // C++ [temp.res]p3:
310
        //   A qualified-id that refers to a type and in which the
311
        //   nested-name-specifier depends on a template-parameter (14.6.2)
312
        //   shall be prefixed by the keyword typename to indicate that the
313
        //   qualified-id denotes a type, forming an
314
        //   elaborated-type-specifier (7.1.5.3).
315
        //
316
        // We therefore do not perform any name lookup if the result would
317
        // refer to a member of an unknown specialization.
318
1.58M
        if (!isClassName && 
!IsCtorOrDtorName1.58M
)
319
1.58M
          return nullptr;
320
321
        // We know from the grammar that this name refers to a type,
322
        // so build a dependent node to describe the type.
323
2.45k
        if (WantNontrivialTypeSourceInfo)
324
2.43k
          return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
325
326
12
        NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
327
12
        QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
328
12
                                       II, NameLoc);
329
12
        return ParsedType::make(T);
330
2.45k
      }
331
332
689
      return nullptr;
333
1.58M
    }
334
335
980k
    if (!LookupCtx->isDependentContext() &&
336
980k
        
RequireCompleteDeclContext(*SS, LookupCtx)979k
)
337
136
      return nullptr;
338
980k
  }
339
340
  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
341
  // lookup for class-names.
342
99.2M
  LookupNameKind Kind = isClassName ? 
LookupNestedNameSpecifierName89.6k
:
343
99.2M
                                      
LookupOrdinaryName99.1M
;
344
99.2M
  LookupResult Result(*this, &II, NameLoc, Kind);
345
99.2M
  if (LookupCtx) {
346
    // Perform "qualified" name lookup into the declaration context we
347
    // computed, which is either the type of the base of a member access
348
    // expression or the declaration context associated with a prior
349
    // nested-name-specifier.
350
980k
    LookupQualifiedName(Result, LookupCtx);
351
352
980k
    if (ObjectTypePtr && 
Result.empty()0
) {
353
      // C++ [basic.lookup.classref]p3:
354
      //   If the unqualified-id is ~type-name, the type-name is looked up
355
      //   in the context of the entire postfix-expression. If the type T of
356
      //   the object expression is of a class type C, the type-name is also
357
      //   looked up in the scope of class C. At least one of the lookups shall
358
      //   find a name that refers to (possibly cv-qualified) T.
359
0
      LookupName(Result, S);
360
0
    }
361
98.2M
  } else {
362
    // Perform unqualified name lookup.
363
98.2M
    LookupName(Result, S);
364
365
    // For unqualified lookup in a class template in MSVC mode, look into
366
    // dependent base classes where the primary class template is known.
367
98.2M
    if (Result.empty() && 
getLangOpts().MSVCCompat119k
&&
(108
!SS108
||
SS->isEmpty()30
)) {
368
108
      if (ParsedType TypeInBase =
369
108
              recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
370
30
        return TypeInBase;
371
108
    }
372
98.2M
  }
373
374
99.2M
  NamedDecl *IIDecl = nullptr;
375
99.2M
  UsingShadowDecl *FoundUsingShadow = nullptr;
376
99.2M
  switch (Result.getResultKind()) {
377
120k
  case LookupResult::NotFound:
378
120k
  case LookupResult::NotFoundInCurrentInstantiation:
379
120k
    if (CorrectedII) {
380
8
      TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
381
8
                               AllowDeducedTemplate);
382
8
      TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
383
8
                                              S, SS, CCC, CTK_ErrorRecovery);
384
8
      IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
385
8
      TemplateTy Template;
386
8
      bool MemberOfUnknownSpecialization;
387
8
      UnqualifiedId TemplateName;
388
8
      TemplateName.setIdentifier(NewII, NameLoc);
389
8
      NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
390
8
      CXXScopeSpec NewSS, *NewSSPtr = SS;
391
8
      if (SS && NNS) {
392
0
        NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
393
0
        NewSSPtr = &NewSS;
394
0
      }
395
8
      if (Correction && 
(2
NNS2
||
NewII != &II2
) &&
396
          // Ignore a correction to a template type as the to-be-corrected
397
          // identifier is not a template (typo correction for template names
398
          // is handled elsewhere).
399
8
          
!(2
getLangOpts().CPlusPlus2
&&
NewSSPtr2
&&
400
2
            isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
401
2
                           Template, MemberOfUnknownSpecialization))) {
402
2
        ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
403
2
                                    isClassName, HasTrailingDot, ObjectTypePtr,
404
2
                                    IsCtorOrDtorName,
405
2
                                    WantNontrivialTypeSourceInfo,
406
2
                                    IsClassTemplateDeductionContext);
407
2
        if (Ty) {
408
2
          diagnoseTypo(Correction,
409
2
                       PDiag(diag::err_unknown_type_or_class_name_suggest)
410
2
                         << Result.getLookupName() << isClassName);
411
2
          if (SS && NNS)
412
0
            SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
413
2
          *CorrectedII = NewII;
414
2
          return Ty;
415
2
        }
416
2
      }
417
8
    }
418
    // If typo correction failed or was not performed, fall through
419
120k
    
LLVM_FALLTHROUGH120k
;120k
420
917k
  case LookupResult::FoundOverloaded:
421
917k
  case LookupResult::FoundUnresolvedValue:
422
917k
    Result.suppressDiagnostics();
423
917k
    return nullptr;
424
425
70
  case LookupResult::Ambiguous:
426
    // Recover from type-hiding ambiguities by hiding the type.  We'll
427
    // do the lookup again when looking for an object, and we can
428
    // diagnose the error then.  If we don't do this, then the error
429
    // about hiding the type will be immediately followed by an error
430
    // that only makes sense if the identifier was treated like a type.
431
70
    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
432
2
      Result.suppressDiagnostics();
433
2
      return nullptr;
434
2
    }
435
436
    // Look to see if we have a type anywhere in the list of results.
437
68
    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
438
192
         Res != ResEnd; 
++Res124
) {
439
124
      NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
440
124
      if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
441
124
              RealRes) ||
442
124
          
(61
AllowDeducedTemplate61
&&
getAsTypeTemplateDecl(RealRes)4
)) {
443
63
        if (!IIDecl ||
444
            // Make the selection of the recovery decl deterministic.
445
63
            
RealRes->getLocation() < IIDecl->getLocation()31
) {
446
43
          IIDecl = RealRes;
447
43
          FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
448
43
        }
449
63
      }
450
124
    }
451
452
68
    if (!IIDecl) {
453
      // None of the entities we found is a type, so there is no way
454
      // to even assume that the result is a type. In this case, don't
455
      // complain about the ambiguity. The parser will either try to
456
      // perform this lookup again (e.g., as an object name), which
457
      // will produce the ambiguity, or will complain that it expected
458
      // a type name.
459
36
      Result.suppressDiagnostics();
460
36
      return nullptr;
461
36
    }
462
463
    // We found a type within the ambiguous lookup; diagnose the
464
    // ambiguity and then return that type. This might be the right
465
    // answer, or it might not be, but it suppresses any attempt to
466
    // perform the name lookup again.
467
32
    break;
468
469
98.3M
  case LookupResult::Found:
470
98.3M
    IIDecl = Result.getFoundDecl();
471
98.3M
    FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
472
98.3M
    break;
473
99.2M
  }
474
475
98.3M
  assert(IIDecl && "Didn't find decl");
476
477
0
  QualType T;
478
98.3M
  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
479
    // C++ [class.qual]p2: A lookup that would find the injected-class-name
480
    // instead names the constructors of the class, except when naming a class.
481
    // This is ill-formed when we're not actually forming a ctor or dtor name.
482
95.6M
    auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
483
95.6M
    auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
484
95.6M
    if (!isClassName && 
!IsCtorOrDtorName95.5M
&&
LookupRD95.5M
&&
FoundRD36.6k
&&
485
95.6M
        
FoundRD->isInjectedClassName()4.36k
&&
486
95.6M
        
declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))76
)
487
52
      Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
488
52
          << &II << /*Type*/1;
489
490
95.6M
    DiagnoseUseOfDecl(IIDecl, NameLoc);
491
492
95.6M
    T = Context.getTypeDeclType(TD);
493
95.6M
    MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
494
95.6M
  } else 
if (ObjCInterfaceDecl *2.65M
IDecl2.65M
= dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
495
1.13M
    (void)DiagnoseUseOfDecl(IDecl, NameLoc);
496
1.13M
    if (!HasTrailingDot)
497
1.13M
      T = Context.getObjCInterfaceType(IDecl);
498
1.13M
    FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
499
1.51M
  } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
500
624
    (void)DiagnoseUseOfDecl(UD, NameLoc);
501
    // Recover with 'int'
502
624
    T = Context.IntTy;
503
624
    FoundUsingShadow = nullptr;
504
1.51M
  } else if (AllowDeducedTemplate) {
505
33.6k
    if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
506
      // FIXME: TemplateName should include FoundUsingShadow sugar.
507
1.28k
      T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
508
1.28k
                                                       QualType(), false);
509
      // Don't wrap in a further UsingType.
510
1.28k
      FoundUsingShadow = nullptr;
511
1.28k
    }
512
33.6k
  }
513
514
98.3M
  if (T.isNull()) {
515
    // If it's not plausibly a type, suppress diagnostics.
516
1.51M
    Result.suppressDiagnostics();
517
1.51M
    return nullptr;
518
1.51M
  }
519
520
96.7M
  if (FoundUsingShadow)
521
271k
    T = Context.getUsingType(FoundUsingShadow, T);
522
523
  // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
524
  // constructor or destructor name (in such a case, the scope specifier
525
  // will be attached to the enclosing Expr or Decl node).
526
96.7M
  if (SS && 
SS->isNotEmpty()22.2M
&&
!IsCtorOrDtorName103k
&&
527
96.7M
      
!isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)103k
) {
528
102k
    if (WantNontrivialTypeSourceInfo) {
529
      // Construct a type with type-source information.
530
102k
      TypeLocBuilder Builder;
531
102k
      Builder.pushTypeSpec(T).setNameLoc(NameLoc);
532
533
102k
      T = getElaboratedType(ETK_None, *SS, T);
534
102k
      ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
535
102k
      ElabTL.setElaboratedKeywordLoc(SourceLocation());
536
102k
      ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
537
102k
      return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
538
102k
    } else {
539
0
      T = getElaboratedType(ETK_None, *SS, T);
540
0
    }
541
102k
  }
542
543
96.6M
  return ParsedType::make(T);
544
96.7M
}
545
546
// Builds a fake NNS for the given decl context.
547
static NestedNameSpecifier *
548
3
synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
549
3
  for (;; 
DC = DC->getLookupParent()0
) {
550
3
    DC = DC->getPrimaryContext();
551
3
    auto *ND = dyn_cast<NamespaceDecl>(DC);
552
3
    if (ND && 
!ND->isInline()2
&&
!ND->isAnonymousNamespace()2
)
553
2
      return NestedNameSpecifier::Create(Context, nullptr, ND);
554
1
    else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
555
1
      return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
556
1
                                         RD->getTypeForDecl());
557
0
    else if (isa<TranslationUnitDecl>(DC))
558
0
      return NestedNameSpecifier::GlobalSpecifier(Context);
559
3
  }
560
0
  llvm_unreachable("something isn't in TU scope?");
561
0
}
562
563
/// Find the parent class with dependent bases of the innermost enclosing method
564
/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
565
/// up allowing unqualified dependent type names at class-level, which MSVC
566
/// correctly rejects.
567
static const CXXRecordDecl *
568
38
findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
569
52
  for (; DC && DC->isDependentContext(); 
DC = DC->getLookupParent()14
) {
570
26
    DC = DC->getPrimaryContext();
571
26
    if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
572
12
      if (MD->getParent()->hasAnyDependentBases())
573
12
        return MD->getParent();
574
26
  }
575
26
  return nullptr;
576
38
}
577
578
ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
579
                                          SourceLocation NameLoc,
580
41
                                          bool IsTemplateTypeArg) {
581
41
  assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
582
583
0
  NestedNameSpecifier *NNS = nullptr;
584
41
  if (IsTemplateTypeArg && 
getCurScope()->isTemplateParamScope()3
) {
585
    // If we weren't able to parse a default template argument, delay lookup
586
    // until instantiation time by making a non-dependent DependentTypeName. We
587
    // pretend we saw a NestedNameSpecifier referring to the current scope, and
588
    // lookup is retried.
589
    // FIXME: This hurts our diagnostic quality, since we get errors like "no
590
    // type named 'Foo' in 'current_namespace'" when the user didn't write any
591
    // name specifiers.
592
3
    NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
593
3
    Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
594
38
  } else if (const CXXRecordDecl *RD =
595
38
                 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
596
    // Build a DependentNameType that will perform lookup into RD at
597
    // instantiation time.
598
12
    NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
599
12
                                      RD->getTypeForDecl());
600
601
    // Diagnose that this identifier was undeclared, and retry the lookup during
602
    // template instantiation.
603
12
    Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
604
12
                                                                      << RD;
605
26
  } else {
606
    // This is not a situation that we should recover from.
607
26
    return ParsedType();
608
26
  }
609
610
15
  QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
611
612
  // Build type location information.  We synthesized the qualifier, so we have
613
  // to build a fake NestedNameSpecifierLoc.
614
15
  NestedNameSpecifierLocBuilder NNSLocBuilder;
615
15
  NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
616
15
  NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
617
618
15
  TypeLocBuilder Builder;
619
15
  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
620
15
  DepTL.setNameLoc(NameLoc);
621
15
  DepTL.setElaboratedKeywordLoc(SourceLocation());
622
15
  DepTL.setQualifierLoc(QualifierLoc);
623
15
  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
624
41
}
625
626
/// isTagName() - This method is called *for error recovery purposes only*
627
/// to determine if the specified name is a valid tag name ("struct foo").  If
628
/// so, this returns the TST for the tag corresponding to it (TST_enum,
629
/// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
630
/// cases in C where the user forgot to specify the tag.
631
1.00k
DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
632
  // Do a tag name lookup in this scope.
633
1.00k
  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
634
1.00k
  LookupName(R, S, false);
635
1.00k
  R.suppressDiagnostics();
636
1.00k
  if (R.getResultKind() == LookupResult::Found)
637
77
    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
638
38
      switch (TD->getTagKind()) {
639
18
      case TTK_Struct: return DeclSpec::TST_struct;
640
0
      case TTK_Interface: return DeclSpec::TST_interface;
641
0
      case TTK_Union:  return DeclSpec::TST_union;
642
9
      case TTK_Class:  return DeclSpec::TST_class;
643
11
      case TTK_Enum:   return DeclSpec::TST_enum;
644
38
      }
645
38
    }
646
647
971
  return DeclSpec::TST_unspecified;
648
1.00k
}
649
650
/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
651
/// if a CXXScopeSpec's type is equal to the type of one of the base classes
652
/// then downgrade the missing typename error to a warning.
653
/// This is needed for MSVC compatibility; Example:
654
/// @code
655
/// template<class T> class A {
656
/// public:
657
///   typedef int TYPE;
658
/// };
659
/// template<class T> class B : public A<T> {
660
/// public:
661
///   A<T>::TYPE a; // no typename required because A<T> is a base class.
662
/// };
663
/// @endcode
664
43
bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
665
43
  if (CurContext->isRecord()) {
666
31
    if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
667
0
      return true;
668
669
31
    const Type *Ty = SS->getScopeRep()->getAsType();
670
671
31
    CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
672
31
    for (const auto &Base : RD->bases())
673
51
      if (Ty && 
Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())50
)
674
20
        return true;
675
11
    return S->isFunctionPrototypeScope();
676
31
  }
677
12
  return CurContext->isFunctionOrMethod() || 
S->isFunctionPrototypeScope()5
;
678
43
}
679
680
void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
681
                                   SourceLocation IILoc,
682
                                   Scope *S,
683
                                   CXXScopeSpec *SS,
684
                                   ParsedType &SuggestedType,
685
1.32k
                                   bool IsTemplateName) {
686
  // Don't report typename errors for editor placeholders.
687
1.32k
  if (II->isEditorPlaceholder())
688
7
    return;
689
  // We don't have anything to suggest (yet).
690
1.31k
  SuggestedType = nullptr;
691
692
  // There may have been a typo in the name of the type. Look up typo
693
  // results, in case we have something that we can suggest.
694
1.31k
  TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
695
1.31k
                           /*AllowTemplates=*/IsTemplateName,
696
1.31k
                           /*AllowNonTemplates=*/!IsTemplateName);
697
1.31k
  if (TypoCorrection Corrected =
698
1.31k
          CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
699
1.31k
                      CCC, CTK_ErrorRecovery)) {
700
    // FIXME: Support error recovery for the template-name case.
701
279
    bool CanRecover = !IsTemplateName;
702
279
    if (Corrected.isKeyword()) {
703
      // We corrected to a keyword.
704
12
      diagnoseTypo(Corrected,
705
12
                   PDiag(IsTemplateName ? 
diag::err_no_template_suggest0
706
12
                                        : diag::err_unknown_typename_suggest)
707
12
                       << II);
708
12
      II = Corrected.getCorrectionAsIdentifierInfo();
709
267
    } else {
710
      // We found a similarly-named type or interface; suggest that.
711
267
      if (!SS || 
!SS->isSet()71
) {
712
196
        diagnoseTypo(Corrected,
713
196
                     PDiag(IsTemplateName ? 
diag::err_no_template_suggest2
714
196
                                          : 
diag::err_unknown_typename_suggest194
)
715
196
                         << II, CanRecover);
716
196
      } else 
if (DeclContext *71
DC71
= computeDeclContext(*SS, false)) {
717
71
        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
718
71
        bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
719
71
                                
II->getName().equals(CorrectedStr)43
;
720
71
        diagnoseTypo(Corrected,
721
71
                     PDiag(IsTemplateName
722
71
                               ? 
diag::err_no_member_template_suggest0
723
71
                               : diag::err_unknown_nested_typename_suggest)
724
71
                         << II << DC << DroppedSpecifier << SS->getRange(),
725
71
                     CanRecover);
726
71
      } else {
727
0
        llvm_unreachable("could not have corrected a typo here");
728
0
      }
729
730
267
      if (!CanRecover)
731
2
        return;
732
733
265
      CXXScopeSpec tmpSS;
734
265
      if (Corrected.getCorrectionSpecifier())
735
39
        tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
736
39
                          SourceRange(IILoc));
737
      // FIXME: Support class template argument deduction here.
738
265
      SuggestedType =
739
265
          getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
740
265
                      tmpSS.isSet() ? 
&tmpSS39
:
SS226
, false, false, nullptr,
741
265
                      /*IsCtorOrDtorName=*/false,
742
265
                      /*WantNontrivialTypeSourceInfo=*/true);
743
265
    }
744
277
    return;
745
279
  }
746
747
1.03k
  if (getLangOpts().CPlusPlus && 
!IsTemplateName856
) {
748
    // See if II is a class template that the user forgot to pass arguments to.
749
847
    UnqualifiedId Name;
750
847
    Name.setIdentifier(II, IILoc);
751
847
    CXXScopeSpec EmptySS;
752
847
    TemplateTy TemplateResult;
753
847
    bool MemberOfUnknownSpecialization;
754
847
    if (isTemplateName(S, SS ? 
*SS402
:
EmptySS445
, /*hasTemplateKeyword=*/false,
755
847
                       Name, nullptr, true, TemplateResult,
756
847
                       MemberOfUnknownSpecialization) == TNK_Type_template) {
757
43
      diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
758
43
      return;
759
43
    }
760
847
  }
761
762
  // FIXME: Should we move the logic that tries to recover from a missing tag
763
  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
764
765
994
  if (!SS || 
(391
!SS->isSet()391
&&
!SS->isInvalid()151
))
766
603
    Diag(IILoc, IsTemplateName ? 
diag::err_no_template0
767
603
                               : diag::err_unknown_typename)
768
603
        << II;
769
391
  else if (DeclContext *DC = computeDeclContext(*SS, false))
770
52
    Diag(IILoc, IsTemplateName ? 
diag::err_no_member_template9
771
52
                               : 
diag::err_typename_nested_not_found43
)
772
52
        << II << DC << SS->getRange();
773
339
  else if (SS->isValid() && 
SS->getScopeRep()->containsErrors()188
) {
774
3
    SuggestedType =
775
3
        ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
776
336
  } else if (isDependentScopeSpecifier(*SS)) {
777
185
    unsigned DiagID = diag::err_typename_missing;
778
185
    if (getLangOpts().MSVCCompat && 
isMicrosoftMissingTypename(SS, S)43
)
779
32
      DiagID = diag::ext_typename_missing;
780
781
185
    Diag(SS->getRange().getBegin(), DiagID)
782
185
      << SS->getScopeRep() << II->getName()
783
185
      << SourceRange(SS->getRange().getBegin(), IILoc)
784
185
      << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
785
185
    SuggestedType = ActOnTypenameType(S, SourceLocation(),
786
185
                                      *SS, *II, IILoc).get();
787
185
  } else {
788
151
    assert(SS && SS->isInvalid() &&
789
151
           "Invalid scope specifier has already been diagnosed");
790
151
  }
791
994
}
792
793
/// Determine whether the given result set contains either a type name
794
/// or
795
5.04k
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
796
5.04k
  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
797
5.04k
                       
NextToken.is(tok::less)1.23k
;
798
799
8.03k
  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; 
++I2.99k
) {
800
4.13k
    if (isa<TypeDecl>(*I) || 
isa<ObjCInterfaceDecl>(*I)3.55k
)
801
1.13k
      return true;
802
803
2.99k
    if (CheckTemplate && 
isa<TemplateDecl>(*I)0
)
804
0
      return true;
805
2.99k
  }
806
807
3.90k
  return false;
808
5.04k
}
809
810
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
811
                                    Scope *S, CXXScopeSpec &SS,
812
                                    IdentifierInfo *&Name,
813
817
                                    SourceLocation NameLoc) {
814
817
  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
815
817
  SemaRef.LookupParsedName(R, S, &SS);
816
817
  if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
817
36
    StringRef FixItTagName;
818
36
    switch (Tag->getTagKind()) {
819
12
      case TTK_Class:
820
12
        FixItTagName = "class ";
821
12
        break;
822
823
10
      case TTK_Enum:
824
10
        FixItTagName = "enum ";
825
10
        break;
826
827
14
      case TTK_Struct:
828
14
        FixItTagName = "struct ";
829
14
        break;
830
831
0
      case TTK_Interface:
832
0
        FixItTagName = "__interface ";
833
0
        break;
834
835
0
      case TTK_Union:
836
0
        FixItTagName = "union ";
837
0
        break;
838
36
    }
839
840
36
    StringRef TagName = FixItTagName.drop_back();
841
36
    SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
842
36
      << Name << TagName << SemaRef.getLangOpts().CPlusPlus
843
36
      << FixItHint::CreateInsertion(NameLoc, FixItTagName);
844
845
36
    for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
846
68
         I != IEnd; 
++I32
)
847
32
      SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
848
32
        << Name << TagName;
849
850
    // Replace lookup results with just the tag decl.
851
36
    Result.clear(Sema::LookupTagName);
852
36
    SemaRef.LookupParsedName(Result, S, &SS);
853
36
    return true;
854
36
  }
855
856
781
  return false;
857
817
}
858
859
Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
860
                                            IdentifierInfo *&Name,
861
                                            SourceLocation NameLoc,
862
                                            const Token &NextToken,
863
14.6M
                                            CorrectionCandidateCallback *CCC) {
864
14.6M
  DeclarationNameInfo NameInfo(Name, NameLoc);
865
14.6M
  ObjCMethodDecl *CurMethod = getCurMethodDecl();
866
867
14.6M
  assert(NextToken.isNot(tok::coloncolon) &&
868
14.6M
         "parse nested name specifiers before calling ClassifyName");
869
14.6M
  if (getLangOpts().CPlusPlus && 
SS.isSet()13.6M
&&
870
14.6M
      
isCurrentClassName(*Name, S, &SS)89.6k
) {
871
    // Per [class.qual]p2, this names the constructors of SS, not the
872
    // injected-class-name. We don't have a classification for that.
873
    // There's not much point caching this result, since the parser
874
    // will reject it later.
875
8
    return NameClassification::Unknown();
876
8
  }
877
878
14.6M
  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
879
14.6M
  LookupParsedName(Result, S, &SS, !CurMethod);
880
881
14.6M
  if (SS.isInvalid())
882
5
    return NameClassification::Error();
883
884
  // For unqualified lookup in a class template in MSVC mode, look into
885
  // dependent base classes where the primary class template is known.
886
14.6M
  if (Result.empty() && 
SS.isEmpty()6.06k
&&
getLangOpts().MSVCCompat3.76k
) {
887
77
    if (ParsedType TypeInBase =
888
77
            recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
889
14
      return TypeInBase;
890
77
  }
891
892
  // Perform lookup for Objective-C instance variables (including automatically
893
  // synthesized instance variables), if we're in an Objective-C method.
894
  // FIXME: This lookup really, really needs to be folded in to the normal
895
  // unqualified lookup mechanism.
896
14.6M
  if (SS.isEmpty() && 
CurMethod14.5M
&&
!isResultTypeOrTemplate(Result, NextToken)5.04k
) {
897
3.90k
    DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
898
3.90k
    if (Ivar.isInvalid())
899
6
      return NameClassification::Error();
900
3.89k
    if (Ivar.isUsable())
901
901
      return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
902
903
    // We defer builtin creation until after ivar lookup inside ObjC methods.
904
2.99k
    if (Result.empty())
905
166
      LookupBuiltin(Result);
906
2.99k
  }
907
908
14.6M
  bool SecondTry = false;
909
14.6M
  bool IsFilteredTemplateName = false;
910
911
14.6M
Corrected:
912
14.6M
  switch (Result.getResultKind()) {
913
3.15k
  case LookupResult::NotFound:
914
    // If an unqualified-id is followed by a '(', then we have a function
915
    // call.
916
3.15k
    if (SS.isEmpty() && 
NextToken.is(tok::l_paren)3.00k
) {
917
      // In C++, this is an ADL-only call.
918
      // FIXME: Reference?
919
770
      if (getLangOpts().CPlusPlus)
920
608
        return NameClassification::UndeclaredNonType();
921
922
      // C90 6.3.2.2:
923
      //   If the expression that precedes the parenthesized argument list in a
924
      //   function call consists solely of an identifier, and if no
925
      //   declaration is visible for this identifier, the identifier is
926
      //   implicitly declared exactly as if, in the innermost block containing
927
      //   the function call, the declaration
928
      //
929
      //     extern int identifier ();
930
      //
931
      //   appeared.
932
      //
933
      // We also allow this in C99 as an extension.
934
162
      if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
935
162
        return NameClassification::NonType(D);
936
162
    }
937
938
2.38k
    if (getLangOpts().CPlusPlus20 && 
SS.isEmpty()96
&&
NextToken.is(tok::less)88
) {
939
      // In C++20 onwards, this could be an ADL-only call to a function
940
      // template, and we're required to assume that this is a template name.
941
      //
942
      // FIXME: Find a way to still do typo correction in this case.
943
2
      TemplateName Template =
944
2
          Context.getAssumedTemplateName(NameInfo.getName());
945
2
      return NameClassification::UndeclaredTemplate(Template);
946
2
    }
947
948
    // In C, we first see whether there is a tag type by the same name, in
949
    // which case it's likely that the user just forgot to write "enum",
950
    // "struct", or "union".
951
2.38k
    if (!getLangOpts().CPlusPlus && 
!SecondTry591
&&
952
2.38k
        
isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)591
) {
953
4
      break;
954
4
    }
955
956
    // Perform typo correction to determine if there is another name that is
957
    // close to this name.
958
2.37k
    if (!SecondTry && CCC) {
959
2.22k
      SecondTry = true;
960
2.22k
      if (TypoCorrection Corrected =
961
2.22k
              CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
962
2.22k
                          &SS, *CCC, CTK_ErrorRecovery)) {
963
94
        unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
964
94
        unsigned QualifiedDiag = diag::err_no_member_suggest;
965
966
94
        NamedDecl *FirstDecl = Corrected.getFoundDecl();
967
94
        NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
968
94
        if (getLangOpts().CPlusPlus && 
NextToken.is(tok::less)79
&&
969
94
            
UnderlyingFirstDecl0
&&
isa<TemplateDecl>(UnderlyingFirstDecl)0
) {
970
0
          UnqualifiedDiag = diag::err_no_template_suggest;
971
0
          QualifiedDiag = diag::err_no_member_template_suggest;
972
94
        } else if (UnderlyingFirstDecl &&
973
94
                   
(77
isa<TypeDecl>(UnderlyingFirstDecl)77
||
974
77
                    
isa<ObjCInterfaceDecl>(UnderlyingFirstDecl)56
||
975
77
                    
isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl)54
)) {
976
23
          UnqualifiedDiag = diag::err_unknown_typename_suggest;
977
23
          QualifiedDiag = diag::err_unknown_nested_typename_suggest;
978
23
        }
979
980
94
        if (SS.isEmpty()) {
981
94
          diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
982
94
        } else {// FIXME: is this even reachable? Test it.
983
0
          std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
984
0
          bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
985
0
                                  Name->getName().equals(CorrectedStr);
986
0
          diagnoseTypo(Corrected, PDiag(QualifiedDiag)
987
0
                                    << Name << computeDeclContext(SS, false)
988
0
                                    << DroppedSpecifier << SS.getRange());
989
0
        }
990
991
        // Update the name, so that the caller has the new name.
992
94
        Name = Corrected.getCorrectionAsIdentifierInfo();
993
994
        // Typo correction corrected to a keyword.
995
94
        if (Corrected.isKeyword())
996
17
          return Name;
997
998
        // Also update the LookupResult...
999
        // FIXME: This should probably go away at some point
1000
77
        Result.clear();
1001
77
        Result.setLookupName(Corrected.getCorrection());
1002
77
        if (FirstDecl)
1003
77
          Result.addDecl(FirstDecl);
1004
1005
        // If we found an Objective-C instance variable, let
1006
        // LookupInObjCMethod build the appropriate expression to
1007
        // reference the ivar.
1008
        // FIXME: This is a gross hack.
1009
77
        if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1010
5
          DeclResult R =
1011
5
              LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1012
5
          if (R.isInvalid())
1013
0
            return NameClassification::Error();
1014
5
          if (R.isUsable())
1015
5
            return NameClassification::NonType(Ivar);
1016
5
        }
1017
1018
72
        goto Corrected;
1019
77
      }
1020
2.22k
    }
1021
1022
    // We failed to correct; just fall through and let the parser deal with it.
1023
2.28k
    Result.suppressDiagnostics();
1024
2.28k
    return NameClassification::Unknown();
1025
1026
2.14k
  case LookupResult::NotFoundInCurrentInstantiation: {
1027
    // We performed name lookup into the current instantiation, and there were
1028
    // dependent bases, so we treat this result the same way as any other
1029
    // dependent nested-name-specifier.
1030
1031
    // C++ [temp.res]p2:
1032
    //   A name used in a template declaration or definition and that is
1033
    //   dependent on a template-parameter is assumed not to name a type
1034
    //   unless the applicable name lookup finds a type name or the name is
1035
    //   qualified by the keyword typename.
1036
    //
1037
    // FIXME: If the next token is '<', we might want to ask the parser to
1038
    // perform some heroics to see if we actually have a
1039
    // template-argument-list, which would indicate a missing 'template'
1040
    // keyword here.
1041
2.14k
    return NameClassification::DependentNonType();
1042
2.37k
  }
1043
1044
14.4M
  case LookupResult::Found:
1045
14.6M
  case LookupResult::FoundOverloaded:
1046
14.6M
  case LookupResult::FoundUnresolvedValue:
1047
14.6M
    break;
1048
1049
29
  case LookupResult::Ambiguous:
1050
29
    if (getLangOpts().CPlusPlus && 
NextToken.is(tok::less)26
&&
1051
29
        hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1052
0
                                      /*AllowDependent=*/false)) {
1053
      // C++ [temp.local]p3:
1054
      //   A lookup that finds an injected-class-name (10.2) can result in an
1055
      //   ambiguity in certain cases (for example, if it is found in more than
1056
      //   one base class). If all of the injected-class-names that are found
1057
      //   refer to specializations of the same class template, and if the name
1058
      //   is followed by a template-argument-list, the reference refers to the
1059
      //   class template itself and not a specialization thereof, and is not
1060
      //   ambiguous.
1061
      //
1062
      // This filtering can make an ambiguous result into an unambiguous one,
1063
      // so try again after filtering out template names.
1064
0
      FilterAcceptableTemplateNames(Result);
1065
0
      if (!Result.isAmbiguous()) {
1066
0
        IsFilteredTemplateName = true;
1067
0
        break;
1068
0
      }
1069
0
    }
1070
1071
    // Diagnose the ambiguity and return an error.
1072
29
    return NameClassification::Error();
1073
14.6M
  }
1074
1075
14.6M
  if (getLangOpts().CPlusPlus && 
NextToken.is(tok::less)13.6M
&&
1076
14.6M
      
(149
IsFilteredTemplateName149
||
1077
149
       hasAnyAcceptableTemplateNames(
1078
149
           Result, /*AllowFunctionTemplates=*/true,
1079
149
           /*AllowDependent=*/false,
1080
149
           /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1081
149
               
getLangOpts().CPlusPlus20128
))) {
1082
    // C++ [temp.names]p3:
1083
    //   After name lookup (3.4) finds that a name is a template-name or that
1084
    //   an operator-function-id or a literal- operator-id refers to a set of
1085
    //   overloaded functions any member of which is a function template if
1086
    //   this is followed by a <, the < is always taken as the delimiter of a
1087
    //   template-argument-list and never as the less-than operator.
1088
    // C++2a [temp.names]p2:
1089
    //   A name is also considered to refer to a template if it is an
1090
    //   unqualified-id followed by a < and name lookup finds either one
1091
    //   or more functions or finds nothing.
1092
0
    if (!IsFilteredTemplateName)
1093
0
      FilterAcceptableTemplateNames(Result);
1094
1095
0
    bool IsFunctionTemplate;
1096
0
    bool IsVarTemplate;
1097
0
    TemplateName Template;
1098
0
    if (Result.end() - Result.begin() > 1) {
1099
0
      IsFunctionTemplate = true;
1100
0
      Template = Context.getOverloadedTemplateName(Result.begin(),
1101
0
                                                   Result.end());
1102
0
    } else if (!Result.empty()) {
1103
0
      auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1104
0
          *Result.begin(), /*AllowFunctionTemplates=*/true,
1105
0
          /*AllowDependent=*/false));
1106
0
      IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1107
0
      IsVarTemplate = isa<VarTemplateDecl>(TD);
1108
1109
0
      if (SS.isNotEmpty())
1110
0
        Template =
1111
0
            Context.getQualifiedTemplateName(SS.getScopeRep(),
1112
0
                                             /*TemplateKeyword=*/false, TD);
1113
0
      else
1114
0
        Template = TemplateName(TD);
1115
0
    } else {
1116
      // All results were non-template functions. This is a function template
1117
      // name.
1118
0
      IsFunctionTemplate = true;
1119
0
      Template = Context.getAssumedTemplateName(NameInfo.getName());
1120
0
    }
1121
1122
0
    if (IsFunctionTemplate) {
1123
      // Function templates always go through overload resolution, at which
1124
      // point we'll perform the various checks (e.g., accessibility) we need
1125
      // to based on which function we selected.
1126
0
      Result.suppressDiagnostics();
1127
1128
0
      return NameClassification::FunctionTemplate(Template);
1129
0
    }
1130
1131
0
    return IsVarTemplate ? NameClassification::VarTemplate(Template)
1132
0
                         : NameClassification::TypeTemplate(Template);
1133
0
  }
1134
1135
14.6M
  auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1136
12.0M
    QualType T = Context.getTypeDeclType(Type);
1137
12.0M
    if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1138
61.6k
      T = Context.getUsingType(USD, T);
1139
1140
12.0M
    if (SS.isEmpty()) // No elaborated type, trivial location info
1141
12.0M
      return ParsedType::make(T);
1142
1143
219
    TypeLocBuilder Builder;
1144
219
    Builder.pushTypeSpec(T).setNameLoc(NameLoc);
1145
219
    T = getElaboratedType(ETK_None, SS, T);
1146
219
    ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
1147
219
    ElabTL.setElaboratedKeywordLoc(SourceLocation());
1148
219
    ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
1149
219
    return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
1150
12.0M
  };
1151
1152
14.6M
  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1153
14.6M
  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1154
12.0M
    DiagnoseUseOfDecl(Type, NameLoc);
1155
12.0M
    MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1156
12.0M
    return BuildTypeFor(Type, *Result.begin());
1157
12.0M
  }
1158
1159
2.62M
  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1160
2.62M
  if (!Class) {
1161
    // FIXME: It's unfortunate that we don't have a Type node for handling this.
1162
2.61M
    if (ObjCCompatibleAliasDecl *Alias =
1163
2.61M
            dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1164
0
      Class = Alias->getClassInterface();
1165
2.61M
  }
1166
1167
2.62M
  if (Class) {
1168
9.62k
    DiagnoseUseOfDecl(Class, NameLoc);
1169
1170
9.62k
    if (NextToken.is(tok::period)) {
1171
      // Interface. <something> is parsed as a property reference expression.
1172
      // Just return "unknown" as a fall-through for now.
1173
70
      Result.suppressDiagnostics();
1174
70
      return NameClassification::Unknown();
1175
70
    }
1176
1177
9.55k
    QualType T = Context.getObjCInterfaceType(Class);
1178
9.55k
    return ParsedType::make(T);
1179
9.62k
  }
1180
1181
2.61M
  if (isa<ConceptDecl>(FirstDecl))
1182
37
    return NameClassification::Concept(
1183
37
        TemplateName(cast<TemplateDecl>(FirstDecl)));
1184
1185
2.61M
  if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1186
113
    (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1187
113
    return NameClassification::Error();
1188
113
  }
1189
1190
  // We can have a type template here if we're classifying a template argument.
1191
2.61M
  if (isa<TemplateDecl>(FirstDecl) && 
!isa<FunctionTemplateDecl>(FirstDecl)124k
&&
1192
2.61M
      
!isa<VarTemplateDecl>(FirstDecl)9.66k
)
1193
9.66k
    return NameClassification::TypeTemplate(
1194
9.66k
        TemplateName(cast<TemplateDecl>(FirstDecl)));
1195
1196
  // Check for a tag type hidden by a non-type decl in a few cases where it
1197
  // seems likely a type is wanted instead of the non-type that was found.
1198
2.60M
  bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1199
2.60M
  if ((NextToken.is(tok::identifier) ||
1200
2.60M
       
(2.60M
NextIsOp2.60M
&&
1201
2.60M
        
FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate()13.3k
)) &&
1202
2.60M
      
isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)226
) {
1203
32
    TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1204
32
    DiagnoseUseOfDecl(Type, NameLoc);
1205
32
    return BuildTypeFor(Type, *Result.begin());
1206
32
  }
1207
1208
  // If we already know which single declaration is referenced, just annotate
1209
  // that declaration directly. Defer resolving even non-overloaded class
1210
  // member accesses, as we need to defer certain access checks until we know
1211
  // the context.
1212
2.60M
  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1213
2.60M
  if (Result.isSingleResult() && 
!ADL2.43M
&&
!FirstDecl->isCXXClassMember()2.22M
)
1214
1.91M
    return NameClassification::NonType(Result.getRepresentativeDecl());
1215
1216
  // Otherwise, this is an overload set that we will need to resolve later.
1217
688k
  Result.suppressDiagnostics();
1218
688k
  return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1219
688k
      Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1220
688k
      Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1221
688k
      Result.begin(), Result.end()));
1222
2.60M
}
1223
1224
ExprResult
1225
Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1226
608
                                             SourceLocation NameLoc) {
1227
608
  assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1228
0
  CXXScopeSpec SS;
1229
608
  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1230
608
  return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1231
608
}
1232
1233
ExprResult
1234
Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1235
                                            IdentifierInfo *Name,
1236
                                            SourceLocation NameLoc,
1237
2.14k
                                            bool IsAddressOfOperand) {
1238
2.14k
  DeclarationNameInfo NameInfo(Name, NameLoc);
1239
2.14k
  return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1240
2.14k
                                    NameInfo, IsAddressOfOperand,
1241
2.14k
                                    /*TemplateArgs=*/nullptr);
1242
2.14k
}
1243
1244
ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1245
                                              NamedDecl *Found,
1246
                                              SourceLocation NameLoc,
1247
1.91M
                                              const Token &NextToken) {
1248
1.91M
  if (getCurMethodDecl() && 
SS.isEmpty()3.59k
)
1249
3.59k
    if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1250
906
      return BuildIvarRefExpr(S, NameLoc, Ivar);
1251
1252
  // Reconstruct the lookup result.
1253
1.91M
  LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1254
1.91M
  Result.addDecl(Found);
1255
1.91M
  Result.resolveKind();
1256
1257
1.91M
  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1258
1.91M
  return BuildDeclarationNameExpr(SS, Result, ADL);
1259
1.91M
}
1260
1261
688k
ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1262
  // For an implicit class member access, transform the result into a member
1263
  // access expression if necessary.
1264
688k
  auto *ULE = cast<UnresolvedLookupExpr>(E);
1265
688k
  if ((*ULE->decls_begin())->isCXXClassMember()) {
1266
359k
    CXXScopeSpec SS;
1267
359k
    SS.Adopt(ULE->getQualifierLoc());
1268
1269
    // Reconstruct the lookup result.
1270
359k
    LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1271
359k
                        LookupOrdinaryName);
1272
359k
    Result.setNamingClass(ULE->getNamingClass());
1273
829k
    for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; 
++I469k
)
1274
469k
      Result.addDecl(*I, I.getAccess());
1275
359k
    Result.resolveKind();
1276
359k
    return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1277
359k
                                           nullptr, S);
1278
359k
  }
1279
1280
  // Otherwise, this is already in the form we needed, and no further checks
1281
  // are necessary.
1282
328k
  return ULE;
1283
688k
}
1284
1285
Sema::TemplateNameKindForDiagnostics
1286
1.42k
Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1287
1.42k
  auto *TD = Name.getAsTemplateDecl();
1288
1.42k
  if (!TD)
1289
116
    return TemplateNameKindForDiagnostics::DependentTemplate;
1290
1.31k
  if (isa<ClassTemplateDecl>(TD))
1291
279
    return TemplateNameKindForDiagnostics::ClassTemplate;
1292
1.03k
  if (isa<FunctionTemplateDecl>(TD))
1293
969
    return TemplateNameKindForDiagnostics::FunctionTemplate;
1294
63
  if (isa<VarTemplateDecl>(TD))
1295
23
    return TemplateNameKindForDiagnostics::VarTemplate;
1296
40
  if (isa<TypeAliasTemplateDecl>(TD))
1297
28
    return TemplateNameKindForDiagnostics::AliasTemplate;
1298
12
  if (isa<TemplateTemplateParmDecl>(TD))
1299
11
    return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1300
1
  if (isa<ConceptDecl>(TD))
1301
1
    return TemplateNameKindForDiagnostics::Concept;
1302
0
  return TemplateNameKindForDiagnostics::DependentTemplate;
1303
1
}
1304
1305
5.95M
void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1306
5.95M
  assert(DC->getLexicalParent() == CurContext &&
1307
5.95M
      "The next DeclContext should be lexically contained in the current one.");
1308
0
  CurContext = DC;
1309
5.95M
  S->setEntity(DC);
1310
5.95M
}
1311
1312
8.04M
void Sema::PopDeclContext() {
1313
8.04M
  assert(CurContext && "DeclContext imbalance!");
1314
1315
0
  CurContext = CurContext->getLexicalParent();
1316
8.04M
  assert(CurContext && "Popped translation unit!");
1317
8.04M
}
1318
1319
Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1320
47
                                                                    Decl *D) {
1321
  // Unlike PushDeclContext, the context to which we return is not necessarily
1322
  // the containing DC of TD, because the new context will be some pre-existing
1323
  // TagDecl definition instead of a fresh one.
1324
47
  auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1325
47
  CurContext = cast<TagDecl>(D)->getDefinition();
1326
47
  assert(CurContext && "skipping definition of undefined tag");
1327
  // Start lookups from the parent of the current context; we don't want to look
1328
  // into the pre-existing complete definition.
1329
0
  S->setEntity(CurContext->getLookupParent());
1330
47
  return Result;
1331
47
}
1332
1333
47
void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1334
47
  CurContext = static_cast<decltype(CurContext)>(Context);
1335
47
}
1336
1337
/// EnterDeclaratorContext - Used when we must lookup names in the context
1338
/// of a declarator's nested name specifier.
1339
///
1340
255k
void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1341
  // C++0x [basic.lookup.unqual]p13:
1342
  //   A name used in the definition of a static data member of class
1343
  //   X (after the qualified-id of the static member) is looked up as
1344
  //   if the name was used in a member function of X.
1345
  // C++0x [basic.lookup.unqual]p14:
1346
  //   If a variable member of a namespace is defined outside of the
1347
  //   scope of its namespace then any name used in the definition of
1348
  //   the variable member (after the declarator-id) is looked up as
1349
  //   if the definition of the variable member occurred in its
1350
  //   namespace.
1351
  // Both of these imply that we should push a scope whose context
1352
  // is the semantic context of the declaration.  We can't use
1353
  // PushDeclContext here because that context is not necessarily
1354
  // lexically contained in the current context.  Fortunately,
1355
  // the containing scope should have the appropriate information.
1356
1357
255k
  assert(!S->getEntity() && "scope already has entity");
1358
1359
0
#ifndef NDEBUG
1360
0
  Scope *Ancestor = S->getParent();
1361
491k
  while (!Ancestor->getEntity()) 
Ancestor = Ancestor->getParent()235k
;
1362
255k
  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1363
0
#endif
1364
1365
0
  CurContext = DC;
1366
255k
  S->setEntity(DC);
1367
1368
255k
  if (S->getParent()->isTemplateParamScope()) {
1369
    // Also set the corresponding entities for all immediately-enclosing
1370
    // template parameter scopes.
1371
200k
    EnterTemplatedContext(S->getParent(), DC);
1372
200k
  }
1373
255k
}
1374
1375
255k
void Sema::ExitDeclaratorContext(Scope *S) {
1376
255k
  assert(S->getEntity() == CurContext && "Context imbalance!");
1377
1378
  // Switch back to the lexical context.  The safety of this is
1379
  // enforced by an assert in EnterDeclaratorContext.
1380
0
  Scope *Ancestor = S->getParent();
1381
491k
  while (!Ancestor->getEntity()) 
Ancestor = Ancestor->getParent()235k
;
1382
255k
  CurContext = Ancestor->getEntity();
1383
1384
  // We don't need to do anything with the scope, which is going to
1385
  // disappear.
1386
255k
}
1387
1388
341k
void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1389
341k
  assert(S->isTemplateParamScope() &&
1390
341k
         "expected to be initializing a template parameter scope");
1391
1392
  // C++20 [temp.local]p7:
1393
  //   In the definition of a member of a class template that appears outside
1394
  //   of the class template definition, the name of a member of the class
1395
  //   template hides the name of a template-parameter of any enclosing class
1396
  //   templates (but not a template-parameter of the member if the member is a
1397
  //   class or function template).
1398
  // C++20 [temp.local]p9:
1399
  //   In the definition of a class template or in the definition of a member
1400
  //   of such a template that appears outside of the template definition, for
1401
  //   each non-dependent base class (13.8.2.1), if the name of the base class
1402
  //   or the name of a member of the base class is the same as the name of a
1403
  //   template-parameter, the base class name or member name hides the
1404
  //   template-parameter name (6.4.10).
1405
  //
1406
  // This means that a template parameter scope should be searched immediately
1407
  // after searching the DeclContext for which it is a template parameter
1408
  // scope. For example, for
1409
  //   template<typename T> template<typename U> template<typename V>
1410
  //     void N::A<T>::B<U>::f(...)
1411
  // we search V then B<U> (and base classes) then U then A<T> (and base
1412
  // classes) then T then N then ::.
1413
0
  unsigned ScopeDepth = getTemplateDepth(S);
1414
716k
  for (; S && S->isTemplateParamScope(); 
S = S->getParent(), --ScopeDepth375k
) {
1415
375k
    DeclContext *SearchDCAfterScope = DC;
1416
390k
    for (; DC; 
DC = DC->getLookupParent()14.3k
) {
1417
386k
      if (const TemplateParameterList *TPL =
1418
386k
              cast<Decl>(DC)->getDescribedTemplateParams()) {
1419
372k
        unsigned DCDepth = TPL->getDepth() + 1;
1420
372k
        if (DCDepth > ScopeDepth)
1421
0
          continue;
1422
372k
        if (ScopeDepth == DCDepth)
1423
337k
          SearchDCAfterScope = DC = DC->getLookupParent();
1424
372k
        break;
1425
372k
      }
1426
386k
    }
1427
375k
    S->setLookupEntity(SearchDCAfterScope);
1428
375k
  }
1429
341k
}
1430
1431
8.06k
void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1432
  // We assume that the caller has already called
1433
  // ActOnReenterTemplateScope so getTemplatedDecl() works.
1434
8.06k
  FunctionDecl *FD = D->getAsFunction();
1435
8.06k
  if (!FD)
1436
0
    return;
1437
1438
  // Same implementation as PushDeclContext, but enters the context
1439
  // from the lexical parent, rather than the top-level class.
1440
8.06k
  assert(CurContext == FD->getLexicalParent() &&
1441
8.06k
    "The next DeclContext should be lexically contained in the current one.");
1442
0
  CurContext = FD;
1443
8.06k
  S->setEntity(CurContext);
1444
1445
19.8k
  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; 
++P11.8k
) {
1446
11.8k
    ParmVarDecl *Param = FD->getParamDecl(P);
1447
    // If the parameter has an identifier, then add it to the scope
1448
11.8k
    if (Param->getIdentifier()) {
1449
11.7k
      S->AddDecl(Param);
1450
11.7k
      IdResolver.AddDecl(Param);
1451
11.7k
    }
1452
11.8k
  }
1453
8.06k
}
1454
1455
8.06k
void Sema::ActOnExitFunctionContext() {
1456
  // Same implementation as PopDeclContext, but returns to the lexical parent,
1457
  // rather than the top-level class.
1458
8.06k
  assert(CurContext && "DeclContext imbalance!");
1459
0
  CurContext = CurContext->getLexicalParent();
1460
8.06k
  assert(CurContext && "Popped translation unit!");
1461
8.06k
}
1462
1463
/// Determine whether we allow overloading of the function
1464
/// PrevDecl with another declaration.
1465
///
1466
/// This routine determines whether overloading is possible, not
1467
/// whether some new function is actually an overload. It will return
1468
/// true in C++ (where we can always provide overloads) or, as an
1469
/// extension, in C when the previous function is already an
1470
/// overloaded function declaration or has the "overloadable"
1471
/// attribute.
1472
static bool AllowOverloadingOfFunction(LookupResult &Previous,
1473
                                       ASTContext &Context,
1474
10.8M
                                       const FunctionDecl *New) {
1475
10.8M
  if (Context.getLangOpts().CPlusPlus)
1476
4.67M
    return true;
1477
1478
6.18M
  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1479
5.24M
    return true;
1480
1481
941k
  return Previous.getResultKind() == LookupResult::Found &&
1482
941k
         
(941k
Previous.getFoundDecl()->hasAttr<OverloadableAttr>()941k
||
1483
941k
          
New->hasAttr<OverloadableAttr>()18.0k
);
1484
6.18M
}
1485
1486
/// Add this decl to the scope shadowed decl chains.
1487
49.6M
void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1488
  // Move up the scope chain until we find the nearest enclosing
1489
  // non-transparent context. The declaration will be introduced into this
1490
  // scope.
1491
58.4M
  while (S->getEntity() && 
S->getEntity()->isTransparentContext()58.0M
)
1492
8.79M
    S = S->getParent();
1493
1494
  // Add scoped declarations into their context, so that they can be
1495
  // found later. Declarations without a context won't be inserted
1496
  // into any context.
1497
49.6M
  if (AddToContext)
1498
49.2M
    CurContext->addDecl(D);
1499
1500
  // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1501
  // are function-local declarations.
1502
49.6M
  if (getLangOpts().CPlusPlus && 
D->isOutOfLine()19.4M
&&
!S->getFnParent()221k
)
1503
219k
    return;
1504
1505
  // Template instantiations should also not be pushed into scope.
1506
49.4M
  if (isa<FunctionDecl>(D) &&
1507
49.4M
      
cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()28.1M
)
1508
1.50k
    return;
1509
1510
  // If this replaces anything in the current scope,
1511
49.4M
  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1512
49.4M
                               IEnd = IdResolver.end();
1513
116M
  for (; I != IEnd; 
++I66.6M
) {
1514
67.0M
    if (S->isDeclScope(*I) && 
D->declarationReplaces(*I)65.2M
) {
1515
413k
      S->RemoveDecl(*I);
1516
413k
      IdResolver.RemoveDecl(*I);
1517
1518
      // Should only need to replace one decl.
1519
413k
      break;
1520
413k
    }
1521
67.0M
  }
1522
1523
49.4M
  S->AddDecl(D);
1524
1525
49.4M
  if (isa<LabelDecl>(D) && 
!cast<LabelDecl>(D)->isGnuLocal()3.49k
) {
1526
    // Implicitly-generated labels may end up getting generated in an order that
1527
    // isn't strictly lexical, which breaks name lookup. Be careful to insert
1528
    // the label at the appropriate place in the identifier chain.
1529
3.50k
    for (I = IdResolver.begin(D->getDeclName()); I != IEnd; 
++I17
) {
1530
312
      DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1531
312
      if (IDC == CurContext) {
1532
17
        if (!S->isDeclScope(*I))
1533
3
          continue;
1534
295
      } else if (IDC->Encloses(CurContext))
1535
295
        break;
1536
312
    }
1537
1538
3.48k
    IdResolver.InsertDeclAfter(I, D);
1539
49.4M
  } else {
1540
49.4M
    IdResolver.AddDecl(D);
1541
49.4M
  }
1542
49.4M
  warnOnReservedIdentifier(D);
1543
49.4M
}
1544
1545
bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1546
66.7M
                         bool AllowInlineNamespace) {
1547
66.7M
  return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1548
66.7M
}
1549
1550
37.2k
Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1551
37.2k
  DeclContext *TargetDC = DC->getPrimaryContext();
1552
107k
  do {
1553
107k
    if (DeclContext *ScopeDC = S->getEntity())
1554
77.5k
      if (ScopeDC->getPrimaryContext() == TargetDC)
1555
36.4k
        return S;
1556
107k
  } while (
(S = S->getParent())71.5k
);
1557
1558
796
  return nullptr;
1559
37.2k
}
1560
1561
static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1562
                                            DeclContext*,
1563
                                            ASTContext&);
1564
1565
/// Filters out lookup results that don't fall within the given scope
1566
/// as determined by isDeclInScope.
1567
void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1568
                                bool ConsiderLinkage,
1569
32.6M
                                bool AllowInlineNamespace) {
1570
32.6M
  LookupResult::Filter F = R.makeFilter();
1571
99.0M
  while (F.hasNext()) {
1572
66.3M
    NamedDecl *D = F.next();
1573
1574
66.3M
    if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1575
66.0M
      continue;
1576
1577
304k
    if (ConsiderLinkage && 
isOutOfScopePreviousDeclaration(D, Ctx, Context)1.14k
)
1578
515
      continue;
1579
1580
304k
    F.erase();
1581
304k
  }
1582
1583
32.6M
  F.done();
1584
32.6M
}
1585
1586
/// We've determined that \p New is a redeclaration of \p Old. Check that they
1587
/// have compatible owning modules.
1588
409k
bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1589
  // FIXME: The Modules TS is not clear about how friend declarations are
1590
  // to be treated. It's not meaningful to have different owning modules for
1591
  // linkage in redeclarations of the same entity, so for now allow the
1592
  // redeclaration and change the owning modules to match.
1593
409k
  if (New->getFriendObjectKind() &&
1594
409k
      
Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()20.0k
) {
1595
0
    New->setLocalOwningModule(Old->getOwningModule());
1596
0
    makeMergedDefinitionVisible(New);
1597
0
    return false;
1598
0
  }
1599
1600
409k
  Module *NewM = New->getOwningModule();
1601
409k
  Module *OldM = Old->getOwningModule();
1602
1603
409k
  if (NewM && 
NewM->Kind == Module::PrivateModuleFragment32.8k
)
1604
3
    NewM = NewM->Parent;
1605
409k
  if (OldM && 
OldM->Kind == Module::PrivateModuleFragment34.6k
)
1606
0
    OldM = OldM->Parent;
1607
1608
409k
  if (NewM == OldM)
1609
400k
    return false;
1610
1611
9.31k
  bool NewIsModuleInterface = NewM && 
NewM->isModulePurview()7.48k
;
1612
9.31k
  bool OldIsModuleInterface = OldM && 
OldM->isModulePurview()9.30k
;
1613
9.31k
  if (NewIsModuleInterface || 
OldIsModuleInterface9.26k
) {
1614
    // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1615
    //   if a declaration of D [...] appears in the purview of a module, all
1616
    //   other such declarations shall appear in the purview of the same module
1617
54
    Diag(New->getLocation(), diag::err_mismatched_owning_module)
1618
54
      << New
1619
54
      << NewIsModuleInterface
1620
54
      << (NewIsModuleInterface ? 
NewM->getFullModuleName()47
:
""7
)
1621
54
      << OldIsModuleInterface
1622
54
      << (OldIsModuleInterface ? 
OldM->getFullModuleName()28
:
""26
);
1623
54
    Diag(Old->getLocation(), diag::note_previous_declaration);
1624
54
    New->setInvalidDecl();
1625
54
    return true;
1626
54
  }
1627
1628
9.26k
  return false;
1629
9.31k
}
1630
1631
790k
static bool isUsingDecl(NamedDecl *D) {
1632
790k
  return isa<UsingShadowDecl>(D) ||
1633
790k
         
isa<UnresolvedUsingTypenameDecl>(D)790k
||
1634
790k
         
isa<UnresolvedUsingValueDecl>(D)790k
;
1635
790k
}
1636
1637
/// Removes using shadow declarations from the lookup results.
1638
195k
static void RemoveUsingDecls(LookupResult &R) {
1639
195k
  LookupResult::Filter F = R.makeFilter();
1640
986k
  while (F.hasNext())
1641
790k
    if (isUsingDecl(F.next()))
1642
8
      F.erase();
1643
1644
195k
  F.done();
1645
195k
}
1646
1647
/// Check for this common pattern:
1648
/// @code
1649
/// class S {
1650
///   S(const S&); // DO NOT IMPLEMENT
1651
///   void operator=(const S&); // DO NOT IMPLEMENT
1652
/// };
1653
/// @endcode
1654
323k
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1655
  // FIXME: Should check for private access too but access is set after we get
1656
  // the decl here.
1657
323k
  if (D->doesThisDeclarationHaveABody())
1658
558
    return false;
1659
1660
322k
  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1661
86.8k
    return CD->isCopyConstructor();
1662
235k
  return D->isCopyAssignmentOperator();
1663
322k
}
1664
1665
// We need this to handle
1666
//
1667
// typedef struct {
1668
//   void *foo() { return 0; }
1669
// } A;
1670
//
1671
// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1672
// for example. If 'A', foo will have external linkage. If we have '*A',
1673
// foo will have no linkage. Since we can't know until we get to the end
1674
// of the typedef, this function finds out if D might have non-external linkage.
1675
// Callers should verify at the end of the TU if it D has external linkage or
1676
// not.
1677
4.18M
bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1678
4.18M
  const DeclContext *DC = D->getDeclContext();
1679
6.75M
  while (!DC->isTranslationUnit()) {
1680
2.57M
    if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1681
441k
      if (!RD->hasNameForLinkage())
1682
749
        return true;
1683
441k
    }
1684
2.57M
    DC = DC->getParent();
1685
2.57M
  }
1686
1687
4.18M
  return !D->isExternallyVisible();
1688
4.18M
}
1689
1690
// FIXME: This needs to be refactored; some other isInMainFile users want
1691
// these semantics.
1692
25.2M
static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1693
25.2M
  if (S.TUKind != TU_Complete)
1694
108k
    return false;
1695
25.1M
  return S.SourceMgr.isInMainFile(Loc);
1696
25.2M
}
1697
1698
29.5M
bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1699
29.5M
  assert(D);
1700
1701
29.5M
  if (D->isInvalidDecl() || 
D->isUsed()29.5M
||
D->hasAttr<UnusedAttr>()29.5M
)
1702
12.8k
    return false;
1703
1704
  // Ignore all entities declared within templates, and out-of-line definitions
1705
  // of members of class templates.
1706
29.5M
  if (D->getDeclContext()->isDependentContext() ||
1707
29.5M
      
D->getLexicalDeclContext()->isDependentContext()28.3M
)
1708
1.17M
    return false;
1709
1710
28.3M
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1711
27.2M
    if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1712
2.75k
      return false;
1713
    // A non-out-of-line declaration of a member specialization was implicitly
1714
    // instantiated; it's the out-of-line declaration that we're interested in.
1715
27.2M
    if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1716
27.2M
        
FD->getMemberSpecializationInfo()9.02k
&&
!FD->isOutOfLine()2.64k
)
1717
43
      return false;
1718
1719
27.2M
    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1720
361k
      if (MD->isVirtual() || 
IsDisallowedCopyOrAssign(MD)323k
)
1721
67.3k
        return false;
1722
26.8M
    } else {
1723
      // 'static inline' functions are defined in headers; don't warn.
1724
26.8M
      if (FD->isInlined() && 
!isMainFileLoc(*this, FD->getLocation())24.2M
)
1725
24.2M
        return false;
1726
26.8M
    }
1727
1728
2.97M
    if (FD->doesThisDeclarationHaveABody() &&
1729
2.97M
        
Context.DeclMustBeEmitted(FD)13.7k
)
1730
205
      return false;
1731
2.97M
  } else 
if (const VarDecl *1.08M
VD1.08M
= dyn_cast<VarDecl>(D)) {
1732
    // Constants and utility variables are defined in headers with internal
1733
    // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1734
    // like "inline".)
1735
1.08M
    if (!isMainFileLoc(*this, VD->getLocation()))
1736
998k
      return false;
1737
1738
89.7k
    if (Context.DeclMustBeEmitted(VD))
1739
56.9k
      return false;
1740
1741
32.8k
    if (VD->isStaticDataMember() &&
1742
32.8k
        
VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation5.88k
)
1743
0
      return false;
1744
32.8k
    if (VD->isStaticDataMember() &&
1745
32.8k
        
VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization5.88k
&&
1746
32.8k
        
VD->getMemberSpecializationInfo()237
&&
!VD->isOutOfLine()161
)
1747
114
      return false;
1748
1749
32.6k
    if (VD->isInline() && 
!isMainFileLoc(*this, VD->getLocation())246
)
1750
0
      return false;
1751
32.6k
  } else {
1752
0
    return false;
1753
0
  }
1754
1755
  // Only warn for unused decls internal to the translation unit.
1756
  // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1757
  // for inline functions defined in the main source file, for instance.
1758
3.01M
  return mightHaveNonExternalLinkage(D);
1759
28.3M
}
1760
1761
29.2M
void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1762
29.2M
  if (!D)
1763
0
    return;
1764
1765
29.2M
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1766
27.9M
    const FunctionDecl *First = FD->getFirstDecl();
1767
27.9M
    if (FD != First && 
ShouldWarnIfUnusedFileScopedDecl(First)221k
)
1768
365
      return; // First should already be in the vector.
1769
27.9M
  }
1770
1771
29.2M
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1772
1.25M
    const VarDecl *First = VD->getFirstDecl();
1773
1.25M
    if (VD != First && 
ShouldWarnIfUnusedFileScopedDecl(First)50.6k
)
1774
104
      return; // First should already be in the vector.
1775
1.25M
  }
1776
1777
29.2M
  if (ShouldWarnIfUnusedFileScopedDecl(D))
1778
24.3k
    UnusedFileScopedDecls.push_back(D);
1779
29.2M
}
1780
1781
92.1M
static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1782
92.1M
  if (D->isInvalidDecl())
1783
541
    return false;
1784
1785
92.1M
  if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1786
    // For a decomposition declaration, warn if none of the bindings are
1787
    // referenced, instead of if the variable itself is referenced (which
1788
    // it is, by the bindings' expressions).
1789
214
    for (auto *BD : DD->bindings())
1790
309
      if (BD->isReferenced())
1791
121
        return false;
1792
92.1M
  } else if (!D->getDeclName()) {
1793
64.0M
    return false;
1794
64.0M
  } else 
if (28.1M
D->isReferenced()28.1M
||
D->isUsed()18.2M
) {
1795
9.89M
    return false;
1796
9.89M
  }
1797
1798
18.2M
  if (D->hasAttr<UnusedAttr>() || 
D->hasAttr<ObjCPreciseLifetimeAttr>()18.2M
)
1799
747
    return false;
1800
1801
18.2M
  if (isa<LabelDecl>(D))
1802
236
    return true;
1803
1804
  // Except for labels, we only care about unused decls that are local to
1805
  // functions.
1806
18.2M
  bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1807
18.2M
  if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1808
    // For dependent types, the diagnostic is deferred.
1809
3.13M
    WithinFunction =
1810
3.13M
        WithinFunction || (R->isLocalClass() && 
!R->isDependentType()44.0k
);
1811
18.2M
  if (!WithinFunction)
1812
16.8M
    return false;
1813
1814
1.35M
  if (isa<TypedefNameDecl>(D))
1815
600
    return true;
1816
1817
  // White-list anything that isn't a local variable.
1818
1.35M
  if (!isa<VarDecl>(D) || 
isa<ParmVarDecl>(D)1.19M
||
isa<ImplicitParamDecl>(D)54.2k
)
1819
1.30M
    return false;
1820
1821
  // Types of valid local variables should be complete, so this should succeed.
1822
43.0k
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1823
1824
    // White-list anything with an __attribute__((unused)) type.
1825
43.0k
    const auto *Ty = VD->getType().getTypePtr();
1826
1827
    // Only look at the outermost level of typedef.
1828
43.0k
    if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1829
3.80k
      if (TT->getDecl()->hasAttr<UnusedAttr>())
1830
5
        return false;
1831
3.80k
    }
1832
1833
    // If we failed to complete the type for some reason, or if the type is
1834
    // dependent, don't diagnose the variable.
1835
43.0k
    if (Ty->isIncompleteType() || 
Ty->isDependentType()42.8k
)
1836
6.01k
      return false;
1837
1838
    // Look at the element type to ensure that the warning behaviour is
1839
    // consistent for both scalars and arrays.
1840
36.9k
    Ty = Ty->getBaseElementTypeUnsafe();
1841
1842
36.9k
    if (const TagType *TT = Ty->getAs<TagType>()) {
1843
10.7k
      const TagDecl *Tag = TT->getDecl();
1844
10.7k
      if (Tag->hasAttr<UnusedAttr>())
1845
4
        return false;
1846
1847
10.7k
      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1848
9.68k
        if (!RD->hasTrivialDestructor() && 
!RD->hasAttr<WarnUnusedAttr>()3.11k
)
1849
3.11k
          return false;
1850
1851
6.56k
        if (const Expr *Init = VD->getInit()) {
1852
6.55k
          if (const ExprWithCleanups *Cleanups =
1853
6.55k
                  dyn_cast<ExprWithCleanups>(Init))
1854
1.77k
            Init = Cleanups->getSubExpr();
1855
6.55k
          const CXXConstructExpr *Construct =
1856
6.55k
            dyn_cast<CXXConstructExpr>(Init);
1857
6.55k
          if (Construct && 
!Construct->isElidable()5.45k
) {
1858
3.97k
            CXXConstructorDecl *CD = Construct->getConstructor();
1859
3.97k
            if (!CD->isTrivial() && 
!RD->hasAttr<WarnUnusedAttr>()2.25k
&&
1860
3.97k
                
(2.25k
VD->getInit()->isValueDependent()2.25k
||
!VD->evaluateValue()2.25k
))
1861
2.10k
              return false;
1862
3.97k
          }
1863
1864
          // Suppress the warning if we don't know how this is constructed, and
1865
          // it could possibly be non-trivial constructor.
1866
4.45k
          if (Init->isTypeDependent())
1867
77
            for (const CXXConstructorDecl *Ctor : RD->ctors())
1868
74
              if (!Ctor->isTrivial())
1869
18
                return false;
1870
4.45k
        }
1871
6.56k
      }
1872
10.7k
    }
1873
1874
    // TODO: __attribute__((unused)) templates?
1875
36.9k
  }
1876
1877
31.7k
  return true;
1878
43.0k
}
1879
1880
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1881
31.9k
                                     FixItHint &Hint) {
1882
31.9k
  if (isa<LabelDecl>(D)) {
1883
236
    SourceLocation AfterColon = Lexer::findLocationAfterToken(
1884
236
        D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1885
236
        true);
1886
236
    if (AfterColon.isInvalid())
1887
8
      return;
1888
228
    Hint = FixItHint::CreateRemoval(
1889
228
        CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1890
228
  }
1891
31.9k
}
1892
1893
1.61M
void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1894
1.61M
  if (D->getTypeForDecl()->isDependentType())
1895
395k
    return;
1896
1897
1.21M
  for (auto *TmpD : D->decls()) {
1898
496k
    if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1899
13.8k
      DiagnoseUnusedDecl(T);
1900
482k
    else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1901
73.9k
      DiagnoseUnusedNestedTypedefs(R);
1902
496k
  }
1903
1.21M
}
1904
1905
/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1906
/// unless they are marked attr(unused).
1907
92.1M
void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1908
92.1M
  if (!ShouldDiagnoseUnusedDecl(D))
1909
92.1M
    return;
1910
1911
32.5k
  if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1912
    // typedefs can be referenced later on, so the diagnostics are emitted
1913
    // at end-of-translation-unit.
1914
600
    UnusedLocalTypedefNameCandidates.insert(TD);
1915
600
    return;
1916
600
  }
1917
1918
31.9k
  FixItHint Hint;
1919
31.9k
  GenerateFixForUnusedDecl(D, Context, Hint);
1920
1921
31.9k
  unsigned DiagID;
1922
31.9k
  if (isa<VarDecl>(D) && 
cast<VarDecl>(D)->isExceptionVariable()31.7k
)
1923
364
    DiagID = diag::warn_unused_exception_param;
1924
31.6k
  else if (isa<LabelDecl>(D))
1925
236
    DiagID = diag::warn_unused_label;
1926
31.3k
  else
1927
31.3k
    DiagID = diag::warn_unused_variable;
1928
1929
31.9k
  Diag(D->getLocation(), DiagID) << D << Hint;
1930
31.9k
}
1931
1932
82.9M
void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
1933
  // If it's not referenced, it can't be set. If it has the Cleanup attribute,
1934
  // it's not really unused.
1935
82.9M
  if (!VD->isReferenced() || 
!VD->getDeclName()7.16M
||
VD->hasAttr<UnusedAttr>()7.16M
||
1936
82.9M
      
VD->hasAttr<CleanupAttr>()7.16M
)
1937
75.8M
    return;
1938
1939
7.16M
  const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
1940
1941
7.16M
  if (Ty->isReferenceType() || 
Ty->isDependentType()6.60M
)
1942
1.70M
    return;
1943
1944
5.46M
  if (const TagType *TT = Ty->getAs<TagType>()) {
1945
161k
    const TagDecl *Tag = TT->getDecl();
1946
161k
    if (Tag->hasAttr<UnusedAttr>())
1947
0
      return;
1948
    // In C++, don't warn for record types that don't have WarnUnusedAttr, to
1949
    // mimic gcc's behavior.
1950
161k
    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1951
62.9k
      if (!RD->hasAttr<WarnUnusedAttr>())
1952
62.9k
        return;
1953
62.9k
    }
1954
161k
  }
1955
1956
  // Don't warn about __block Objective-C pointer variables, as they might
1957
  // be assigned in the block but not used elsewhere for the purpose of lifetime
1958
  // extension.
1959
5.39M
  if (VD->hasAttr<BlocksAttr>() && 
Ty->isObjCObjectPointerType()350
)
1960
80
    return;
1961
1962
5.39M
  auto iter = RefsMinusAssignments.find(VD);
1963
5.39M
  if (iter == RefsMinusAssignments.end())
1964
35.1k
    return;
1965
1966
5.36M
  assert(iter->getSecond() >= 0 &&
1967
5.36M
         "Found a negative number of references to a VarDecl");
1968
5.36M
  if (iter->getSecond() != 0)
1969
5.36M
    return;
1970
3.20k
  unsigned DiagID = isa<ParmVarDecl>(VD) ? 
diag::warn_unused_but_set_parameter744
1971
3.20k
                                         : 
diag::warn_unused_but_set_variable2.46k
;
1972
3.20k
  Diag(VD->getLocation(), DiagID) << VD;
1973
3.20k
}
1974
1975
3.49k
static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1976
  // Verify that we have no forward references left.  If so, there was a goto
1977
  // or address of a label taken, but no definition of it.  Label fwd
1978
  // definitions are indicated with a null substmt which is also not a resolved
1979
  // MS inline assembly label name.
1980
3.49k
  bool Diagnose = false;
1981
3.49k
  if (L->isMSAsmLabel())
1982
28
    Diagnose = !L->isResolvedMSAsmLabel();
1983
3.46k
  else
1984
3.46k
    Diagnose = L->getStmt() == nullptr;
1985
3.49k
  if (Diagnose)
1986
358
    S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1987
3.49k
}
1988
1989
38.4M
void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1990
38.4M
  S->mergeNRVOIntoParent();
1991
1992
38.4M
  if (S->decl_empty()) 
return4.10M
;
1993
34.3M
  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1994
34.3M
         "Scope shouldn't contain decls!");
1995
1996
92.2M
  for (auto *TmpD : S->decls()) {
1997
92.2M
    assert(TmpD && "This decl didn't get pushed??");
1998
1999
0
    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2000
0
    NamedDecl *D = cast<NamedDecl>(TmpD);
2001
2002
    // Diagnose unused variables in this scope.
2003
92.2M
    if (!S->hasUnrecoverableErrorOccurred()) {
2004
92.0M
      DiagnoseUnusedDecl(D);
2005
92.0M
      if (const auto *RD = dyn_cast<RecordDecl>(D))
2006
761k
        DiagnoseUnusedNestedTypedefs(RD);
2007
92.0M
      if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2008
82.9M
        DiagnoseUnusedButSetDecl(VD);
2009
82.9M
        RefsMinusAssignments.erase(VD);
2010
82.9M
      }
2011
92.0M
    }
2012
2013
92.2M
    if (!D->getDeclName()) 
continue64.0M
;
2014
2015
    // If this was a forward reference to a label, verify it was defined.
2016
28.1M
    if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2017
3.49k
      CheckPoppedLabel(LD, *this);
2018
2019
    // Remove this name from our lexical scope, and warn on it if we haven't
2020
    // already.
2021
28.1M
    IdResolver.RemoveDecl(D);
2022
28.1M
    auto ShadowI = ShadowingDecls.find(D);
2023
28.1M
    if (ShadowI != ShadowingDecls.end()) {
2024
4
      if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2025
4
        Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2026
4
            << D << FD << FD->getParent();
2027
4
        Diag(FD->getLocation(), diag::note_previous_declaration);
2028
4
      }
2029
4
      ShadowingDecls.erase(ShadowI);
2030
4
    }
2031
28.1M
  }
2032
34.3M
}
2033
2034
/// Look for an Objective-C class in the translation unit.
2035
///
2036
/// \param Id The name of the Objective-C class we're looking for. If
2037
/// typo-correction fixes this name, the Id will be updated
2038
/// to the fixed name.
2039
///
2040
/// \param IdLoc The location of the name in the translation unit.
2041
///
2042
/// \param DoTypoCorrection If true, this routine will attempt typo correction
2043
/// if there is no class with the given name.
2044
///
2045
/// \returns The declaration of the named Objective-C class, or NULL if the
2046
/// class could not be found.
2047
ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2048
                                              SourceLocation IdLoc,
2049
41.2k
                                              bool DoTypoCorrection) {
2050
  // The third "scope" argument is 0 since we aren't enabling lazy built-in
2051
  // creation from this context.
2052
41.2k
  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2053
2054
41.2k
  if (!IDecl && 
DoTypoCorrection112
) {
2055
    // Perform typo correction at the given location, but only if we
2056
    // find an Objective-C class name.
2057
35
    DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2058
35
    if (TypoCorrection C =
2059
35
            CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2060
35
                        TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2061
1
      diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2062
1
      IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2063
1
      Id = IDecl->getIdentifier();
2064
1
    }
2065
35
  }
2066
41.2k
  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2067
  // This routine must always return a class definition, if any.
2068
41.2k
  if (Def && 
Def->getDefinition()41.1k
)
2069
41.1k
      Def = Def->getDefinition();
2070
41.2k
  return Def;
2071
41.2k
}
2072
2073
/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2074
/// from S, where a non-field would be declared. This routine copes
2075
/// with the difference between C and C++ scoping rules in structs and
2076
/// unions. For example, the following code is well-formed in C but
2077
/// ill-formed in C++:
2078
/// @code
2079
/// struct S6 {
2080
///   enum { BAR } e;
2081
/// };
2082
///
2083
/// void test_S6() {
2084
///   struct S6 a;
2085
///   a.e = BAR;
2086
/// }
2087
/// @endcode
2088
/// For the declaration of BAR, this routine will return a different
2089
/// scope. The scope S will be the scope of the unnamed enumeration
2090
/// within S6. In C++, this routine will return the scope associated
2091
/// with S6, because the enumeration's scope is a transparent
2092
/// context but structures can contain non-field names. In C, this
2093
/// routine will return the translation unit scope, since the
2094
/// enumeration's scope is a transparent context and structures cannot
2095
/// contain non-field names.
2096
5.64M
Scope *Sema::getNonFieldDeclScope(Scope *S) {
2097
10.0M
  while (((S->getFlags() & Scope::DeclScope) == 0) ||
2098
10.0M
         
(10.0M
S->getEntity()10.0M
&&
S->getEntity()->isTransparentContext()10.0M
) ||
2099
10.0M
         
(5.64M
S->isClassScope()5.64M
&&
!getLangOpts().CPlusPlus83.9k
))
2100
4.39M
    S = S->getParent();
2101
5.64M
  return S;
2102
5.64M
}
2103
2104
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2105
5
                               ASTContext::GetBuiltinTypeError Error) {
2106
5
  switch (Error) {
2107
0
  case ASTContext::GE_None:
2108
0
    return "";
2109
0
  case ASTContext::GE_Missing_type:
2110
0
    return BuiltinInfo.getHeaderName(ID);
2111
5
  case ASTContext::GE_Missing_stdio:
2112
5
    return "stdio.h";
2113
0
  case ASTContext::GE_Missing_setjmp:
2114
0
    return "setjmp.h";
2115
0
  case ASTContext::GE_Missing_ucontext:
2116
0
    return "ucontext.h";
2117
5
  }
2118
0
  llvm_unreachable("unhandled error kind");
2119
0
}
2120
2121
FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2122
841k
                                  unsigned ID, SourceLocation Loc) {
2123
841k
  DeclContext *Parent = Context.getTranslationUnitDecl();
2124
2125
841k
  if (getLangOpts().CPlusPlus) {
2126
202k
    LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2127
202k
        Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2128
202k
    CLinkageDecl->setImplicit();
2129
202k
    Parent->addDecl(CLinkageDecl);
2130
202k
    Parent = CLinkageDecl;
2131
202k
  }
2132
2133
841k
  FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2134
841k
                                           /*TInfo=*/nullptr, SC_Extern,
2135
841k
                                           getCurFPFeatures().isFPConstrained(),
2136
841k
                                           false, Type->isFunctionProtoType());
2137
841k
  New->setImplicit();
2138
841k
  New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2139
2140
  // Create Decl objects for each parameter, adding them to the
2141
  // FunctionDecl.
2142
841k
  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2143
839k
    SmallVector<ParmVarDecl *, 16> Params;
2144
2.28M
    for (unsigned i = 0, e = FT->getNumParams(); i != e; 
++i1.44M
) {
2145
1.44M
      ParmVarDecl *parm = ParmVarDecl::Create(
2146
1.44M
          Context, New, SourceLocation(), SourceLocation(), nullptr,
2147
1.44M
          FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2148
1.44M
      parm->setScopeInfo(0, i);
2149
1.44M
      Params.push_back(parm);
2150
1.44M
    }
2151
839k
    New->setParams(Params);
2152
839k
  }
2153
2154
841k
  AddKnownFunctionAttributes(New);
2155
841k
  return New;
2156
841k
}
2157
2158
/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2159
/// file scope.  lazily create a decl for it. ForRedeclaration is true
2160
/// if we're creating this built-in in anticipation of redeclaring the
2161
/// built-in.
2162
NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2163
                                     Scope *S, bool ForRedeclaration,
2164
841k
                                     SourceLocation Loc) {
2165
841k
  LookupNecessaryTypesForBuiltin(S, ID);
2166
2167
841k
  ASTContext::GetBuiltinTypeError Error;
2168
841k
  QualType R = Context.GetBuiltinType(ID, Error);
2169
841k
  if (Error) {
2170
26
    if (!ForRedeclaration)
2171
4
      return nullptr;
2172
2173
    // If we have a builtin without an associated type we should not emit a
2174
    // warning when we were not able to find a type for it.
2175
22
    if (Error == ASTContext::GE_Missing_type ||
2176
22
        
Context.BuiltinInfo.allowTypeMismatch(ID)15
)
2177
17
      return nullptr;
2178
2179
    // If we could not find a type for setjmp it is because the jmp_buf type was
2180
    // not defined prior to the setjmp declaration.
2181
5
    if (Error == ASTContext::GE_Missing_setjmp) {
2182
0
      Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2183
0
          << Context.BuiltinInfo.getName(ID);
2184
0
      return nullptr;
2185
0
    }
2186
2187
    // Generally, we emit a warning that the declaration requires the
2188
    // appropriate header.
2189
5
    Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2190
5
        << getHeaderName(Context.BuiltinInfo, ID, Error)
2191
5
        << Context.BuiltinInfo.getName(ID);
2192
5
    return nullptr;
2193
5
  }
2194
2195
841k
  if (!ForRedeclaration &&
2196
841k
      
(832k
Context.BuiltinInfo.isPredefinedLibFunction(ID)832k
||
2197
832k
       
Context.BuiltinInfo.isHeaderDependentFunction(ID)831k
)) {
2198
1.19k
    Diag(Loc, diag::ext_implicit_lib_function_decl)
2199
1.19k
        << Context.BuiltinInfo.getName(ID) << R;
2200
1.19k
    if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2201
1.19k
      Diag(Loc, diag::note_include_header_or_declare)
2202
1.19k
          << Header << Context.BuiltinInfo.getName(ID);
2203
1.19k
  }
2204
2205
841k
  if (R.isNull())
2206
8
    return nullptr;
2207
2208
841k
  FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2209
841k
  RegisterLocallyScopedExternCDecl(New, S);
2210
2211
  // TUScope is the translation-unit scope to insert this function into.
2212
  // FIXME: This is hideous. We need to teach PushOnScopeChains to
2213
  // relate Scopes to DeclContexts, and probably eliminate CurContext
2214
  // entirely, but we're not there yet.
2215
841k
  DeclContext *SavedContext = CurContext;
2216
841k
  CurContext = New->getDeclContext();
2217
841k
  PushOnScopeChains(New, TUScope);
2218
841k
  CurContext = SavedContext;
2219
841k
  return New;
2220
841k
}
2221
2222
/// Typedef declarations don't have linkage, but they still denote the same
2223
/// entity if their types are the same.
2224
/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2225
/// isSameEntity.
2226
static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2227
                                                     TypedefNameDecl *Decl,
2228
2.18M
                                                     LookupResult &Previous) {
2229
  // This is only interesting when modules are enabled.
2230
2.18M
  if (!S.getLangOpts().Modules && 
!S.getLangOpts().ModulesLocalVisibility2.06M
)
2231
2.06M
    return;
2232
2233
  // Empty sets are uninteresting.
2234
113k
  if (Previous.empty())
2235
107k
    return;
2236
2237
6.78k
  LookupResult::Filter Filter = Previous.makeFilter();
2238
13.5k
  while (Filter.hasNext()) {
2239
6.78k
    NamedDecl *Old = Filter.next();
2240
2241
    // Non-hidden declarations are never ignored.
2242
6.78k
    if (S.isVisible(Old))
2243
6.76k
      continue;
2244
2245
    // Declarations of the same entity are not ignored, even if they have
2246
    // different linkages.
2247
17
    if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2248
16
      if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2249
16
                                Decl->getUnderlyingType()))
2250
5
        continue;
2251
2252
      // If both declarations give a tag declaration a typedef name for linkage
2253
      // purposes, then they declare the same entity.
2254
11
      if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2255
11
          Decl->getAnonDeclWithTypedefName())
2256
11
        continue;
2257
11
    }
2258
2259
1
    Filter.erase();
2260
1
  }
2261
2262
6.78k
  Filter.done();
2263
6.78k
}
2264
2265
33.9k
bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2266
33.9k
  QualType OldType;
2267
33.9k
  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2268
6.37k
    OldType = OldTypedef->getUnderlyingType();
2269
27.5k
  else
2270
27.5k
    OldType = Context.getTypeDeclType(Old);
2271
33.9k
  QualType NewType = New->getUnderlyingType();
2272
2273
33.9k
  if (NewType->isVariablyModifiedType()) {
2274
    // Must not redefine a typedef with a variably-modified type.
2275
2
    int Kind = isa<TypeAliasDecl>(Old) ? 
10
: 0;
2276
2
    Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2277
2
      << Kind << NewType;
2278
2
    if (Old->getLocation().isValid())
2279
2
      notePreviousDefinition(Old, New->getLocation());
2280
2
    New->setInvalidDecl();
2281
2
    return true;
2282
2
  }
2283
2284
33.9k
  if (OldType != NewType &&
2285
33.9k
      
!OldType->isDependentType()31.7k
&&
2286
33.9k
      
!NewType->isDependentType()31.6k
&&
2287
33.9k
      
!Context.hasSameType(OldType, NewType)31.6k
) {
2288
93
    int Kind = isa<TypeAliasDecl>(Old) ? 
145
:
048
;
2289
93
    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2290
93
      << Kind << NewType << OldType;
2291
93
    if (Old->getLocation().isValid())
2292
88
      notePreviousDefinition(Old, New->getLocation());
2293
93
    New->setInvalidDecl();
2294
93
    return true;
2295
93
  }
2296
33.8k
  return false;
2297
33.9k
}
2298
2299
/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2300
/// same name and scope as a previous declaration 'Old'.  Figure out
2301
/// how to resolve this situation, merging decls or emitting
2302
/// diagnostics as appropriate. If there was an error, set New to be invalid.
2303
///
2304
void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2305
34.5k
                                LookupResult &OldDecls) {
2306
  // If the new decl is known invalid already, don't bother doing any
2307
  // merging checks.
2308
34.5k
  if (New->isInvalidDecl()) 
return10
;
2309
2310
  // Allow multiple definitions for ObjC built-in typedefs.
2311
  // FIXME: Verify the underlying types are equivalent!
2312
34.5k
  if (getLangOpts().ObjC) {
2313
22.7k
    const IdentifierInfo *TypeID = New->getIdentifier();
2314
22.7k
    switch (TypeID->getLength()) {
2315
21.5k
    default: break;
2316
21.5k
    case 2:
2317
344
      {
2318
344
        if (!TypeID->isStr("id"))
2319
4
          break;
2320
340
        QualType T = New->getUnderlyingType();
2321
340
        if (!T->isPointerType())
2322
3
          break;
2323
337
        if (!T->isVoidPointerType()) {
2324
332
          QualType PT = T->castAs<PointerType>()->getPointeeType();
2325
332
          if (!PT->isStructureType())
2326
2
            break;
2327
332
        }
2328
335
        Context.setObjCIdRedefinitionType(T);
2329
        // Install the built-in type for 'id', ignoring the current definition.
2330
335
        New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2331
335
        return;
2332
337
      }
2333
469
    case 5:
2334
469
      if (!TypeID->isStr("Class"))
2335
145
        break;
2336
324
      Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2337
      // Install the built-in type for 'Class', ignoring the current definition.
2338
324
      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2339
324
      return;
2340
322
    case 3:
2341
322
      if (!TypeID->isStr("SEL"))
2342
2
        break;
2343
320
      Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2344
      // Install the built-in type for 'SEL', ignoring the current definition.
2345
320
      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2346
320
      return;
2347
22.7k
    }
2348
    // Fall through - the typedef name was not a builtin type.
2349
22.7k
  }
2350
2351
  // Verify the old decl was also a type.
2352
33.5k
  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2353
33.5k
  if (!Old) {
2354
14
    Diag(New->getLocation(), diag::err_redefinition_different_kind)
2355
14
      << New->getDeclName();
2356
2357
14
    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2358
14
    if (OldD->getLocation().isValid())
2359
14
      notePreviousDefinition(OldD, New->getLocation());
2360
2361
14
    return New->setInvalidDecl();
2362
14
  }
2363
2364
  // If the old declaration is invalid, just give up here.
2365
33.5k
  if (Old->isInvalidDecl())
2366
15
    return New->setInvalidDecl();
2367
2368
33.4k
  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2369
5.90k
    auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2370
5.90k
    auto *NewTag = New->getAnonDeclWithTypedefName();
2371
5.90k
    NamedDecl *Hidden = nullptr;
2372
5.90k
    if (OldTag && 
NewTag18
&&
2373
5.90k
        
OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl()12
&&
2374
5.90k
        
!hasVisibleDefinition(OldTag, &Hidden)12
) {
2375
      // There is a definition of this tag, but it is not visible. Use it
2376
      // instead of our tag.
2377
11
      New->setTypeForDecl(OldTD->getTypeForDecl());
2378
11
      if (OldTD->isModed())
2379
0
        New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2380
0
                                    OldTD->getUnderlyingType());
2381
11
      else
2382
11
        New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2383
2384
      // Make the old tag definition visible.
2385
11
      makeMergedDefinitionVisible(Hidden);
2386
2387
      // If this was an unscoped enumeration, yank all of its enumerators
2388
      // out of the scope.
2389
11
      if (isa<EnumDecl>(NewTag)) {
2390
5
        Scope *EnumScope = getNonFieldDeclScope(S);
2391
5
        for (auto *D : NewTag->decls()) {
2392
0
          auto *ED = cast<EnumConstantDecl>(D);
2393
0
          assert(EnumScope->isDeclScope(ED));
2394
0
          EnumScope->RemoveDecl(ED);
2395
0
          IdResolver.RemoveDecl(ED);
2396
0
          ED->getLexicalDeclContext()->removeDecl(ED);
2397
0
        }
2398
5
      }
2399
11
    }
2400
5.90k
  }
2401
2402
  // If the typedef types are not identical, reject them in all languages and
2403
  // with any extensions enabled.
2404
33.4k
  if (isIncompatibleTypedef(Old, New))
2405
58
    return;
2406
2407
  // The types match.  Link up the redeclaration chain and merge attributes if
2408
  // the old declaration was a typedef.
2409
33.4k
  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2410
5.84k
    New->setPreviousDecl(Typedef);
2411
5.84k
    mergeDeclAttributes(New, Old);
2412
5.84k
  }
2413
2414
33.4k
  if (getLangOpts().MicrosoftExt)
2415
42
    return;
2416
2417
33.3k
  if (getLangOpts().CPlusPlus) {
2418
    // C++ [dcl.typedef]p2:
2419
    //   In a given non-class scope, a typedef specifier can be used to
2420
    //   redefine the name of any type declared in that scope to refer
2421
    //   to the type to which it already refers.
2422
30.4k
    if (!isa<CXXRecordDecl>(CurContext))
2423
30.3k
      return;
2424
2425
    // C++0x [dcl.typedef]p4:
2426
    //   In a given class scope, a typedef specifier can be used to redefine
2427
    //   any class-name declared in that scope that is not also a typedef-name
2428
    //   to refer to the type to which it already refers.
2429
    //
2430
    // This wording came in via DR424, which was a correction to the
2431
    // wording in DR56, which accidentally banned code like:
2432
    //
2433
    //   struct S {
2434
    //     typedef struct A { } A;
2435
    //   };
2436
    //
2437
    // in the C++03 standard. We implement the C++0x semantics, which
2438
    // allow the above but disallow
2439
    //
2440
    //   struct S {
2441
    //     typedef int I;
2442
    //     typedef int I;
2443
    //   };
2444
    //
2445
    // since that was the intent of DR56.
2446
34
    if (!isa<TypedefNameDecl>(Old))
2447
12
      return;
2448
2449
22
    Diag(New->getLocation(), diag::err_redefinition)
2450
22
      << New->getDeclName();
2451
22
    notePreviousDefinition(Old, New->getLocation());
2452
22
    return New->setInvalidDecl();
2453
34
  }
2454
2455
  // Modules always permit redefinition of typedefs, as does C11.
2456
2.96k
  if (getLangOpts().Modules || 
getLangOpts().C11580
)
2457
2.92k
    return;
2458
2459
  // If we have a redefinition of a typedef in C, emit a warning.  This warning
2460
  // is normally mapped to an error, but can be controlled with
2461
  // -Wtypedef-redefinition.  If either the original or the redefinition is
2462
  // in a system header, don't emit this for compatibility with GCC.
2463
39
  if (getDiagnostics().getSuppressSystemWarnings() &&
2464
      // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2465
39
      (Old->isImplicit() ||
2466
39
       
Context.getSourceManager().isInSystemHeader(Old->getLocation())38
||
2467
39
       
Context.getSourceManager().isInSystemHeader(New->getLocation())15
))
2468
24
    return;
2469
2470
15
  Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2471
15
    << New->getDeclName();
2472
15
  notePreviousDefinition(Old, New->getLocation());
2473
15
}
2474
2475
/// DeclhasAttr - returns true if decl Declaration already has the target
2476
/// attribute.
2477
205k
static bool DeclHasAttr(const Decl *D, const Attr *A) {
2478
205k
  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2479
205k
  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2480
205k
  for (const auto *i : D->attrs())
2481
160k
    if (i->getKind() == A->getKind()) {
2482
32.9k
      if (Ann) {
2483
47
        if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2484
30
          return true;
2485
17
        continue;
2486
47
      }
2487
      // FIXME: Don't hardcode this check
2488
32.9k
      if (OA && 
isa<OwnershipAttr>(i)0
)
2489
0
        return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2490
32.9k
      return true;
2491
32.9k
    }
2492
2493
172k
  return false;
2494
205k
}
2495
2496
10
static bool isAttributeTargetADefinition(Decl *D) {
2497
10
  if (VarDecl *VD = dyn_cast<VarDecl>(D))
2498
5
    return VD->isThisDeclarationADefinition();
2499
5
  if (TagDecl *TD = dyn_cast<TagDecl>(D))
2500
5
    return TD->isCompleteDefinition() || TD->isBeingDefined();
2501
0
  return true;
2502
5
}
2503
2504
/// Merge alignment attributes from \p Old to \p New, taking into account the
2505
/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2506
///
2507
/// \return \c true if any attributes were added to \p New.
2508
284k
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2509
  // Look for alignas attributes on Old, and pick out whichever attribute
2510
  // specifies the strictest alignment requirement.
2511
284k
  AlignedAttr *OldAlignasAttr = nullptr;
2512
284k
  AlignedAttr *OldStrictestAlignAttr = nullptr;
2513
284k
  unsigned OldAlign = 0;
2514
284k
  for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2515
    // FIXME: We have no way of representing inherited dependent alignments
2516
    // in a case like:
2517
    //   template<int A, int B> struct alignas(A) X;
2518
    //   template<int A, int B> struct alignas(B) X {};
2519
    // For now, we just ignore any alignas attributes which are not on the
2520
    // definition in such a case.
2521
69
    if (I->isAlignmentDependent())
2522
3
      return false;
2523
2524
66
    if (I->isAlignas())
2525
21
      OldAlignasAttr = I;
2526
2527
66
    unsigned Align = I->getAlignment(S.Context);
2528
66
    if (Align > OldAlign) {
2529
64
      OldAlign = Align;
2530
64
      OldStrictestAlignAttr = I;
2531
64
    }
2532
66
  }
2533
2534
  // Look for alignas attributes on New.
2535
284k
  AlignedAttr *NewAlignasAttr = nullptr;
2536
284k
  unsigned NewAlign = 0;
2537
284k
  for (auto *I : New->specific_attrs<AlignedAttr>()) {
2538
51
    if (I->isAlignmentDependent())
2539
0
      return false;
2540
2541
51
    if (I->isAlignas())
2542
11
      NewAlignasAttr = I;
2543
2544
51
    unsigned Align = I->getAlignment(S.Context);
2545
51
    if (Align > NewAlign)
2546
49
      NewAlign = Align;
2547
51
  }
2548
2549
284k
  if (OldAlignasAttr && 
NewAlignasAttr19
&&
OldAlign != NewAlign9
) {
2550
    // Both declarations have 'alignas' attributes. We require them to match.
2551
    // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2552
    // fall short. (If two declarations both have alignas, they must both match
2553
    // every definition, and so must match each other if there is a definition.)
2554
2555
    // If either declaration only contains 'alignas(0)' specifiers, then it
2556
    // specifies the natural alignment for the type.
2557
7
    if (OldAlign == 0 || NewAlign == 0) {
2558
0
      QualType Ty;
2559
0
      if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2560
0
        Ty = VD->getType();
2561
0
      else
2562
0
        Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2563
2564
0
      if (OldAlign == 0)
2565
0
        OldAlign = S.Context.getTypeAlign(Ty);
2566
0
      if (NewAlign == 0)
2567
0
        NewAlign = S.Context.getTypeAlign(Ty);
2568
0
    }
2569
2570
7
    if (OldAlign != NewAlign) {
2571
7
      S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2572
7
        << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2573
7
        << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2574
7
      S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2575
7
    }
2576
7
  }
2577
2578
284k
  if (OldAlignasAttr && 
!NewAlignasAttr19
&&
isAttributeTargetADefinition(New)10
) {
2579
    // C++11 [dcl.align]p6:
2580
    //   if any declaration of an entity has an alignment-specifier,
2581
    //   every defining declaration of that entity shall specify an
2582
    //   equivalent alignment.
2583
    // C11 6.7.5/7:
2584
    //   If the definition of an object does not have an alignment
2585
    //   specifier, any other declaration of that object shall also
2586
    //   have no alignment specifier.
2587
3
    S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2588
3
      << OldAlignasAttr;
2589
3
    S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2590
3
      << OldAlignasAttr;
2591
3
  }
2592
2593
284k
  bool AnyAdded = false;
2594
2595
  // Ensure we have an attribute representing the strictest alignment.
2596
284k
  if (OldAlign > NewAlign) {
2597
52
    AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2598
52
    Clone->setInherited(true);
2599
52
    New->addAttr(Clone);
2600
52
    AnyAdded = true;
2601
52
  }
2602
2603
  // Ensure we have an alignas attribute if the old declaration had one.
2604
284k
  if (OldAlignasAttr && 
!NewAlignasAttr19
&&
2605
284k
      
!(10
AnyAdded10
&&
OldStrictestAlignAttr->isAlignas()10
)) {
2606
0
    AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2607
0
    Clone->setInherited(true);
2608
0
    New->addAttr(Clone);
2609
0
    AnyAdded = true;
2610
0
  }
2611
2612
284k
  return AnyAdded;
2613
284k
}
2614
2615
#define WANT_DECL_MERGE_LOGIC
2616
#include "clang/Sema/AttrParsedAttrImpl.inc"
2617
#undef WANT_DECL_MERGE_LOGIC
2618
2619
static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2620
                               const InheritableAttr *Attr,
2621
507k
                               Sema::AvailabilityMergeKind AMK) {
2622
  // Diagnose any mutual exclusions between the attribute that we want to add
2623
  // and attributes that already exist on the declaration.
2624
507k
  if (!DiagnoseMutualExclusions(S, D, Attr))
2625
8
    return false;
2626
2627
  // This function copies an attribute Attr from a previous declaration to the
2628
  // new declaration D if the new declaration doesn't itself have that attribute
2629
  // yet or if that attribute allows duplicates.
2630
  // If you're adding a new attribute that requires logic different from
2631
  // "use explicit attribute on decl if present, else use attribute from
2632
  // previous decl", for example if the attribute needs to be consistent
2633
  // between redeclarations, you need to call a custom merge function here.
2634
507k
  InheritableAttr *NewAttr = nullptr;
2635
507k
  if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2636
168k
    NewAttr = S.mergeAvailabilityAttr(
2637
168k
        D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2638
168k
        AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2639
168k
        AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2640
168k
        AA->getPriority());
2641
338k
  else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2642
92.2k
    NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2643
246k
  else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2644
20.0k
    NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2645
226k
  else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2646
1.47k
    NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2647
224k
  else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2648
1.35k
    NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2649
223k
  else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2650
5
    NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2651
223k
  else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2652
801
    NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2653
801
                                FA->getFirstArg());
2654
222k
  else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2655
29
    NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2656
222k
  else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2657
17
    NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2658
222k
  else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2659
33
    NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2660
33
                                       IA->getInheritanceModel());
2661
222k
  else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2662
13.1k
    NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2663
13.1k
                                      &S.Context.Idents.get(AA->getSpelling()));
2664
209k
  else if (S.getLangOpts().CUDA && 
isa<FunctionDecl>(D)72
&&
2665
209k
           
(47
isa<CUDAHostAttr>(Attr)47
||
isa<CUDADeviceAttr>(Attr)26
||
2666
47
            
isa<CUDAGlobalAttr>(Attr)0
)) {
2667
    // CUDA target attributes are part of function signature for
2668
    // overloading purposes and must not be merged.
2669
47
    return false;
2670
209k
  } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2671
3
    NewAttr = S.mergeMinSizeAttr(D, *MA);
2672
209k
  else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2673
11
    NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2674
209k
  else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2675
12
    NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2676
209k
  else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2677
7
    NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2678
209k
  else if (isa<AlignedAttr>(Attr))
2679
    // AlignedAttrs are handled separately, because we need to handle all
2680
    // such attributes on a declaration at the same time.
2681
71
    NewAttr = nullptr;
2682
209k
  else if ((isa<DeprecatedAttr>(Attr) || 
isa<UnavailableAttr>(Attr)209k
) &&
2683
209k
           
(230
AMK == Sema::AMK_Override230
||
2684
230
            
AMK == Sema::AMK_ProtocolImplementation158
||
2685
230
            
AMK == Sema::AMK_OptionalProtocolImplementation149
))
2686
89
    NewAttr = nullptr;
2687
209k
  else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2688
37
    NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2689
209k
  else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2690
7
    NewAttr = S.mergeImportModuleAttr(D, *IMA);
2691
209k
  else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2692
7
    NewAttr = S.mergeImportNameAttr(D, *INA);
2693
209k
  else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2694
12
    NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2695
209k
  else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2696
3
    NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2697
209k
  else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2698
21
    NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2699
209k
  else if (Attr->shouldInheritEvenIfAlreadyPresent() || 
!DeclHasAttr(D, Attr)205k
)
2700
176k
    NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2701
2702
507k
  if (NewAttr) {
2703
278k
    NewAttr->setInherited(true);
2704
278k
    D->addAttr(NewAttr);
2705
278k
    if (isa<MSInheritanceAttr>(NewAttr))
2706
30
      S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2707
278k
    return true;
2708
278k
  }
2709
2710
228k
  return false;
2711
507k
}
2712
2713
147k
static const NamedDecl *getDefinition(const Decl *D) {
2714
147k
  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2715
27.5k
    return TD->getDefinition();
2716
119k
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2717
1.08k
    const VarDecl *Def = VD->getDefinition();
2718
1.08k
    if (Def)
2719
43
      return Def;
2720
1.03k
    return VD->getActingDefinition();
2721
1.08k
  }
2722
118k
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2723
53.5k
    const FunctionDecl *Def = nullptr;
2724
53.5k
    if (FD->isDefined(Def, true))
2725
282
      return Def;
2726
53.5k
  }
2727
118k
  return nullptr;
2728
118k
}
2729
2730
2.03k
static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2731
2.03k
  for (const auto *Attribute : D->attrs())
2732
2.37k
    if (Attribute->getKind() == Kind)
2733
1.99k
      return true;
2734
41
  return false;
2735
2.03k
}
2736
2737
/// checkNewAttributesAfterDef - If we already have a definition, check that
2738
/// there are no new attributes in this declaration.
2739
306k
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2740
306k
  if (!New->hasAttrs())
2741
159k
    return;
2742
2743
147k
  const NamedDecl *Def = getDefinition(Old);
2744
147k
  if (!Def || 
Def == New12.7k
)
2745
145k
    return;
2746
2747
1.99k
  AttrVec &NewAttributes = New->getAttrs();
2748
4.05k
  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2749
2.06k
    const Attr *NewAttribute = NewAttributes[I];
2750
2751
2.06k
    if (isa<AliasAttr>(NewAttribute) || 
isa<IFuncAttr>(NewAttribute)2.05k
) {
2752
5
      if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2753
4
        Sema::SkipBodyInfo SkipBody;
2754
4
        S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2755
2756
        // If we're skipping this definition, drop the "alias" attribute.
2757
4
        if (SkipBody.ShouldSkip) {
2758
0
          NewAttributes.erase(NewAttributes.begin() + I);
2759
0
          --E;
2760
0
          continue;
2761
0
        }
2762
4
      } else {
2763
1
        VarDecl *VD = cast<VarDecl>(New);
2764
1
        unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2765
1
                                VarDecl::TentativeDefinition
2766
1
                            ? diag::err_alias_after_tentative
2767
1
                            : 
diag::err_redefinition0
;
2768
1
        S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2769
1
        if (Diag == diag::err_redefinition)
2770
0
          S.notePreviousDefinition(Def, VD->getLocation());
2771
1
        else
2772
1
          S.Diag(Def->getLocation(), diag::note_previous_definition);
2773
1
        VD->setInvalidDecl();
2774
1
      }
2775
5
      ++I;
2776
5
      continue;
2777
5
    }
2778
2779
2.05k
    if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2780
      // Tentative definitions are only interesting for the alias check above.
2781
70
      if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2782
24
        ++I;
2783
24
        continue;
2784
24
      }
2785
70
    }
2786
2787
2.03k
    if (hasAttribute(Def, NewAttribute->getKind())) {
2788
1.99k
      ++I;
2789
1.99k
      continue; // regular attr merging will take care of validating this.
2790
1.99k
    }
2791
2792
41
    if (isa<C11NoReturnAttr>(NewAttribute)) {
2793
      // C's _Noreturn is allowed to be added to a function after it is defined.
2794
1
      ++I;
2795
1
      continue;
2796
40
    } else if (isa<UuidAttr>(NewAttribute)) {
2797
      // msvc will allow a subsequent definition to add an uuid to a class
2798
2
      ++I;
2799
2
      continue;
2800
38
    } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2801
4
      if (AA->isAlignas()) {
2802
        // C++11 [dcl.align]p6:
2803
        //   if any declaration of an entity has an alignment-specifier,
2804
        //   every defining declaration of that entity shall specify an
2805
        //   equivalent alignment.
2806
        // C11 6.7.5/7:
2807
        //   If the definition of an object does not have an alignment
2808
        //   specifier, any other declaration of that object shall also
2809
        //   have no alignment specifier.
2810
4
        S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2811
4
          << AA;
2812
4
        S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2813
4
          << AA;
2814
4
        NewAttributes.erase(NewAttributes.begin() + I);
2815
4
        --E;
2816
4
        continue;
2817
4
      }
2818
34
    } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2819
      // If there is a C definition followed by a redeclaration with this
2820
      // attribute then there are two different definitions. In C++, prefer the
2821
      // standard diagnostics.
2822
2
      if (!S.getLangOpts().CPlusPlus) {
2823
1
        S.Diag(NewAttribute->getLocation(),
2824
1
               diag::err_loader_uninitialized_redeclaration);
2825
1
        S.Diag(Def->getLocation(), diag::note_previous_definition);
2826
1
        NewAttributes.erase(NewAttributes.begin() + I);
2827
1
        --E;
2828
1
        continue;
2829
1
      }
2830
32
    } else if (isa<SelectAnyAttr>(NewAttribute) &&
2831
32
               
cast<VarDecl>(New)->isInline()8
&&
2832
32
               
!cast<VarDecl>(New)->isInlineSpecified()2
) {
2833
      // Don't warn about applying selectany to implicitly inline variables.
2834
      // Older compilers and language modes would require the use of selectany
2835
      // to make such variables inline, and it would have no effect if we
2836
      // honored it.
2837
2
      ++I;
2838
2
      continue;
2839
30
    } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2840
      // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2841
      // declarations after defintions.
2842
0
      ++I;
2843
0
      continue;
2844
0
    }
2845
2846
31
    S.Diag(NewAttribute->getLocation(),
2847
31
           diag::warn_attribute_precede_definition);
2848
31
    S.Diag(Def->getLocation(), diag::note_previous_definition);
2849
31
    NewAttributes.erase(NewAttributes.begin() + I);
2850
31
    --E;
2851
31
  }
2852
1.99k
}
2853
2854
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2855
                                     const ConstInitAttr *CIAttr,
2856
26
                                     bool AttrBeforeInit) {
2857
26
  SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2858
2859
  // Figure out a good way to write this specifier on the old declaration.
2860
  // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2861
  // enough of the attribute list spelling information to extract that without
2862
  // heroics.
2863
26
  std::string SuitableSpelling;
2864
26
  if (S.getLangOpts().CPlusPlus20)
2865
20
    SuitableSpelling = std::string(
2866
20
        S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2867
26
  if (SuitableSpelling.empty() && 
S.getLangOpts().CPlusPlus1124
)
2868
22
    SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2869
22
        InsertLoc, {tok::l_square, tok::l_square,
2870
22
                    S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2871
22
                    S.PP.getIdentifierInfo("require_constant_initialization"),
2872
22
                    tok::r_square, tok::r_square}));
2873
26
  if (SuitableSpelling.empty())
2874
20
    SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2875
20
        InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2876
20
                    S.PP.getIdentifierInfo("require_constant_initialization"),
2877
20
                    tok::r_paren, tok::r_paren}));
2878
26
  if (SuitableSpelling.empty() && 
S.getLangOpts().CPlusPlus2020
)
2879
14
    SuitableSpelling = "constinit";
2880
26
  if (SuitableSpelling.empty() && 
S.getLangOpts().CPlusPlus116
)
2881
4
    SuitableSpelling = "[[clang::require_constant_initialization]]";
2882
26
  if (SuitableSpelling.empty())
2883
2
    SuitableSpelling = "__attribute__((require_constant_initialization))";
2884
26
  SuitableSpelling += " ";
2885
2886
26
  if (AttrBeforeInit) {
2887
    // extern constinit int a;
2888
    // int a = 0; // error (missing 'constinit'), accepted as extension
2889
14
    assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2890
0
    S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2891
14
        << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2892
14
    S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2893
14
  } else {
2894
    // int a = 0;
2895
    // constinit extern int a; // error (missing 'constinit')
2896
12
    S.Diag(CIAttr->getLocation(),
2897
12
           CIAttr->isConstinit() ? 
diag::err_constinit_added_too_late6
2898
12
                                 : 
diag::warn_require_const_init_added_too_late6
)
2899
12
        << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2900
12
    S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2901
12
        << CIAttr->isConstinit()
2902
12
        << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2903
12
  }
2904
26
}
2905
2906
/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2907
void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2908
687k
                               AvailabilityMergeKind AMK) {
2909
687k
  if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2910
167
    UsedAttr *NewAttr = OldAttr->clone(Context);
2911
167
    NewAttr->setInherited(true);
2912
167
    New->addAttr(NewAttr);
2913
167
  }
2914
687k
  if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2915
3
    RetainAttr *NewAttr = OldAttr->clone(Context);
2916
3
    NewAttr->setInherited(true);
2917
3
    New->addAttr(NewAttr);
2918
3
  }
2919
2920
687k
  if (!Old->hasAttrs() && 
!New->hasAttrs()403k
)
2921
380k
    return;
2922
2923
  // [dcl.constinit]p1:
2924
  //   If the [constinit] specifier is applied to any declaration of a
2925
  //   variable, it shall be applied to the initializing declaration.
2926
306k
  const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2927
306k
  const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2928
306k
  if (bool(OldConstInit) != bool(NewConstInit)) {
2929
51
    const auto *OldVD = cast<VarDecl>(Old);
2930
51
    auto *NewVD = cast<VarDecl>(New);
2931
2932
    // Find the initializing declaration. Note that we might not have linked
2933
    // the new declaration into the redeclaration chain yet.
2934
51
    const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2935
51
    if (!InitDecl &&
2936
51
        
(37
NewVD->hasInit()37
||
NewVD->isThisDeclarationADefinition()37
))
2937
37
      InitDecl = NewVD;
2938
2939
51
    if (InitDecl == NewVD) {
2940
      // This is the initializing declaration. If it would inherit 'constinit',
2941
      // that's ill-formed. (Note that we do not apply this to the attribute
2942
      // form).
2943
37
      if (OldConstInit && 
OldConstInit->isConstinit()36
)
2944
14
        diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2945
14
                                 /*AttrBeforeInit=*/true);
2946
37
    } else 
if (14
NewConstInit14
) {
2947
      // This is the first time we've been told that this declaration should
2948
      // have a constant initializer. If we already saw the initializing
2949
      // declaration, this is too late.
2950
12
      if (InitDecl && InitDecl != NewVD) {
2951
12
        diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2952
12
                                 /*AttrBeforeInit=*/false);
2953
12
        NewVD->dropAttr<ConstInitAttr>();
2954
12
      }
2955
12
    }
2956
51
  }
2957
2958
  // Attributes declared post-definition are currently ignored.
2959
306k
  checkNewAttributesAfterDef(*this, New, Old);
2960
2961
306k
  if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2962
667
    if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2963
587
      if (!OldA->isEquivalent(NewA)) {
2964
        // This redeclaration changes __asm__ label.
2965
2
        Diag(New->getLocation(), diag::err_different_asm_label);
2966
2
        Diag(OldA->getLocation(), diag::note_previous_declaration);
2967
2
      }
2968
587
    } else 
if (80
Old->isUsed()80
) {
2969
      // This redeclaration adds an __asm__ label to a declaration that has
2970
      // already been ODR-used.
2971
2
      Diag(New->getLocation(), diag::err_late_asm_label_name)
2972
2
        << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2973
2
    }
2974
667
  }
2975
2976
  // Re-declaration cannot add abi_tag's.
2977
306k
  if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2978
3
    if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2979
4
      for (const auto &NewTag : NewAbiTagAttr->tags()) {
2980
4
        if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
2981
1
          Diag(NewAbiTagAttr->getLocation(),
2982
1
               diag::err_new_abi_tag_on_redeclaration)
2983
1
              << NewTag;
2984
1
          Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2985
1
        }
2986
4
      }
2987
2
    } else {
2988
1
      Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2989
1
      Diag(Old->getLocation(), diag::note_previous_declaration);
2990
1
    }
2991
3
  }
2992
2993
  // This redeclaration adds a section attribute.
2994
306k
  if (New->hasAttr<SectionAttr>() && 
!Old->hasAttr<SectionAttr>()25
) {
2995
17
    if (auto *VD = dyn_cast<VarDecl>(New)) {
2996
7
      if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2997
2
        Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2998
2
        Diag(Old->getLocation(), diag::note_previous_declaration);
2999
2
      }
3000
7
    }
3001
17
  }
3002
3003
  // Redeclaration adds code-seg attribute.
3004
306k
  const auto *NewCSA = New->getAttr<CodeSegAttr>();
3005
306k
  if (NewCSA && 
!Old->hasAttr<CodeSegAttr>()16
&&
3006
306k
      
!NewCSA->isImplicit()1
&&
isa<CXXMethodDecl>(New)1
) {
3007
1
    Diag(New->getLocation(), diag::warn_mismatched_section)
3008
1
         << 0 /*codeseg*/;
3009
1
    Diag(Old->getLocation(), diag::note_previous_declaration);
3010
1
  }
3011
3012
306k
  if (!Old->hasAttrs())
3013
22.5k
    return;
3014
3015
284k
  bool foundAny = New->hasAttrs();
3016
3017
  // Ensure that any moving of objects within the allocated map is done before
3018
  // we process them.
3019
284k
  if (!foundAny) 
New->setAttrs(AttrVec())159k
;
3020
3021
507k
  for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3022
    // Ignore deprecated/unavailable/availability attributes if requested.
3023
507k
    AvailabilityMergeKind LocalAMK = AMK_None;
3024
507k
    if (isa<DeprecatedAttr>(I) ||
3025
507k
        
isa<UnavailableAttr>(I)507k
||
3026
507k
        
isa<AvailabilityAttr>(I)507k
) {
3027
168k
      switch (AMK) {
3028
0
      case AMK_None:
3029
0
        continue;
3030
3031
34.2k
      case AMK_Redeclaration:
3032
167k
      case AMK_Override:
3033
167k
      case AMK_ProtocolImplementation:
3034
168k
      case AMK_OptionalProtocolImplementation:
3035
168k
        LocalAMK = AMK;
3036
168k
        break;
3037
168k
      }
3038
168k
    }
3039
3040
    // Already handled.
3041
507k
    if (isa<UsedAttr>(I) || 
isa<RetainAttr>(I)507k
)
3042
167
      continue;
3043
3044
507k
    if (mergeDeclAttribute(*this, New, I, LocalAMK))
3045
278k
      foundAny = true;
3046
507k
  }
3047
3048
284k
  if (mergeAlignedAttrs(*this, New, Old))
3049
52
    foundAny = true;
3050
3051
284k
  if (!foundAny) 
New->dropAttrs()4.47k
;
3052
284k
}
3053
3054
/// mergeParamDeclAttributes - Copy attributes from the old parameter
3055
/// to the new one.
3056
static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3057
                                     const ParmVarDecl *oldDecl,
3058
454k
                                     Sema &S) {
3059
  // C++11 [dcl.attr.depend]p2:
3060
  //   The first declaration of a function shall specify the
3061
  //   carries_dependency attribute for its declarator-id if any declaration
3062
  //   of the function specifies the carries_dependency attribute.
3063
454k
  const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3064
454k
  if (CDA && 
!oldDecl->hasAttr<CarriesDependencyAttr>()2
) {
3065
1
    S.Diag(CDA->getLocation(),
3066
1
           diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3067
    // Find the first declaration of the parameter.
3068
    // FIXME: Should we build redeclaration chains for function parameters?
3069
1
    const FunctionDecl *FirstFD =
3070
1
      cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3071
1
    const ParmVarDecl *FirstVD =
3072
1
      FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3073
1
    S.Diag(FirstVD->getLocation(),
3074
1
           diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3075
1
  }
3076
3077
454k
  if (!oldDecl->hasAttrs())
3078
449k
    return;
3079
3080
5.02k
  bool foundAny = newDecl->hasAttrs();
3081
3082
  // Ensure that any moving of objects within the allocated map is
3083
  // done before we process them.
3084
5.02k
  if (!foundAny) 
newDecl->setAttrs(AttrVec())19
;
3085
3086
5.02k
  for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3087
257
    if (!DeclHasAttr(newDecl, I)) {
3088
15
      InheritableAttr *newAttr =
3089
15
        cast<InheritableParamAttr>(I->clone(S.Context));
3090
15
      newAttr->setInherited(true);
3091
15
      newDecl->addAttr(newAttr);
3092
15
      foundAny = true;
3093
15
    }
3094
257
  }
3095
3096
5.02k
  if (!foundAny) 
newDecl->dropAttrs()6
;
3097
5.02k
}
3098
3099
static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3100
                                const ParmVarDecl *OldParam,
3101
365k
                                Sema &S) {
3102
365k
  if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3103
1.87k
    if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3104
1.39k
      if (*Oldnullability != *Newnullability) {
3105
2
        S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3106
2
          << DiagNullabilityKind(
3107
2
               *Newnullability,
3108
2
               ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3109
2
                != 0))
3110
2
          << DiagNullabilityKind(
3111
2
               *Oldnullability,
3112
2
               ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3113
2
                != 0));
3114
2
        S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3115
2
      }
3116
1.39k
    } else {
3117
481
      QualType NewT = NewParam->getType();
3118
481
      NewT = S.Context.getAttributedType(
3119
481
                         AttributedType::getNullabilityAttrKind(*Oldnullability),
3120
481
                         NewT, NewT);
3121
481
      NewParam->setType(NewT);
3122
481
    }
3123
1.87k
  }
3124
365k
}
3125
3126
namespace {
3127
3128
/// Used in MergeFunctionDecl to keep track of function parameters in
3129
/// C.
3130
struct GNUCompatibleParamWarning {
3131
  ParmVarDecl *OldParm;
3132
  ParmVarDecl *NewParm;
3133
  QualType PromotedType;
3134
};
3135
3136
} // end anonymous namespace
3137
3138
// Determine whether the previous declaration was a definition, implicit
3139
// declaration, or a declaration.
3140
template <typename T>
3141
static std::pair<diag::kind, SourceLocation>
3142
295k
getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3143
295k
  diag::kind PrevDiag;
3144
295k
  SourceLocation OldLocation = Old->getLocation();
3145
295k
  if (Old->isThisDeclarationADefinition())
3146
9.41k
    PrevDiag = diag::note_previous_definition;
3147
286k
  else if (Old->isImplicit()) {
3148
12.2k
    PrevDiag = diag::note_previous_implicit_declaration;
3149
12.2k
    if (OldLocation.isInvalid())
3150
2.53k
      OldLocation = New->getLocation();
3151
12.2k
  } else
3152
273k
    PrevDiag = diag::note_previous_declaration;
3153
295k
  return std::make_pair(PrevDiag, OldLocation);
3154
295k
}
SemaDecl.cpp:std::__1::pair<unsigned int, clang::SourceLocation> getNoteDiagForInvalidRedeclaration<clang::FunctionDecl>(clang::FunctionDecl const*, clang::FunctionDecl const*)
Line
Count
Source
3142
233k
getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3143
233k
  diag::kind PrevDiag;
3144
233k
  SourceLocation OldLocation = Old->getLocation();
3145
233k
  if (Old->isThisDeclarationADefinition())
3146
7.85k
    PrevDiag = diag::note_previous_definition;
3147
225k
  else if (Old->isImplicit()) {
3148
12.2k
    PrevDiag = diag::note_previous_implicit_declaration;
3149
12.2k
    if (OldLocation.isInvalid())
3150
2.53k
      OldLocation = New->getLocation();
3151
12.2k
  } else
3152
213k
    PrevDiag = diag::note_previous_declaration;
3153
233k
  return std::make_pair(PrevDiag, OldLocation);
3154
233k
}
SemaDecl.cpp:std::__1::pair<unsigned int, clang::SourceLocation> getNoteDiagForInvalidRedeclaration<clang::VarDecl>(clang::VarDecl const*, clang::VarDecl const*)
Line
Count
Source
3142
61.9k
getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3143
61.9k
  diag::kind PrevDiag;
3144
61.9k
  SourceLocation OldLocation = Old->getLocation();
3145
61.9k
  if (Old->isThisDeclarationADefinition())
3146
1.55k
    PrevDiag = diag::note_previous_definition;
3147
60.4k
  else if (Old->isImplicit()) {
3148
0
    PrevDiag = diag::note_previous_implicit_declaration;
3149
0
    if (OldLocation.isInvalid())
3150
0
      OldLocation = New->getLocation();
3151
0
  } else
3152
60.4k
    PrevDiag = diag::note_previous_declaration;
3153
61.9k
  return std::make_pair(PrevDiag, OldLocation);
3154
61.9k
}
3155
3156
/// canRedefineFunction - checks if a function can be redefined. Currently,
3157
/// only extern inline functions can be redefined, and even then only in
3158
/// GNU89 mode.
3159
static bool canRedefineFunction(const FunctionDecl *FD,
3160
590
                                const LangOptions& LangOpts) {
3161
590
  return ((FD->hasAttr<GNUInlineAttr>() || 
LangOpts.GNUInline584
) &&
3162
590
          
!LangOpts.CPlusPlus19
&&
3163
590
          
FD->isInlineSpecified()19
&&
3164
590
          
FD->getStorageClass() == SC_Extern17
);
3165
590
}
3166
3167
1.16k
const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3168
1.16k
  const AttributedType *AT = T->getAs<AttributedType>();
3169
1.16k
  while (AT && 
!AT->isCallingConv()154
)
3170
0
    AT = AT->getModifiedType()->getAs<AttributedType>();
3171
1.16k
  return AT;
3172
1.16k
}
3173
3174
template <typename T>
3175
276k
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3176
276k
  const DeclContext *DC = Old->getDeclContext();
3177
276k
  if (DC->isRecord())
3178
206k
    return false;
3179
3180
70.3k
  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3181
70.3k
  if (OldLinkage == CXXLanguageLinkage && 
New->isInExternCContext()47.6k
)
3182
24
    return true;
3183
70.3k
  if (OldLinkage == CLanguageLinkage && 
New->isInExternCXXContext()21.3k
)
3184
17
    return true;
3185
70.3k
  return false;
3186
70.3k
}
SemaDecl.cpp:bool haveIncompatibleLanguageLinkages<clang::FunctionDecl>(clang::FunctionDecl const*, clang::FunctionDecl const*)
Line
Count
Source
3175
215k
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3176
215k
  const DeclContext *DC = Old->getDeclContext();
3177
215k
  if (DC->isRecord())
3178
147k
    return false;
3179
3180
67.4k
  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3181
67.4k
  if (OldLinkage == CXXLanguageLinkage && 
New->isInExternCContext()46.2k
)
3182
21
    return true;
3183
67.4k
  if (OldLinkage == CLanguageLinkage && 
New->isInExternCXXContext()20.0k
)
3184
17
    return true;
3185
67.3k
  return false;
3186
67.4k
}
SemaDecl.cpp:bool haveIncompatibleLanguageLinkages<clang::VarDecl>(clang::VarDecl const*, clang::VarDecl const*)
Line
Count
Source
3175
61.6k
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3176
61.6k
  const DeclContext *DC = Old->getDeclContext();
3177
61.6k
  if (DC->isRecord())
3178
58.7k
    return false;
3179
3180
2.93k
  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3181
2.93k
  if (OldLinkage == CXXLanguageLinkage && 
New->isInExternCContext()1.41k
)
3182
3
    return true;
3183
2.92k
  if (OldLinkage == CLanguageLinkage && 
New->isInExternCXXContext()1.39k
)
3184
0
    return true;
3185
2.92k
  return false;
3186
2.92k
}
3187
3188
24
template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
SemaDecl.cpp:bool isExternC<clang::FunctionDecl>(clang::FunctionDecl*)
Line
Count
Source
3188
17
template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
SemaDecl.cpp:bool isExternC<clang::VarDecl>(clang::VarDecl*)
Line
Count
Source
3188
7
template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3189
2
static bool isExternC(VarTemplateDecl *) { return false; }
3190
6
static bool isExternC(FunctionTemplateDecl *) { return false; }
3191
3192
/// Check whether a redeclaration of an entity introduced by a
3193
/// using-declaration is valid, given that we know it's not an overload
3194
/// (nor a hidden tag declaration).
3195
template<typename ExpectedDecl>
3196
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3197
41
                                   ExpectedDecl *New) {
3198
  // C++11 [basic.scope.declarative]p4:
3199
  //   Given a set of declarations in a single declarative region, each of
3200
  //   which specifies the same unqualified name,
3201
  //   -- they shall all refer to the same entity, or all refer to functions
3202
  //      and function templates; or
3203
  //   -- exactly one declaration shall declare a class name or enumeration
3204
  //      name that is not a typedef name and the other declarations shall all
3205
  //      refer to the same variable or enumerator, or all refer to functions
3206
  //      and function templates; in this case the class name or enumeration
3207
  //      name is hidden (3.3.10).
3208
3209
  // C++11 [namespace.udecl]p14:
3210
  //   If a function declaration in namespace scope or block scope has the
3211
  //   same name and the same parameter-type-list as a function introduced
3212
  //   by a using-declaration, and the declarations do not declare the same
3213
  //   function, the program is ill-formed.
3214
3215
41
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3216
41
  if (Old &&
3217
41
      !Old->getDeclContext()->getRedeclContext()->Equals(
3218
40
          New->getDeclContext()->getRedeclContext()) &&
3219
41
      
!(28
isExternC(Old)28
&&
isExternC(New)4
))
3220
24
    Old = nullptr;
3221
3222
41
  if (!Old) {
3223
25
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3224
25
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3225
25
    S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3226
25
    return true;
3227
25
  }
3228
16
  return false;
3229
41
}
SemaDecl.cpp:bool checkUsingShadowRedecl<clang::FunctionTemplateDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::FunctionTemplateDecl*)
Line
Count
Source
3197
8
                                   ExpectedDecl *New) {
3198
  // C++11 [basic.scope.declarative]p4:
3199
  //   Given a set of declarations in a single declarative region, each of
3200
  //   which specifies the same unqualified name,
3201
  //   -- they shall all refer to the same entity, or all refer to functions
3202
  //      and function templates; or
3203
  //   -- exactly one declaration shall declare a class name or enumeration
3204
  //      name that is not a typedef name and the other declarations shall all
3205
  //      refer to the same variable or enumerator, or all refer to functions
3206
  //      and function templates; in this case the class name or enumeration
3207
  //      name is hidden (3.3.10).
3208
3209
  // C++11 [namespace.udecl]p14:
3210
  //   If a function declaration in namespace scope or block scope has the
3211
  //   same name and the same parameter-type-list as a function introduced
3212
  //   by a using-declaration, and the declarations do not declare the same
3213
  //   function, the program is ill-formed.
3214
3215
8
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3216
8
  if (Old &&
3217
8
      !Old->getDeclContext()->getRedeclContext()->Equals(
3218
8
          New->getDeclContext()->getRedeclContext()) &&
3219
8
      
!(6
isExternC(Old)6
&&
isExternC(New)0
))
3220
6
    Old = nullptr;
3221
3222
8
  if (!Old) {
3223
6
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3224
6
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3225
6
    S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3226
6
    return true;
3227
6
  }
3228
2
  return false;
3229
8
}
SemaDecl.cpp:bool checkUsingShadowRedecl<clang::FunctionDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::FunctionDecl*)
Line
Count
Source
3197
21
                                   ExpectedDecl *New) {
3198
  // C++11 [basic.scope.declarative]p4:
3199
  //   Given a set of declarations in a single declarative region, each of
3200
  //   which specifies the same unqualified name,
3201
  //   -- they shall all refer to the same entity, or all refer to functions
3202
  //      and function templates; or
3203
  //   -- exactly one declaration shall declare a class name or enumeration
3204
  //      name that is not a typedef name and the other declarations shall all
3205
  //      refer to the same variable or enumerator, or all refer to functions
3206
  //      and function templates; in this case the class name or enumeration
3207
  //      name is hidden (3.3.10).
3208
3209
  // C++11 [namespace.udecl]p14:
3210
  //   If a function declaration in namespace scope or block scope has the
3211
  //   same name and the same parameter-type-list as a function introduced
3212
  //   by a using-declaration, and the declarations do not declare the same
3213
  //   function, the program is ill-formed.
3214
3215
21
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3216
21
  if (Old &&
3217
21
      !Old->getDeclContext()->getRedeclContext()->Equals(
3218
21
          New->getDeclContext()->getRedeclContext()) &&
3219
21
      
!(13
isExternC(Old)13
&&
isExternC(New)4
))
3220
9
    Old = nullptr;
3221
3222
21
  if (!Old) {
3223
9
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3224
9
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3225
9
    S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3226
9
    return true;
3227
9
  }
3228
12
  return false;
3229
21
}
SemaDecl.cpp:bool checkUsingShadowRedecl<clang::VarTemplateDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::VarTemplateDecl*)
Line
Count
Source
3197
3
                                   ExpectedDecl *New) {
3198
  // C++11 [basic.scope.declarative]p4:
3199
  //   Given a set of declarations in a single declarative region, each of
3200
  //   which specifies the same unqualified name,
3201
  //   -- they shall all refer to the same entity, or all refer to functions
3202
  //      and function templates; or
3203
  //   -- exactly one declaration shall declare a class name or enumeration
3204
  //      name that is not a typedef name and the other declarations shall all
3205
  //      refer to the same variable or enumerator, or all refer to functions
3206
  //      and function templates; in this case the class name or enumeration
3207
  //      name is hidden (3.3.10).
3208
3209
  // C++11 [namespace.udecl]p14:
3210
  //   If a function declaration in namespace scope or block scope has the
3211
  //   same name and the same parameter-type-list as a function introduced
3212
  //   by a using-declaration, and the declarations do not declare the same
3213
  //   function, the program is ill-formed.
3214
3215
3
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3216
3
  if (Old &&
3217
3
      !Old->getDeclContext()->getRedeclContext()->Equals(
3218
3
          New->getDeclContext()->getRedeclContext()) &&
3219
3
      
!(2
isExternC(Old)2
&&
isExternC(New)0
))
3220
2
    Old = nullptr;
3221
3222
3
  if (!Old) {
3223
2
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3224
2
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3225
2
    S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3226
2
    return true;
3227
2
  }
3228
1
  return false;
3229
3
}
SemaDecl.cpp:bool checkUsingShadowRedecl<clang::VarDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::VarDecl*)
Line
Count
Source
3197
9
                                   ExpectedDecl *New) {
3198
  // C++11 [basic.scope.declarative]p4:
3199
  //   Given a set of declarations in a single declarative region, each of
3200
  //   which specifies the same unqualified name,
3201
  //   -- they shall all refer to the same entity, or all refer to functions
3202
  //      and function templates; or
3203
  //   -- exactly one declaration shall declare a class name or enumeration
3204
  //      name that is not a typedef name and the other declarations shall all
3205
  //      refer to the same variable or enumerator, or all refer to functions
3206
  //      and function templates; in this case the class name or enumeration
3207
  //      name is hidden (3.3.10).
3208
3209
  // C++11 [namespace.udecl]p14:
3210
  //   If a function declaration in namespace scope or block scope has the
3211
  //   same name and the same parameter-type-list as a function introduced
3212
  //   by a using-declaration, and the declarations do not declare the same
3213
  //   function, the program is ill-formed.
3214
3215
9
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3216
9
  if (Old &&
3217
9
      !Old->getDeclContext()->getRedeclContext()->Equals(
3218
8
          New->getDeclContext()->getRedeclContext()) &&
3219
9
      
!(7
isExternC(Old)7
&&
isExternC(New)0
))
3220
7
    Old = nullptr;
3221
3222
9
  if (!Old) {
3223
8
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3224
8
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3225
8
    S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3226
8
    return true;
3227
8
  }
3228
1
  return false;
3229
9
}
3230
3231
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3232
191k
                                            const FunctionDecl *B) {
3233
191k
  assert(A->getNumParams() == B->getNumParams());
3234
3235
365k
  auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3236
365k
    const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3237
365k
    const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3238
365k
    if (AttrA == AttrB)
3239
365k
      return true;
3240
7
    return AttrA && AttrB && 
AttrA->getType() == AttrB->getType()6
&&
3241
7
           
AttrA->isDynamic() == AttrB->isDynamic()2
;
3242
365k
  };
3243
3244
191k
  return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3245
191k
}
3246
3247
/// If necessary, adjust the semantic declaration context for a qualified
3248
/// declaration to name the correct inline namespace within the qualifier.
3249
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3250
295k
                                               DeclaratorDecl *OldD) {
3251
  // The only case where we need to update the DeclContext is when
3252
  // redeclaration lookup for a qualified name finds a declaration
3253
  // in an inline namespace within the context named by the qualifier:
3254
  //
3255
  //   inline namespace N { int f(); }
3256
  //   int ::f(); // Sema DC needs adjusting from :: to N::.
3257
  //
3258
  // For unqualified declarations, the semantic context *can* change
3259
  // along the redeclaration chain (for local extern declarations,
3260
  // extern "C" declarations, and friend declarations in particular).
3261
295k
  if (!NewD->getQualifier())
3262
88.5k
    return;
3263
3264
  // NewD is probably already in the right context.
3265
207k
  auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3266
207k
  auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3267
207k
  if (NamedDC->Equals(SemaDC))
3268
207k
    return;
3269
3270
21
  assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3271
21
          NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3272
21
         "unexpected context for redeclaration");
3273
3274
0
  auto *LexDC = NewD->getLexicalDeclContext();
3275
42
  auto FixSemaDC = [=](NamedDecl *D) {
3276
42
    if (!D)
3277
21
      return;
3278
21
    D->setDeclContext(SemaDC);
3279
21
    D->setLexicalDeclContext(LexDC);
3280
21
  };
3281
3282
21
  FixSemaDC(NewD);
3283
21
  if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3284
15
    FixSemaDC(FD->getDescribedFunctionTemplate());
3285
6
  else if (auto *VD = dyn_cast<VarDecl>(NewD))
3286
6
    FixSemaDC(VD->getDescribedVarTemplate());
3287
21
}
3288
3289
/// MergeFunctionDecl - We just parsed a function 'New' from
3290
/// declarator D which has the same name and scope as a previous
3291
/// declaration 'Old'.  Figure out how to resolve this situation,
3292
/// merging decls or emitting diagnostics as appropriate.
3293
///
3294
/// In C++, New and Old must be declarations that are not
3295
/// overloaded. Use IsOverload to determine whether New and Old are
3296
/// overloaded, and to select the Old declaration that New should be
3297
/// merged with.
3298
///
3299
/// Returns true if there was an error, false otherwise.
3300
bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3301
233k
                             Scope *S, bool MergeTypeWithOld) {
3302
  // Verify the old decl was also a function.
3303
233k
  FunctionDecl *Old = OldD->getAsFunction();
3304
233k
  if (!Old) {
3305
78
    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3306
40
      if (New->getFriendObjectKind()) {
3307
11
        Diag(New->getLocation(), diag::err_using_decl_friend);
3308
11
        Diag(Shadow->getTargetDecl()->getLocation(),
3309
11
             diag::note_using_decl_target);
3310
11
        Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3311
11
            << 0;
3312
11
        return true;
3313
11
      }
3314
3315
      // Check whether the two declarations might declare the same function or
3316
      // function template.
3317
29
      if (FunctionTemplateDecl *NewTemplate =
3318
29
              New->getDescribedFunctionTemplate()) {
3319
8
        if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3320
8
                                                         NewTemplate))
3321
6
          return true;
3322
2
        OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3323
2
                         ->getAsFunction();
3324
21
      } else {
3325
21
        if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3326
9
          return true;
3327
12
        OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3328
12
      }
3329
38
    } else {
3330
38
      Diag(New->getLocation(), diag::err_redefinition_different_kind)
3331
38
        << New->getDeclName();
3332
38
      notePreviousDefinition(OldD, New->getLocation());
3333
38
      return true;
3334
38
    }
3335
78
  }
3336
3337
  // If the old declaration was found in an inline namespace and the new
3338
  // declaration was qualified, update the DeclContext to match.
3339
233k
  adjustDeclContextForDeclaratorDecl(New, Old);
3340
3341
  // If the old declaration is invalid, just give up here.
3342
233k
  if (Old->isInvalidDecl())
3343
43
    return true;
3344
3345
  // Disallow redeclaration of some builtins.
3346
233k
  if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3347
11
    Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3348
11
    Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3349
11
        << Old << Old->getType();
3350
11
    return true;
3351
11
  }
3352
3353
233k
  diag::kind PrevDiag;
3354
233k
  SourceLocation OldLocation;
3355
233k
  std::tie(PrevDiag, OldLocation) =
3356
233k
      getNoteDiagForInvalidRedeclaration(Old, New);
3357
3358
  // Don't complain about this if we're in GNU89 mode and the old function
3359
  // is an extern inline function.
3360
  // Don't complain about specializations. They are not supposed to have
3361
  // storage classes.
3362
233k
  if (!isa<CXXMethodDecl>(New) && 
!isa<CXXMethodDecl>(Old)85.6k
&&
3363
233k
      
New->getStorageClass() == SC_Static85.6k
&&
3364
233k
      
Old->hasExternalFormalLinkage()2.44k
&&
3365
233k
      
!New->getTemplateSpecializationInfo()245
&&
3366
233k
      
!canRedefineFunction(Old, getLangOpts())244
) {
3367
240
    if (getLangOpts().MicrosoftExt) {
3368
234
      Diag(New->getLocation(), diag::ext_static_non_static) << New;
3369
234
      Diag(OldLocation, PrevDiag);
3370
234
    } else {
3371
6
      Diag(New->getLocation(), diag::err_static_non_static) << New;
3372
6
      Diag(OldLocation, PrevDiag);
3373
6
      return true;
3374
6
    }
3375
240
  }
3376
3377
233k
  if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3378
1
    if (!Old->hasAttr<InternalLinkageAttr>()) {
3379
1
      Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3380
1
          << ILA;
3381
1
      Diag(Old->getLocation(), diag::note_previous_declaration);
3382
1
      New->dropAttr<InternalLinkageAttr>();
3383
1
    }
3384
3385
233k
  if (auto *EA = New->getAttr<ErrorAttr>()) {
3386
7
    if (!Old->hasAttr<ErrorAttr>()) {
3387
2
      Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3388
2
      Diag(Old->getLocation(), diag::note_previous_declaration);
3389
2
      New->dropAttr<ErrorAttr>();
3390
2
    }
3391
7
  }
3392
3393
233k
  if (CheckRedeclarationModuleOwnership(New, Old))
3394
14
    return true;
3395
3396
233k
  if (!getLangOpts().CPlusPlus) {
3397
18.0k
    bool OldOvl = Old->hasAttr<OverloadableAttr>();
3398
18.0k
    if (OldOvl != New->hasAttr<OverloadableAttr>() && 
!Old->isImplicit()17
) {
3399
14
      Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3400
14
        << New << OldOvl;
3401
3402
      // Try our best to find a decl that actually has the overloadable
3403
      // attribute for the note. In most cases (e.g. programs with only one
3404
      // broken declaration/definition), this won't matter.
3405
      //
3406
      // FIXME: We could do this if we juggled some extra state in
3407
      // OverloadableAttr, rather than just removing it.
3408
14
      const Decl *DiagOld = Old;
3409
14
      if (OldOvl) {
3410
14
        auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3411
14
          const auto *A = D->getAttr<OverloadableAttr>();
3412
14
          return A && !A->isImplicit();
3413
14
        });
3414
        // If we've implicitly added *all* of the overloadable attrs to this
3415
        // chain, emitting a "previous redecl" note is pointless.
3416
11
        DiagOld = OldIter == Old->redecls_end() ? 
nullptr2
:
*OldIter9
;
3417
11
      }
3418
3419
14
      if (DiagOld)
3420
12
        Diag(DiagOld->getLocation(),
3421
12
             diag::note_attribute_overloadable_prev_overload)
3422
12
          << OldOvl;
3423
3424
14
      if (OldOvl)
3425
11
        New->addAttr(OverloadableAttr::CreateImplicit(Context));
3426
3
      else
3427
3
        New->dropAttr<OverloadableAttr>();
3428
14
    }
3429
18.0k
  }
3430
3431
  // If a function is first declared with a calling convention, but is later
3432
  // declared or defined without one, all following decls assume the calling
3433
  // convention of the first.
3434
  //
3435
  // It's OK if a function is first declared without a calling convention,
3436
  // but is later declared or defined with the default calling convention.
3437
  //
3438
  // To test if either decl has an explicit calling convention, we look for
3439
  // AttributedType sugar nodes on the type as written.  If they are missing or
3440
  // were canonicalized away, we assume the calling convention was implicit.
3441
  //
3442
  // Note also that we DO NOT return at this point, because we still have
3443
  // other tests to run.
3444
233k
  QualType OldQType = Context.getCanonicalType(Old->getType());
3445
233k
  QualType NewQType = Context.getCanonicalType(New->getType());
3446
233k
  const FunctionType *OldType = cast<FunctionType>(OldQType);
3447
233k
  const FunctionType *NewType = cast<FunctionType>(NewQType);
3448
233k
  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3449
233k
  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3450
233k
  bool RequiresAdjustment = false;
3451
3452
233k
  if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3453
895
    FunctionDecl *First = Old->getFirstDecl();
3454
895
    const FunctionType *FT =
3455
895
        First->getType().getCanonicalType()->castAs<FunctionType>();
3456
895
    FunctionType::ExtInfo FI = FT->getExtInfo();
3457
895
    bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3458
895
    if (!NewCCExplicit) {
3459
      // Inherit the CC from the previous declaration if it was specified
3460
      // there but not here.
3461
810
      NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3462
810
      RequiresAdjustment = true;
3463
810
    } else 
if (85
Old->getBuiltinID()85
) {
3464
      // Builtin attribute isn't propagated to the new one yet at this point,
3465
      // so we check if the old one is a builtin.
3466
3467
      // Calling Conventions on a Builtin aren't really useful and setting a
3468
      // default calling convention and cdecl'ing some builtin redeclarations is
3469
      // common, so warn and ignore the calling convention on the redeclaration.
3470
2
      Diag(New->getLocation(), diag::warn_cconv_unsupported)
3471
2
          << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3472
2
          << (int)CallingConventionIgnoredReason::BuiltinFunction;
3473
2
      NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3474
2
      RequiresAdjustment = true;
3475
83
    } else {
3476
      // Calling conventions aren't compatible, so complain.
3477
83
      bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3478
83
      Diag(New->getLocation(), diag::err_cconv_change)
3479
83
        << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3480
83
        << !FirstCCExplicit
3481
83
        << (!FirstCCExplicit ? 
""39
:
3482
83
            
FunctionType::getNameForCallConv(FI.getCC())44
);
3483
3484
      // Put the note on the first decl, since it is the one that matters.
3485
83
      Diag(First->getLocation(), diag::note_previous_declaration);
3486
83
      return true;
3487
83
    }
3488
895
  }
3489
3490
  // FIXME: diagnose the other way around?
3491
233k
  if (OldTypeInfo.getNoReturn() && 
!NewTypeInfo.getNoReturn()666
) {
3492
111
    NewTypeInfo = NewTypeInfo.withNoReturn(true);
3493
111
    RequiresAdjustment = true;
3494
111
  }
3495
3496
  // Merge regparm attribute.
3497
233k
  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3498
233k
      
OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()233k
) {
3499
21
    if (NewTypeInfo.getHasRegParm()) {
3500
5
      Diag(New->getLocation(), diag::err_regparm_mismatch)
3501
5
        << NewType->getRegParmType()
3502
5
        << OldType->getRegParmType();
3503
5
      Diag(OldLocation, diag::note_previous_declaration);
3504
5
      return true;
3505
5
    }
3506
3507
16
    NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3508
16
    RequiresAdjustment = true;
3509
16
  }
3510
3511
  // Merge ns_returns_retained attribute.
3512
233k
  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3513
2
    if (NewTypeInfo.getProducesResult()) {
3514
1
      Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3515
1
          << "'ns_returns_retained'";
3516
1
      Diag(OldLocation, diag::note_previous_declaration);
3517
1
      return true;
3518
1
    }
3519
3520
1
    NewTypeInfo = NewTypeInfo.withProducesResult(true);
3521
1
    RequiresAdjustment = true;
3522
1
  }
3523
3524
233k
  if (OldTypeInfo.getNoCallerSavedRegs() !=
3525
233k
      NewTypeInfo.getNoCallerSavedRegs()) {
3526
1
    if (NewTypeInfo.getNoCallerSavedRegs()) {
3527
1
      AnyX86NoCallerSavedRegistersAttr *Attr =
3528
1
        New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3529
1
      Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3530
1
      Diag(OldLocation, diag::note_previous_declaration);
3531
1
      return true;
3532
1
    }
3533
3534
0
    NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3535
0
    RequiresAdjustment = true;
3536
0
  }
3537
3538
233k
  if (RequiresAdjustment) {
3539
931
    const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3540
931
    AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3541
931
    New->setType(QualType(AdjustedType, 0));
3542
931
    NewQType = Context.getCanonicalType(New->getType());
3543
931
  }
3544
3545
  // If this redeclaration makes the function inline, we may need to add it to
3546
  // UndefinedButUsed.
3547
233k
  if (!Old->isInlined() && 
New->isInlined()186k
&&
3548
233k
      
!New->hasAttr<GNUInlineAttr>()61.4k
&&
3549
233k
      
!getLangOpts().GNUInline61.4k
&&
3550
233k
      
Old->isUsed(false)61.4k
&&
3551
233k
      
!Old->isDefined()23
&&
!New->isThisDeclarationADefinition()17
)
3552
17
    UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3553
17
                                           SourceLocation()));
3554
3555
  // If this redeclaration makes it newly gnu_inline, we don't want to warn
3556
  // about it.
3557
233k
  if (New->hasAttr<GNUInlineAttr>() &&
3558
233k
      
Old->isInlined()44
&&
!Old->hasAttr<GNUInlineAttr>()17
) {
3559
1
    UndefinedButUsed.erase(Old->getCanonicalDecl());
3560
1
  }
3561
3562
  // If pass_object_size params don't match up perfectly, this isn't a valid
3563
  // redeclaration.
3564
233k
  if (Old->getNumParams() > 0 && 
Old->getNumParams() == New->getNumParams()191k
&&
3565
233k
      
!hasIdenticalPassObjectSizeAttrs(Old, New)191k
) {
3566
6
    Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3567
6
        << New->getDeclName();
3568
6
    Diag(OldLocation, PrevDiag) << Old << Old->getType();
3569
6
    return true;
3570
6
  }
3571
3572
233k
  if (getLangOpts().CPlusPlus) {
3573
    // C++1z [over.load]p2
3574
    //   Certain function declarations cannot be overloaded:
3575
    //     -- Function declarations that differ only in the return type,
3576
    //        the exception specification, or both cannot be overloaded.
3577
3578
    // Check the exception specifications match. This may recompute the type of
3579
    // both Old and New if it resolved exception specifications, so grab the
3580
    // types again after this. Because this updates the type, we do this before
3581
    // any of the other checks below, which may update the "de facto" NewQType
3582
    // but do not necessarily update the type of New.
3583
215k
    if (CheckEquivalentExceptionSpec(Old, New))
3584
53
      return true;
3585
215k
    OldQType = Context.getCanonicalType(Old->getType());
3586
215k
    NewQType = Context.getCanonicalType(New->getType());
3587
3588
    // Go back to the type source info to compare the declared return types,
3589
    // per C++1y [dcl.type.auto]p13:
3590
    //   Redeclarations or specializations of a function or function template
3591
    //   with a declared return type that uses a placeholder type shall also
3592
    //   use that placeholder, not a deduced type.
3593
215k
    QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3594
215k
    QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3595
215k
    if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3596
215k
        canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3597
100
                                       OldDeclaredReturnType)) {
3598
96
      QualType ResQT;
3599
96
      if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3600
96
          
OldDeclaredReturnType->isObjCObjectPointerType()9
)
3601
        // FIXME: This does the wrong thing for a deduced return type.
3602
9
        ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3603
96
      if (ResQT.isNull()) {
3604
88
        if (New->isCXXClassMember() && 
New->isOutOfLine()26
)
3605
23
          Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3606
23
              << New << New->getReturnTypeSourceRange();
3607
65
        else
3608
65
          Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3609
65
              << New->getReturnTypeSourceRange();
3610
88
        Diag(OldLocation, PrevDiag) << Old << Old->getType()
3611
88
                                    << Old->getReturnTypeSourceRange();
3612
88
        return true;
3613
88
      }
3614
8
      else
3615
8
        NewQType = ResQT;
3616
96
    }
3617
3618
215k
    QualType OldReturnType = OldType->getReturnType();
3619
215k
    QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3620
215k
    if (OldReturnType != NewReturnType) {
3621
      // If this function has a deduced return type and has already been
3622
      // defined, copy the deduced value from the old declaration.
3623
77
      AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3624
77
      if (OldAT && 
OldAT->isDeduced()73
) {
3625
49
        QualType DT = OldAT->getDeducedType();
3626
49
        if (DT.isNull()) {
3627
24
          New->setType(SubstAutoTypeDependent(New->getType()));
3628
24
          NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3629
25
        } else {
3630
25
          New->setType(SubstAutoType(New->getType(), DT));
3631
25
          NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3632
25
        }
3633
49
      }
3634
77
    }
3635
3636
215k
    const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3637
215k
    CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3638
215k
    if (OldMethod && 
NewMethod147k
) {
3639
      // Preserve triviality.
3640
147k
      NewMethod->setTrivial(OldMethod->isTrivial());
3641
3642
      // MSVC allows explicit template specialization at class scope:
3643
      // 2 CXXMethodDecls referring to the same function will be injected.
3644
      // We don't want a redeclaration error.
3645
147k
      bool IsClassScopeExplicitSpecialization =
3646
147k
                              OldMethod->isFunctionTemplateSpecialization() &&
3647
147k
                              
NewMethod->isFunctionTemplateSpecialization()744
;
3648
147k
      bool isFriend = NewMethod->getFriendObjectKind();
3649
3650
147k
      if (!isFriend && 
NewMethod->getLexicalDeclContext()->isRecord()147k
&&
3651
147k
          
!IsClassScopeExplicitSpecialization294
) {
3652
        //    -- Member function declarations with the same name and the
3653
        //       same parameter types cannot be overloaded if any of them
3654
        //       is a static member function declaration.
3655
121
        if (OldMethod->isStatic() != NewMethod->isStatic()) {
3656
1
          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3657
1
          Diag(OldLocation, PrevDiag) << Old << Old->getType();
3658
1
          return true;
3659
1
        }
3660
3661
        // C++ [class.mem]p1:
3662
        //   [...] A member shall not be declared twice in the
3663
        //   member-specification, except that a nested class or member
3664
        //   class template can be declared and then later defined.
3665
120
        if (!inTemplateInstantiation()) {
3666
118
          unsigned NewDiag;
3667
118
          if (isa<CXXConstructorDecl>(OldMethod))
3668
10
            NewDiag = diag::err_constructor_redeclared;
3669
108
          else if (isa<CXXDestructorDecl>(NewMethod))
3670
14
            NewDiag = diag::err_destructor_redeclared;
3671
94
          else if (isa<CXXConversionDecl>(NewMethod))
3672
14
            NewDiag = diag::err_conv_function_redeclared;
3673
80
          else
3674
80
            NewDiag = diag::err_member_redeclared;
3675
3676
118
          Diag(New->getLocation(), NewDiag);
3677
118
        } else {
3678
2
          Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3679
2
            << New << New->getType();
3680
2
        }
3681
120
        Diag(OldLocation, PrevDiag) << Old << Old->getType();
3682
120
        return true;
3683
3684
      // Complain if this is an explicit declaration of a special
3685
      // member that was initially declared implicitly.
3686
      //
3687
      // As an exception, it's okay to befriend such methods in order
3688
      // to permit the implicit constructor/destructor/operator calls.
3689
147k
      } else if (OldMethod->isImplicit()) {
3690
117
        if (isFriend) {
3691
113
          NewMethod->setImplicit();
3692
113
        } else {
3693
4
          Diag(NewMethod->getLocation(),
3694
4
               diag::err_definition_of_implicitly_declared_member)
3695
4
            << New << getSpecialMember(OldMethod);
3696
4
          return true;
3697
4
        }
3698
147k
      } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && 
!isFriend36
) {
3699
10
        Diag(NewMethod->getLocation(),
3700
10
             diag::err_definition_of_explicitly_defaulted_member)
3701
10
          << getSpecialMember(OldMethod);
3702
10
        return true;
3703
10
      }
3704
147k
    }
3705
3706
    // C++11 [dcl.attr.noreturn]p1:
3707
    //   The first declaration of a function shall specify the noreturn
3708
    //   attribute if any declaration of that function specifies the noreturn
3709
    //   attribute.
3710
215k
    if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3711
2
      if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3712
1
        Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3713
1
            << NRA;
3714
1
        Diag(Old->getLocation(), diag::note_previous_declaration);
3715
1
      }
3716
3717
    // C++11 [dcl.attr.depend]p2:
3718
    //   The first declaration of a function shall specify the
3719
    //   carries_dependency attribute for its declarator-id if any declaration
3720
    //   of the function specifies the carries_dependency attribute.
3721
215k
    const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3722
215k
    if (CDA && 
!Old->hasAttr<CarriesDependencyAttr>()3
) {
3723
2
      Diag(CDA->getLocation(),
3724
2
           diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3725
2
      Diag(Old->getFirstDecl()->getLocation(),
3726
2
           diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3727
2
    }
3728
3729
    // (C++98 8.3.5p3):
3730
    //   All declarations for a function shall agree exactly in both the
3731
    //   return type and the parameter-type-list.
3732
    // We also want to respect all the extended bits except noreturn.
3733
3734
    // noreturn should now match unless the old type info didn't have it.
3735
215k
    QualType OldQTypeForComparison = OldQType;
3736
215k
    if (!OldTypeInfo.getNoReturn() && 
NewTypeInfo.getNoReturn()214k
) {
3737
0
      auto *OldType = OldQType->castAs<FunctionProtoType>();
3738
0
      const FunctionType *OldTypeForComparison
3739
0
        = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3740
0
      OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3741
0
      assert(OldQTypeForComparison.isCanonical());
3742
0
    }
3743
3744
215k
    if (haveIncompatibleLanguageLinkages(Old, New)) {
3745
      // As a special case, retain the language linkage from previous
3746
      // declarations of a friend function as an extension.
3747
      //
3748
      // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3749
      // and is useful because there's otherwise no way to specify language
3750
      // linkage within class scope.
3751
      //
3752
      // Check cautiously as the friend object kind isn't yet complete.
3753
38
      if (New->getFriendObjectKind() != Decl::FOK_None) {
3754
2
        Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3755
2
        Diag(OldLocation, PrevDiag);
3756
36
      } else {
3757
36
        Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3758
36
        Diag(OldLocation, PrevDiag);
3759
36
        return true;
3760
36
      }
3761
38
    }
3762
3763
    // If the function types are compatible, merge the declarations. Ignore the
3764
    // exception specifier because it was already checked above in
3765
    // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3766
    // about incompatible types under -fms-compatibility.
3767
215k
    if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3768
215k
                                                         NewQType))
3769
214k
      return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3770
3771
    // If the types are imprecise (due to dependent constructs in friends or
3772
    // local extern declarations), it's OK if they differ. We'll check again
3773
    // during instantiation.
3774
45
    if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3775
28
      return false;
3776
3777
    // Fall through for conflicting redeclarations and redefinitions.
3778
45
  }
3779
3780
  // C: Function types need to be compatible, not identical. This handles
3781
  // duplicate function decls like "void f(int); void f(enum X);" properly.
3782
18.0k
  if (!getLangOpts().CPlusPlus &&
3783
18.0k
      
Context.typesAreCompatible(OldQType, NewQType)18.0k
) {
3784
17.9k
    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3785
17.9k
    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3786
17.9k
    const FunctionProtoType *OldProto = nullptr;
3787
17.9k
    if (MergeTypeWithOld && 
isa<FunctionNoProtoType>(NewFuncType)17.8k
&&
3788
17.9k
        
(OldProto = dyn_cast<FunctionProtoType>(OldFuncType))535
) {
3789
      // The old declaration provided a function prototype, but the
3790
      // new declaration does not. Merge in the prototype.
3791
63
      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3792
0
      SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3793
63
      NewQType =
3794
63
          Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3795
63
                                  OldProto->getExtProtoInfo());
3796
63
      New->setType(NewQType);
3797
63
      New->setHasInheritedPrototype();
3798
3799
      // Synthesize parameters with the same types.
3800
63
      SmallVector<ParmVarDecl*, 16> Params;
3801
63
      for (const auto &ParamType : OldProto->param_types()) {
3802
29
        ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3803
29
                                                 SourceLocation(), nullptr,
3804
29
                                                 ParamType, /*TInfo=*/nullptr,
3805
29
                                                 SC_None, nullptr);
3806
29
        Param->setScopeInfo(0, Params.size());
3807
29
        Param->setImplicit();
3808
29
        Params.push_back(Param);
3809
29
      }
3810
3811
63
      New->setParams(Params);
3812
63
    }
3813
3814
0
    return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3815
17.9k
  }
3816
3817
  // Check if the function types are compatible when pointer size address
3818
  // spaces are ignored.
3819
165
  if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3820
3
    return false;
3821
3822
  // GNU C permits a K&R definition to follow a prototype declaration
3823
  // if the declared types of the parameters in the K&R definition
3824
  // match the types in the prototype declaration, even when the
3825
  // promoted types of the parameters from the K&R definition differ
3826
  // from the types in the prototype. GCC then keeps the types from
3827
  // the prototype.
3828
  //
3829
  // If a variadic prototype is followed by a non-variadic K&R definition,
3830
  // the K&R definition becomes variadic.  This is sort of an edge case, but
3831
  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3832
  // C99 6.9.1p8.
3833
162
  if (!getLangOpts().CPlusPlus &&
3834
162
      
Old->hasPrototype()145
&&
!New->hasPrototype()116
&&
3835
162
      
New->getType()->getAs<FunctionProtoType>()32
&&
3836
162
      
Old->getNumParams() == New->getNumParams()9
) {
3837
8
    SmallVector<QualType, 16> ArgTypes;
3838
8
    SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3839
8
    const FunctionProtoType *OldProto
3840
8
      = Old->getType()->getAs<FunctionProtoType>();
3841
8
    const FunctionProtoType *NewProto
3842
8
      = New->getType()->getAs<FunctionProtoType>();
3843
3844
    // Determine whether this is the GNU C extension.
3845
8
    QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3846
8
                                               NewProto->getReturnType());
3847
8
    bool LooseCompatible = !MergedReturn.isNull();
3848
8
    for (unsigned Idx = 0, End = Old->getNumParams();
3849
18
         LooseCompatible && 
Idx != End15
;
++Idx10
) {
3850
10
      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3851
10
      ParmVarDecl *NewParm = New->getParamDecl(Idx);
3852
10
      if (Context.typesAreCompatible(OldParm->getType(),
3853
10
                                     NewProto->getParamType(Idx))) {
3854
3
        ArgTypes.push_back(NewParm->getType());
3855
7
      } else if (Context.typesAreCompatible(OldParm->getType(),
3856
7
                                            NewParm->getType(),
3857
7
                                            /*CompareUnqualified=*/true)) {
3858
4
        GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3859
4
                                           NewProto->getParamType(Idx) };
3860
4
        Warnings.push_back(Warn);
3861
4
        ArgTypes.push_back(NewParm->getType());
3862
4
      } else
3863
3
        LooseCompatible = false;
3864
10
    }
3865
3866
8
    if (LooseCompatible) {
3867
9
      for (unsigned Warn = 0; Warn < Warnings.size(); 
++Warn4
) {
3868
4
        Diag(Warnings[Warn].NewParm->getLocation(),
3869
4
             diag::ext_param_promoted_not_compatible_with_prototype)
3870
4
          << Warnings[Warn].PromotedType
3871
4
          << Warnings[Warn].OldParm->getType();
3872
4
        if (Warnings[Warn].OldParm->getLocation().isValid())
3873
3
          Diag(Warnings[Warn].OldParm->getLocation(),
3874
3
               diag::note_previous_declaration);
3875
4
      }
3876
3877
5
      if (MergeTypeWithOld)
3878
5
        New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3879
5
                                             OldProto->getExtProtoInfo()));
3880
5
      return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3881
5
    }
3882
3883
    // Fall through to diagnose conflicting types.
3884
8
  }
3885
3886
  // A function that has already been declared has been redeclared or
3887
  // defined with a different type; show an appropriate diagnostic.
3888
3889
  // If the previous declaration was an implicitly-generated builtin
3890
  // declaration, then at the very least we should use a specialized note.
3891
157
  unsigned BuiltinID;
3892
157
  if (Old->isImplicit() && 
(BuiltinID = Old->getBuiltinID())71
) {
3893
    // If it's actually a library-defined builtin function like 'malloc'
3894
    // or 'printf', just warn about the incompatible redeclaration.
3895
68
    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3896
65
      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3897
65
      Diag(OldLocation, diag::note_previous_builtin_declaration)
3898
65
        << Old << Old->getType();
3899
65
      return false;
3900
65
    }
3901
3902
3
    PrevDiag = diag::note_previous_builtin_declaration;
3903
3
  }
3904
3905
92
  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3906
92
  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3907
92
  return true;
3908
157
}
3909
3910
/// Completes the merge of two function declarations that are
3911
/// known to be compatible.
3912
///
3913
/// This routine handles the merging of attributes and other
3914
/// properties of function declarations from the old declaration to
3915
/// the new declaration, once we know that New is in fact a
3916
/// redeclaration of Old.
3917
///
3918
/// \returns false
3919
bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3920
232k
                                        Scope *S, bool MergeTypeWithOld) {
3921
  // Merge the attributes
3922
232k
  mergeDeclAttributes(New, Old);
3923
3924
  // Merge "pure" flag.
3925
232k
  if (Old->isPure())
3926
18
    New->setPure();
3927
3928
  // Merge "used" flag.
3929
232k
  if (Old->getMostRecentDecl()->isUsed(false))
3930
2.73k
    New->setIsUsed();
3931
3932
  // Merge attributes from the parameters.  These can mismatch with K&R
3933
  // declarations.
3934
232k
  if (New->getNumParams() == Old->getNumParams())
3935
598k
      
for (unsigned i = 0, e = New->getNumParams(); 232k
i != e;
++i365k
) {
3936
365k
        ParmVarDecl *NewParam = New->getParamDecl(i);
3937
365k
        ParmVarDecl *OldParam = Old->getParamDecl(i);
3938
365k
        mergeParamDeclAttributes(NewParam, OldParam, *this);
3939
365k
        mergeParamDeclTypes(NewParam, OldParam, *this);
3940
365k
      }
3941
3942
232k
  if (getLangOpts().CPlusPlus)
3943
214k
    return MergeCXXFunctionDecl(New, Old, S);
3944
3945
  // Merge the function types so the we get the composite types for the return
3946
  // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3947
  // was visible.
3948
17.9k
  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3949
17.9k
  if (!Merged.isNull() && 
MergeTypeWithOld17.9k
)
3950
17.8k
    New->setType(Merged);
3951
3952
17.9k
  return false;
3953
232k
}
3954
3955
void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3956
143k
                                ObjCMethodDecl *oldMethod) {
3957
  // Merge the attributes, including deprecated/unavailable
3958
143k
  AvailabilityMergeKind MergeKind =
3959
143k
      isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3960
143k
          ? 
(11.1k
oldMethod->isOptional()11.1k
?
AMK_OptionalProtocolImplementation579
3961
11.1k
                                     : 
AMK_ProtocolImplementation10.5k
)
3962
143k
          : 
isa<ObjCImplDecl>(newMethod->getDeclContext())132k
?
AMK_Redeclaration4.74k
3963
132k
                                                           : 
AMK_Override127k
;
3964
3965
143k
  mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3966
3967
  // Merge attributes from the parameters.
3968
143k
  ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3969
143k
                                       oe = oldMethod->param_end();
3970
143k
  for (ObjCMethodDecl::param_iterator
3971
143k
         ni = newMethod->param_begin(), ne = newMethod->param_end();
3972
233k
       ni != ne && 
oi != oe89.6k
;
++ni, ++oi89.6k
)
3973
89.6k
    mergeParamDeclAttributes(*ni, *oi, *this);
3974
3975
143k
  CheckObjCMethodOverride(newMethod, oldMethod);
3976
143k
}
3977
3978
187
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3979
187
  assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3980
3981
187
  S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3982
187
         ? 
diag::err_redefinition_different_type96
3983
187
         : 
diag::err_redeclaration_different_type91
)
3984
187
    << New->getDeclName() << New->getType() << Old->getType();
3985
3986
187
  diag::kind PrevDiag;
3987
187
  SourceLocation OldLocation;
3988
187
  std::tie(PrevDiag, OldLocation)
3989
187
    = getNoteDiagForInvalidRedeclaration(Old, New);
3990
187
  S.Diag(OldLocation, PrevDiag);
3991
187
  New->setInvalidDecl();
3992
187
}
3993
3994
/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3995
/// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3996
/// emitting diagnostics as appropriate.
3997
///
3998
/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3999
/// to here in AddInitializerToDecl. We can't check them before the initializer
4000
/// is attached.
4001
void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4002
62.1k
                             bool MergeTypeWithOld) {
4003
62.1k
  if (New->isInvalidDecl() || 
Old->isInvalidDecl()62.1k
)
4004
49
    return;
4005
4006
62.0k
  QualType MergedT;
4007
62.0k
  if (getLangOpts().CPlusPlus) {
4008
60.9k
    if (New->getType()->isUndeducedType()) {
4009
      // We don't know what the new type is until the initializer is attached.
4010
22
      return;
4011
60.9k
    } else if (Context.hasSameType(New->getType(), Old->getType())) {
4012
      // These could still be something that needs exception specs checked.
4013
60.6k
      return MergeVarDeclExceptionSpecs(New, Old);
4014
60.6k
    }
4015
    // C++ [basic.link]p10:
4016
    //   [...] the types specified by all declarations referring to a given
4017
    //   object or function shall be identical, except that declarations for an
4018
    //   array object can specify array types that differ by the presence or
4019
    //   absence of a major array bound (8.3.4).
4020
262
    else if (Old->getType()->isArrayType() && 
New->getType()->isArrayType()150
) {
4021
131
      const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4022
131
      const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4023
4024
      // We are merging a variable declaration New into Old. If it has an array
4025
      // bound, and that bound differs from Old's bound, we should diagnose the
4026
      // mismatch.
4027
131
      if (!NewArray->isIncompleteArrayType() && 
!NewArray->isDependentType()62
) {
4028
122
        for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4029
75
             
PrevVD = PrevVD->getPreviousDecl()73
) {
4030
75
          QualType PrevVDTy = PrevVD->getType();
4031
75
          if (PrevVDTy->isIncompleteArrayType() || 
PrevVDTy->isDependentType()27
)
4032
52
            continue;
4033
4034
23
          if (!Context.hasSameType(New->getType(), PrevVDTy))
4035
2
            return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4036
23
        }
4037
49
      }
4038
4039
129
      if (OldArray->isIncompleteArrayType() && 
NewArray->isArrayType()56
) {
4040
56
        if (Context.hasSameType(OldArray->getElementType(),
4041
56
                                NewArray->getElementType()))
4042
56
          MergedT = New->getType();
4043
56
      }
4044
      // FIXME: Check visibility. New is hidden but has a complete type. If New
4045
      // has no array bound, it should not inherit one from Old, if Old is not
4046
      // visible.
4047
73
      else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4048
69
        if (Context.hasSameType(OldArray->getElementType(),
4049
69
                                NewArray->getElementType()))
4050
68
          MergedT = Old->getType();
4051
69
      }
4052
129
    }
4053
131
    else if (New->getType()->isObjCObjectPointerType() &&
4054
131
               
Old->getType()->isObjCObjectPointerType()4
) {
4055
4
      MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4056
4
                                              Old->getType());
4057
4
    }
4058
60.9k
  } else {
4059
    // C 6.2.7p2:
4060
    //   All declarations that refer to the same object or function shall have
4061
    //   compatible type.
4062
1.08k
    MergedT = Context.mergeTypes(New->getType(), Old->getType());
4063
1.08k
  }
4064
1.34k
  if (MergedT.isNull()) {
4065
    // It's OK if we couldn't merge types if either type is dependent, for a
4066
    // block-scope variable. In other cases (static data members of class
4067
    // templates, variable templates, ...), we require the types to be
4068
    // equivalent.
4069
    // FIXME: The C++ standard doesn't say anything about this.
4070
215
    if ((New->getType()->isDependentType() ||
4071
215
         
Old->getType()->isDependentType()175
) &&
New->isLocalVarDecl()56
) {
4072
      // If the old type was dependent, we can't merge with it, so the new type
4073
      // becomes dependent for now. We'll reproduce the original type when we
4074
      // instantiate the TypeSourceInfo for the variable.
4075
30
      if (!New->getType()->isDependentType() && 
MergeTypeWithOld7
)
4076
1
        New->setType(Context.DependentTy);
4077
30
      return;
4078
30
    }
4079
185
    return diagnoseVarDeclTypeMismatch(*this, New, Old);
4080
215
  }
4081
4082
  // Don't actually update the type on the new declaration if the old
4083
  // declaration was an extern declaration in a different scope.
4084
1.12k
  if (MergeTypeWithOld)
4085
1.06k
    New->setType(MergedT);
4086
1.12k
}
4087
4088
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4089
62.1k
                                  LookupResult &Previous) {
4090
  // C11 6.2.7p4:
4091
  //   For an identifier with internal or external linkage declared
4092
  //   in a scope in which a prior declaration of that identifier is
4093
  //   visible, if the prior declaration specifies internal or
4094
  //   external linkage, the type of the identifier at the later
4095
  //   declaration becomes the composite type.
4096
  //
4097
  // If the variable isn't visible, we do not merge with its type.
4098
62.1k
  if (Previous.isShadowed())
4099
38
    return false;
4100
4101
62.0k
  if (S.getLangOpts().CPlusPlus) {
4102
    // C++11 [dcl.array]p3:
4103
    //   If there is a preceding declaration of the entity in the same
4104
    //   scope in which the bound was specified, an omitted array bound
4105
    //   is taken to be the same as in that earlier declaration.
4106
60.9k
    return NewVD->isPreviousDeclInSameBlockScope() ||
4107
60.9k
           
(60.9k
!OldVD->getLexicalDeclContext()->isFunctionOrMethod()60.9k
&&
4108
60.9k
            
!NewVD->getLexicalDeclContext()->isFunctionOrMethod()60.7k
);
4109
60.9k
  } else {
4110
    // If the old declaration was function-local, don't merge with its
4111
    // type unless we're in the same function.
4112
1.07k
    return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4113
1.07k
           
OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext()31
;
4114
1.07k
  }
4115
62.0k
}
4116
4117
/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4118
/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4119
/// situation, merging decls or emitting diagnostics as appropriate.
4120
///
4121
/// Tentative definition rules (C99 6.9.2p2) are checked by
4122
/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4123
/// definitions here, since the initializer hasn't been attached.
4124
///
4125
62.0k
void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4126
  // If the new decl is already invalid, don't do any other checking.
4127
62.0k
  if (New->isInvalidDecl())
4128
0
    return;
4129
4130
62.0k
  if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4131
4
    return;
4132
4133
62.0k
  VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4134
4135
  // Verify the old decl was also a variable or variable template.
4136
62.0k
  VarDecl *Old = nullptr;
4137
62.0k
  VarTemplateDecl *OldTemplate = nullptr;
4138
62.0k
  if (Previous.isSingleResult()) {
4139
62.0k
    if (NewTemplate) {
4140
420
      OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4141
420
      Old = OldTemplate ? 
OldTemplate->getTemplatedDecl()416
:
nullptr4
;
4142
4143
420
      if (auto *Shadow =
4144
420
              dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4145
3
        if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4146
2
          return New->setInvalidDecl();
4147
61.6k
    } else {
4148
61.6k
      Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4149
4150
61.6k
      if (auto *Shadow =
4151
61.6k
              dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4152
9
        if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4153
8
          return New->setInvalidDecl();
4154
61.6k
    }
4155
62.0k
  }
4156
62.0k
  if (!Old) {
4157
52
    Diag(New->getLocation(), diag::err_redefinition_different_kind)
4158
52
        << New->getDeclName();
4159
52
    notePreviousDefinition(Previous.getRepresentativeDecl(),
4160
52
                           New->getLocation());
4161
52
    return New->setInvalidDecl();
4162
52
  }
4163
4164
  // If the old declaration was found in an inline namespace and the new
4165
  // declaration was qualified, update the DeclContext to match.
4166
62.0k
  adjustDeclContextForDeclaratorDecl(New, Old);
4167
4168
  // Ensure the template parameters are compatible.
4169
62.0k
  if (NewTemplate &&
4170
62.0k
      !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4171
414
                                      OldTemplate->getTemplateParameters(),
4172
414
                                      /*Complain=*/true, TPL_TemplateMatch))
4173
10
    return New->setInvalidDecl();
4174
4175
  // C++ [class.mem]p1:
4176
  //   A member shall not be declared twice in the member-specification [...]
4177
  //
4178
  // Here, we need only consider static data members.
4179
62.0k
  if (Old->isStaticDataMember() && 
!New->isOutOfLine()58.7k
) {
4180
11
    Diag(New->getLocation(), diag::err_duplicate_member)
4181
11
      << New->getIdentifier();
4182
11
    Diag(Old->getLocation(), diag::note_previous_declaration);
4183
11
    New->setInvalidDecl();
4184
11
  }
4185
4186
62.0k
  mergeDeclAttributes(New, Old);
4187
  // Warn if an already-declared variable is made a weak_import in a subsequent
4188
  // declaration
4189
62.0k
  if (New->hasAttr<WeakImportAttr>() &&
4190
62.0k
      
Old->getStorageClass() == SC_None15
&&
4191
62.0k
      
!Old->hasAttr<WeakImportAttr>()3
) {
4192
2
    Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4193
2
    Diag(Old->getLocation(), diag::note_previous_declaration);
4194
    // Remove weak_import attribute on new declaration.
4195
2
    New->dropAttr<WeakImportAttr>();
4196
2
  }
4197
4198
62.0k
  if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4199
5
    if (!Old->hasAttr<InternalLinkageAttr>()) {
4200
2
      Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4201
2
          << ILA;
4202
2
      Diag(Old->getLocation(), diag::note_previous_declaration);
4203
2
      New->dropAttr<InternalLinkageAttr>();
4204
2
    }
4205
4206
  // Merge the types.
4207
62.0k
  VarDecl *MostRecent = Old->getMostRecentDecl();
4208
62.0k
  if (MostRecent != Old) {
4209
101
    MergeVarDeclTypes(New, MostRecent,
4210
101
                      mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4211
101
    if (New->isInvalidDecl())
4212
6
      return;
4213
101
  }
4214
4215
62.0k
  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4216
62.0k
  if (New->isInvalidDecl())
4217
198
    return;
4218
4219
61.8k
  diag::kind PrevDiag;
4220
61.8k
  SourceLocation OldLocation;
4221
61.8k
  std::tie(PrevDiag, OldLocation) =
4222
61.8k
      getNoteDiagForInvalidRedeclaration(Old, New);
4223
4224
  // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4225
61.8k
  if (New->getStorageClass() == SC_Static &&
4226
61.8k
      
!New->isStaticDataMember()71
&&
4227
61.8k
      
Old->hasExternalFormalLinkage()68
) {
4228
16
    if (getLangOpts().MicrosoftExt) {
4229
3
      Diag(New->getLocation(), diag::ext_static_non_static)
4230
3
          << New->getDeclName();
4231
3
      Diag(OldLocation, PrevDiag);
4232
13
    } else {
4233
13
      Diag(New->getLocation(), diag::err_static_non_static)
4234
13
          << New->getDeclName();
4235
13
      Diag(OldLocation, PrevDiag);
4236
13
      return New->setInvalidDecl();
4237
13
    }
4238
16
  }
4239
  // C99 6.2.2p4:
4240
  //   For an identifier declared with the storage-class specifier
4241
  //   extern in a scope in which a prior declaration of that
4242
  //   identifier is visible,23) if the prior declaration specifies
4243
  //   internal or external linkage, the linkage of the identifier at
4244
  //   the later declaration is the same as the linkage specified at
4245
  //   the prior declaration. If no prior declaration is visible, or
4246
  //   if the prior declaration specifies no linkage, then the
4247
  //   identifier has external linkage.
4248
61.7k
  if (New->hasExternalStorage() && 
Old->hasLinkage()1.84k
)
4249
1.83k
    /* Okay */;
4250
59.9k
  else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4251
59.9k
           
!New->isStaticDataMember()59.8k
&&
4252
59.9k
           
Old->getCanonicalDecl()->getStorageClass() == SC_Static1.17k
) {
4253
4
    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4254
4
    Diag(OldLocation, PrevDiag);
4255
4
    return New->setInvalidDecl();
4256
4
  }
4257
4258
  // Check if extern is followed by non-extern and vice-versa.
4259
61.7k
  if (New->hasExternalStorage() &&
4260
61.7k
      
!Old->hasLinkage()1.84k
&&
Old->isLocalVarDeclOrParm()5
) {
4261
5
    Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4262
5
    Diag(OldLocation, PrevDiag);
4263
5
    return New->setInvalidDecl();
4264
5
  }
4265
61.7k
  if (Old->hasLinkage() && 
New->isLocalVarDeclOrParm()61.7k
&&
4266
61.7k
      
!New->hasExternalStorage()212
) {
4267
4
    Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4268
4
    Diag(OldLocation, PrevDiag);
4269
4
    return New->setInvalidDecl();
4270
4
  }
4271
4272
61.7k
  if (CheckRedeclarationModuleOwnership(New, Old))
4273
19
    return;
4274
4275
  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4276
4277
  // FIXME: The test for external storage here seems wrong? We still
4278
  // need to check for mismatches.
4279
61.7k
  if (!New->hasExternalStorage() && 
!New->isFileVarDecl()59.9k
&&
4280
      // Don't complain about out-of-line definitions of static members.
4281
61.7k
      
!(72
Old->getLexicalDeclContext()->isRecord()72
&&
4282
72
        
!New->getLexicalDeclContext()->isRecord()0
)) {
4283
72
    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4284
72
    Diag(OldLocation, PrevDiag);
4285
72
    return New->setInvalidDecl();
4286
72
  }
4287
4288
61.6k
  if (New->isInline() && 
!Old->getMostRecentDecl()->isInline()979
) {
4289
293
    if (VarDecl *Def = Old->getDefinition()) {
4290
      // C++1z [dcl.fcn.spec]p4:
4291
      //   If the definition of a variable appears in a translation unit before
4292
      //   its first declaration as inline, the program is ill-formed.
4293
0
      Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4294
0
      Diag(Def->getLocation(), diag::note_previous_definition);
4295
0
    }
4296
293
  }
4297
4298
  // If this redeclaration makes the variable inline, we may need to add it to
4299
  // UndefinedButUsed.
4300
61.6k
  if (!Old->isInline() && 
New->isInline()60.9k
&&
Old->isUsed(false)293
&&
4301
61.6k
      
!Old->getDefinition()0
&&
!New->isThisDeclarationADefinition()0
)
4302
0
    UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4303
0
                                           SourceLocation()));
4304
4305
61.6k
  if (New->getTLSKind() != Old->getTLSKind()) {
4306
25
    if (!Old->getTLSKind()) {
4307
11
      Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4308
11
      Diag(OldLocation, PrevDiag);
4309
14
    } else if (!New->getTLSKind()) {
4310
10
      Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4311
10
      Diag(OldLocation, PrevDiag);
4312
10
    } else {
4313
      // Do not allow redeclaration to change the variable between requiring
4314
      // static and dynamic initialization.
4315
      // FIXME: GCC allows this, but uses the TLS keyword on the first
4316
      // declaration to determine the kind. Do we need to be compatible here?
4317
4
      Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4318
4
        << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4319
4
      Diag(OldLocation, PrevDiag);
4320
4
    }
4321
25
  }
4322
4323
  // C++ doesn't have tentative definitions, so go right ahead and check here.
4324
61.6k
  if (getLangOpts().CPlusPlus &&
4325
61.6k
      
New->isThisDeclarationADefinition() == VarDecl::Definition60.7k
) {
4326
58.2k
    if (Old->isStaticDataMember() && 
Old->getCanonicalDecl()->isInline()57.6k
&&
4327
58.2k
        
Old->getCanonicalDecl()->isConstexpr()12
) {
4328
      // This definition won't be a definition any more once it's been merged.
4329
8
      Diag(New->getLocation(),
4330
8
           diag::warn_deprecated_redundant_constexpr_static_def);
4331
58.2k
    } else if (VarDecl *Def = Old->getDefinition()) {
4332
42
      if (checkVarDeclRedefinition(Def, New))
4333
33
        return;
4334
42
    }
4335
58.2k
  }
4336
4337
61.6k
  if (haveIncompatibleLanguageLinkages(Old, New)) {
4338
3
    Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4339
3
    Diag(OldLocation, PrevDiag);
4340
3
    New->setInvalidDecl();
4341
3
    return;
4342
3
  }
4343
4344
  // Merge "used" flag.
4345
61.6k
  if (Old->getMostRecentDecl()->isUsed(false))
4346
585
    New->setIsUsed();
4347
4348
  // Keep a chain of previous declarations.
4349
61.6k
  New->setPreviousDecl(Old);
4350
61.6k
  if (NewTemplate)
4351
380
    NewTemplate->setPreviousDecl(OldTemplate);
4352
4353
  // Inherit access appropriately.
4354
61.6k
  New->setAccess(Old->getAccess());
4355
61.6k
  if (NewTemplate)
4356
380
    NewTemplate->setAccess(New->getAccess());
4357
4358
61.6k
  if (Old->isInline())
4359
694
    New->setImplicitlyInline();
4360
61.6k
}
4361
4362
332
void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4363
332
  SourceManager &SrcMgr = getSourceManager();
4364
332
  auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4365
332
  auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4366
332
  auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4367
332
  auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4368
332
  auto &HSI = PP.getHeaderSearchInfo();
4369
332
  StringRef HdrFilename =
4370
332
      SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4371
4372
332
  auto noteFromModuleOrInclude = [&](Module *Mod,
4373
332
                                     SourceLocation IncLoc) -> bool {
4374
    // Redefinition errors with modules are common with non modular mapped
4375
    // headers, example: a non-modular header H in module A that also gets
4376
    // included directly in a TU. Pointing twice to the same header/definition
4377
    // is confusing, try to get better diagnostics when modules is on.
4378
16
    if (IncLoc.isValid()) {
4379
8
      if (Mod) {
4380
3
        Diag(IncLoc, diag::note_redefinition_modules_same_file)
4381
3
            << HdrFilename.str() << Mod->getFullModuleName();
4382
3
        if (!Mod->DefinitionLoc.isInvalid())
4383
1
          Diag(Mod->DefinitionLoc, diag::note_defined_here)
4384
1
              << Mod->getFullModuleName();
4385
5
      } else {
4386
5
        Diag(IncLoc, diag::note_redefinition_include_same_file)
4387
5
            << HdrFilename.str();
4388
5
      }
4389
8
      return true;
4390
8
    }
4391
4392
8
    return false;
4393
16
  };
4394
4395
  // Is it the same file and same offset? Provide more information on why
4396
  // this leads to a redefinition error.
4397
332
  if (FNew == FOld && 
FNewDecLoc.second == FOldDecLoc.second313
) {
4398
8
    SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4399
8
    SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4400
8
    bool EmittedDiag =
4401
8
        noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4402
8
    EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4403
4404
    // If the header has no guards, emit a note suggesting one.
4405
8
    if (FOld && 
!HSI.isFileMultipleIncludeGuarded(FOld)5
)
4406
4
      Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4407
4408
8
    if (EmittedDiag)
4409
5
      return;
4410
8
  }
4411
4412
  // Redefinition coming from different files or couldn't do better above.
4413
327
  if (Old->getLocation().isValid())
4414
317
    Diag(Old->getLocation(), diag::note_previous_definition);
4415
327
}
4416
4417
/// We've just determined that \p Old and \p New both appear to be definitions
4418
/// of the same variable. Either diagnose or fix the problem.
4419
61
bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4420
61
  if (!hasVisibleDefinition(Old) &&
4421
61
      
(10
New->getFormalLinkage() == InternalLinkage10
||
4422
10
       New->isInline() ||
4423
10
       New->getDescribedVarTemplate() ||
4424
10
       
New->getNumTemplateParameterLists()8
||
4425
10
       
New->getDeclContext()->isDependentContext()1
)) {
4426
    // The previous definition is hidden, and multiple definitions are
4427
    // permitted (in separate TUs). Demote this to a declaration.
4428
9
    New->demoteThisDefinitionToDeclaration();
4429
4430
    // Make the canonical definition visible.
4431
9
    if (auto *OldTD = Old->getDescribedVarTemplate())
4432
2
      makeMergedDefinitionVisible(OldTD);
4433
9
    makeMergedDefinitionVisible(Old);
4434
9
    return false;
4435
52
  } else {
4436
52
    Diag(New->getLocation(), diag::err_redefinition) << New;
4437
52
    notePreviousDefinition(Old, New->getLocation());
4438
52
    New->setInvalidDecl();
4439
52
    return true;
4440
52
  }
4441
61
}
4442
4443
/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4444
/// no declarator (e.g. "struct foo;") is parsed.
4445
Decl *
4446
Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4447
836k
                                 RecordDecl *&AnonRecord) {
4448
836k
  return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4449
836k
                                    AnonRecord);
4450
836k
}
4451
4452
// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4453
// disambiguate entities defined in different scopes.
4454
// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4455
// compatibility.
4456
// We will pick our mangling number depending on which version of MSVC is being
4457
// targeted.
4458
38.2k
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4459
38.2k
  return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4460
38.2k
             ? 
S->getMSCurManglingNumber()148
4461
38.2k
             : 
S->getMSLastManglingNumber()38.1k
;
4462
38.2k
}
4463
4464
2.16M
void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4465
2.16M
  if (!Context.getLangOpts().CPlusPlus)
4466
1.05M
    return;
4467
4468
1.10M
  if (isa<CXXRecordDecl>(Tag->getParent())) {
4469
    // If this tag is the direct child of a class, number it if
4470
    // it is anonymous.
4471
60.8k
    if (!Tag->getName().empty() || 
Tag->getTypedefNameForAnonDecl()17.4k
)
4472
43.4k
      return;
4473
17.3k
    MangleNumberingContext &MCtx =
4474
17.3k
        Context.getManglingNumberContext(Tag->getParent());
4475
17.3k
    Context.setManglingNumber(
4476
17.3k
        Tag, MCtx.getManglingNumber(
4477
17.3k
                 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4478
17.3k
    return;
4479
60.8k
  }
4480
4481
  // If this tag isn't a direct child of a class, number it if it is local.
4482
1.04M
  MangleNumberingContext *MCtx;
4483
1.04M
  Decl *ManglingContextDecl;
4484
1.04M
  std::tie(MCtx, ManglingContextDecl) =
4485
1.04M
      getCurrentMangleNumberContext(Tag->getDeclContext());
4486
1.04M
  if (MCtx) {
4487
16.1k
    Context.setManglingNumber(
4488
16.1k
        Tag, MCtx->getManglingNumber(
4489
16.1k
                 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4490
16.1k
  }
4491
1.04M
}
4492
4493
namespace {
4494
struct NonCLikeKind {
4495
  enum {
4496
    None,
4497
    BaseClass,
4498
    DefaultMemberInit,
4499
    Lambda,
4500
    Friend,
4501
    OtherMember,
4502
    Invalid,
4503
  } Kind = None;
4504
  SourceRange Range;
4505
4506
159k
  explicit operator bool() { return Kind != None; }
4507
};
4508
}
4509
4510
/// Determine whether a class is C-like, according to the rules of C++
4511
/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4512
29.7k
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4513
29.7k
  if (RD->isInvalidDecl())
4514
0
    return {NonCLikeKind::Invalid, {}};
4515
4516
  // C++ [dcl.typedef]p9: [P1766R1]
4517
  //   An unnamed class with a typedef name for linkage purposes shall not
4518
  //
4519
  //    -- have any base classes
4520
29.7k
  if (RD->getNumBases())
4521
4
    return {NonCLikeKind::BaseClass,
4522
4
            SourceRange(RD->bases_begin()->getBeginLoc(),
4523
4
                        RD->bases_end()[-1].getEndLoc())};
4524
29.7k
  bool Invalid = false;
4525
116k
  for (Decl *D : RD->decls()) {
4526
    // Don't complain about things we already diagnosed.
4527
116k
    if (D->isInvalidDecl()) {
4528
12
      Invalid = true;
4529
12
      continue;
4530
12
    }
4531
4532
    //  -- have any [...] default member initializers
4533
116k
    if (auto *FD = dyn_cast<FieldDecl>(D)) {
4534
115k
      if (FD->hasInClassInitializer()) {
4535
4
        auto *Init = FD->getInClassInitializer();
4536
4
        return {NonCLikeKind::DefaultMemberInit,
4537
4
                Init ? Init->getSourceRange() : 
D->getSourceRange()0
};
4538
4
      }
4539
115k
      continue;
4540
115k
    }
4541
4542
    // FIXME: We don't allow friend declarations. This violates the wording of
4543
    // P1766, but not the intent.
4544
592
    if (isa<FriendDecl>(D))
4545
8
      return {NonCLikeKind::Friend, D->getSourceRange()};
4546
4547
    //  -- declare any members other than non-static data members, member
4548
    //     enumerations, or member classes,
4549
584
    if (isa<StaticAssertDecl>(D) || 
isa<IndirectFieldDecl>(D)572
||
4550
584
        
isa<EnumDecl>(D)540
)
4551
56
      continue;
4552
528
    auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4553
528
    if (!MemberRD) {
4554
110
      if (D->isImplicit())
4555
58
        continue;
4556
52
      return {NonCLikeKind::OtherMember, D->getSourceRange()};
4557
110
    }
4558
4559
    //  -- contain a lambda-expression,
4560
418
    if (MemberRD->isLambda())
4561
0
      return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4562
4563
    //  and all member classes shall also satisfy these requirements
4564
    //  (recursively).
4565
418
    if (MemberRD->isThisDeclarationADefinition()) {
4566
387
      if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4567
4
        return Kind;
4568
387
    }
4569
418
  }
4570
4571
29.6k
  return {Invalid ? 
NonCLikeKind::Invalid12
:
NonCLikeKind::None29.6k
, {}};
4572
29.7k
}
4573
4574
void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4575
595k
                                        TypedefNameDecl *NewTD) {
4576
595k
  if (TagFromDeclSpec->isInvalidDecl())
4577
9
    return;
4578
4579
  // Do nothing if the tag already has a name for linkage purposes.
4580
595k
  if (TagFromDeclSpec->hasNameForLinkage())
4581
436k
    return;
4582
4583
  // A well-formed anonymous tag must always be a TUK_Definition.
4584
159k
  assert(TagFromDeclSpec->isThisDeclarationADefinition());
4585
4586
  // The type must match the tag exactly;  no qualifiers allowed.
4587
159k
  if (!Context.hasSameType(NewTD->getUnderlyingType(),
4588
159k
                           Context.getTagDeclType(TagFromDeclSpec))) {
4589
558
    if (getLangOpts().CPlusPlus)
4590
157
      Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4591
558
    return;
4592
558
  }
4593
4594
  // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4595
  //   An unnamed class with a typedef name for linkage purposes shall [be
4596
  //   C-like].
4597
  //
4598
  // FIXME: Also diagnose if we've already computed the linkage. That ideally
4599
  // shouldn't happen, but there are constructs that the language rule doesn't
4600
  // disallow for which we can't reasonably avoid computing linkage early.
4601
158k
  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4602
158k
  NonCLikeKind NonCLike = RD ? 
getNonCLikeKindForAnonymousStruct(RD)29.3k
4603
158k
                             : 
NonCLikeKind()129k
;
4604
158k
  bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4605
158k
  if (NonCLike || 
ChangesLinkage158k
) {
4606
87
    if (NonCLike.Kind == NonCLikeKind::Invalid)
4607
12
      return;
4608
4609
75
    unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4610
75
    if (ChangesLinkage) {
4611
      // If the linkage changes, we can't accept this as an extension.
4612
12
      if (NonCLike.Kind == NonCLikeKind::None)
4613
7
        DiagID = diag::err_typedef_changes_linkage;
4614
5
      else
4615
5
        DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4616
12
    }
4617
4618
75
    SourceLocation FixitLoc =
4619
75
        getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4620
75
    llvm::SmallString<40> TextToInsert;
4621
75
    TextToInsert += ' ';
4622
75
    TextToInsert += NewTD->getIdentifier()->getName();
4623
4624
75
    Diag(FixitLoc, DiagID)
4625
75
      << isa<TypeAliasDecl>(NewTD)
4626
75
      << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4627
75
    if (NonCLike.Kind != NonCLikeKind::None) {
4628
68
      Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4629
68
        << NonCLike.Kind - 1 << NonCLike.Range;
4630
68
    }
4631
75
    Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4632
75
      << NewTD << isa<TypeAliasDecl>(NewTD);
4633
4634
75
    if (ChangesLinkage)
4635
12
      return;
4636
75
  }
4637
4638
  // Otherwise, set this as the anon-decl typedef for the tag.
4639
158k
  TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4640
158k
}
4641
4642
98
static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4643
98
  switch (T) {
4644
18
  case DeclSpec::TST_class:
4645
18
    return 0;
4646
38
  case DeclSpec::TST_struct:
4647
38
    return 1;
4648
0
  case DeclSpec::TST_interface:
4649
0
    return 2;
4650
22
  case DeclSpec::TST_union:
4651
22
    return 3;
4652
20
  case DeclSpec::TST_enum:
4653
20
    return 4;
4654
0
  default:
4655
0
    llvm_unreachable("unexpected type specifier");
4656
98
  }
4657
98
}
4658
4659
/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4660
/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4661
/// parameters to cope with template friend declarations.
4662
Decl *
4663
Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4664
                                 MultiTemplateParamsArg TemplateParams,
4665
                                 bool IsExplicitInstantiation,
4666
1.36M
                                 RecordDecl *&AnonRecord) {
4667
1.36M
  Decl *TagD = nullptr;
4668
1.36M
  TagDecl *Tag = nullptr;
4669
1.36M
  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4670
1.36M
      
DS.getTypeSpecType() == DeclSpec::TST_struct1.21M
||
4671
1.36M
      
DS.getTypeSpecType() == DeclSpec::TST_interface479k
||
4672
1.36M
      
DS.getTypeSpecType() == DeclSpec::TST_union479k
||
4673
1.36M
      
DS.getTypeSpecType() == DeclSpec::TST_enum461k
) {
4674
1.36M
    TagD = DS.getRepAsDecl();
4675
4676
1.36M
    if (!TagD) // We probably had an error
4677
170
      return nullptr;
4678
4679
    // Note that the above type specs guarantee that the
4680
    // type rep is a Decl, whereas in many of the others
4681
    // it's a Type.
4682
1.36M
    if (isa<TagDecl>(TagD))
4683
1.10M
      Tag = cast<TagDecl>(TagD);
4684
261k
    else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4685
261k
      Tag = CTD->getTemplatedDecl();
4686
1.36M
  }
4687
4688
1.36M
  if (Tag) {
4689
1.36M
    handleTagNumbering(Tag, S);
4690
1.36M
    Tag->setFreeStanding();
4691
1.36M
    if (Tag->isInvalidDecl())
4692
700
      return Tag;
4693
1.36M
  }
4694
4695
1.36M
  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4696
    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4697
    // or incomplete types shall not be restrict-qualified."
4698
17
    if (TypeQuals & DeclSpec::TQ_restrict)
4699
2
      Diag(DS.getRestrictSpecLoc(),
4700
2
           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4701
2
           << DS.getSourceRange();
4702
17
  }
4703
4704
1.36M
  if (DS.isInlineSpecified())
4705
2
    Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4706
2
        << getLangOpts().CPlusPlus17;
4707
4708
1.36M
  if (DS.hasConstexprSpecifier()) {
4709
    // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4710
    // and definitions of functions and variables.
4711
    // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4712
    // the declaration of a function or function template
4713
68
    if (Tag)
4714
61
      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4715
61
          << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4716
61
          << static_cast<int>(DS.getConstexprSpecifier());
4717
7
    else
4718
7
      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4719
7
          << static_cast<int>(DS.getConstexprSpecifier());
4720
    // Don't emit warnings after this error.
4721
68
    return TagD;
4722
68
  }
4723
4724
1.36M
  DiagnoseFunctionSpecifiers(DS);
4725
4726
1.36M
  if (DS.isFriendSpecified()) {
4727
    // If we're dealing with a decl but not a TagDecl, assume that
4728
    // whatever routines created it handled the friendship aspect.
4729
19.5k
    if (TagD && 
!Tag14.0k
)
4730
11
      return nullptr;
4731
19.5k
    return ActOnFriendTypeDecl(S, DS, TemplateParams);
4732
19.5k
  }
4733
4734
1.34M
  const CXXScopeSpec &SS = DS.getTypeSpecScope();
4735
1.34M
  bool IsExplicitSpecialization =
4736
1.34M
    !TemplateParams.empty() && 
TemplateParams.back()->size() == 0468k
;
4737
1.34M
  if (Tag && 
SS.isNotEmpty()1.34M
&&
!Tag->isCompleteDefinition()1.55k
&&
4738
1.34M
      
!IsExplicitInstantiation133
&&
!IsExplicitSpecialization123
&&
4739
1.34M
      
!isa<ClassTemplatePartialSpecializationDecl>(Tag)27
) {
4740
    // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4741
    // nested-name-specifier unless it is an explicit instantiation
4742
    // or an explicit specialization.
4743
    //
4744
    // FIXME: We allow class template partial specializations here too, per the
4745
    // obvious intent of DR1819.
4746
    //
4747
    // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4748
15
    Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4749
15
        << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4750
15
    return nullptr;
4751
15
  }
4752
4753
  // Track whether this decl-specifier declares anything.
4754
1.34M
  bool DeclaresAnything = true;
4755
4756
  // Handle anonymous struct definitions.
4757
1.34M
  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4758
893k
    if (!Record->getDeclName() && 
Record->isCompleteDefinition()1.75k
&&
4759
893k
        
DS.getStorageClassSpec() != DeclSpec::SCS_typedef1.75k
) {
4760
1.75k
      if (getLangOpts().CPlusPlus ||
4761
1.75k
          
Record->getDeclContext()->isRecord()297
) {
4762
        // If CurContext is a DeclContext that can contain statements,
4763
        // RecursiveASTVisitor won't visit the decls that
4764
        // BuildAnonymousStructOrUnion() will put into CurContext.
4765
        // Also store them here so that they can be part of the
4766
        // DeclStmt that gets created in this case.
4767
        // FIXME: Also return the IndirectFieldDecls created by
4768
        // BuildAnonymousStructOr union, for the same reason?
4769
1.74k
        if (CurContext->isFunctionOrMethod())
4770
36
          AnonRecord = Record;
4771
1.74k
        return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4772
1.74k
                                           Context.getPrintingPolicy());
4773
1.74k
      }
4774
4775
8
      DeclaresAnything = false;
4776
8
    }
4777
893k
  }
4778
4779
  // C11 6.7.2.1p2:
4780
  //   A struct-declaration that does not declare an anonymous structure or
4781
  //   anonymous union shall contain a struct-declarator-list.
4782
  //
4783
  // This rule also existed in C89 and C99; the grammar for struct-declaration
4784
  // did not permit a struct-declaration without a struct-declarator-list.
4785
1.34M
  if (!getLangOpts().CPlusPlus && 
CurContext->isRecord()569k
&&
4786
1.34M
      
DS.getStorageClassSpec() == DeclSpec::SCS_unspecified21
) {
4787
    // Check for Microsoft C extension: anonymous struct/union member.
4788
    // Handle 2 kinds of anonymous struct/union:
4789
    //   struct STRUCT;
4790
    //   union UNION;
4791
    // and
4792
    //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4793
    //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4794
21
    if ((Tag && 
Tag->getDeclName()17
) ||
4795
21
        
DS.getTypeSpecType() == DeclSpec::TST_typename7
) {
4796
18
      RecordDecl *Record = nullptr;
4797
18
      if (Tag)
4798
14
        Record = dyn_cast<RecordDecl>(Tag);
4799
4
      else if (const RecordType *RT =
4800
4
                   DS.getRepAsType().get()->getAsStructureType())
4801
3
        Record = RT->getDecl();
4802
1
      else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4803
1
        Record = UT->getDecl();
4804
4805
18
      if (Record && getLangOpts().MicrosoftExt) {
4806
9
        Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4807
9
            << Record->isUnion() << DS.getSourceRange();
4808
9
        return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4809
9
      }
4810
4811
9
      DeclaresAnything = false;
4812
9
    }
4813
21
  }
4814
4815
  // Skip all the checks below if we have a type error.
4816
1.34M
  if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4817
1.34M
      
(1.34M
TagD1.34M
&&
TagD->isInvalidDecl()1.34M
))
4818
266
    return TagD;
4819
4820
1.34M
  if (getLangOpts().CPlusPlus &&
4821
1.34M
      
DS.getStorageClassSpec() != DeclSpec::SCS_typedef778k
)
4822
778k
    if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4823
74.3k
      if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4824
74.3k
          
!Enum->getIdentifier()1.52k
&&
!Enum->isInvalidDecl()12
)
4825
12
        DeclaresAnything = false;
4826
4827
1.34M
  if (!DS.isMissingDeclaratorOk()) {
4828
    // Customize diagnostic for a typedef missing a name.
4829
182
    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4830
54
      Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4831
54
          << DS.getSourceRange();
4832
128
    else
4833
128
      DeclaresAnything = false;
4834
182
  }
4835
4836
1.34M
  if (DS.isModulePrivateSpecified() &&
4837
1.34M
      
Tag18
&&
Tag->getDeclContext()->isFunctionOrMethod()18
)
4838
1
    Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4839
1
      << Tag->getTagKind()
4840
1
      << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4841
4842
1.34M
  ActOnDocumentableDecl(TagD);
4843
4844
  // C 6.7/2:
4845
  //   A declaration [...] shall declare at least a declarator [...], a tag,
4846
  //   or the members of an enumeration.
4847
  // C++ [dcl.dcl]p3:
4848
  //   [If there are no declarators], and except for the declaration of an
4849
  //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4850
  //   names into the program, or shall redeclare a name introduced by a
4851
  //   previous declaration.
4852
1.34M
  if (!DeclaresAnything) {
4853
    // In C, we allow this as a (popular) extension / bug. Don't bother
4854
    // producing furth