Coverage Report

Created: 2022-05-17 06:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaAttr.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaAttr.cpp - Semantic Analysis for Attributes ------------------===//
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 non-trivial attributes and
10
// pragmas.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/AST/ASTConsumer.h"
15
#include "clang/AST/Attr.h"
16
#include "clang/AST/Expr.h"
17
#include "clang/Basic/TargetInfo.h"
18
#include "clang/Lex/Preprocessor.h"
19
#include "clang/Sema/Lookup.h"
20
#include "clang/Sema/SemaInternal.h"
21
using namespace clang;
22
23
//===----------------------------------------------------------------------===//
24
// Pragma 'pack' and 'options align'
25
//===----------------------------------------------------------------------===//
26
27
Sema::PragmaStackSentinelRAII::PragmaStackSentinelRAII(Sema &S,
28
                                                       StringRef SlotLabel,
29
                                                       bool ShouldAct)
30
3.40M
    : S(S), SlotLabel(SlotLabel), ShouldAct(ShouldAct) {
31
3.40M
  if (ShouldAct) {
32
623k
    S.VtorDispStack.SentinelAction(PSK_Push, SlotLabel);
33
623k
    S.DataSegStack.SentinelAction(PSK_Push, SlotLabel);
34
623k
    S.BSSSegStack.SentinelAction(PSK_Push, SlotLabel);
35
623k
    S.ConstSegStack.SentinelAction(PSK_Push, SlotLabel);
36
623k
    S.CodeSegStack.SentinelAction(PSK_Push, SlotLabel);
37
623k
  }
38
3.40M
}
39
40
3.40M
Sema::PragmaStackSentinelRAII::~PragmaStackSentinelRAII() {
41
3.40M
  if (ShouldAct) {
42
623k
    S.VtorDispStack.SentinelAction(PSK_Pop, SlotLabel);
43
623k
    S.DataSegStack.SentinelAction(PSK_Pop, SlotLabel);
44
623k
    S.BSSSegStack.SentinelAction(PSK_Pop, SlotLabel);
45
623k
    S.ConstSegStack.SentinelAction(PSK_Pop, SlotLabel);
46
623k
    S.CodeSegStack.SentinelAction(PSK_Pop, SlotLabel);
47
623k
  }
48
3.40M
}
49
50
1.09M
void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
51
1.09M
  AlignPackInfo InfoVal = AlignPackStack.CurrentValue;
52
1.09M
  AlignPackInfo::Mode M = InfoVal.getAlignMode();
53
1.09M
  bool IsPackSet = InfoVal.IsPackSet();
54
1.09M
  bool IsXLPragma = getLangOpts().XLPragmaPack;
55
56
  // If we are not under mac68k/natural alignment mode and also there is no pack
57
  // value, we don't need any attributes.
58
1.09M
  if (!IsPackSet && 
M != AlignPackInfo::Mac68k856k
&&
M != AlignPackInfo::Natural856k
)
59
856k
    return;
60
61
240k
  if (M == AlignPackInfo::Mac68k && 
(14
IsXLPragma14
||
InfoVal.IsAlignAttr()14
)) {
62
14
    RD->addAttr(AlignMac68kAttr::CreateImplicit(Context));
63
240k
  } else if (IsPackSet) {
64
    // Check to see if we need a max field alignment attribute.
65
240k
    RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(
66
240k
        Context, InfoVal.getPackNumber() * 8));
67
240k
  }
68
69
240k
  if (IsXLPragma && 
M == AlignPackInfo::Natural78
)
70
26
    RD->addAttr(AlignNaturalAttr::CreateImplicit(Context));
71
72
240k
  if (AlignPackIncludeStack.empty())
73
468
    return;
74
  // The #pragma align/pack affected a record in an included file, so Clang
75
  // should warn when that pragma was written in a file that included the
76
  // included file.
77
240k
  
for (auto &AlignPackedInclude : llvm::reverse(AlignPackIncludeStack))240k
{
78
240k
    if (AlignPackedInclude.CurrentPragmaLocation !=
79
240k
        AlignPackStack.CurrentPragmaLocation)
80
240k
      break;
81
18
    if (AlignPackedInclude.HasNonDefaultValue)
82
14
      AlignPackedInclude.ShouldWarnOnInclude = true;
83
18
  }
84
240k
}
85
86
1.09M
void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
87
1.09M
  if (MSStructPragmaOn)
88
21
    RD->addAttr(MSStructAttr::CreateImplicit(Context));
89
90
  // FIXME: We should merge AddAlignmentAttributesForRecord with
91
  // AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes
92
  // all active pragmas and applies them as attributes to class definitions.
93
1.09M
  if (VtorDispStack.CurrentValue != getLangOpts().getVtorDispMode())
94
29
    RD->addAttr(MSVtorDispAttr::CreateImplicit(
95
29
        Context, unsigned(VtorDispStack.CurrentValue)));
96
1.09M
}
97
98
template <typename Attribute>
99
static void addGslOwnerPointerAttributeIfNotExisting(ASTContext &Context,
100
10.2k
                                                     CXXRecordDecl *Record) {
101
10.2k
  if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
102
2.83k
    return;
103
104
7.46k
  for (Decl *Redecl : Record->redecls())
105
7.75k
    Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
106
7.46k
}
SemaAttr.cpp:void addGslOwnerPointerAttributeIfNotExisting<clang::PointerAttr>(clang::ASTContext&, clang::CXXRecordDecl*)
Line
Count
Source
100
6.29k
                                                     CXXRecordDecl *Record) {
101
6.29k
  if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
102
2.83k
    return;
103
104
3.46k
  for (Decl *Redecl : Record->redecls())
105
3.75k
    Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
106
3.46k
}
SemaAttr.cpp:void addGslOwnerPointerAttributeIfNotExisting<clang::OwnerAttr>(clang::ASTContext&, clang::CXXRecordDecl*)
Line
Count
Source
100
4.00k
                                                     CXXRecordDecl *Record) {
101
4.00k
  if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
102
0
    return;
103
104
4.00k
  for (Decl *Redecl : Record->redecls())
105
4.00k
    Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
106
4.00k
}
107
108
void Sema::inferGslPointerAttribute(NamedDecl *ND,
109
2.60M
                                    CXXRecordDecl *UnderlyingRecord) {
110
2.60M
  if (!UnderlyingRecord)
111
2.03M
    return;
112
113
570k
  const auto *Parent = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
114
570k
  if (!Parent)
115
379k
    return;
116
117
191k
  static llvm::StringSet<> Containers{
118
191k
      "array",
119
191k
      "basic_string",
120
191k
      "deque",
121
191k
      "forward_list",
122
191k
      "vector",
123
191k
      "list",
124
191k
      "map",
125
191k
      "multiset",
126
191k
      "multimap",
127
191k
      "priority_queue",
128
191k
      "queue",
129
191k
      "set",
130
191k
      "stack",
131
191k
      "unordered_set",
132
191k
      "unordered_map",
133
191k
      "unordered_multiset",
134
191k
      "unordered_multimap",
135
191k
  };
136
137
191k
  static llvm::StringSet<> Iterators{"iterator", "const_iterator",
138
191k
                                     "reverse_iterator",
139
191k
                                     "const_reverse_iterator"};
140
141
191k
  if (Parent->isInStdNamespace() && 
Iterators.count(ND->getName())170k
&&
142
191k
      
Containers.count(Parent->getName())6.89k
)
143
5.48k
    addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context,
144
5.48k
                                                          UnderlyingRecord);
145
191k
}
146
147
2.34M
void Sema::inferGslPointerAttribute(TypedefNameDecl *TD) {
148
149
2.34M
  QualType Canonical = TD->getUnderlyingType().getCanonicalType();
150
151
2.34M
  CXXRecordDecl *RD = Canonical->getAsCXXRecordDecl();
152
2.34M
  if (!RD) {
153
2.09M
    if (auto *TST =
154
2.09M
            dyn_cast<TemplateSpecializationType>(Canonical.getTypePtr())) {
155
156
60.9k
      RD = dyn_cast_or_null<CXXRecordDecl>(
157
60.9k
          TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl());
158
60.9k
    }
159
2.09M
  }
160
161
2.34M
  inferGslPointerAttribute(TD, RD);
162
2.34M
}
163
164
567k
void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl *Record) {
165
567k
  static llvm::StringSet<> StdOwners{
166
567k
      "any",
167
567k
      "array",
168
567k
      "basic_regex",
169
567k
      "basic_string",
170
567k
      "deque",
171
567k
      "forward_list",
172
567k
      "vector",
173
567k
      "list",
174
567k
      "map",
175
567k
      "multiset",
176
567k
      "multimap",
177
567k
      "optional",
178
567k
      "priority_queue",
179
567k
      "queue",
180
567k
      "set",
181
567k
      "stack",
182
567k
      "unique_ptr",
183
567k
      "unordered_set",
184
567k
      "unordered_map",
185
567k
      "unordered_multiset",
186
567k
      "unordered_multimap",
187
567k
      "variant",
188
567k
  };
189
567k
  static llvm::StringSet<> StdPointers{
190
567k
      "basic_string_view",
191
567k
      "reference_wrapper",
192
567k
      "regex_iterator",
193
567k
  };
194
195
567k
  if (!Record->getIdentifier())
196
41.7k
    return;
197
198
  // Handle classes that directly appear in std namespace.
199
525k
  if (Record->isInStdNamespace()) {
200
261k
    if (Record->hasAttr<OwnerAttr>() || 
Record->hasAttr<PointerAttr>()259k
)
201
3.79k
      return;
202
203
257k
    if (StdOwners.count(Record->getName()))
204
4.00k
      addGslOwnerPointerAttributeIfNotExisting<OwnerAttr>(Context, Record);
205
253k
    else if (StdPointers.count(Record->getName()))
206
807
      addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context, Record);
207
208
257k
    return;
209
261k
  }
