Coverage Report

Created: 2021-09-21 08:58

/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.57M
    : S(S), SlotLabel(SlotLabel), ShouldAct(ShouldAct) {
31
3.57M
  if (ShouldAct) {
32
650k
    S.VtorDispStack.SentinelAction(PSK_Push, SlotLabel);
33
650k
    S.DataSegStack.SentinelAction(PSK_Push, SlotLabel);
34
650k
    S.BSSSegStack.SentinelAction(PSK_Push, SlotLabel);
35
650k
    S.ConstSegStack.SentinelAction(PSK_Push, SlotLabel);
36
650k
    S.CodeSegStack.SentinelAction(PSK_Push, SlotLabel);
37
650k
  }
38
3.57M
}
39
40
3.57M
Sema::PragmaStackSentinelRAII::~PragmaStackSentinelRAII() {
41
3.57M
  if (ShouldAct) {
42
650k
    S.VtorDispStack.SentinelAction(PSK_Pop, SlotLabel);
43
650k
    S.DataSegStack.SentinelAction(PSK_Pop, SlotLabel);
44
650k
    S.BSSSegStack.SentinelAction(PSK_Pop, SlotLabel);
45
650k
    S.ConstSegStack.SentinelAction(PSK_Pop, SlotLabel);
46
650k
    S.CodeSegStack.SentinelAction(PSK_Pop, SlotLabel);
47
650k
  }
48
3.57M
}
49
50
1.06M
void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
51
1.06M
  AlignPackInfo InfoVal = AlignPackStack.CurrentValue;
52
1.06M
  AlignPackInfo::Mode M = InfoVal.getAlignMode();
53
1.06M
  bool IsPackSet = InfoVal.IsPackSet();
54
1.06M
  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.06M
  if (!IsPackSet && 
M != AlignPackInfo::Mac68k833k
&&
M != AlignPackInfo::Natural833k
)
59
833k
    return;
60
61
235k
  if (M == AlignPackInfo::Mac68k && 
(14
IsXLPragma14
||
InfoVal.IsAlignAttr()14
)) {
62
14
    RD->addAttr(AlignMac68kAttr::CreateImplicit(Context));
63
235k
  } else if (IsPackSet) {
64
    // Check to see if we need a max field alignment attribute.
65
235k
    RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(
66
235k
        Context, InfoVal.getPackNumber() * 8));
67
235k
  }
68
69
235k
  if (IsXLPragma && 
M == AlignPackInfo::Natural70
)
70
26
    RD->addAttr(AlignNaturalAttr::CreateImplicit(Context));
71
72
235k
  if (AlignPackIncludeStack.empty())
73
421
    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
235k
  
for (auto &AlignPackedInclude : llvm::reverse(AlignPackIncludeStack))235k
{
78
235k
    if (AlignPackedInclude.CurrentPragmaLocation !=
79
235k
        AlignPackStack.CurrentPragmaLocation)
80
235k
      break;
81
18
    if (AlignPackedInclude.HasNonDefaultValue)
82
14
      AlignPackedInclude.ShouldWarnOnInclude = true;
83
18
  }
84
235k
}
85
86
1.06M
void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
87
1.06M
  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.06M
  if (VtorDispStack.CurrentValue != getLangOpts().getVtorDispMode())
94
29
    RD->addAttr(MSVtorDispAttr::CreateImplicit(
95
29
        Context, unsigned(VtorDispStack.CurrentValue)));
96
1.06M
}
97
98
template <typename Attribute>
99
static void addGslOwnerPointerAttributeIfNotExisting(ASTContext &Context,
100
9.81k
                                                     CXXRecordDecl *Record) {
101
9.81k
  if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
102
2.83k
    return;
103
104
6.97k
  for (Decl *Redecl : Record->redecls())
105
7.27k
    Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
106
6.97k
}
SemaAttr.cpp:void addGslOwnerPointerAttributeIfNotExisting<clang::PointerAttr>(clang::ASTContext&, clang::CXXRecordDecl*)
Line
Count
Source
100
6.17k
                                                     CXXRecordDecl *Record) {
101
6.17k
  if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
102
2.83k
    return;
103
104
3.33k
  for (Decl *Redecl : Record->redecls())
105
3.63k
    Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
106
3.33k
}
SemaAttr.cpp:void addGslOwnerPointerAttributeIfNotExisting<clang::OwnerAttr>(clang::ASTContext&, clang::CXXRecordDecl*)
Line
Count
Source
100
3.63k
                                                     CXXRecordDecl *Record) {
101
3.63k
  if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
102
0
    return;
103
104
3.63k
  for (Decl *Redecl : Record->redecls())
105
3.63k
    Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
106
3.63k
}
107
108
void Sema::inferGslPointerAttribute(NamedDecl *ND,
109
2.81M
                                    CXXRecordDecl *UnderlyingRecord) {
110
2.81M
  if (!UnderlyingRecord)
111
2.23M
    return;
112
113
576k
  const auto *Parent = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
114
576k
  if (!Parent)
115
383k
    return;
116
117
193k
  static llvm::StringSet<> Containers{
118
193k
      "array",
119
193k
      "basic_string",
120
193k
      "deque",
121
193k
      "forward_list",
122
193k
      "vector",
123
193k
      "list",
124
193k
      "map",
125
193k
      "multiset",
126
193k
      "multimap",
127
193k
      "priority_queue",
128
193k
      "queue",
129
193k
      "set",
130
193k
      "stack",
131
193k
      "unordered_set",
132
193k
      "unordered_map",
133
193k
      "unordered_multiset",
134
193k
      "unordered_multimap",
135
193k
  };
136
137
193k
  static llvm::StringSet<> Iterators{"iterator", "const_iterator",
138
193k
                                     "reverse_iterator",
139
193k
                                     "const_reverse_iterator"};
140
141
193k
  if (Parent->isInStdNamespace() && 
Iterators.count(ND->getName())170k
&&
142
193k
      
Containers.count(Parent->getName())6.81k
)
143
5.39k
    addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context,
144
5.39k
                                                          UnderlyingRecord);