210
211
  // Handle nested classes that could be a gsl::Pointer.
212
264k
  inferGslPointerAttribute(Record, Record);
213
264k
}
214
215
void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
216
2.83k
                                   SourceLocation PragmaLoc) {
217
2.83k
  PragmaMsStackAction Action = Sema::PSK_Reset;
218
2.83k
  AlignPackInfo::Mode ModeVal = AlignPackInfo::Native;
219
220
2.83k
  switch (Kind) {
221
    // For most of the platforms we support, native and natural are the same.
222
    // With XL, native is the same as power, natural means something else.
223
    //
224
    // FIXME: This is not true on Darwin/PPC.
225
1
  case POAK_Native:
226
1.35k
  case POAK_Power:
227
1.35k
    Action = Sema::PSK_Push_Set;
228
1.35k
    break;
229
29
  case POAK_Natural:
230
29
    Action = Sema::PSK_Push_Set;
231
29
    ModeVal = AlignPackInfo::Natural;
232
29
    break;
233
234
    // Note that '#pragma options align=packed' is not equivalent to attribute
235
    // packed, it has a different precedence relative to attribute aligned.
236
25
  case POAK_Packed:
237
25
    Action = Sema::PSK_Push_Set;
238
25
    ModeVal = AlignPackInfo::Packed;
239
25
    break;
240
241
9
  case POAK_Mac68k:
242
    // Check if the target supports this.
243
9
    if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
244
2
      Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
245
2
      return;
246
2
    }
247
7
    Action = Sema::PSK_Push_Set;
248
7
    ModeVal = AlignPackInfo::Mac68k;
249
7
    break;
250
1.41k
  case POAK_Reset:
251
    // Reset just pops the top of the stack, or resets the current alignment to
252
    // default.
253
1.41k
    Action = Sema::PSK_Pop;
254
1.41k
    if (AlignPackStack.Stack.empty()) {
255
10
      if (AlignPackStack.CurrentValue.getAlignMode() != AlignPackInfo::Native ||
256
10
          AlignPackStack.CurrentValue.IsPackAttr()) {
257
7
        Action = Sema::PSK_Reset;
258
7
      } else {
259
3
        Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
260
3
            << "stack empty";
261
3
        return;
262
3
      }
263
10
    }
264
1.40k
    break;
265
2.83k
  }
266
267
2.82k
  AlignPackInfo Info(ModeVal, getLangOpts().XLPragmaPack);
268
269
2.82k
  AlignPackStack.Act(PragmaLoc, Action, StringRef(), Info);
270
2.82k
}
271
272
void Sema::ActOnPragmaClangSection(SourceLocation PragmaLoc,
273
                                   PragmaClangSectionAction Action,
274
                                   PragmaClangSectionKind SecKind,
275
91
                                   StringRef SecName) {
276
91
  PragmaClangSection *CSec;
277
91
  int SectionFlags = ASTContext::PSF_Read;
278
91
  switch (SecKind) {
279
24
    case PragmaClangSectionKind::PCSK_BSS:
280
24
      CSec = &PragmaClangBSSSection;
281
24
      SectionFlags |= ASTContext::PSF_Write | ASTContext::PSF_ZeroInit;
282
24
      break;
283
21
    case PragmaClangSectionKind::PCSK_Data:
284
21
      CSec = &PragmaClangDataSection;
285
21
      SectionFlags |= ASTContext::PSF_Write;
286
21
      break;
287
22
    case PragmaClangSectionKind::PCSK_Rodata:
288
22
      CSec = &PragmaClangRodataSection;
289
22
      break;
290
2
    case PragmaClangSectionKind::PCSK_Relro:
291
2
      CSec = &PragmaClangRelroSection;
292
2
      break;
293
22
    case PragmaClangSectionKind::PCSK_Text:
294
22
      CSec = &PragmaClangTextSection;
295
22
      SectionFlags |= ASTContext::PSF_Execute;
296
22
      break;
297
0
    default:
298
0
      llvm_unreachable("invalid clang section kind");
299
91
  }
300
301
91
  if (Action == PragmaClangSectionAction::PCSA_Clear) {
302
45
    CSec->Valid = false;
303
45
    return;
304
45
  }
305
306
46
  if (llvm::Error E = isValidSectionSpecifier(SecName)) {
307
2
    Diag(PragmaLoc, diag::err_pragma_section_invalid_for_target)
308
2
        << toString(std::move(E));
309
2
    CSec->Valid = false;
310
2
    return;
311
2
  }
312
313
44
  if (UnifySection(SecName, SectionFlags, PragmaLoc))
314
5
    return;
315
316
39
  CSec->Valid = true;
317
39
  CSec->SectionName = std::string(SecName);
318
39
  CSec->PragmaLocation = PragmaLoc;
319
39
}
320
321
void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
322
260k
                           StringRef SlotLabel, Expr *alignment) {
323
260k
  bool IsXLPragma = getLangOpts().XLPragmaPack;
324
  // XL pragma pack does not support identifier syntax.
325
260k
  if (IsXLPragma && 
!SlotLabel.empty()188
) {
326
2
    Diag(PragmaLoc, diag::err_pragma_pack_identifer_not_supported);
327
2
    return;
328
2
  }
329
330
260k
  const AlignPackInfo CurVal = AlignPackStack.CurrentValue;
331
260k
  Expr *Alignment = static_cast<Expr *>(alignment);
332
333
  // If specified then alignment must be a "small" power of two.
334
260k
  unsigned AlignmentVal = 0;
335
260k
  AlignPackInfo::Mode ModeVal = CurVal.getAlignMode();
336
337
260k
  if (Alignment) {
338
130k
    Optional<llvm::APSInt> Val;
339
130k
    Val = Alignment->getIntegerConstantExpr(Context);
340
341
    // pack(0) is like pack(), which just works out since that is what
342
    // we use 0 for in PackAttr.
343
130k
    if (Alignment->isTypeDependent() || !Val ||
344
130k
        !(*Val == 0 || 
Val->isPowerOf2()130k
) ||
Val->getZExtValue() > 16130k
) {
345
1
      Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
346
1
      return; // Ignore
347
1
    }
348
349
130k
    if (IsXLPragma && 
*Val == 072
) {
350
      // pack(0) does not work out with XL.
351
2
      Diag(PragmaLoc, diag::err_pragma_pack_invalid_alignment);
352
2
      return; // Ignore
353
2
    }
354
355
130k
    AlignmentVal = (unsigned)Val->getZExtValue();
356
130k
  }
357
358
260k
  if (Action == Sema::PSK_Show) {
359
    // Show the current alignment, making sure to show the right value
360
    // for the default.
361
    // FIXME: This should come from the target.
362
80
    AlignmentVal = CurVal.IsPackSet() ? 
CurVal.getPackNumber()40
:
840
;
363
80
    if (ModeVal == AlignPackInfo::Mac68k &&
364
80
        
(0
IsXLPragma0
||
CurVal.IsAlignAttr()0
))
365
0
      Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
366
80
    else
367
80
      Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
368
80
  }
369
370
  // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
371
  // "#pragma pack(pop, identifier, n) is undefined"
372
260k
  if (Action & Sema::PSK_Pop) {
373
128k
    if (Alignment && 
!SlotLabel.empty()1
)
374
0
      Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifier_and_alignment);
375
128k
    if (AlignPackStack.Stack.empty()) {
376
22
      assert(CurVal.getAlignMode() == AlignPackInfo::Native &&
377
22
             "Empty pack stack can only be at Native alignment mode.");
378
0
      Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "pack" << "stack empty";
379
22
    }
380
128k
  }
381
382
0
  AlignPackInfo Info(ModeVal, AlignmentVal, IsXLPragma);
383
384
260k
  AlignPackStack.Act(PragmaLoc, Action, SlotLabel, Info);
385
260k
}
386
387
void Sema::DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
388
1.15M
                                             SourceLocation IncludeLoc) {
389
1.15M
  if (Kind == PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude) {
390
578k
    SourceLocation PrevLocation = AlignPackStack.CurrentPragmaLocation;
391
    // Warn about non-default alignment at #includes (without redundant
392
    // warnings for the same directive in nested includes).
393
    // The warning is delayed until the end of the file to avoid warnings
394
    // for files that don't have any records that are affected by the modified
395
    // alignment.
396
578k
    bool HasNonDefaultValue =
397
578k
        AlignPackStack.hasValue() &&
398
578k
        
(21
AlignPackIncludeStack.empty()21
||
399
21
         
AlignPackIncludeStack.back().CurrentPragmaLocation != PrevLocation9
);
400
578k
    AlignPackIncludeStack.push_back(
401
578k
        {AlignPackStack.CurrentValue,
402
578k
         AlignPackStack.hasValue() ? 
PrevLocation21
:
SourceLocation()578k
,
403
578k
         HasNonDefaultValue, /*ShouldWarnOnInclude*/ false});
404
578k
    return;
405
578k
  }
406
407
578k
  assert(Kind == PragmaAlignPackDiagnoseKind::ChangedStateAtExit &&
408
578k
         "invalid kind");
409
0
  AlignPackIncludeState PrevAlignPackState =
410
578k
      AlignPackIncludeStack.pop_back_val();
411
  // FIXME: AlignPackStack may contain both #pragma align and #pragma pack
412
  // information, diagnostics below might not be accurate if we have mixed
413
  // pragmas.
414
578k
  if (PrevAlignPackState.ShouldWarnOnInclude) {
415
    // Emit the delayed non-default alignment at #include warning.
416
12
    Diag(IncludeLoc, diag::warn_pragma_pack_non_default_at_include);
417
12
    Diag(PrevAlignPackState.CurrentPragmaLocation, diag::note_pragma_pack_here);
418
12
  }
419
  // Warn about modified alignment after #includes.
420
578k
  if (PrevAlignPackState.CurrentValue != AlignPackStack.CurrentValue) {
421
22
    Diag(IncludeLoc, diag::warn_pragma_pack_modified_after_include);
422
22
    Diag(AlignPackStack.CurrentPragmaLocation, diag::note_pragma_pack_here);
423
22
  }
424
578k
}
425
426
83.8k
void Sema::DiagnoseUnterminatedPragmaAlignPack() {
427
83.8k
  if (AlignPackStack.Stack.empty())
428
83.8k
    return;
429
37
  bool IsInnermost = true;
430
431
  // FIXME: AlignPackStack may contain both #pragma align and #pragma pack
432
  // information, diagnostics below might not be accurate if we have mixed
433
  // pragmas.
434
48
  for (const auto &StackSlot : llvm::reverse(AlignPackStack.Stack)) {
435
48
    Diag(StackSlot.PragmaPushLocation, diag::warn_pragma_pack_no_pop_eof);
436
    // The user might have already reset the alignment, so suggest replacing
437
    // the reset with a pop.
438
48
    if (IsInnermost &&
439
48
        
AlignPackStack.CurrentValue == AlignPackStack.DefaultValue37
) {
440
4
      auto DB = Diag(AlignPackStack.CurrentPragmaLocation,
441
4
                     diag::note_pragma_pack_pop_instead_reset);
442
4
      SourceLocation FixItLoc =
443
4
          Lexer::findLocationAfterToken(AlignPackStack.CurrentPragmaLocation,
444
4
                                        tok::l_paren, SourceMgr, LangOpts,
445
4
                                        /*SkipTrailing=*/false);
446
4
      if (FixItLoc.isValid())
447
4
        DB << FixItHint::CreateInsertion(FixItLoc, "pop");
448
4
    }
449
48
    IsInnermost = false;
450
48
  }
451
37
}
452
453
3.95k
void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {
454
3.95k
  MSStructPragmaOn = (Kind == PMSST_ON);
455
3.95k
}
456
457
void Sema::ActOnPragmaMSComment(SourceLocation CommentLoc,
458
54
                                PragmaMSCommentKind Kind, StringRef Arg) {
459
54
  auto *PCD = PragmaCommentDecl::Create(
460
54
      Context, Context.getTranslationUnitDecl(), CommentLoc, Kind, Arg);
461
54
  Context.getTranslationUnitDecl()->addDecl(PCD);
462
54
  Consumer.HandleTopLevelDecl(DeclGroupRef(PCD));
463
54
}
464
465
void Sema::ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
466
16
                                     StringRef Value) {
467
16
  auto *PDMD = PragmaDetectMismatchDecl::Create(
468
16
      Context, Context.getTranslationUnitDecl(), Loc, Name, Value);
469
16
  Context.getTranslationUnitDecl()->addDecl(PDMD);
470
16
  Consumer.HandleTopLevelDecl(DeclGroupRef(PDMD));
471
16
}
472
473
void Sema::ActOnPragmaFPEvalMethod(SourceLocation Loc,
474
101
                                   LangOptions::FPEvalMethodKind Value) {
475
101
  FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
476
101
  switch (Value) {
477
0
  default:
478
0
    llvm_unreachable("invalid pragma eval_method kind");
479
35
  case LangOptions::FEM_Source:
480
35
    NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Source);
481
35
    break;
482
41
  case LangOptions::FEM_Double:
483
41
    NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Double);
484
41
    break;
485
25
  case LangOptions::FEM_Extended:
486
25
    NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Extended);
487
25
    break;
488
101
  }
489
101
  if (getLangOpts().ApproxFunc)
490
2
    Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 0;
491
101
  if (getLangOpts().AllowFPReassoc)
492
3
    Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 1;
493
101
  if (getLangOpts().AllowRecip)
494
3
    Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 2;
495
101
  FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
496
101
  CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
497
101
  PP.setCurrentFPEvalMethod(Loc, Value);
498
101
}
499
500
void Sema::ActOnPragmaFloatControl(SourceLocation Loc,
501
                                   PragmaMsStackAction Action,
502
470
                                   PragmaFloatControlKind Value) {
503
470
  FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
504
470
  if ((Action == PSK_Push_Set || 
Action == PSK_Push459
||
Action == PSK_Pop396
) &&
505
470
      
!CurContext->getRedeclContext()->isFileContext()165
) {
506
    // Push and pop can only occur at file or namespace scope, or within a
507
    // language linkage declaration.
508
4
    Diag(Loc, diag::err_pragma_fc_pp_scope);
509
4
    return;
510
4
  }
511
466
  switch (Value) {
512
0
  default:
513
0
    llvm_unreachable("invalid pragma float_control kind");
514
75
  case PFC_Precise:
515
75
    NewFPFeatures.setFPPreciseEnabled(true);
516
75
    FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
517
75
    if (PP.getCurrentFPEvalMethod() ==
518
75
            LangOptions::FPEvalMethodKind::FEM_Indeterminable &&
519
75
        
PP.getLastFPEvalPragmaLocation().isValid()23
)
520
      // A preceding `pragma float_control(precise,off)` has changed
521
      // the value of the evaluation method.
522
      // Set it back to its old value.
523
16
      PP.setCurrentFPEvalMethod(SourceLocation(), PP.getLastFPEvalMethod());
524
75
    break;
525
118
  case PFC_NoPrecise:
526
118
    if (CurFPFeatures.getFPExceptionMode() == LangOptions::FPE_Strict)
527
13
      Diag(Loc, diag::err_pragma_fc_noprecise_requires_noexcept);
528
105
    else if (CurFPFeatures.getAllowFEnvAccess())
529
0
      Diag(Loc, diag::err_pragma_fc_noprecise_requires_nofenv);
530
105
    else
531
105
      NewFPFeatures.setFPPreciseEnabled(false);
532
118
    FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
533
118
    PP.setLastFPEvalMethod(PP.getCurrentFPEvalMethod());
534
    // `AllowFPReassoc` or `AllowReciprocal` option is enabled.
535
118
    PP.setCurrentFPEvalMethod(
536
118
        Loc, LangOptions::FPEvalMethodKind::FEM_Indeterminable);
537
118
    break;
538
95
  case PFC_Except:
539
95
    if (!isPreciseFPEnabled())
540
0
      Diag(Loc, diag::err_pragma_fc_except_requires_precise);
541
95
    else
542
95
      NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Strict);
543
95
    FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
544
95
    break;
545
26
  case PFC_NoExcept:
546
26
    NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Ignore);
547
26
    FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
548
26
    break;
549
62
  case PFC_Push:
550
62
    FpPragmaStack.Act(Loc, Sema::PSK_Push_Set, StringRef(), NewFPFeatures);
551
62
    break;
552
90
  case PFC_Pop:
553
90
    if (FpPragmaStack.Stack.empty()) {
554
20
      Diag(Loc, diag::warn_pragma_pop_failed) << "float_control"
555
20
                                              << "stack empty";
556
20
      return;
557
20
    }
558
70
    FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
559
70
    NewFPFeatures = FpPragmaStack.CurrentValue;
560
70
    if (CurFPFeatures.getAllowFPReassociate() ||
561
70
        
CurFPFeatures.getAllowReciprocal()45
)
562
      // Since we are popping the pragma, we don't want to be passing
563
      // a location here.
564
25
      PP.setCurrentFPEvalMethod(SourceLocation(),
565
25
                                CurFPFeatures.getFPEvalMethod());
566
70
    break;
567
466
  }
568
446
  CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
569
446
}
570
571
void Sema::ActOnPragmaMSPointersToMembers(
572
    LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
573
26
    SourceLocation PragmaLoc) {
574
26
  MSPointerToMemberRepresentationMethod = RepresentationMethod;
575
26
  ImplicitMSInheritanceAttrLoc = PragmaLoc;
576
26
}
577
578
void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
579
                                 SourceLocation PragmaLoc,
580
45
                                 MSVtorDispMode Mode) {
581
45
  if (Action & PSK_Pop && 
VtorDispStack.Stack.empty()20
)
582
4
    Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
583
4
                                                  << "stack empty";
584
45
  VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);
585
45
}
586
587
template <>
588
void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
589
                                                 PragmaMsStackAction Action,
590
                                                 llvm::StringRef StackSlotLabel,
591
263k
                                                 AlignPackInfo Value) {
592
263k
  if (Action == PSK_Reset) {
593
1.87k
    CurrentValue = DefaultValue;
594
1.87k
    CurrentPragmaLocation = PragmaLocation;
595
1.87k
    return;
596
1.87k
  }
597
261k
  if (Action & PSK_Push)
598
129k
    Stack.emplace_back(Slot(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
599
129k
                            PragmaLocation));
600
131k
  else if (Action & PSK_Pop) {
601
129k
    if (!StackSlotLabel.empty()) {
602
      // If we've got a label, try to find it and jump there.
603
10
      auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
604
10
        return x.StackSlotLabel == StackSlotLabel;
605
10
      });
606
      // We found the label, so pop from there.
607
9
      if (I != Stack.rend()) {
608
5
        CurrentValue = I->Value;
609
5
        CurrentPragmaLocation = I->PragmaLocation;
610
5
        Stack.erase(std::prev(I.base()), Stack.end());
611
5
      }
612
129k
    } else if (Value.IsXLStack() && 
Value.IsAlignAttr()114
&&
613
129k
               
CurrentValue.IsPackAttr()40
) {
614
      // XL '#pragma align(reset)' would pop the stack until
615
      // a current in effect pragma align is popped.
616
8
      auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
617
8
        return x.Value.IsAlignAttr();
618
8
      });
619
      // If we found pragma align so pop from there.
620
8
      if (I != Stack.rend()) {
621
8
        Stack.erase(std::prev(I.base()), Stack.end());
622
8
        if (Stack.empty()) {
623
2
          CurrentValue = DefaultValue;
624
2
          CurrentPragmaLocation = PragmaLocation;
625
6
        } else {
626
6
          CurrentValue = Stack.back().Value;
627
6
          CurrentPragmaLocation = Stack.back().PragmaLocation;
628
6
          Stack.pop_back();
629
6
        }
630
8
      }
631
129k
    } else if (!Stack.empty()) {
632
      // xl '#pragma align' sets the baseline, and `#pragma pack` cannot pop
633
      // over the baseline.
634
129k
      if (Value.IsXLStack() && 
Value.IsPackAttr()96
&&
CurrentValue.IsAlignAttr()64
)
635
2
        return;
636
637
      // We don't have a label, just pop the last entry.
638
129k
      CurrentValue = Stack.back().Value;
639
129k
      CurrentPragmaLocation = Stack.back().PragmaLocation;
640
129k
      Stack.pop_back();
641
129k
    }
642
129k
  }
643
261k
  if (Action & PSK_Set) {
644
131k
    CurrentValue = Value;
645
131k
    CurrentPragmaLocation = PragmaLocation;
646
131k
  }
647
261k
}
648
649
bool Sema::UnifySection(StringRef SectionName, int SectionFlags,
650
1.30k
                        NamedDecl *Decl) {
651
1.30k
  SourceLocation PragmaLocation;
652
1.30k
  if (auto A = Decl->getAttr<SectionAttr>())
653
1.30k
    if (A->isImplicit())
654
68
      PragmaLocation = A->getLocation();
655
1.30k
  auto SectionIt = Context.SectionInfos.find(SectionName);
656
1.30k
  if (SectionIt == Context.SectionInfos.end()) {
657
100
    Context.SectionInfos[SectionName] =
658
100
        ASTContext::SectionInfo(Decl, PragmaLocation, SectionFlags);
659
100
    return false;
660
100
  }
661
  // A pre-declared section takes precedence w/o diagnostic.
662
1.20k
  const auto &Section = SectionIt->second;
663
1.20k
  if (Section.SectionFlags == SectionFlags ||
664
1.20k
      
(26
(SectionFlags & ASTContext::PSF_Implicit)26
&&
665
26
       
!(Section.SectionFlags & ASTContext::PSF_Implicit)13
))
666
1.18k
    return false;
667
16
  Diag(Decl->getLocation(), diag::err_section_conflict) << Decl << Section;
668
16
  if (Section.Decl)
669
15
    Diag(Section.Decl->getLocation(), diag::note_declared_at)
670
15
        << Section.Decl->getName();
671
16
  if (PragmaLocation.isValid())
672
2
    Diag(PragmaLocation, diag::note_pragma_entered_here);
673
16
  if (Section.PragmaSectionLocation.isValid())
674
3
    Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
675
16
  return true;
676
1.20k
}
677
678
bool Sema::UnifySection(StringRef SectionName,
679
                        int SectionFlags,
680
66
                        SourceLocation PragmaSectionLocation) {
681
66
  auto SectionIt = Context.SectionInfos.find(SectionName);
682
66
  if (SectionIt != Context.SectionInfos.end()) {
683
7
    const auto &Section = SectionIt->second;
684
7
    if (Section.SectionFlags == SectionFlags)
685
0
      return false;
686
7
    if (!(Section.SectionFlags & ASTContext::PSF_Implicit)) {
687
7
      Diag(PragmaSectionLocation, diag::err_section_conflict)
688
7
          << "this" << Section;
689
7
      if (Section.Decl)
690
1
        Diag(Section.Decl->getLocation(), diag::note_declared_at)
691
1
            << Section.Decl->getName();
692
7
      if (Section.PragmaSectionLocation.isValid())
693
6
        Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
694
7
      return true;
695
7
    }
696
7
  }
697
59
  Context.SectionInfos[SectionName] =
698
59
      ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
699
59
  return false;
700
66
}
701
702
/// Called on well formed \#pragma bss_seg().
703
void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
704
                            PragmaMsStackAction Action,
705
                            llvm::StringRef StackSlotLabel,
706
                            StringLiteral *SegmentName,