145
193k
}
146
147
2.55M
void Sema::inferGslPointerAttribute(TypedefNameDecl *TD) {
148
149
2.55M
  QualType Canonical = TD->getUnderlyingType().getCanonicalType();
150
151
2.55M
  CXXRecordDecl *RD = Canonical->getAsCXXRecordDecl();
152
2.55M
  if (!RD) {
153
2.30M
    if (auto *TST =
154
2.30M
            dyn_cast<TemplateSpecializationType>(Canonical.getTypePtr())) {
155
156
67.9k
      RD = dyn_cast_or_null<CXXRecordDecl>(
157
67.9k
          TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl());
158
67.9k
    }
159
2.30M
  }
160
161
2.55M
  inferGslPointerAttribute(TD, RD);
162
2.55M
}
163
164
557k
void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl *Record) {
165
557k
  static llvm::StringSet<> StdOwners{
166
557k
      "any",
167
557k
      "array",
168
557k
      "basic_regex",
169
557k
      "basic_string",
170
557k
      "deque",
171
557k
      "forward_list",
172
557k
      "vector",
173
557k
      "list",
174
557k
      "map",
175
557k
      "multiset",
176
557k
      "multimap",
177
557k
      "optional",
178
557k
      "priority_queue",
179
557k
      "queue",
180
557k
      "set",
181
557k
      "stack",
182
557k
      "unique_ptr",
183
557k
      "unordered_set",
184
557k
      "unordered_map",
185
557k
      "unordered_multiset",
186
557k
      "unordered_multimap",
187
557k
      "variant",
188
557k
  };
189
557k
  static llvm::StringSet<> StdPointers{
190
557k
      "basic_string_view",
191
557k
      "reference_wrapper",
192
557k
      "regex_iterator",
193
557k
  };
194
195
557k
  if (!Record->getIdentifier())
196
39.6k
    return;
197
198
  // Handle classes that directly appear in std namespace.
199
517k
  if (Record->isInStdNamespace()) {
200
255k
    if (Record->hasAttr<OwnerAttr>() || 
Record->hasAttr<PointerAttr>()253k
)
201
3.76k
      return;
202
203
252k
    if (StdOwners.count(Record->getName()))
204
3.63k
      addGslOwnerPointerAttributeIfNotExisting<OwnerAttr>(Context, Record);
205
248k
    else if (StdPointers.count(Record->getName()))
206
783
      addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context, Record);
207
208
252k
    return;
209
255k
  }
210
211
  // Handle nested classes that could be a gsl::Pointer.
212
261k
  inferGslPointerAttribute(Record, Record);
213
261k
}
214
215
void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
216
2.76k
                                   SourceLocation PragmaLoc) {
217
2.76k
  PragmaMsStackAction Action = Sema::PSK_Reset;
218
2.76k
  AlignPackInfo::Mode ModeVal = AlignPackInfo::Native;
219
220
2.76k
  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.32k
  case POAK_Power:
227
1.32k
    Action = Sema::PSK_Push_Set;
228
1.32k
    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
23
  case POAK_Packed:
237
23
    Action = Sema::PSK_Push_Set;
238
23
    ModeVal = AlignPackInfo::Packed;
239
23
    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.37k
  case POAK_Reset:
251
    // Reset just pops the top of the stack, or resets the current alignment to
252
    // default.
253
1.37k
    Action = Sema::PSK_Pop;
254
1.37k
    if (AlignPackStack.Stack.empty()) {
255
9
      if (AlignPackStack.CurrentValue.getAlignMode() != AlignPackInfo::Native ||
256
9
          AlignPackStack.CurrentValue.IsPackAttr()) {
257
6
        Action = Sema::PSK_Reset;
258
6
      } else {
259
3
        Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
260
3
            << "stack empty";
261
3
        return;
262
3
      }
263
9
    }
264
1.37k
    break;
265
2.76k
  }
266
267
2.76k
  AlignPackInfo Info(ModeVal, getLangOpts().XLPragmaPack);
268
269
2.76k
  AlignPackStack.Act(PragmaLoc, Action, StringRef(), Info);
270
2.76k
}
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
254k
                           StringRef SlotLabel, Expr *alignment) {
323
254k
  bool IsXLPragma = getLangOpts().XLPragmaPack;
324
  // XL pragma pack does not support identifier syntax.
325
254k
  if (IsXLPragma && 
!SlotLabel.empty()188
) {
326
2
    Diag(PragmaLoc, diag::err_pragma_pack_identifer_not_supported);
327
2
    return;
328
2
  }
329
330
254k
  const AlignPackInfo CurVal = AlignPackStack.CurrentValue;
331
254k
  Expr *Alignment = static_cast<Expr *>(alignment);
332
333
  // If specified then alignment must be a "small" power of two.
334
254k
  unsigned AlignmentVal = 0;
335
254k
  AlignPackInfo::Mode ModeVal = CurVal.getAlignMode();
336
337
254k
  if (Alignment) {
338
127k
    Optional<llvm::APSInt> Val;
339
127k
    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
127k
    if (Alignment->isTypeDependent() || Alignment->isValueDependent() || !Val ||
344
127k
        !(*Val == 0 || 
Val->isPowerOf2()127k
) ||
Val->getZExtValue() > 16127k
) {
345
1
      Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
346
1
      return; // Ignore
347
1
    }
348
349
127k
    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
127k
    AlignmentVal = (unsigned)Val->getZExtValue();
356
127k
  }
357
358
254k
  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
254k
  if (Action & Sema::PSK_Pop) {
373
125k
    if (Alignment && 
!SlotLabel.empty()1
)
374
0
      Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifier_and_alignment);
375
125k
    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
125k
  }
381
382
0
  AlignPackInfo Info(ModeVal, AlignmentVal, IsXLPragma);
383
384
254k
  AlignPackStack.Act(PragmaLoc, Action, SlotLabel, Info);