707
57
                            llvm::StringRef PragmaName) {
708
57
  PragmaStack<StringLiteral *> *Stack =
709
57
    llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
710
57
        .Case("data_seg", &DataSegStack)
711
57
        .Case("bss_seg", &BSSSegStack)
712
57
        .Case("const_seg", &ConstSegStack)
713
57
        .Case("code_seg", &CodeSegStack);
714
57
  if (Action & PSK_Pop && 
Stack->Stack.empty()7
)
715
0
    Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
716
0
        << "stack empty";
717
57
  if (SegmentName) {
718
45
    if (!checkSectionName(SegmentName->getBeginLoc(), SegmentName->getString()))
719
1
      return;
720
721
44
    if (SegmentName->getString() == ".drectve" &&
722
44
        
Context.getTargetInfo().getCXXABI().isMicrosoft()4
)
723
4
      Diag(PragmaLocation, diag::warn_attribute_section_drectve) << PragmaName;
724
44
  }
725
726
56
  Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
727
56
}
728
729
/// Called on well formed \#pragma bss_seg().
730
void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
731
22
                                int SectionFlags, StringLiteral *SegmentName) {
732
22
  UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
733
22
}
734
735
void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
736
24
                                StringLiteral *SegmentName) {
737
  // There's no stack to maintain, so we just have a current section.  When we
738
  // see the default section, reset our current section back to null so we stop
739
  // tacking on unnecessary attributes.
740
24
  CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? 
nullptr1
:
SegmentName23
;
741
24
  CurInitSegLoc = PragmaLocation;
742
24
}
743
744
void Sema::ActOnPragmaMSAllocText(
745
    SourceLocation PragmaLocation, StringRef Section,
746
    const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
747
11
        &Functions) {
748
11
  if (!CurContext->getRedeclContext()->isFileContext()) {
749
1
    Diag(PragmaLocation, diag::err_pragma_expected_file_scope) << "alloc_text";
750
1
    return;
751
1
  }
752
753
11
  
for (auto &Function : Functions)10
{
754
11
    IdentifierInfo *II;
755
11
    SourceLocation Loc;
756
11
    std::tie(II, Loc) = Function;
757
758
11
    DeclarationName DN(II);
759
11
    NamedDecl *ND = LookupSingleName(TUScope, DN, Loc, LookupOrdinaryName);
760
11
    if (!ND) {
761
1
      Diag(Loc, diag::err_undeclared_use) << II->getName();
762
1
      return;
763
1
    }
764
765
10
    DeclContext *DC = ND->getDeclContext();
766
10
    if (!DC->isExternCContext()) {
767
2
      Diag(Loc, diag::err_pragma_alloc_text_c_linkage);
768
2
      return;
769
2
    }
770
771
8
    FunctionToSectionMap[II->getName()] = std::make_tuple(Section, Loc);
772
8
  }
773
10
}
774
775
void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
776
25
                             SourceLocation PragmaLoc) {
777
778
25
  IdentifierInfo *Name = IdTok.getIdentifierInfo();
779
25
  LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
780
25
  LookupParsedName(Lookup, curScope, nullptr, true);
781
782
25
  if (Lookup.empty()) {
783
3
    Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
784
3
      << Name << SourceRange(IdTok.getLocation());
785
3
    return;
786
3
  }
787
788
22
  VarDecl *VD = Lookup.getAsSingle<VarDecl>();
789
22
  if (!VD) {
790
0
    Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
791
0
      << Name << SourceRange(IdTok.getLocation());
792
0
    return;
793
0
  }
794
795
  // Warn if this was used before being marked unused.
796
22
  if (VD->isUsed())
797
1
    Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
798
799
22
  VD->addAttr(UnusedAttr::CreateImplicit(Context, IdTok.getLocation(),
800
22
                                         AttributeCommonInfo::AS_Pragma,
801
22
                                         UnusedAttr::GNU_unused));
802
22
}
803
804
24.3M
void Sema::AddCFAuditedAttribute(Decl *D) {
805
24.3M
  IdentifierInfo *Ident;
806
24.3M
  SourceLocation Loc;
807
24.3M
  std::tie(Ident, Loc) = PP.getPragmaARCCFCodeAuditedInfo();
808
24.3M
  if (!Loc.isValid()) 
return23.8M
;
809
810
  // Don't add a redundant or conflicting attribute.
811
480k
  if (D->hasAttr<CFAuditedTransferAttr>() ||
812
480k
      
D->hasAttr<CFUnknownTransferAttr>()479k
)
813
896
    return;
814
815
479k
  AttributeCommonInfo Info(Ident, SourceRange(Loc),
816
479k
                           AttributeCommonInfo::AS_Pragma);
817
479k
  D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Info));
818
479k
}
819
820
namespace {
821
822
Optional<attr::SubjectMatchRule>
823
342
getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {
824
342
  using namespace attr;
825
342
  switch (Rule) {
826
233
  default:
827
233
    return None;
828
0
#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
829
0
#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated)    \
830
109
  case Value:                                                                  \
831
109
    return Parent;
832
342
#include 
"clang/Basic/AttrSubMatchRulesList.inc"233
833
342
  }
834
342
}
835
836
59
bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {
837
59
  using namespace attr;
838
59
  switch (Rule) {
839
4
  default:
840
4
    return false;
841
0
#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
842
0
#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated)    \
843
55
  case Value:                                                                  \
844
55
    return IsNegated;
845
59
#include 
"clang/Basic/AttrSubMatchRulesList.inc"4
846
59
  }
847
59
}
848
849
CharSourceRange replacementRangeForListElement(const Sema &S,
850
44
                                               SourceRange Range) {
851
  // Make sure that the ',' is removed as well.
852
44
  SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(
853
44
      Range.getEnd(), tok::comma, S.getSourceManager(), S.getLangOpts(),
854
44
      /*SkipTrailingWhitespaceAndNewLine=*/false);
855
44
  if (AfterCommaLoc.isValid())
856
16
    return CharSourceRange::getCharRange(Range.getBegin(), AfterCommaLoc);
857
28
  else
858
28
    return CharSourceRange::getTokenRange(Range);
859
44
}
860
861
std::string
862
22
attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules) {
863
22
  std::string Result;
864
22
  llvm::raw_string_ostream OS(Result);
865
27
  for (const auto &I : llvm::enumerate(Rules)) {
866
27
    if (I.index())
867
5
      OS << (I.index() == Rules.size() - 1 ? ", and " : 
", "0
);
868
27
    OS << "'" << attr::getSubjectMatchRuleSpelling(I.value()) << "'";
869
27
  }
870
22
  return Result;
871
22
}
872
873
} // end anonymous namespace
874
875
void Sema::ActOnPragmaAttributeAttribute(
876
    ParsedAttr &Attribute, SourceLocation PragmaLoc,
877
1.07k
    attr::ParsedSubjectMatchRuleSet Rules) {
878
1.07k
  Attribute.setIsPragmaClangAttribute();
879
1.07k
  SmallVector<attr::SubjectMatchRule, 4> SubjectMatchRules;
880
  // Gather the subject match rules that are supported by the attribute.
881
1.07k
  SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4>
882
1.07k
      StrictSubjectMatchRuleSet;
883
1.07k
  Attribute.getMatchRules(LangOpts, StrictSubjectMatchRuleSet);
884
885
  // Figure out which subject matching rules are valid.
886
1.07k
  if (StrictSubjectMatchRuleSet.empty()) {
887
    // Check for contradicting match rules. Contradicting match rules are
888
    // either:
889
    //  - a top-level rule and one of its sub-rules. E.g. variable and
890
    //    variable(is_parameter).
891
    //  - a sub-rule and a sibling that's negated. E.g.
892
    //    variable(is_thread_local) and variable(unless(is_parameter))
893
86
    llvm::SmallDenseMap<int, std::pair<int, SourceRange>, 2>
894
86
        RulesToFirstSpecifiedNegatedSubRule;
895
155
    for (const auto &Rule : Rules) {
896
155
      attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
897
155
      Optional<attr::SubjectMatchRule> ParentRule =
898
155
          getParentAttrMatcherRule(MatchRule);
899
155
      if (!ParentRule)
900
105
        continue;
901
50
      auto It = Rules.find(*ParentRule);
902
50
      if (It != Rules.end()) {
903
        // A sub-rule contradicts a parent rule.
904
11
        Diag(Rule.second.getBegin(),
905
11
             diag::err_pragma_attribute_matcher_subrule_contradicts_rule)
906
11
            << attr::getSubjectMatchRuleSpelling(MatchRule)
907
11
            << attr::getSubjectMatchRuleSpelling(*ParentRule) << It->second
908
11
            << FixItHint::CreateRemoval(
909
11
                   replacementRangeForListElement(*this, Rule.second));
910
        // Keep going without removing this rule as it won't change the set of
911
        // declarations that receive the attribute.
912
11
        continue;
913
11
      }
914
39
      if (isNegatedAttrMatcherSubRule(MatchRule))
915
12
        RulesToFirstSpecifiedNegatedSubRule.insert(
916
12
            std::make_pair(*ParentRule, Rule));
917
39
    }
918
86
    bool IgnoreNegatedSubRules = false;
919
155
    for (const auto &Rule : Rules) {
920
155
      attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
921
155
      Optional<attr::SubjectMatchRule> ParentRule =
922
155
          getParentAttrMatcherRule(MatchRule);
923
155
      if (!ParentRule)
924
105
        continue;
925
50
      auto It = RulesToFirstSpecifiedNegatedSubRule.find(*ParentRule);
926
50
      if (It != RulesToFirstSpecifiedNegatedSubRule.end() &&
927
50
          
It->second != Rule12
) {
928
        // Negated sub-rule contradicts another sub-rule.
929
6
        Diag(
930
6
            It->second.second.getBegin(),
931
6
            diag::
932
6
                err_pragma_attribute_matcher_negated_subrule_contradicts_subrule)
933
6
            << attr::getSubjectMatchRuleSpelling(
934
6
                   attr::SubjectMatchRule(It->second.first))
935
6
            << attr::getSubjectMatchRuleSpelling(MatchRule) << Rule.second
936
6
            << FixItHint::CreateRemoval(
937
6
                   replacementRangeForListElement(*this, It->second.second));
938
        // Keep going but ignore all of the negated sub-rules.
939
6
        IgnoreNegatedSubRules = true;
940
6
        RulesToFirstSpecifiedNegatedSubRule.erase(It);
941
6
      }
942
50
    }
943
944
86
    if (!IgnoreNegatedSubRules) {
945
80
      for (const auto &Rule : Rules)
946
135
        SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
947
80
    } else {
948
20
      for (const auto &Rule : Rules) {
949
20
        if (!isNegatedAttrMatcherSubRule(attr::SubjectMatchRule(Rule.first)))
950
14
          SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
951
20
      }
952
6
    }
953
86
    Rules.clear();
954
991
  } else {
955
    // Each rule in Rules must be a strict subset of the attribute's
956
    // SubjectMatch rules.  I.e. we're allowed to use
957
    // `apply_to=variables(is_global)` on an attrubute with SubjectList<[Var]>,
958
    // but should not allow `apply_to=variables` on an attribute which has
959
    // `SubjectList<[GlobalVar]>`.
960
13.7k
    for (const auto &StrictRule : StrictSubjectMatchRuleSet) {
961
      // First, check for exact match.
962
13.7k
      if (Rules.erase(StrictRule.first)) {
963
        // Add the rule to the set of attribute receivers only if it's supported
964
        // in the current language mode.
965
10.7k
        if (StrictRule.second)
966
10.7k
          SubjectMatchRules.push_back(StrictRule.first);
967
10.7k
      }
968
13.7k
    }
969
    // Check remaining rules for subset matches.
970
991
    auto RulesToCheck = Rules;
971
991
    for (const auto &Rule : RulesToCheck) {
972
32
      attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
973
32
      if (auto ParentRule = getParentAttrMatcherRule(MatchRule)) {
974
9
        if (llvm::any_of(StrictSubjectMatchRuleSet,
975
10
                         [ParentRule](const auto &StrictRule) {
976
10
                           return StrictRule.first == *ParentRule &&
977
10
                                  
StrictRule.second5
; // IsEnabled
978
10
                         })) {
979
5
          SubjectMatchRules.push_back(MatchRule);
980
5
          Rules.erase(MatchRule);
981
5
        }
982
9
      }
983
32
    }
984
991
  }
985
986
1.07k
  if (!Rules.empty()) {
987
22
    auto Diagnostic =
988
22
        Diag(PragmaLoc, diag::err_pragma_attribute_invalid_matchers)
989
22
        << Attribute;
990
22
    SmallVector<attr::SubjectMatchRule, 2> ExtraRules;
991
27
    for (const auto &Rule : Rules) {
992
27
      ExtraRules.push_back(attr::SubjectMatchRule(Rule.first));
993
27
      Diagnostic << FixItHint::CreateRemoval(
994
27
          replacementRangeForListElement(*this, Rule.second));
995
27
    }
996
22
    Diagnostic << attrMatcherRuleListToString(ExtraRules);
997
22
  }
998
999
1.07k
  if (PragmaAttributeStack.empty()) {
1000
1
    Diag(PragmaLoc, diag::err_pragma_attr_attr_no_push);
1001
1
    return;
1002
1
  }
1003
1004
1.07k
  PragmaAttributeStack.back().Entries.push_back(
1005
1.07k
      {PragmaLoc, &Attribute, std::move(SubjectMatchRules), /*IsUsed=*/false});
1006
1.07k
}
1007
1008
void Sema::ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
1009
1.07k
                                         const IdentifierInfo *Namespace) {
1010
1.07k
  PragmaAttributeStack.emplace_back();
1011
1.07k
  PragmaAttributeStack.back().Loc = PragmaLoc;
1012
1.07k
  PragmaAttributeStack.back().Namespace = Namespace;
1013
1.07k
}
1014
1015
void Sema::ActOnPragmaAttributePop(SourceLocation PragmaLoc,
1016
1.06k
                                   const IdentifierInfo *Namespace) {
1017
1.06k
  if (PragmaAttributeStack.empty()) {
1018
4
    Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
1019
4
    return;
1020
4
  }
1021
1022
  // Dig back through the stack trying to find the most recently pushed group
1023
  // that in Namespace. Note that this works fine if no namespace is present,
1024
  // think of push/pops without namespaces as having an implicit "nullptr"
1025
  // namespace.
1026
1.06k
  
for (size_t Index = PragmaAttributeStack.size(); 1.05k
Index;) {
1027
1.06k
    --Index;
1028
1.06k
    if (PragmaAttributeStack[Index].Namespace == Namespace) {
1029
1.05k
      for (const PragmaAttributeEntry &Entry :
1030
1.06k
           PragmaAttributeStack[Index].Entries) {
1031
1.06k
        if (!Entry.IsUsed) {
1032
69
          assert(Entry.Attribute && "Expected an attribute");
1033
0
          Diag(Entry.Attribute->getLoc(), diag::warn_pragma_attribute_unused)
1034
69
              << *Entry.Attribute;
1035
69
          Diag(PragmaLoc, diag::note_pragma_attribute_region_ends_here);
1036
69
        }
1037
1.06k
      }
1038
1.05k
      PragmaAttributeStack.erase(PragmaAttributeStack.begin() + Index);
1039
1.05k
      return;
1040
1.05k
    }
1041
1.06k
  }
1042
1043
2
  if (Namespace)
1044
1
    Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch)
1045
1
        << 0 << Namespace->getName();
1046
1
  else
1047
1
    Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
1048
2
}
1049
1050
103M
void Sema::AddPragmaAttributes(Scope *S, Decl *D) {
1051
103M
  if (PragmaAttributeStack.empty())
1052
103M
    return;
1053
64.7k
  
for (auto &Group : PragmaAttributeStack)64.6k
{
1054
64.7k
    for (auto &Entry : Group.Entries) {
1055
64.7k
      ParsedAttr *Attribute = Entry.Attribute;
1056
64.7k
      assert(Attribute && "Expected an attribute");
1057
0
      assert(Attribute->isPragmaClangAttribute() &&
1058
64.7k
             "expected #pragma clang attribute");
1059
1060
      // Ensure that the attribute can be applied to the given declaration.
1061
0
      bool Applies = false;
1062
598k
      for (const auto &Rule : Entry.MatchRules) {
1063
598k
        if (Attribute->appliesToDecl(D, Rule)) {
1064
64.1k
          Applies = true;
1065
64.1k
          break;
1066
64.1k
        }
1067
598k
      }
1068
64.7k
      if (!Applies)
1069
640
        continue;
1070
64.1k
      Entry.IsUsed = true;
1071
64.1k
      PragmaAttributeCurrentTargetDecl = D;
1072
64.1k
      ParsedAttributesView Attrs;
1073
64.1k
      Attrs.addAtEnd(Attribute);
1074
64.1k
      ProcessDeclAttributeList(S, D, Attrs);
1075
64.1k
      PragmaAttributeCurrentTargetDecl = nullptr;
1076
64.1k
    }
1077
64.7k
  }
1078
64.6k
}
1079
1080
21
void Sema::PrintPragmaAttributeInstantiationPoint() {
1081
21
  assert(PragmaAttributeCurrentTargetDecl && "Expected an active declaration");
1082
0
  Diags.Report(PragmaAttributeCurrentTargetDecl->getBeginLoc(),
1083
21
               diag::note_pragma_attribute_applied_decl_here);
1084
21
}
1085
1086
83.8k
void Sema::DiagnoseUnterminatedPragmaAttribute() {
1087
83.8k
  if (PragmaAttributeStack.empty())
1088
83.8k
    return;
1089
3
  Diag(PragmaAttributeStack.back().Loc, diag::err_pragma_attribute_no_pop_eof);
1090
3
}
1091
1092
31
void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {
1093
31
  if(On)
1094
14
    OptimizeOffPragmaLocation = SourceLocation();
1095
17
  else
1096
17
    OptimizeOffPragmaLocation = PragmaLoc;
1097
31
}
1098
1099
void Sema::ActOnPragmaMSFunction(
1100
12
    SourceLocation Loc, const llvm::SmallVectorImpl<StringRef> &NoBuiltins) {
1101
12
  if (!CurContext->getRedeclContext()->isFileContext()) {
1102
1
    Diag(Loc, diag::err_pragma_expected_file_scope) << "function";
1103
1
    return;
1104
1
  }
1105
1106
11
  MSFunctionNoBuiltins.insert(NoBuiltins.begin(), NoBuiltins.end());
1107
11
}
1108
1109
3.45M
void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
1110
  // In the future, check other pragmas if they're implemented (e.g. pragma
1111
  // optimize 0 will probably map to this functionality too).
1112
3.45M
  if(OptimizeOffPragmaLocation.isValid())
1113
29
    AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation);