385
254k
}
386
387
void Sema::DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
388
1.12M
                                             SourceLocation IncludeLoc) {
389
1.12M
  if (Kind == PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude) {
390
564k
    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
564k
    bool HasNonDefaultValue =
397
564k
        AlignPackStack.hasValue() &&
398
564k
        
(21
AlignPackIncludeStack.empty()21
||
399
21
         
AlignPackIncludeStack.back().CurrentPragmaLocation != PrevLocation9
);
400
564k
    AlignPackIncludeStack.push_back(
401
564k
        {AlignPackStack.CurrentValue,
402
564k
         AlignPackStack.hasValue() ? 
PrevLocation21
:
SourceLocation()564k
,
403
564k
         HasNonDefaultValue, /*ShouldWarnOnInclude*/ false});
404
564k
    return;
405
564k
  }
406
407
564k
  assert(Kind == PragmaAlignPackDiagnoseKind::ChangedStateAtExit &&
408
564k
         "invalid kind");
409
0
  AlignPackIncludeState PrevAlignPackState =
410
564k
      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
564k
  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
564k
  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
564k
}
425
426
93.0k
void Sema::DiagnoseUnterminatedPragmaAlignPack() {
427
93.0k
  if (AlignPackStack.Stack.empty())
428
93.0k
    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.92k
void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {
454
3.92k
  MSStructPragmaOn = (Kind == PMSST_ON);
455
3.92k
}
456
457
void Sema::ActOnPragmaMSComment(SourceLocation CommentLoc,
458
56
                                PragmaMSCommentKind Kind, StringRef Arg) {
459
56
  auto *PCD = PragmaCommentDecl::Create(
460
56
      Context, Context.getTranslationUnitDecl(), CommentLoc, Kind, Arg);
461
56
  Context.getTranslationUnitDecl()->addDecl(PCD);
462
56
  Consumer.HandleTopLevelDecl(DeclGroupRef(PCD));
463
56
}
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::ActOnPragmaFloatControl(SourceLocation Loc,
474
                                   PragmaMsStackAction Action,
475
294
                                   PragmaFloatControlKind Value) {
476
294
  FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
477
294
  if ((Action == PSK_Push_Set || 
Action == PSK_Push283
||
Action == PSK_Pop242
) &&
478
294
      
!CurContext->getRedeclContext()->isFileContext()121
) {
479
    // Push and pop can only occur at file or namespace scope, or within a
480
    // language linkage declaration.
481
4
    Diag(Loc, diag::err_pragma_fc_pp_scope);
482
4
    return;
483
4
  }
484
290
  switch (Value) {
485
0
  default:
486
0
    llvm_unreachable("invalid pragma float_control kind");
487
38
  case PFC_Precise:
488
38
    NewFPFeatures.setFPPreciseEnabled(true);
489
38
    FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
490
38
    break;
491
53
  case PFC_NoPrecise:
492
53
    if (CurFPFeatures.getFPExceptionMode() == LangOptions::FPE_Strict)
493
13
      Diag(Loc, diag::err_pragma_fc_noprecise_requires_noexcept);
494
40
    else if (CurFPFeatures.getAllowFEnvAccess())
495
0
      Diag(Loc, diag::err_pragma_fc_noprecise_requires_nofenv);
496
40
    else
497
40
      NewFPFeatures.setFPPreciseEnabled(false);
498
53
    FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
499
53
    break;
500
75
  case PFC_Except:
501
75
    if (!isPreciseFPEnabled())
502
0
      Diag(Loc, diag::err_pragma_fc_except_requires_precise);
503
75
    else
504
75
      NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Strict);
505
75
    FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
506
75
    break;
507
16
  case PFC_NoExcept:
508
16
    NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Ignore);
509
16
    FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
510
16
    break;
511
40
  case PFC_Push:
512
40
    FpPragmaStack.Act(Loc, Sema::PSK_Push_Set, StringRef(), NewFPFeatures);
513
40
    break;
514
68
  case PFC_Pop:
515
68
    if (FpPragmaStack.Stack.empty()) {
516
20
      Diag(Loc, diag::warn_pragma_pop_failed) << "float_control"
517
20
                                              << "stack empty";
518
20
      return;
519
20
    }
520
48
    FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
521
48
    NewFPFeatures = FpPragmaStack.CurrentValue;
522
48
    break;
523
290
  }
524
270
  CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
525
270
}
526
527
void Sema::ActOnPragmaMSPointersToMembers(
528
    LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
529
26
    SourceLocation PragmaLoc) {
530
26
  MSPointerToMemberRepresentationMethod = RepresentationMethod;
531
26
  ImplicitMSInheritanceAttrLoc = PragmaLoc;
532
26
}
533
534
void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
535
                                 SourceLocation PragmaLoc,
536
45
                                 MSVtorDispMode Mode) {
537
45
  if (Action & PSK_Pop && 
VtorDispStack.Stack.empty()20
)
538
4
    Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
539
4
                                                  << "stack empty";
540
45
  VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);
541
45
}
542
543
template <>
544
void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
545
                                                 PragmaMsStackAction Action,
546
                                                 llvm::StringRef StackSlotLabel,
547
257k
                                                 AlignPackInfo Value) {
548
257k
  if (Action == PSK_Reset) {
549
1.82k
    CurrentValue = DefaultValue;
550
1.82k
    CurrentPragmaLocation = PragmaLocation;
551
1.82k
    return;
552
1.82k
  }
553
255k
  if (Action & PSK_Push)
554
126k
    Stack.emplace_back(Slot(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
555
126k
                            PragmaLocation));
556
128k
  else if (Action & PSK_Pop) {
557
126k
    if (!StackSlotLabel.empty()) {
558
      // If we've got a label, try to find it and jump there.
559
10
      auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
560
10
        return x.StackSlotLabel == StackSlotLabel;
561
10
      });
562
      // We found the label, so pop from there.
563
9
      if (I != Stack.rend()) {
564
5
        CurrentValue = I->Value;
565
5
        CurrentPragmaLocation = I->PragmaLocation;
566
5
        Stack.erase(std::prev(I.base()), Stack.end());
567
5
      }
568
126k
    } else if (Value.IsXLStack() && 
Value.IsAlignAttr()112
&&
569
126k
               
CurrentValue.IsPackAttr()38
) {
570
      // XL '#pragma align(reset)' would pop the stack until
571
      // a current in effect pragma align is popped.
572
8
      auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
573
8
        return x.Value.IsAlignAttr();
574
8
      });
575
      // If we found pragma align so pop from there.
576
8
      if (I != Stack.rend()) {
577
8
        Stack.erase(std::prev(I.base()), Stack.end());
578
8
        if (Stack.empty()) {
579
2
          CurrentValue = DefaultValue;
580
2
          CurrentPragmaLocation = PragmaLocation;
581
6
        } else {
582
6
          CurrentValue = Stack.back().Value;
583
6
          CurrentPragmaLocation = Stack.back().PragmaLocation;
584
6
          Stack.pop_back();
585
6
        }
586
8
      }
587
126k
    } else if (!Stack.empty()) {
588
      // xl '#pragma align' sets the baseline, and `#pragma pack` cannot pop
589
      // over the baseline.
590
126k
      if (Value.IsXLStack() && 
Value.IsPackAttr()94
&&
CurrentValue.IsAlignAttr()64
)
591
2
        return;
592
593
      // We don't have a label, just pop the last entry.
594
126k
      CurrentValue = Stack.back().Value;
595
126k
      CurrentPragmaLocation = Stack.back().PragmaLocation;
596
126k
      Stack.pop_back();
597
126k
    }
598
126k
  }
599
255k
  if (Action & PSK_Set) {
600
128k
    CurrentValue = Value;
601
128k
    CurrentPragmaLocation = PragmaLocation;
602
128k
  }
603
255k
}
604
605
bool Sema::UnifySection(StringRef SectionName, int SectionFlags,
606
1.32k
                        NamedDecl *Decl) {
607
1.32k
  SourceLocation PragmaLocation;
608
1.32k
  if (auto A = Decl->getAttr<SectionAttr>())
609
1.32k
    if (A->isImplicit())
610
68
      PragmaLocation = A->getLocation();
611
1.32k
  auto SectionIt = Context.SectionInfos.find(SectionName);
612
1.32k
  if (SectionIt == Context.SectionInfos.end()) {
613
114
    Context.SectionInfos[SectionName] =
614
114
        ASTContext::SectionInfo(Decl, PragmaLocation, SectionFlags);
615
114
    return false;
616
114
  }
617
  // A pre-declared section takes precedence w/o diagnostic.
618
1.21k
  const auto &Section = SectionIt->second;
619
1.21k
  if (Section.SectionFlags == SectionFlags ||
620
1.21k
      
(26
(SectionFlags & ASTContext::PSF_Implicit)26
&&
621
26
       
!(Section.SectionFlags & ASTContext::PSF_Implicit)13
))
622
1.19k
    return false;
623
16
  Diag(Decl->getLocation(), diag::err_section_conflict) << Decl << Section;
624
16
  if (Section.Decl)
625
15
    Diag(Section.Decl->getLocation(), diag::note_declared_at)
626
15
        << Section.Decl->getName();
627
16
  if (PragmaLocation.isValid())
628
2
    Diag(PragmaLocation, diag::note_pragma_entered_here);
629
16
  if (Section.PragmaSectionLocation.isValid())
630
3
    Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
631
16
  return true;
632
1.21k
}
633
634
bool Sema::UnifySection(StringRef SectionName,
635
                        int SectionFlags,
636
66
                        SourceLocation PragmaSectionLocation) {
637
66
  auto SectionIt = Context.SectionInfos.find(SectionName);
638
66
  if (SectionIt != Context.SectionInfos.end()) {
639
7
    const auto &Section = SectionIt->second;
640
7
    if (Section.SectionFlags == SectionFlags)
641
0
      return false;
642
7
    if (!(Section.SectionFlags & ASTContext::PSF_Implicit)) {
643
7
      Diag(PragmaSectionLocation, diag::err_section_conflict)
644
7
          << "this" << Section;
645
7
      if (Section.Decl)
646
1
        Diag(Section.Decl->getLocation(), diag::note_declared_at)
647
1
            << Section.Decl->getName();
648
7
      if (Section.PragmaSectionLocation.isValid())
649
6
        Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
650
7
      return true;
651
7
    }
652
7
  }
653
59
  Context.SectionInfos[SectionName] =
654
59
      ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
655
59
  return false;
656
66
}
657
658
/// Called on well formed \#pragma bss_seg().
659
void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
660
                            PragmaMsStackAction Action,
661
                            llvm::StringRef StackSlotLabel,
662
                            StringLiteral *SegmentName,
663
57
                            llvm::StringRef PragmaName) {
664
57
  PragmaStack<StringLiteral *> *Stack =
665
57
    llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
666
57
        .Case("data_seg", &DataSegStack)
667
57
        .Case("bss_seg", &BSSSegStack)
668
57
        .Case("const_seg", &ConstSegStack)
669
57
        .Case("code_seg", &CodeSegStack);
670
57
  if (Action & PSK_Pop && 
Stack->Stack.empty()7
)
671
0
    Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
672
0
        << "stack empty";
673
57
  if (SegmentName) {
674
45
    if (!checkSectionName(SegmentName->getBeginLoc(), SegmentName->getString()))
675
1
      return;
676
677
44
    if (SegmentName->getString() == ".drectve" &&
678
44
        
Context.getTargetInfo().getCXXABI().isMicrosoft()4
)
679
4
      Diag(PragmaLocation, diag::warn_attribute_section_drectve) << PragmaName;
680
44
  }
681
682
56
  Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
683
56
}
684
685
/// Called on well formed \#pragma bss_seg().
686
void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
687
22
                                int SectionFlags, StringLiteral *SegmentName) {
688
22
  UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
689
22
}
690
691
void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
692
24
                                StringLiteral *SegmentName) {
693
  // There's no stack to maintain, so we just have a current section.  When we
694
  // see the default section, reset our current section back to null so we stop
695
  // tacking on unnecessary attributes.
696
24
  CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? 
nullptr1
:
SegmentName23
;
697
24
  CurInitSegLoc = PragmaLocation;
698
24
}
699
700
void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
701
25
                             SourceLocation PragmaLoc) {
702
703
25
  IdentifierInfo *Name = IdTok.getIdentifierInfo();
704
25
  LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
705
25
  LookupParsedName(Lookup, curScope, nullptr, true);
706
707
25
  if (Lookup.empty()) {
708
3
    Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
709
3
      << Name << SourceRange(IdTok.getLocation());
710
3
    return;
711
3
  }
712
713
22
  VarDecl *VD = Lookup.getAsSingle<VarDecl>();
714
22
  if (!VD) {
715
0
    Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
716
0
      << Name << SourceRange(IdTok.getLocation());
717
0
    return;
718
0
  }
719
720
  // Warn if this was used before being marked unused.
721
22
  if (VD->isUsed())
722
1
    Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
723
724
22
  VD->addAttr(UnusedAttr::CreateImplicit(Context, IdTok.getLocation(),
725
22
                                         AttributeCommonInfo::AS_Pragma,
726
22
                                         UnusedAttr::GNU_unused));
727
22
}
728
729
32.0M
void Sema::AddCFAuditedAttribute(Decl *D) {
730
32.0M
  IdentifierInfo *Ident;
731
32.0M
  SourceLocation Loc;
732
32.0M
  std::tie(Ident, Loc) = PP.getPragmaARCCFCodeAuditedInfo();
733
32.0M
  if (!Loc.isValid()) 
return31.5M
;
734
735
  // Don't add a redundant or conflicting attribute.
736
469k
  if (D->hasAttr<CFAuditedTransferAttr>() ||
737
469k
      
D->hasAttr<CFUnknownTransferAttr>()468k
)
738
876
    return;
739
740
468k
  AttributeCommonInfo Info(Ident, SourceRange(Loc),
741
468k
                           AttributeCommonInfo::AS_Pragma);
742
468k
  D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Info));