1114
3.45M
}
1115
1116
3.44M
void Sema::AddSectionMSAllocText(FunctionDecl *FD) {
1117
3.44M
  if (!FD->getIdentifier())
1118
484k
    return;
1119
1120
2.95M
  StringRef Name = FD->getName();
1121
2.95M
  auto It = FunctionToSectionMap.find(Name);
1122
2.95M
  if (It != FunctionToSectionMap.end()) {
1123
5
    StringRef Section;
1124
5
    SourceLocation Loc;
1125
5
    std::tie(Section, Loc) = It->second;
1126
1127
5
    if (!FD->hasAttr<SectionAttr>())
1128
5
      FD->addAttr(SectionAttr::CreateImplicit(Context, Section));
1129
5
  }
1130
2.95M
}
1131
1132
void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD,
1133
29
                                            SourceLocation Loc) {
1134
  // Don't add a conflicting attribute. No diagnostic is needed.
1135
29
  if (FD->hasAttr<MinSizeAttr>() || 
FD->hasAttr<AlwaysInlineAttr>()26
)
1136
6
    return;
1137
1138
  // Add attributes only if required. Optnone requires noinline as well, but if
1139
  // either is already present then don't bother adding them.
1140
23
  if (!FD->hasAttr<OptimizeNoneAttr>())
1141
23
    FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
1142
23
  if (!FD->hasAttr<NoInlineAttr>())
1143
23
    FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
1144
23
}
1145
1146
3.44M
void Sema::AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD) {
1147
3.44M
  SmallVector<StringRef> V(MSFunctionNoBuiltins.begin(),
1148
3.44M
                           MSFunctionNoBuiltins.end());
1149
3.44M
  if (!MSFunctionNoBuiltins.empty())
1150
3
    FD->addAttr(NoBuiltinAttr::CreateImplicit(Context, V.data(), V.size()));
1151
3.44M
}
1152
1153
typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
1154
enum : unsigned { NoVisibility = ~0U };
1155
1156
7.19M
void Sema::AddPushedVisibilityAttribute(Decl *D) {
1157
7.19M
  if (!VisContext)
1158
7.19M
    return;
1159
1160
438
  NamedDecl *ND = dyn_cast<NamedDecl>(D);
1161
438
  if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue))
1162
96
    return;
1163
1164
342
  VisStack *Stack = static_cast<VisStack*>(VisContext);
1165
342
  unsigned rawType = Stack->back().first;
1166
342
  if (rawType == NoVisibility) 
return30
;
1167
1168
312
  VisibilityAttr::VisibilityType type
1169
312
    = (VisibilityAttr::VisibilityType) rawType;
1170
312
  SourceLocation loc = Stack->back().second;
1171
1172
312
  D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
1173
312
}
1174
1175
/// FreeVisContext - Deallocate and null out VisContext.
1176
76
void Sema::FreeVisContext() {
1177
76
  delete static_cast<VisStack*>(VisContext);
1178
76
  VisContext = nullptr;
1179
76
}
1180
1181
80
static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
1182
  // Put visibility on stack.
1183
80
  if (!S.VisContext)
1184
76
    S.VisContext = new VisStack;
1185
1186
80
  VisStack *Stack = static_cast<VisStack*>(S.VisContext);
1187
80
  Stack->push_back(std::make_pair(type, loc));
1188
80
}
1189
1190
void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
1191
115
                                 SourceLocation PragmaLoc) {
1192
115
  if (VisType) {
1193
    // Compute visibility to use.
1194
59
    VisibilityAttr::VisibilityType T;
1195
59
    if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
1196
1
      Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
1197
1
      return;
1198
1
    }
1199
58
    PushPragmaVisibility(*this, T, PragmaLoc);
1200
58
  } else {
1201
56
    PopPragmaVisibility(false, PragmaLoc);
1202
56
  }
1203
115
}
1204
1205
void Sema::ActOnPragmaFPContract(SourceLocation Loc,
1206
51
                                 LangOptions::FPModeKind FPC) {
1207
51
  FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1208
51
  switch (FPC) {
1209
31
  case LangOptions::FPM_On:
1210
31
    NewFPFeatures.setAllowFPContractWithinStatement();
1211
31
    break;
1212
10
  case LangOptions::FPM_Fast:
1213
10
    NewFPFeatures.setAllowFPContractAcrossStatement();
1214
10
    break;
1215
10
  case LangOptions::FPM_Off:
1216
10
    NewFPFeatures.setDisallowFPContract();
1217
10
    break;
1218
0
  case LangOptions::FPM_FastHonorPragmas:
1219
0
    llvm_unreachable("Should not happen");
1220
51
  }
1221
51
  FpPragmaStack.Act(Loc, Sema::PSK_Set, StringRef(), NewFPFeatures);
1222
51
  CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1223
51
}
1224
1225
39
void Sema::ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled) {
1226
39
  if (IsEnabled) {
1227
    // For value unsafe context, combining this pragma with eval method
1228
    // setting is not recommended. See comment in function FixupInvocation#506.
1229
29
    int Reason = -1;
1230
29
    if (getLangOpts().getFPEvalMethod() != LangOptions::FEM_UnsetOnCommandLine)
1231
      // Eval method set using the option 'ffp-eval-method'.
1232
2
      Reason = 1;
1233
29
    if (PP.getLastFPEvalPragmaLocation().isValid())
1234
      // Eval method set using the '#pragma clang fp eval_method'.
1235
      // We could have both an option and a pragma used to the set the eval
1236
      // method. The pragma overrides the option in the command line. The Reason
1237
      // of the diagnostic is overriden too.
1238
7
      Reason = 0;
1239
29
    if (Reason != -1)
1240
8
      Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context)
1241
8
          << Reason << 4;
1242
29
  }
1243
39
  FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1244
39
  NewFPFeatures.setAllowFPReassociateOverride(IsEnabled);
1245
39
  FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1246
39
  CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1247
39
}
1248
1249
34
void Sema::setRoundingMode(SourceLocation Loc, llvm::RoundingMode FPR) {
1250
  // C2x: 7.6.2p3  If the FE_DYNAMIC mode is specified and FENV_ACCESS is "off",
1251
  // the translator may assume that the default rounding mode is in effect.
1252
34
  if (FPR == llvm::RoundingMode::Dynamic &&
1253
34
      
!CurFPFeatures.getAllowFEnvAccess()2
&&
1254
34
      
CurFPFeatures.getFPExceptionMode() == LangOptions::FPE_Ignore2
)
1255
2
    FPR = llvm::RoundingMode::NearestTiesToEven;
1256
1257
34
  FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1258
34
  NewFPFeatures.setRoundingModeOverride(FPR);
1259
34
  FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1260
34
  CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1261
34
}
1262
1263
void Sema::setExceptionMode(SourceLocation Loc,
1264
3
                            LangOptions::FPExceptionModeKind FPE) {
1265
3
  FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1266
3
  NewFPFeatures.setFPExceptionModeOverride(FPE);
1267
3
  FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1268
3
  CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1269
3
}
1270
1271
25
void Sema::ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled) {
1272
25
  FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1273
25
  auto LO = getLangOpts();
1274
25
  if (IsEnabled) {
1275
    // Verify Microsoft restriction:
1276
    // You can't enable fenv_access unless precise semantics are enabled.
1277
    // Precise semantics can be enabled either by the float_control
1278
    // pragma, or by using the /fp:precise or /fp:strict compiler options
1279
14
    if (!isPreciseFPEnabled())
1280
0
      Diag(Loc, diag::err_pragma_fenv_requires_precise);
1281
14
    NewFPFeatures.setAllowFEnvAccessOverride(true);
1282
    // Enabling FENV access sets the RoundingMode to Dynamic.
1283
    // and ExceptionBehavior to Strict
1284
14
    NewFPFeatures.setRoundingModeOverride(llvm::RoundingMode::Dynamic);
1285
14
    NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Strict);
1286
14
  } else {
1287
11
    NewFPFeatures.setAllowFEnvAccessOverride(false);
1288
11
  }
1289
25
  FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1290
25
  CurFPFeatures = NewFPFeatures.applyOverrides(LO);
1291
25
}
1292
1293
void Sema::ActOnPragmaFPExceptions(SourceLocation Loc,
1294
3
                                   LangOptions::FPExceptionModeKind FPE) {
1295
3
  setExceptionMode(Loc, FPE);
1296
3
}
1297
1298
void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
1299
22
                                       SourceLocation Loc) {
1300
  // Visibility calculations will consider the namespace's visibility.
1301
  // Here we just want to note that we're in a visibility context
1302
  // which overrides any enclosing #pragma context, but doesn't itself
1303
  // contribute visibility.
1304
22
  PushPragmaVisibility(*this, NoVisibility, Loc);
1305
22
}
1306
1307
78
void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
1308
78
  if (!VisContext) {
1309
2
    Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
1310
2
    return;
1311
2
  }