743
468k
}
744
745
namespace {
746
747
Optional<attr::SubjectMatchRule>
748
334
getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {
749
334
  using namespace attr;
750
334
  switch (Rule) {
751
229
  default:
752
229
    return None;
753
0
#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
754
0
#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated)    \
755
105
  case Value:                                                                  \
756
105
    return Parent;
757
334
#include 
"clang/Basic/AttrSubMatchRulesList.inc"229
758
334
  }
759
334
}
760
761
57
bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {
762
57
  using namespace attr;
763
57
  switch (Rule) {
764
4
  default:
765
4
    return false;
766
0
#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
767
0
#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated)    \
768
53
  case Value:                                                                  \
769
53
    return IsNegated;
770
57
#include 
"clang/Basic/AttrSubMatchRulesList.inc"4
771
57
  }
772
57
}
773
774
CharSourceRange replacementRangeForListElement(const Sema &S,
775
44
                                               SourceRange Range) {
776
  // Make sure that the ',' is removed as well.
777
44
  SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(
778
44
      Range.getEnd(), tok::comma, S.getSourceManager(), S.getLangOpts(),
779
44
      /*SkipTrailingWhitespaceAndNewLine=*/false);
780
44
  if (AfterCommaLoc.isValid())
781
16
    return CharSourceRange::getCharRange(Range.getBegin(), AfterCommaLoc);
782
28
  else
783
28
    return CharSourceRange::getTokenRange(Range);
784
44
}
785
786
std::string
787
22
attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules) {
788
22
  std::string Result;
789
22
  llvm::raw_string_ostream OS(Result);
790
27
  for (const auto &I : llvm::enumerate(Rules)) {
791
27
    if (I.index())
792
5
      OS << (I.index() == Rules.size() - 1 ? ", and " : 
", "0
);
793
27
    OS << "'" << attr::getSubjectMatchRuleSpelling(I.value()) << "'";
794
27
  }
795
22
  return OS.str();
796
22
}
797
798
} // end anonymous namespace
799
800
void Sema::ActOnPragmaAttributeAttribute(
801
    ParsedAttr &Attribute, SourceLocation PragmaLoc,
802
1.28k
    attr::ParsedSubjectMatchRuleSet Rules) {
803
1.28k
  Attribute.setIsPragmaClangAttribute();
804
1.28k
  SmallVector<attr::SubjectMatchRule, 4> SubjectMatchRules;
805
  // Gather the subject match rules that are supported by the attribute.
806
1.28k
  SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4>
807
1.28k
      StrictSubjectMatchRuleSet;
808
1.28k
  Attribute.getMatchRules(LangOpts, StrictSubjectMatchRuleSet);
809
810
  // Figure out which subject matching rules are valid.
811
1.28k
  if (StrictSubjectMatchRuleSet.empty()) {
812
    // Check for contradicting match rules. Contradicting match rules are
813
    // either:
814
    //  - a top-level rule and one of its sub-rules. E.g. variable and
815
    //    variable(is_parameter).
816
    //  - a sub-rule and a sibling that's negated. E.g.
817
    //    variable(is_thread_local) and variable(unless(is_parameter))
818
82
    llvm::SmallDenseMap<int, std::pair<int, SourceRange>, 2>
819
82
        RulesToFirstSpecifiedNegatedSubRule;
820
151
    for (const auto &Rule : Rules) {
821
151
      attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
822
151
      Optional<attr::SubjectMatchRule> ParentRule =
823
151
          getParentAttrMatcherRule(MatchRule);
824
151
      if (!ParentRule)
825
103
        continue;
826
48
      auto It = Rules.find(*ParentRule);
827
48
      if (It != Rules.end()) {
828
        // A sub-rule contradicts a parent rule.
829
11
        Diag(Rule.second.getBegin(),
830
11
             diag::err_pragma_attribute_matcher_subrule_contradicts_rule)
831
11
            << attr::getSubjectMatchRuleSpelling(MatchRule)
832
11
            << attr::getSubjectMatchRuleSpelling(*ParentRule) << It->second
833
11
            << FixItHint::CreateRemoval(
834
11
                   replacementRangeForListElement(*this, Rule.second));
835
        // Keep going without removing this rule as it won't change the set of
836
        // declarations that receive the attribute.
837
11
        continue;
838
11
      }
839
37
      if (isNegatedAttrMatcherSubRule(MatchRule))
840
12
        RulesToFirstSpecifiedNegatedSubRule.insert(
841
12
            std::make_pair(*ParentRule, Rule));
842
37
    }
843
82
    bool IgnoreNegatedSubRules = false;
844
151
    for (const auto &Rule : Rules) {
845
151
      attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
846
151
      Optional<attr::SubjectMatchRule> ParentRule =
847
151
          getParentAttrMatcherRule(MatchRule);
848
151
      if (!ParentRule)
849
103
        continue;
850
48
      auto It = RulesToFirstSpecifiedNegatedSubRule.find(*ParentRule);
851
48
      if (It != RulesToFirstSpecifiedNegatedSubRule.end() &&
852
48
          
It->second != Rule12
) {
853
        // Negated sub-rule contradicts another sub-rule.
854
6
        Diag(
855
6
            It->second.second.getBegin(),
856
6
            diag::
857
6
                err_pragma_attribute_matcher_negated_subrule_contradicts_subrule)
858
6
            << attr::getSubjectMatchRuleSpelling(
859
6
                   attr::SubjectMatchRule(It->second.first))
860
6
            << attr::getSubjectMatchRuleSpelling(MatchRule) << Rule.second
861
6
            << FixItHint::CreateRemoval(
862
6
                   replacementRangeForListElement(*this, It->second.second));
863
        // Keep going but ignore all of the negated sub-rules.
864
6
        IgnoreNegatedSubRules = true;
865
6
        RulesToFirstSpecifiedNegatedSubRule.erase(It);
866
6
      }
867
48
    }
868
869
82
    if (!IgnoreNegatedSubRules) {
870
76
      for (const auto &Rule : Rules)
871
131
        SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
872
76
    } else {
873
20
      for (const auto &Rule : Rules) {
874
20
        if (!isNegatedAttrMatcherSubRule(attr::SubjectMatchRule(Rule.first)))
875
14
          SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
876
20
      }
877
6
    }
878
82
    Rules.clear();
879
1.20k
  } else {
880
    // Each rule in Rules must be a strict subset of the attribute's
881
    // SubjectMatch rules.  I.e. we're allowed to use
882
    // `apply_to=variables(is_global)` on an attrubute with SubjectList<[Var]>,
883
    // but should not allow `apply_to=variables` on an attribute which has
884
    // `SubjectList<[GlobalVar]>`.
885
17.0k
    for (const auto &StrictRule : StrictSubjectMatchRuleSet) {
886
      // First, check for exact match.
887
17.0k
      if (Rules.erase(StrictRule.first)) {
888
        // Add the rule to the set of attribute receivers only if it's supported
889
        // in the current language mode.
890
13.4k
        if (StrictRule.second)
891
13.4k
          SubjectMatchRules.push_back(StrictRule.first);
892
13.4k
      }
893
17.0k
    }
894
    // Check remaining rules for subset matches.
895
1.20k
    auto RulesToCheck = Rules;
896
1.20k
    for (const auto &Rule : RulesToCheck) {
897
32
      attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
898
32
      if (auto ParentRule = getParentAttrMatcherRule(MatchRule)) {
899
9
        if (llvm::any_of(StrictSubjectMatchRuleSet,
900
10
                         [ParentRule](const auto &StrictRule) {
901
10
                           return StrictRule.first == *ParentRule &&
902
10
                                  
StrictRule.second5
; // IsEnabled
903
10
                         })) {
904
5
          SubjectMatchRules.push_back(MatchRule);
905
5
          Rules.erase(MatchRule);
906
5
        }
907
9
      }
908
32
    }
909
1.20k
  }
910
911
1.28k
  if (!Rules.empty()) {
912
22
    auto Diagnostic =
913
22
        Diag(PragmaLoc, diag::err_pragma_attribute_invalid_matchers)
914
22
        << Attribute;
915
22
    SmallVector<attr::SubjectMatchRule, 2> ExtraRules;
916
27
    for (const auto &Rule : Rules) {
917
27
      ExtraRules.push_back(attr::SubjectMatchRule(Rule.first));
918
27
      Diagnostic << FixItHint::CreateRemoval(
919
27
          replacementRangeForListElement(*this, Rule.second));
920
27
    }
921
22
    Diagnostic << attrMatcherRuleListToString(ExtraRules);
922
22
  }
923
924
1.28k
  if (PragmaAttributeStack.empty()) {
925
1
    Diag(PragmaLoc, diag::err_pragma_attr_attr_no_push);
926
1
    return;
927
1
  }
928
929
1.28k
  PragmaAttributeStack.back().Entries.push_back(
930
1.28k
      {PragmaLoc, &Attribute, std::move(SubjectMatchRules), /*IsUsed=*/false});
931
1.28k
}
932
933
void Sema::ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
934
1.28k
                                         const IdentifierInfo *Namespace) {
935
1.28k
  PragmaAttributeStack.emplace_back();
936
1.28k
  PragmaAttributeStack.back().Loc = PragmaLoc;
937
1.28k
  PragmaAttributeStack.back().Namespace = Namespace;
938
1.28k
}
939
940
void Sema::ActOnPragmaAttributePop(SourceLocation PragmaLoc,
941
1.27k
                                   const IdentifierInfo *Namespace) {
942
1.27k
  if (PragmaAttributeStack.empty()) {
943
4
    Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
944
4
    return;
945
4
  }
946
947
  // Dig back through the stack trying to find the most recently pushed group
948
  // that in Namespace. Note that this works fine if no namespace is present,
949
  // think of push/pops without namespaces as having an implicit "nullptr"
950
  // namespace.
951
1.27k
  
for (size_t Index = PragmaAttributeStack.size(); 1.27k
Index;) {
952
1.27k
    --Index;
953
1.27k
    if (PragmaAttributeStack[Index].Namespace == Namespace) {
954
1.27k
      for (const PragmaAttributeEntry &Entry :
955
1.27k
           PragmaAttributeStack[Index].Entries) {
956
1.27k
        if (!Entry.IsUsed) {
957
63
          assert(Entry.Attribute && "Expected an attribute");
958
0
          Diag(Entry.Attribute->getLoc(), diag::warn_pragma_attribute_unused)
959
63
              << *Entry.Attribute;
960
63
          Diag(PragmaLoc, diag::note_pragma_attribute_region_ends_here);
961
63
        }
962
1.27k
      }
963
1.27k
      PragmaAttributeStack.erase(PragmaAttributeStack.begin() + Index);
964
1.27k
      return;
965
1.27k
    }
966
1.27k
  }
967
968
2
  if (Namespace)
969
1
    Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch)
970
1
        << 0 << Namespace->getName();
971
1
  else
972
1
    Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
973
2
}
974
975
138M
void Sema::AddPragmaAttributes(Scope *S, Decl *D) {
976
138M
  if (PragmaAttributeStack.empty())
977
138M
    return;
978
80.6k
  
for (auto &Group : PragmaAttributeStack)80.6k
{
979
80.6k
    for (auto &Entry : Group.Entries) {
980
80.6k
      ParsedAttr *Attribute = Entry.Attribute;
981
80.6k
      assert(Attribute && "Expected an attribute");
982
0
      assert(Attribute->isPragmaClangAttribute() &&
983
80.6k
             "expected #pragma clang attribute");
984
985
      // Ensure that the attribute can be applied to the given declaration.
986
0
      bool Applies = false;
987
747k
      for (const auto &Rule : Entry.MatchRules) {
988
747k
        if (Attribute->appliesToDecl(D, Rule)) {
989
80.0k
          Applies = true;
990
80.0k
          break;
991
80.0k
        }
992
747k
      }
993
80.6k
      if (!Applies)
994
596
        continue;
995
80.0k
      Entry.IsUsed = true;
996
80.0k
      PragmaAttributeCurrentTargetDecl = D;
997
80.0k
      ParsedAttributesView Attrs;
998
80.0k
      Attrs.addAtEnd(Attribute);
999
80.0k
      ProcessDeclAttributeList(S, D, Attrs);
1000
80.0k
      PragmaAttributeCurrentTargetDecl = nullptr;
1001
80.0k
    }
1002
80.6k
  }
1003
80.6k
}
1004
1005
21
void Sema::PrintPragmaAttributeInstantiationPoint() {
1006
21
  assert(PragmaAttributeCurrentTargetDecl && "Expected an active declaration");
1007
0
  Diags.Report(PragmaAttributeCurrentTargetDecl->getBeginLoc(),
1008
21
               diag::note_pragma_attribute_applied_decl_here);
1009
21
}
1010
1011
93.0k
void Sema::DiagnoseUnterminatedPragmaAttribute() {
1012
93.0k
  if (PragmaAttributeStack.empty())
1013
93.0k
    return;
1014
3
  Diag(PragmaAttributeStack.back().Loc, diag::err_pragma_attribute_no_pop_eof);
1015
3
}
1016
1017
31
void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {
1018
31
  if(On)
1019
14
    OptimizeOffPragmaLocation = SourceLocation();
1020
17
  else
1021
17
    OptimizeOffPragmaLocation = PragmaLoc;
1022
31
}
1023
1024
3.61M
void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
1025
  // In the future, check other pragmas if they're implemented (e.g. pragma
1026
  // optimize 0 will probably map to this functionality too).
1027
3.61M
  if(OptimizeOffPragmaLocation.isValid())
1028
29
    AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation);
1029
3.61M
}
1030
1031
void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD,
1032
29
                                            SourceLocation Loc) {
1033
  // Don't add a conflicting attribute. No diagnostic is needed.
1034
29
  if (FD->hasAttr<MinSizeAttr>() || 
FD->hasAttr<AlwaysInlineAttr>()26
)
1035
6
    return;
1036
1037
  // Add attributes only if required. Optnone requires noinline as well, but if
1038
  // either is already present then don't bother adding them.
1039
23
  if (!FD->hasAttr<OptimizeNoneAttr>())
1040
23
    FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
1041
23
  if (!FD->hasAttr<NoInlineAttr>())
1042
23
    FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
1043
23
}
1044
1045
typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
1046
enum : unsigned { NoVisibility = ~0U };
1047
1048
7.04M
void Sema::AddPushedVisibilityAttribute(Decl *D) {
1049
7.04M
  if (!VisContext)
1050
7.04M
    return;
1051
1052
438
  NamedDecl *ND = dyn_cast<NamedDecl>(D);
1053
438
  if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue))
1054
96
    return;
1055
1056
342
  VisStack *Stack = static_cast<VisStack*>(VisContext);
1057
342
  unsigned rawType = Stack->back().first;