1312
1313
  // Pop visibility from stack
1314
76
  VisStack *Stack = static_cast<VisStack*>(VisContext);
1315
1316
76
  const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
1317
76
  bool StartsWithPragma = Back->first != NoVisibility;
1318
76
  if (StartsWithPragma && 
IsNamespaceEnd54
) {
1319
1
    Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
1320
1
    Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
1321
1322
    // For better error recovery, eat all pushes inside the namespace.
1323
1
    do {
1324
1
      Stack->pop_back();
1325
1
      Back = &Stack->back();
1326
1
      StartsWithPragma = Back->first != NoVisibility;
1327
1
    } while (StartsWithPragma);
1328
75
  } else if (!StartsWithPragma && 
!IsNamespaceEnd22
) {
1329
1
    Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
1330
1
    Diag(Back->second, diag::note_surrounding_namespace_starts_here);
1331
1
    return;
1332
1
  }
1333
1334
75
  Stack->pop_back();
1335
  // To simplify the implementation, never keep around an empty stack.
1336
75
  if (Stack->empty())
1337
72
    FreeVisContext();
1338
75
}
1339
1340
template <typename Ty>
1341
static bool checkCommonAttributeFeatures(Sema &S, const Ty *Node,
1342
                                         const ParsedAttr &A,
1343
79.7M
                                         bool SkipArgCountCheck) {
1344
  // Several attributes carry different semantics than the parsing requires, so
1345
  // those are opted out of the common argument checks.
1346
  //
1347
  // We also bail on unknown and ignored attributes because those are handled
1348
  // as part of the target-specific handling logic.
1349
79.7M
  if (A.getKind() == ParsedAttr::UnknownAttribute)
1350
0
    return false;
1351
  // Check whether the attribute requires specific language extensions to be
1352
  // enabled.
1353
79.7M
  if (!A.diagnoseLangOpts(S))
1354
35
    return true;
1355
  // Check whether the attribute appertains to the given subject.
1356
79.7M
  if (!A.diagnoseAppertainsTo(S, Node))
1357
1.05k
    return true;
1358
  // Check whether the attribute is mutually exclusive with other attributes
1359
  // that have already been applied to the declaration.
1360
79.7M
  if (!A.diagnoseMutualExclusion(S, Node))
1361
69
    return true;
1362
  // Check whether the attribute exists in the target architecture.
1363
79.7M
  if (S.CheckAttrTarget(A))
1364
0
    return true;
1365
1366
79.7M
  if (A.hasCustomParsing())
1367
6.08M
    return false;
1368
1369
73.6M
  if (!SkipArgCountCheck) {
1370
73.6M
    if (A.getMinArgs() == A.getMaxArgs()) {
1371
      // If there are no optional arguments, then checking for the argument
1372
      // count is trivial.
1373
73.4M
      if (!A.checkExactlyNumArgs(S, A.getMinArgs()))
1374
258
        return true;
1375
73.4M
    } else {
1376
      // There are optional arguments, so checking is slightly more involved.
1377
183k
      if (A.getMinArgs() && 
!A.checkAtLeastNumArgs(S, A.getMinArgs())6.19k
)
1378
42
        return true;
1379
183k
      else if (!A.hasVariadicArg() && 
A.getMaxArgs()100k
&&
1380
183k
               
!A.checkAtMostNumArgs(S, A.getMaxArgs())100k
)
1381
14
        return true;
1382
183k
    }
1383
73.6M
  }
1384
1385
73.6M
  return false;
1386
73.6M
}
SemaAttr.cpp:bool checkCommonAttributeFeatures<clang::Decl>(clang::Sema&, clang::Decl const*, clang::ParsedAttr const&, bool)
Line
Count
Source
1343
79.7M
                                         bool SkipArgCountCheck) {
1344
  // Several attributes carry different semantics than the parsing requires, so
1345
  // those are opted out of the common argument checks.
1346
  //
1347
  // We also bail on unknown and ignored attributes because those are handled
1348
  // as part of the target-specific handling logic.
1349
79.7M
  if (A.getKind() == ParsedAttr::UnknownAttribute)
1350
0
    return false;
1351
  // Check whether the attribute requires specific language extensions to be
1352
  // enabled.
1353
79.7M
  if (!A.diagnoseLangOpts(S))
1354
35
    return true;
1355
  // Check whether the attribute appertains to the given subject.
1356
79.7M
  if (!A.diagnoseAppertainsTo(S, Node))
1357
1.00k
    return true;
1358
  // Check whether the attribute is mutually exclusive with other attributes
1359
  // that have already been applied to the declaration.
1360
79.7M
  if (!A.diagnoseMutualExclusion(S, Node))
1361
69
    return true;
1362
  // Check whether the attribute exists in the target architecture.
1363
79.7M
  if (S.CheckAttrTarget(A))
1364
0
    return true;
1365
1366
79.7M
  if (A.hasCustomParsing())
1367
6.08M
    return false;
1368
1369
73.6M
  if (!SkipArgCountCheck) {
1370
73.6M
    if (A.getMinArgs() == A.getMaxArgs()) {
1371
      // If there are no optional arguments, then checking for the argument
1372
      // count is trivial.
1373
73.4M
      if (!A.checkExactlyNumArgs(S, A.getMinArgs()))
1374
253
        return true;
1375
73.4M
    } else {
1376
      // There are optional arguments, so checking is slightly more involved.
1377
183k
      if (A.getMinArgs() && 
!A.checkAtLeastNumArgs(S, A.getMinArgs())6.19k
)
1378
42
        return true;
1379
183k
      else if (!A.hasVariadicArg() && 
A.getMaxArgs()100k
&&
1380
183k
               
!A.checkAtMostNumArgs(S, A.getMaxArgs())100k
)
1381
13
        return true;
1382
183k
    }
1383
73.6M
  }
1384
1385
73.6M
  return false;
1386
73.6M
}
SemaAttr.cpp:bool checkCommonAttributeFeatures<clang::Stmt>(clang::Sema&, clang::Stmt const*, clang::ParsedAttr const&, bool)
Line
Count
Source
1343
1.78k
                                         bool SkipArgCountCheck) {
1344
  // Several attributes carry different semantics than the parsing requires, so
1345
  // those are opted out of the common argument checks.
1346
  //
1347
  // We also bail on unknown and ignored attributes because those are handled
1348
  // as part of the target-specific handling logic.
1349
1.78k
  if (A.getKind() == ParsedAttr::UnknownAttribute)
1350
0
    return false;
1351
  // Check whether the attribute requires specific language extensions to be
1352
  // enabled.
1353
1.78k
  if (!A.diagnoseLangOpts(S))
1354
0
    return true;
1355
  // Check whether the attribute appertains to the given subject.
1356
1.78k
  if (!A.diagnoseAppertainsTo(S, Node))
1357
48
    return true;
1358
  // Check whether the attribute is mutually exclusive with other attributes
1359
  // that have already been applied to the declaration.
1360
1.73k
  if (!A.diagnoseMutualExclusion(S, Node))
1361
0
    return true;
1362
  // Check whether the attribute exists in the target architecture.
1363
1.73k
  if (S.CheckAttrTarget(A))
1364
0
    return true;
1365
1366
1.73k
  if (A.hasCustomParsing())
1367
352
    return false;
1368
1369
1.38k
  if (!SkipArgCountCheck) {
1370
1.38k
    if (A.getMinArgs() == A.getMaxArgs()) {
1371
      // If there are no optional arguments, then checking for the argument
1372
      // count is trivial.
1373
1.35k
      if (!A.checkExactlyNumArgs(S, A.getMinArgs()))
1374
5
        return true;
1375
1.35k
    } else {
1376
      // There are optional arguments, so checking is slightly more involved.
1377
29
      if (A.getMinArgs() && 
!A.checkAtLeastNumArgs(S, A.getMinArgs())0
)
1378
0
        return true;
1379
29
      else if (!A.hasVariadicArg() && 
A.getMaxArgs()24
&&
1380
29
               
!A.checkAtMostNumArgs(S, A.getMaxArgs())24
)
1381
1
        return true;
1382
29
    }
1383
1.38k
  }
1384
1385
1.38k
  return false;
1386
1.38k
}
1387
1388
bool Sema::checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
1389
79.7M
                                        bool SkipArgCountCheck) {
1390
79.7M
  return ::checkCommonAttributeFeatures(*this, D, A, SkipArgCountCheck);
1391
79.7M
}
1392
bool Sema::checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
1393
1.78k
                                        bool SkipArgCountCheck) {
1394
1.78k
  return ::checkCommonAttributeFeatures(*this, S, A, SkipArgCountCheck);
1395
1.78k
}