1058
342
  if (rawType == NoVisibility) 
return30
;
1059
1060
312
  VisibilityAttr::VisibilityType type
1061
312
    = (VisibilityAttr::VisibilityType) rawType;
1062
312
  SourceLocation loc = Stack->back().second;
1063
1064
312
  D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
1065
312
}
1066
1067
/// FreeVisContext - Deallocate and null out VisContext.
1068
76
void Sema::FreeVisContext() {
1069
76
  delete static_cast<VisStack*>(VisContext);
1070
76
  VisContext = nullptr;
1071
76
}
1072
1073
80
static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
1074
  // Put visibility on stack.
1075
80
  if (!S.VisContext)
1076
76
    S.VisContext = new VisStack;
1077
1078
80
  VisStack *Stack = static_cast<VisStack*>(S.VisContext);
1079
80
  Stack->push_back(std::make_pair(type, loc));
1080
80
}
1081
1082
void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
1083
115
                                 SourceLocation PragmaLoc) {
1084
115
  if (VisType) {
1085
    // Compute visibility to use.
1086
59
    VisibilityAttr::VisibilityType T;
1087
59
    if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
1088
1
      Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
1089
1
      return;
1090
1
    }
1091
58
    PushPragmaVisibility(*this, T, PragmaLoc);
1092
58
  } else {
1093
56
    PopPragmaVisibility(false, PragmaLoc);
1094
56
  }
1095
115
}
1096
1097
void Sema::ActOnPragmaFPContract(SourceLocation Loc,
1098
76
                                 LangOptions::FPModeKind FPC) {
1099
76
  FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1100
76
  switch (FPC) {
1101
56
  case LangOptions::FPM_On:
1102
56
    NewFPFeatures.setAllowFPContractWithinStatement();
1103
56
    break;
1104
10
  case LangOptions::FPM_Fast:
1105
10
    NewFPFeatures.setAllowFPContractAcrossStatement();
1106
10
    break;
1107
10
  case LangOptions::FPM_Off:
1108
10
    NewFPFeatures.setDisallowFPContract();
1109
10
    break;
1110
0
  case LangOptions::FPM_FastHonorPragmas:
1111
0
    llvm_unreachable("Should not happen");
1112
76
  }
1113
76
  FpPragmaStack.Act(Loc, Sema::PSK_Set, StringRef(), NewFPFeatures);
1114
76
  CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1115
76
}
1116
1117
18
void Sema::ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled) {
1118
18
  FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1119
18
  NewFPFeatures.setAllowFPReassociateOverride(IsEnabled);
1120
18
  FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1121
18
  CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1122
18
}
1123
1124
34
void Sema::setRoundingMode(SourceLocation Loc, llvm::RoundingMode FPR) {
1125
  // C2x: 7.6.2p3  If the FE_DYNAMIC mode is specified and FENV_ACCESS is "off",
1126
  // the translator may assume that the default rounding mode is in effect.
1127
34
  if (FPR == llvm::RoundingMode::Dynamic &&
1128
34
      
!CurFPFeatures.getAllowFEnvAccess()2
&&
1129
34
      
CurFPFeatures.getFPExceptionMode() == LangOptions::FPE_Ignore2
)
1130
2
    FPR = llvm::RoundingMode::NearestTiesToEven;
1131
1132
34
  FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1133
34
  NewFPFeatures.setRoundingModeOverride(FPR);
1134
34
  FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1135
34
  CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1136
34
}
1137
1138
void Sema::setExceptionMode(SourceLocation Loc,
1139
3
                            LangOptions::FPExceptionModeKind FPE) {
1140
3
  FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1141
3
  NewFPFeatures.setFPExceptionModeOverride(FPE);
1142
3
  FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1143
3
  CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1144
3
}
1145
1146
18
void Sema::ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled) {
1147
18
  FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1148
18
  auto LO = getLangOpts();
1149
18
  if (IsEnabled) {
1150
    // Verify Microsoft restriction:
1151
    // You can't enable fenv_access unless precise semantics are enabled.
1152
    // Precise semantics can be enabled either by the float_control
1153
    // pragma, or by using the /fp:precise or /fp:strict compiler options
1154
10
    if (!isPreciseFPEnabled())
1155
0
      Diag(Loc, diag::err_pragma_fenv_requires_precise);
1156
10
    NewFPFeatures.setAllowFEnvAccessOverride(true);
1157
    // Enabling FENV access sets the RoundingMode to Dynamic.
1158
    // and ExceptionBehavior to Strict
1159
10
    NewFPFeatures.setRoundingModeOverride(llvm::RoundingMode::Dynamic);
1160
10
    NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Strict);
1161
10
  } else {
1162
8
    NewFPFeatures.setAllowFEnvAccessOverride(false);
1163
8
  }
1164
18
  FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1165
18
  CurFPFeatures = NewFPFeatures.applyOverrides(LO);
1166
18
}
1167
1168
void Sema::ActOnPragmaFPExceptions(SourceLocation Loc,
1169
3
                                   LangOptions::FPExceptionModeKind FPE) {
1170
3
  setExceptionMode(Loc, FPE);
1171
3
}
1172
1173
void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
1174
22
                                       SourceLocation Loc) {
1175
  // Visibility calculations will consider the namespace's visibility.
1176
  // Here we just want to note that we're in a visibility context
1177
  // which overrides any enclosing #pragma context, but doesn't itself
1178
  // contribute visibility.
1179
22
  PushPragmaVisibility(*this, NoVisibility, Loc);
1180
22
}
1181
1182
78
void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
1183
78
  if (!VisContext) {
1184
2
    Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
1185
2
    return;
1186
2
  }
1187
1188
  // Pop visibility from stack
1189
76
  VisStack *Stack = static_cast<VisStack*>(VisContext);
1190
1191
76
  const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
1192
76
  bool StartsWithPragma = Back->first != NoVisibility;
1193
76
  if (StartsWithPragma && 
IsNamespaceEnd54
) {
1194
1
    Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
1195
1
    Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
1196
1197
    // For better error recovery, eat all pushes inside the namespace.
1198
1
    do {
1199
1
      Stack->pop_back();
1200
1
      Back = &Stack->back();
1201
1
      StartsWithPragma = Back->first != NoVisibility;
1202
1
    } while (StartsWithPragma);
1203
75
  } else if (!StartsWithPragma && 
!IsNamespaceEnd22
) {
1204
1
    Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
1205
1
    Diag(Back->second, diag::note_surrounding_namespace_starts_here);
1206
1
    return;
1207
1
  }
1208
1209
75
  Stack->pop_back();
1210
  // To simplify the implementation, never keep around an empty stack.
1211
75
  if (Stack->empty())
1212
72
    FreeVisContext();
1213
75
}
1214
1215
template <typename Ty>
1216
static bool checkCommonAttributeFeatures(Sema& S, const Ty *Node,
1217
108M
                                         const ParsedAttr& A) {
1218
  // Several attributes carry different semantics than the parsing requires, so
1219
  // those are opted out of the common argument checks.
1220
  //
1221
  // We also bail on unknown and ignored attributes because those are handled
1222
  // as part of the target-specific handling logic.
1223
108M
  if (A.getKind() == ParsedAttr::UnknownAttribute)
1224
0
    return false;
1225
  // Check whether the attribute requires specific language extensions to be
1226
  // enabled.
1227
108M
  if (!A.diagnoseLangOpts(S))
1228
34
    return true;
1229
  // Check whether the attribute appertains to the given subject.
1230
108M
  if (!A.diagnoseAppertainsTo(S, Node))
1231
1.02k
    return true;
1232
  // Check whether the attribute is mutually exclusive with other attributes
1233
  // that have already been applied to the declaration.
1234
108M
  if (!A.diagnoseMutualExclusion(S, Node))
1235
62
    return true;
1236
  // Check whether the attribute exists in the target architecture.
1237
108M
  if (S.CheckAttrTarget(A))
1238
0
    return true;
1239
1240
108M
  if (A.hasCustomParsing())
1241
5.94M
    return false;
1242
1243
102M
  if (A.getMinArgs() == A.getMaxArgs()) {
1244
    // If there are no optional arguments, then checking for the argument count
1245
    // is trivial.
1246
101M
    if (!A.checkExactlyNumArgs(S, A.getMinArgs()))
1247
243
      return true;
1248
101M
  } else {
1249
    // There are optional arguments, so checking is slightly more involved.
1250
189k
    if (A.getMinArgs() && 
!A.checkAtLeastNumArgs(S, A.getMinArgs())5.78k
)
1251
36
      return true;
1252
189k
    else if (!A.hasVariadicArg() && 
A.getMaxArgs()107k
&&
1253
189k
             
!A.checkAtMostNumArgs(S, A.getMaxArgs())107k
)
1254
13
      return true;
1255
189k
  }
1256
1257
102M
  return false;
1258
102M
}
SemaAttr.cpp:bool checkCommonAttributeFeatures<clang::Decl>(clang::Sema&, clang::Decl const*, clang::ParsedAttr const&)
Line
Count
Source
1217
108M
                                         const ParsedAttr& A) {
1218
  // Several attributes carry different semantics than the parsing requires, so
1219
  // those are opted out of the common argument checks.
1220
  //
1221
  // We also bail on unknown and ignored attributes because those are handled
1222
  // as part of the target-specific handling logic.
1223
108M
  if (A.getKind() == ParsedAttr::UnknownAttribute)
1224
0
    return false;
1225
  // Check whether the attribute requires specific language extensions to be
1226
  // enabled.
1227
108M
  if (!A.diagnoseLangOpts(S))
1228
34
    return true;
1229
  // Check whether the attribute appertains to the given subject.
1230
108M
  if (!A.diagnoseAppertainsTo(S, Node))
1231
973
    return true;
1232
  // Check whether the attribute is mutually exclusive with other attributes
1233
  // that have already been applied to the declaration.
1234
108M
  if (!A.diagnoseMutualExclusion(S, Node))
1235
62
    return true;
1236
  // Check whether the attribute exists in the target architecture.
1237
108M
  if (S.CheckAttrTarget(A))
1238
0
    return true;
1239
1240
108M
  if (A.hasCustomParsing())
1241
5.94M
    return false;
1242
1243
102M
  if (A.getMinArgs() == A.getMaxArgs()) {
1244
    // If there are no optional arguments, then checking for the argument count
1245
    // is trivial.
1246
101M
    if (!A.checkExactlyNumArgs(S, A.getMinArgs()))
1247
240
      return true;
1248
101M
  } else {
1249
    // There are optional arguments, so checking is slightly more involved.
1250
189k
    if (A.getMinArgs() && 
!A.checkAtLeastNumArgs(S, A.getMinArgs())5.78k
)
1251
36
      return true;
1252
189k
    else if (!A.hasVariadicArg() && 
A.getMaxArgs()107k
&&
1253
189k
             
!A.checkAtMostNumArgs(S, A.getMaxArgs())107k
)
1254
12
      return true;
1255
189k
  }
1256
1257
102M
  return false;
1258
102M
}
SemaAttr.cpp:bool checkCommonAttributeFeatures<clang::Stmt>(clang::Sema&, clang::Stmt const*, clang::ParsedAttr const&)
Line
Count
Source
1217
1.69k
                                         const ParsedAttr& A) {
1218
  // Several attributes carry different semantics than the parsing requires, so
1219
  // those are opted out of the common argument checks.
1220
  //
1221
  // We also bail on unknown and ignored attributes because those are handled
1222
  // as part of the target-specific handling logic.
1223
1.69k
  if (A.getKind() == ParsedAttr::UnknownAttribute)
1224
0
    return false;
1225
  // Check whether the attribute requires specific language extensions to be
1226
  // enabled.
1227
1.69k
  if (!A.diagnoseLangOpts(S))
1228
0
    return true;
1229
  // Check whether the attribute appertains to the given subject.
1230
1.69k
  if (!A.diagnoseAppertainsTo(S, Node))
1231
48
    return true;
1232
  // Check whether the attribute is mutually exclusive with other attributes
1233
  // that have already been applied to the declaration.
1234
1.64k
  if (!A.diagnoseMutualExclusion(S, Node))
1235
0
    return true;
1236
  // Check whether the attribute exists in the target architecture.
1237
1.64k
  if (S.CheckAttrTarget(A))
1238
0
    return true;
1239
1240
1.64k
  if (A.hasCustomParsing())
1241
352
    return false;
1242
1243
1.29k
  if (A.getMinArgs() == A.getMaxArgs()) {
1244
    // If there are no optional arguments, then checking for the argument count
1245
    // is trivial.
1246
1.26k
    if (!A.checkExactlyNumArgs(S, A.getMinArgs()))
1247
3
      return true;
1248
1.26k
  } else {
1249
    // There are optional arguments, so checking is slightly more involved.
1250
29
    if (A.getMinArgs() && 
!A.checkAtLeastNumArgs(S, A.getMinArgs())0
)
1251
0
      return true;
1252
29
    else if (!A.hasVariadicArg() && 
A.getMaxArgs()24
&&
1253
29
             
!A.checkAtMostNumArgs(S, A.getMaxArgs())24
)
1254
1
      return true;
1255
29
  }
1256
1257
1.28k
  return false;
1258
1.29k
}
1259
1260
108M
bool Sema::checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A) {
1261
108M
  return ::checkCommonAttributeFeatures(*this, D, A);
1262
108M
}
1263
1.69k
bool Sema::checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A) {
1264
1.69k
  return ::checkCommonAttributeFeatures(*this, S, A);
1265
1.69k
}