Coverage Report

Created: 2020-09-22 08:39

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/utils/TableGen/ClangAttrEmitter.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=//
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
// These tablegen backends emit Clang attribute processing code
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "TableGenBackends.h"
14
#include "ASTTableGen.h"
15
16
#include "llvm/ADT/ArrayRef.h"
17
#include "llvm/ADT/DenseMap.h"
18
#include "llvm/ADT/DenseSet.h"
19
#include "llvm/ADT/STLExtras.h"
20
#include "llvm/ADT/SmallString.h"
21
#include "llvm/ADT/StringExtras.h"
22
#include "llvm/ADT/StringRef.h"
23
#include "llvm/ADT/StringSet.h"
24
#include "llvm/ADT/StringSwitch.h"
25
#include "llvm/ADT/iterator_range.h"
26
#include "llvm/Support/ErrorHandling.h"
27
#include "llvm/Support/raw_ostream.h"
28
#include "llvm/TableGen/Error.h"
29
#include "llvm/TableGen/Record.h"
30
#include "llvm/TableGen/StringMatcher.h"
31
#include "llvm/TableGen/TableGenBackend.h"
32
#include <algorithm>
33
#include <cassert>
34
#include <cctype>
35
#include <cstddef>
36
#include <cstdint>
37
#include <map>
38
#include <memory>
39
#include <set>
40
#include <sstream>
41
#include <string>
42
#include <utility>
43
#include <vector>
44
45
using namespace llvm;
46
47
namespace {
48
49
class FlattenedSpelling {
50
  std::string V, N, NS;
51
  bool K = false;
52
53
public:
54
  FlattenedSpelling(const std::string &Variety, const std::string &Name,
55
                    const std::string &Namespace, bool KnownToGCC) :
56
654
    V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
57
  explicit FlattenedSpelling(const Record &Spelling)
58
      : V(std::string(Spelling.getValueAsString("Variety"))),
59
131
        N(std::string(Spelling.getValueAsString("Name"))) {
60
131
    assert(V != "GCC" && V != "Clang" &&
61
131
           "Given a GCC spelling, which means this hasn't been flattened!");
62
131
    if (V == "CXX11" || 
V == "C2x"117
||
V == "Pragma"111
)
63
25
      NS = std::string(Spelling.getValueAsString("Namespace"));
64
131
  }
65
66
361
  const std::string &variety() const { return V; }
67
0
  const std::string &name() const { return N; }
68
0
  const std::string &nameSpace() const { return NS; }
69
0
  bool knownToGCC() const { return K; }
70
};
71
72
} // end anonymous namespace
73
74
static std::vector<FlattenedSpelling>
75
279
GetFlattenedSpellings(const Record &Attr) {
76
279
  std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
77
279
  std::vector<FlattenedSpelling> Ret;
78
79
358
  for (const auto &Spelling : Spellings) {
80
358
    StringRef Variety = Spelling->getValueAsString("Variety");
81
358
    StringRef Name = Spelling->getValueAsString("Name");
82
358
    if (Variety == "GCC") {
83
82
      Ret.emplace_back("GNU", std::string(Name), "", true);
84
82
      Ret.emplace_back("CXX11", std::string(Name), "gnu", true);
85
82
      if (Spelling->getValueAsBit("AllowInC"))
86
80
        Ret.emplace_back("C2x", std::string(Name), "gnu", true);
87
276
    } else if (Variety == "Clang") {
88
145
      Ret.emplace_back("GNU", std::string(Name), "", false);
89
145
      Ret.emplace_back("CXX11", std::string(Name), "clang", false);
90
145
      if (Spelling->getValueAsBit("AllowInC"))
91
120
        Ret.emplace_back("C2x", std::string(Name), "clang", false);
92
145
    } else
93
131
      Ret.push_back(FlattenedSpelling(*Spelling));
94
358
  }
95
96
279
  return Ret;
97
279
}
98
99
0
static std::string ReadPCHRecord(StringRef type) {
100
0
  return StringSwitch<std::string>(type)
101
0
      .EndsWith("Decl *", "Record.GetLocalDeclAs<" +
102
0
                              std::string(type.data(), 0, type.size() - 1) +
103
0
                              ">(Record.readInt())")
104
0
      .Case("TypeSourceInfo *", "Record.readTypeSourceInfo()")
105
0
      .Case("Expr *", "Record.readExpr()")
106
0
      .Case("IdentifierInfo *", "Record.readIdentifier()")
107
0
      .Case("StringRef", "Record.readString()")
108
0
      .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
109
0
      .Case("OMPTraitInfo *", "Record.readOMPTraitInfo()")
110
0
      .Default("Record.readInt()");
111
0
}
112
113
// Get a type that is suitable for storing an object of the specified type.
114
0
static StringRef getStorageType(StringRef type) {
115
0
  return StringSwitch<StringRef>(type)
116
0
    .Case("StringRef", "std::string")
117
0
    .Default(type);
118
0
}
119
120
// Assumes that the way to get the value is SA->getname()
121
0
static std::string WritePCHRecord(StringRef type, StringRef name) {
122
0
  return "Record." +
123
0
         StringSwitch<std::string>(type)
124
0
             .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
125
0
             .Case("TypeSourceInfo *",
126
0
                   "AddTypeSourceInfo(" + std::string(name) + ");\n")
127
0
             .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
128
0
             .Case("IdentifierInfo *",
129
0
                   "AddIdentifierRef(" + std::string(name) + ");\n")
130
0
             .Case("StringRef", "AddString(" + std::string(name) + ");\n")
131
0
             .Case("ParamIdx",
132
0
                   "push_back(" + std::string(name) + ".serialize());\n")
133
0
             .Case("OMPTraitInfo *",
134
0
                   "writeOMPTraitInfo(" + std::string(name) + ");\n")
135
0
             .Default("push_back(" + std::string(name) + ");\n");
136
0
}
137
138
// Normalize attribute name by removing leading and trailing
139
// underscores. For example, __foo, foo__, __foo__ would
140
// become foo.
141
300
static StringRef NormalizeAttrName(StringRef AttrName) {
142
300
  AttrName.consume_front("__");
143
300
  AttrName.consume_back("__");
144
300
  return AttrName;
145
300
}
146
147
// Normalize the name by removing any and all leading and trailing underscores.
148
// This is different from NormalizeAttrName in that it also handles names like
149
// _pascal and __pascal.
150
0
static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
151
0
  return Name.trim("_");
152
0
}
153
154
// Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
155
// removing "__" if it appears at the beginning and end of the attribute's name.
156
0
static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
157
0
  if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
158
0
    AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
159
0
  }
160
161
0
  return AttrSpelling;
162
0
}
163
164
typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
165
166
static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
167
1
                                       ParsedAttrMap *Dupes = nullptr) {
168
1
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
169
1
  std::set<std::string> Seen;
170
1
  ParsedAttrMap R;
171
330
  for (const auto *Attr : Attrs) {
172
330
    if (Attr->getValueAsBit("SemaHandler")) {
173
306
      std::string AN;
174
306
      if (Attr->isSubClassOf("TargetSpecificAttr") &&
175
34
          !Attr->isValueUnset("ParseKind")) {
176
6
        AN = std::string(Attr->getValueAsString("ParseKind"));
177
178
        // If this attribute has already been handled, it does not need to be
179
        // handled again.
180
6
        if (Seen.find(AN) != Seen.end()) {
181
5
          if (Dupes)
182
0
            Dupes->push_back(std::make_pair(AN, Attr));
183
5
          continue;
184
5
        }
185
1
        Seen.insert(AN);
186
1
      } else
187
300
        AN = NormalizeAttrName(Attr->getName()).str();
188
189
301
      R.push_back(std::make_pair(AN, Attr));
190
301
    }
191
330
  }
192
1
  return R;
193
1
}
194
195
namespace {
196
197
  class Argument {
198
    std::string lowerName, upperName;
199
    StringRef attrName;
200
    bool isOpt;
201
    bool Fake;
202
203
  public:
204
    Argument(const Record &Arg, StringRef Attr)
205
        : lowerName(std::string(Arg.getValueAsString("Name"))),
206
0
          upperName(lowerName), attrName(Attr), isOpt(false), Fake(false) {
207
0
      if (!lowerName.empty()) {
208
0
        lowerName[0] = std::tolower(lowerName[0]);
209
0
        upperName[0] = std::toupper(upperName[0]);
210
0
      }
211
      // Work around MinGW's macro definition of 'interface' to 'struct'. We
212
      // have an attribute argument called 'Interface', so only the lower case
213
      // name conflicts with the macro definition.
214
0
      if (lowerName == "interface")
215
0
        lowerName = "interface_";
216
0
    }
217
0
    virtual ~Argument() = default;
218
219
0
    StringRef getLowerName() const { return lowerName; }
220
0
    StringRef getUpperName() const { return upperName; }
221
0
    StringRef getAttrName() const { return attrName; }
222
223
0
    bool isOptional() const { return isOpt; }
224
0
    void setOptional(bool set) { isOpt = set; }
225
226
0
    bool isFake() const { return Fake; }
227
0
    void setFake(bool fake) { Fake = fake; }
228
229
    // These functions print the argument contents formatted in different ways.
230
    virtual void writeAccessors(raw_ostream &OS) const = 0;
231
0
    virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
232
0
    virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
233
    virtual void writeCloneArgs(raw_ostream &OS) const = 0;
234
    virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
235
0
    virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
236
0
    virtual void writeCtorBody(raw_ostream &OS) const {}
237
    virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
238
    virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
239
    virtual void writeCtorParameters(raw_ostream &OS) const = 0;
240
    virtual void writeDeclarations(raw_ostream &OS) const = 0;
241
    virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
242
    virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
243
    virtual void writePCHWrite(raw_ostream &OS) const = 0;
244
0
    virtual std::string getIsOmitted() const { return "false"; }
245
    virtual void writeValue(raw_ostream &OS) const = 0;
246
    virtual void writeDump(raw_ostream &OS) const = 0;
247
0
    virtual void writeDumpChildren(raw_ostream &OS) const {}
248
0
    virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
249
250
0
    virtual bool isEnumArg() const { return false; }
251
0
    virtual bool isVariadicEnumArg() const { return false; }
252
0
    virtual bool isVariadic() const { return false; }
253
254
0
    virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
255
0
      OS << getUpperName();
256
0
    }
257
  };
258
259
  class SimpleArgument : public Argument {
260
    std::string type;
261
262
  public:
263
    SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
264
0
        : Argument(Arg, Attr), type(std::move(T)) {}
265
266
0
    std::string getType() const { return type; }
267
268
0
    void writeAccessors(raw_ostream &OS) const override {
269
0
      OS << "  " << type << " get" << getUpperName() << "() const {\n";
270
0
      OS << "    return " << getLowerName() << ";\n";
271
0
      OS << "  }";
272
0
    }
273
274
0
    void writeCloneArgs(raw_ostream &OS) const override {
275
0
      OS << getLowerName();
276
0
    }
277
278
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
279
0
      OS << "A->get" << getUpperName() << "()";
280
0
    }
281
282
0
    void writeCtorInitializers(raw_ostream &OS) const override {
283
0
      OS << getLowerName() << "(" << getUpperName() << ")";
284
0
    }
285
286
0
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
287
0
      OS << getLowerName() << "()";
288
0
    }
289
290
0
    void writeCtorParameters(raw_ostream &OS) const override {
291
0
      OS << type << " " << getUpperName();
292
0
    }
293
294
0
    void writeDeclarations(raw_ostream &OS) const override {
295
0
      OS << type << " " << getLowerName() << ";";
296
0
    }
297
298
0
    void writePCHReadDecls(raw_ostream &OS) const override {
299
0
      std::string read = ReadPCHRecord(type);
300
0
      OS << "    " << type << " " << getLowerName() << " = " << read << ";\n";
301
0
    }
302
303
0
    void writePCHReadArgs(raw_ostream &OS) const override {
304
0
      OS << getLowerName();
305
0
    }
306
307
0
    void writePCHWrite(raw_ostream &OS) const override {
308
0
      OS << "    "
309
0
         << WritePCHRecord(type,
310
0
                           "SA->get" + std::string(getUpperName()) + "()");
311
0
    }
312
313
0
    std::string getIsOmitted() const override {
314
0
      if (type == "IdentifierInfo *")
315
0
        return "!get" + getUpperName().str() + "()";
316
0
      if (type == "TypeSourceInfo *")
317
0
        return "!get" + getUpperName().str() + "Loc()";
318
0
      if (type == "ParamIdx")
319
0
        return "!get" + getUpperName().str() + "().isValid()";
320
0
      return "false";
321
0
    }
322
323
0
    void writeValue(raw_ostream &OS) const override {
324
0
      if (type == "FunctionDecl *")
325
0
        OS << "\" << get" << getUpperName()
326
0
           << "()->getNameInfo().getAsString() << \"";
327
0
      else if (type == "IdentifierInfo *")
328
        // Some non-optional (comma required) identifier arguments can be the
329
        // empty string but are then recorded as a nullptr.
330
0
        OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
331
0
           << "()->getName() : \"\") << \"";
332
0
      else if (type == "VarDecl *")
333
0
        OS << "\" << get" << getUpperName() << "()->getName() << \"";
334
0
      else if (type == "TypeSourceInfo *")
335
0
        OS << "\" << get" << getUpperName() << "().getAsString() << \"";
336
0
      else if (type == "ParamIdx")
337
0
        OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
338
0
      else
339
0
        OS << "\" << get" << getUpperName() << "() << \"";
340
0
    }
341
342
0
    void writeDump(raw_ostream &OS) const override {
343
0
      if (StringRef(type).endswith("Decl *")) {
344
0
        OS << "    OS << \" \";\n";
345
0
        OS << "    dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
346
0
      } else if (type == "IdentifierInfo *") {
347
        // Some non-optional (comma required) identifier arguments can be the
348
        // empty string but are then recorded as a nullptr.
349
0
        OS << "    if (SA->get" << getUpperName() << "())\n"
350
0
           << "      OS << \" \" << SA->get" << getUpperName()
351
0
           << "()->getName();\n";
352
0
      } else if (type == "TypeSourceInfo *") {
353
0
        if (isOptional())
354
0
          OS << "    if (SA->get" << getUpperName() << "Loc())";
355
0
        OS << "    OS << \" \" << SA->get" << getUpperName()
356
0
           << "().getAsString();\n";
357
0
      } else if (type == "bool") {
358
0
        OS << "    if (SA->get" << getUpperName() << "()) OS << \" "
359
0
           << getUpperName() << "\";\n";
360
0
      } else if (type == "int" || type == "unsigned") {
361
0
        OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
362
0
      } else if (type == "ParamIdx") {
363
0
        if (isOptional())
364
0
          OS << "    if (SA->get" << getUpperName() << "().isValid())\n  ";
365
0
        OS << "    OS << \" \" << SA->get" << getUpperName()
366
0
           << "().getSourceIndex();\n";
367
0
      } else if (type == "OMPTraitInfo *") {
368
0
        OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
369
0
      } else {
370
0
        llvm_unreachable("Unknown SimpleArgument type!");
371
0
      }
372
0
    }
373
  };
374
375
  class DefaultSimpleArgument : public SimpleArgument {
376
    int64_t Default;
377
378
  public:
379
    DefaultSimpleArgument(const Record &Arg, StringRef Attr,
380
                          std::string T, int64_t Default)
381
0
      : SimpleArgument(Arg, Attr, T), Default(Default) {}
382
383
0
    void writeAccessors(raw_ostream &OS) const override {
384
0
      SimpleArgument::writeAccessors(OS);
385
386
0
      OS << "\n\n  static const " << getType() << " Default" << getUpperName()
387
0
         << " = ";
388
0
      if (getType() == "bool")
389
0
        OS << (Default != 0 ? "true" : "false");
390
0
      else
391
0
        OS << Default;
392
0
      OS << ";";
393
0
    }
394
  };
395
396
  class StringArgument : public Argument {
397
  public:
398
    StringArgument(const Record &Arg, StringRef Attr)
399
      : Argument(Arg, Attr)
400
0
    {}
401
402
0
    void writeAccessors(raw_ostream &OS) const override {
403
0
      OS << "  llvm::StringRef get" << getUpperName() << "() const {\n";
404
0
      OS << "    return llvm::StringRef(" << getLowerName() << ", "
405
0
         << getLowerName() << "Length);\n";
406
0
      OS << "  }\n";
407
0
      OS << "  unsigned get" << getUpperName() << "Length() const {\n";
408
0
      OS << "    return " << getLowerName() << "Length;\n";
409
0
      OS << "  }\n";
410
0
      OS << "  void set" << getUpperName()
411
0
         << "(ASTContext &C, llvm::StringRef S) {\n";
412
0
      OS << "    " << getLowerName() << "Length = S.size();\n";
413
0
      OS << "    this->" << getLowerName() << " = new (C, 1) char ["
414
0
         << getLowerName() << "Length];\n";
415
0
      OS << "    if (!S.empty())\n";
416
0
      OS << "      std::memcpy(this->" << getLowerName() << ", S.data(), "
417
0
         << getLowerName() << "Length);\n";
418
0
      OS << "  }";
419
0
    }
420
421
0
    void writeCloneArgs(raw_ostream &OS) const override {
422
0
      OS << "get" << getUpperName() << "()";
423
0
    }
424
425
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
426
0
      OS << "A->get" << getUpperName() << "()";
427
0
    }
428
429
0
    void writeCtorBody(raw_ostream &OS) const override {
430
0
      OS << "    if (!" << getUpperName() << ".empty())\n";
431
0
      OS << "      std::memcpy(" << getLowerName() << ", " << getUpperName()
432
0
         << ".data(), " << getLowerName() << "Length);\n";
433
0
    }
434
435
0
    void writeCtorInitializers(raw_ostream &OS) const override {
436
0
      OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
437
0
         << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
438
0
         << "Length])";
439
0
    }
440
441
0
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
442
0
      OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
443
0
    }
444
445
0
    void writeCtorParameters(raw_ostream &OS) const override {
446
0
      OS << "llvm::StringRef " << getUpperName();
447
0
    }
448
449
0
    void writeDeclarations(raw_ostream &OS) const override {
450
0
      OS << "unsigned " << getLowerName() << "Length;\n";
451
0
      OS << "char *" << getLowerName() << ";";
452
0
    }
453
454
0
    void writePCHReadDecls(raw_ostream &OS) const override {
455
0
      OS << "    std::string " << getLowerName()
456
0
         << "= Record.readString();\n";
457
0
    }
458
459
0
    void writePCHReadArgs(raw_ostream &OS) const override {
460
0
      OS << getLowerName();
461
0
    }
462
463
0
    void writePCHWrite(raw_ostream &OS) const override {
464
0
      OS << "    Record.AddString(SA->get" << getUpperName() << "());\n";
465
0
    }
466
467
0
    void writeValue(raw_ostream &OS) const override {
468
0
      OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
469
0
    }
470
471
0
    void writeDump(raw_ostream &OS) const override {
472
0
      OS << "    OS << \" \\\"\" << SA->get" << getUpperName()
473
0
         << "() << \"\\\"\";\n";
474
0
    }
475
  };
476
477
  class AlignedArgument : public Argument {
478
  public:
479
    AlignedArgument(const Record &Arg, StringRef Attr)
480
      : Argument(Arg, Attr)
481
0
    {}
482
483
0
    void writeAccessors(raw_ostream &OS) const override {
484
0
      OS << "  bool is" << getUpperName() << "Dependent() const;\n";
485
0
      OS << "  bool is" << getUpperName() << "ErrorDependent() const;\n";
486
487
0
      OS << "  unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
488
489
0
      OS << "  bool is" << getUpperName() << "Expr() const {\n";
490
0
      OS << "    return is" << getLowerName() << "Expr;\n";
491
0
      OS << "  }\n";
492
493
0
      OS << "  Expr *get" << getUpperName() << "Expr() const {\n";
494
0
      OS << "    assert(is" << getLowerName() << "Expr);\n";
495
0
      OS << "    return " << getLowerName() << "Expr;\n";
496
0
      OS << "  }\n";
497
498
0
      OS << "  TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
499
0
      OS << "    assert(!is" << getLowerName() << "Expr);\n";
500
0
      OS << "    return " << getLowerName() << "Type;\n";
501
0
      OS << "  }";
502
0
    }
503
504
0
    void writeAccessorDefinitions(raw_ostream &OS) const override {
505
0
      OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
506
0
         << "Dependent() const {\n";
507
0
      OS << "  if (is" << getLowerName() << "Expr)\n";
508
0
      OS << "    return " << getLowerName() << "Expr && (" << getLowerName()
509
0
         << "Expr->isValueDependent() || " << getLowerName()
510
0
         << "Expr->isTypeDependent());\n";
511
0
      OS << "  else\n";
512
0
      OS << "    return " << getLowerName()
513
0
         << "Type->getType()->isDependentType();\n";
514
0
      OS << "}\n";
515
516
0
      OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
517
0
         << "ErrorDependent() const {\n";
518
0
      OS << "  if (is" << getLowerName() << "Expr)\n";
519
0
      OS << "    return " << getLowerName() << "Expr && " << getLowerName()
520
0
         << "Expr->containsErrors();\n";
521
0
      OS << "  return " << getLowerName()
522
0
         << "Type->getType()->containsErrors();\n";
523
0
      OS << "}\n";
524
525
      // FIXME: Do not do the calculation here
526
      // FIXME: Handle types correctly
527
      // A null pointer means maximum alignment
528
0
      OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
529
0
         << "(ASTContext &Ctx) const {\n";
530
0
      OS << "  assert(!is" << getUpperName() << "Dependent());\n";
531
0
      OS << "  if (is" << getLowerName() << "Expr)\n";
532
0
      OS << "    return " << getLowerName() << "Expr ? " << getLowerName()
533
0
         << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
534
0
         << " * Ctx.getCharWidth() : "
535
0
         << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
536
0
      OS << "  else\n";
537
0
      OS << "    return 0; // FIXME\n";
538
0
      OS << "}\n";
539
0
    }
540
541
0
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
542
0
      StringRef Name = getUpperName();
543
0
      OS << "  if (A->is" << Name << "Expr()) {\n"
544
0
         << "    if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n"
545
0
         << "      return false;\n"
546
0
         << "  } else if (auto *TSI = A->get" << Name << "Type()) {\n"
547
0
         << "    if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
548
0
         << "      return false;\n"
549
0
         << "  }\n";
550
0
    }
551
552
0
    void writeCloneArgs(raw_ostream &OS) const override {
553
0
      OS << "is" << getLowerName() << "Expr, is" << getLowerName()
554
0
         << "Expr ? static_cast<void*>(" << getLowerName()
555
0
         << "Expr) : " << getLowerName()
556
0
         << "Type";
557
0
    }
558
559
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
560
      // FIXME: move the definition in Sema::InstantiateAttrs to here.
561
      // In the meantime, aligned attributes are cloned.
562
0
    }
563
564
0
    void writeCtorBody(raw_ostream &OS) const override {
565
0
      OS << "    if (is" << getLowerName() << "Expr)\n";
566
0
      OS << "       " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
567
0
         << getUpperName() << ");\n";
568
0
      OS << "    else\n";
569
0
      OS << "       " << getLowerName()
570
0
         << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
571
0
         << ");\n";
572
0
    }
573
574
0
    void writeCtorInitializers(raw_ostream &OS) const override {
575
0
      OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
576
0
    }
577
578
0
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
579
0
      OS << "is" << getLowerName() << "Expr(false)";
580
0
    }
581
582
0
    void writeCtorParameters(raw_ostream &OS) const override {
583
0
      OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
584
0
    }
585
586
0
    void writeImplicitCtorArgs(raw_ostream &OS) const override {
587
0
      OS << "Is" << getUpperName() << "Expr, " << getUpperName();
588
0
    }
589
590
0
    void writeDeclarations(raw_ostream &OS) const override {
591
0
      OS << "bool is" << getLowerName() << "Expr;\n";
592
0
      OS << "union {\n";
593
0
      OS << "Expr *" << getLowerName() << "Expr;\n";
594
0
      OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
595
0
      OS << "};";
596
0
    }
597
598
0
    void writePCHReadArgs(raw_ostream &OS) const override {
599
0
      OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
600
0
    }
601
602
0
    void writePCHReadDecls(raw_ostream &OS) const override {
603
0
      OS << "    bool is" << getLowerName() << "Expr = Record.readInt();\n";
604
0
      OS << "    void *" << getLowerName() << "Ptr;\n";
605
0
      OS << "    if (is" << getLowerName() << "Expr)\n";
606
0
      OS << "      " << getLowerName() << "Ptr = Record.readExpr();\n";
607
0
      OS << "    else\n";
608
0
      OS << "      " << getLowerName()
609
0
         << "Ptr = Record.readTypeSourceInfo();\n";
610
0
    }
611
612
0
    void writePCHWrite(raw_ostream &OS) const override {
613
0
      OS << "    Record.push_back(SA->is" << getUpperName() << "Expr());\n";
614
0
      OS << "    if (SA->is" << getUpperName() << "Expr())\n";
615
0
      OS << "      Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
616
0
      OS << "    else\n";
617
0
      OS << "      Record.AddTypeSourceInfo(SA->get" << getUpperName()
618
0
         << "Type());\n";
619
0
    }
620
621
0
    std::string getIsOmitted() const override {
622
0
      return "!is" + getLowerName().str() + "Expr || !" + getLowerName().str()
623
0
             + "Expr";
624
0
    }
625
626
0
    void writeValue(raw_ostream &OS) const override {
627
0
      OS << "\";\n";
628
0
      OS << "    " << getLowerName()
629
0
         << "Expr->printPretty(OS, nullptr, Policy);\n";
630
0
      OS << "    OS << \"";
631
0
    }
632
633
0
    void writeDump(raw_ostream &OS) const override {
634
0
      OS << "    if (!SA->is" << getUpperName() << "Expr())\n";
635
0
      OS << "      dumpType(SA->get" << getUpperName()
636
0
         << "Type()->getType());\n";
637
0
    }
638
639
0
    void writeDumpChildren(raw_ostream &OS) const override {
640
0
      OS << "    if (SA->is" << getUpperName() << "Expr())\n";
641
0
      OS << "      Visit(SA->get" << getUpperName() << "Expr());\n";
642
0
    }
643
644
0
    void writeHasChildren(raw_ostream &OS) const override {
645
0
      OS << "SA->is" << getUpperName() << "Expr()";
646
0
    }
647
  };
648
649
  class VariadicArgument : public Argument {
650
    std::string Type, ArgName, ArgSizeName, RangeName;
651
652
  protected:
653
    // Assumed to receive a parameter: raw_ostream OS.
654
0
    virtual void writeValueImpl(raw_ostream &OS) const {
655
0
      OS << "    OS << Val;\n";
656
0
    }
657
    // Assumed to receive a parameter: raw_ostream OS.
658
0
    virtual void writeDumpImpl(raw_ostream &OS) const {
659
0
      OS << "      OS << \" \" << Val;\n";
660
0
    }
661
662
  public:
663
    VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
664
        : Argument(Arg, Attr), Type(std::move(T)),
665
          ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
666
0
          RangeName(std::string(getLowerName())) {}
667
668
0
    const std::string &getType() const { return Type; }
669
0
    const std::string &getArgName() const { return ArgName; }
670
0
    const std::string &getArgSizeName() const { return ArgSizeName; }
671
0
    bool isVariadic() const override { return true; }
672
673
0
    void writeAccessors(raw_ostream &OS) const override {
674
0
      std::string IteratorType = getLowerName().str() + "_iterator";
675
0
      std::string BeginFn = getLowerName().str() + "_begin()";
676
0
      std::string EndFn = getLowerName().str() + "_end()";
677
678
0
      OS << "  typedef " << Type << "* " << IteratorType << ";\n";
679
0
      OS << "  " << IteratorType << " " << BeginFn << " const {"
680
0
         << " return " << ArgName << "; }\n";
681
0
      OS << "  " << IteratorType << " " << EndFn << " const {"
682
0
         << " return " << ArgName << " + " << ArgSizeName << "; }\n";
683
0
      OS << "  unsigned " << getLowerName() << "_size() const {"
684
0
         << " return " << ArgSizeName << "; }\n";
685
0
      OS << "  llvm::iterator_range<" << IteratorType << "> " << RangeName
686
0
         << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
687
0
         << "); }\n";
688
0
    }
689
690
0
    void writeCloneArgs(raw_ostream &OS) const override {
691
0
      OS << ArgName << ", " << ArgSizeName;
692
0
    }
693
694
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
695
      // This isn't elegant, but we have to go through public methods...
696
0
      OS << "A->" << getLowerName() << "_begin(), "
697
0
         << "A->" << getLowerName() << "_size()";
698
0
    }
699
700
0
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
701
      // FIXME: Traverse the elements.
702
0
    }
703
704
0
    void writeCtorBody(raw_ostream &OS) const override {
705
0
      OS << "  std::copy(" << getUpperName() << ", " << getUpperName() << " + "
706
0
         << ArgSizeName << ", " << ArgName << ");\n";
707
0
    }
708
709
0
    void writeCtorInitializers(raw_ostream &OS) const override {
710
0
      OS << ArgSizeName << "(" << getUpperName() << "Size), "
711
0
         << ArgName << "(new (Ctx, 16) " << getType() << "["
712
0
         << ArgSizeName << "])";
713
0
    }
714
715
0
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
716
0
      OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
717
0
    }
718
719
0
    void writeCtorParameters(raw_ostream &OS) const override {
720
0
      OS << getType() << " *" << getUpperName() << ", unsigned "
721
0
         << getUpperName() << "Size";
722
0
    }
723
724
0
    void writeImplicitCtorArgs(raw_ostream &OS) const override {
725
0
      OS << getUpperName() << ", " << getUpperName() << "Size";
726
0
    }
727
728
0
    void writeDeclarations(raw_ostream &OS) const override {
729
0
      OS << "  unsigned " << ArgSizeName << ";\n";
730
0
      OS << "  " << getType() << " *" << ArgName << ";";
731
0
    }
732
733
0
    void writePCHReadDecls(raw_ostream &OS) const override {
734
0
      OS << "    unsigned " << getLowerName() << "Size = Record.readInt();\n";
735
0
      OS << "    SmallVector<" << getType() << ", 4> "
736
0
         << getLowerName() << ";\n";
737
0
      OS << "    " << getLowerName() << ".reserve(" << getLowerName()
738
0
         << "Size);\n";
739
740
      // If we can't store the values in the current type (if it's something
741
      // like StringRef), store them in a different type and convert the
742
      // container afterwards.
743
0
      std::string StorageType = std::string(getStorageType(getType()));
744
0
      std::string StorageName = std::string(getLowerName());
745
0
      if (StorageType != getType()) {
746
0
        StorageName += "Storage";
747
0
        OS << "    SmallVector<" << StorageType << ", 4> "
748
0
           << StorageName << ";\n";
749
0
        OS << "    " << StorageName << ".reserve(" << getLowerName()
750
0
           << "Size);\n";
751
0
      }
752
753
0
      OS << "    for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
754
0
      std::string read = ReadPCHRecord(Type);
755
0
      OS << "      " << StorageName << ".push_back(" << read << ");\n";
756
757
0
      if (StorageType != getType()) {
758
0
        OS << "    for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
759
0
        OS << "      " << getLowerName() << ".push_back("
760
0
           << StorageName << "[i]);\n";
761
0
      }
762
0
    }
763
764
0
    void writePCHReadArgs(raw_ostream &OS) const override {
765
0
      OS << getLowerName() << ".data(), " << getLowerName() << "Size";
766
0
    }
767
768
0
    void writePCHWrite(raw_ostream &OS) const override {
769
0
      OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
770
0
      OS << "    for (auto &Val : SA->" << RangeName << "())\n";
771
0
      OS << "      " << WritePCHRecord(Type, "Val");
772
0
    }
773
774
0
    void writeValue(raw_ostream &OS) const override {
775
0
      OS << "\";\n";
776
0
      OS << "  bool isFirst = true;\n"
777
0
         << "  for (const auto &Val : " << RangeName << "()) {\n"
778
0
         << "    if (isFirst) isFirst = false;\n"
779
0
         << "    else OS << \", \";\n";
780
0
      writeValueImpl(OS);
781
0
      OS << "  }\n";
782
0
      OS << "  OS << \"";
783
0
    }
784
785
0
    void writeDump(raw_ostream &OS) const override {
786
0
      OS << "    for (const auto &Val : SA->" << RangeName << "())\n";
787
0
      writeDumpImpl(OS);
788
0
    }
789
  };
790
791
  class VariadicParamIdxArgument : public VariadicArgument {
792
  public:
793
    VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
794
0
        : VariadicArgument(Arg, Attr, "ParamIdx") {}
795
796
  public:
797
0
    void writeValueImpl(raw_ostream &OS) const override {
798
0
      OS << "    OS << Val.getSourceIndex();\n";
799
0
    }
800
801
0
    void writeDumpImpl(raw_ostream &OS) const override {
802
0
      OS << "      OS << \" \" << Val.getSourceIndex();\n";
803
0
    }
804
  };
805
806
  struct VariadicParamOrParamIdxArgument : public VariadicArgument {
807
    VariadicParamOrParamIdxArgument(const Record &Arg, StringRef Attr)
808
0
        : VariadicArgument(Arg, Attr, "int") {}
809
  };
810
811
  // Unique the enums, but maintain the original declaration ordering.
812
  std::vector<StringRef>
813
0
  uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
814
0
    std::vector<StringRef> uniques;
815
0
    SmallDenseSet<StringRef, 8> unique_set;
816
0
    for (const auto &i : enums) {
817
0
      if (unique_set.insert(i).second)
818
0
        uniques.push_back(i);
819
0
    }
820
0
    return uniques;
821
0
  }
822
823
  class EnumArgument : public Argument {
824
    std::string type;
825
    std::vector<StringRef> values, enums, uniques;
826
827
  public:
828
    EnumArgument(const Record &Arg, StringRef Attr)
829
        : Argument(Arg, Attr), type(std::string(Arg.getValueAsString("Type"))),
830
          values(Arg.getValueAsListOfStrings("Values")),
831
          enums(Arg.getValueAsListOfStrings("Enums")),
832
0
          uniques(uniqueEnumsInOrder(enums)) {
833
      // FIXME: Emit a proper error
834
0
      assert(!uniques.empty());
835
0
    }
836
837
0
    bool isEnumArg() const override { return true; }
838
839
0
    void writeAccessors(raw_ostream &OS) const override {
840
0
      OS << "  " << type << " get" << getUpperName() << "() const {\n";
841
0
      OS << "    return " << getLowerName() << ";\n";
842
0
      OS << "  }";
843
0
    }
844
845
0
    void writeCloneArgs(raw_ostream &OS) const override {
846
0
      OS << getLowerName();
847
0
    }
848
849
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
850
0
      OS << "A->get" << getUpperName() << "()";
851
0
    }
852
0
    void writeCtorInitializers(raw_ostream &OS) const override {
853
0
      OS << getLowerName() << "(" << getUpperName() << ")";
854
0
    }
855
0
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
856
0
      OS << getLowerName() << "(" << type << "(0))";
857
0
    }
858
0
    void writeCtorParameters(raw_ostream &OS) const override {
859
0
      OS << type << " " << getUpperName();
860
0
    }
861
0
    void writeDeclarations(raw_ostream &OS) const override {
862
0
      auto i = uniques.cbegin(), e = uniques.cend();
863
      // The last one needs to not have a comma.
864
0
      --e;
865
866
0
      OS << "public:\n";
867
0
      OS << "  enum " << type << " {\n";
868
0
      for (; i != e; ++i)
869
0
        OS << "    " << *i << ",\n";
870
0
      OS << "    " << *e << "\n";
871
0
      OS << "  };\n";
872
0
      OS << "private:\n";
873
0
      OS << "  " << type << " " << getLowerName() << ";";
874
0
    }
875
876
0
    void writePCHReadDecls(raw_ostream &OS) const override {
877
0
      OS << "    " << getAttrName() << "Attr::" << type << " " << getLowerName()
878
0
         << "(static_cast<" << getAttrName() << "Attr::" << type
879
0
         << ">(Record.readInt()));\n";
880
0
    }
881
882
0
    void writePCHReadArgs(raw_ostream &OS) const override {
883
0
      OS << getLowerName();
884
0
    }
885
886
0
    void writePCHWrite(raw_ostream &OS) const override {
887
0
      OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
888
0
    }
889
890
0
    void writeValue(raw_ostream &OS) const override {
891
      // FIXME: this isn't 100% correct -- some enum arguments require printing
892
      // as a string literal, while others require printing as an identifier.
893
      // Tablegen currently does not distinguish between the two forms.
894
0
      OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
895
0
         << getUpperName() << "()) << \"\\\"";
896
0
    }
897
898
0
    void writeDump(raw_ostream &OS) const override {
899
0
      OS << "    switch(SA->get" << getUpperName() << "()) {\n";
900
0
      for (const auto &I : uniques) {
901
0
        OS << "    case " << getAttrName() << "Attr::" << I << ":\n";
902
0
        OS << "      OS << \" " << I << "\";\n";
903
0
        OS << "      break;\n";
904
0
      }
905
0
      OS << "    }\n";
906
0
    }
907
908
0
    void writeConversion(raw_ostream &OS, bool Header) const {
909
0
      if (Header) {
910
0
        OS << "  static bool ConvertStrTo" << type << "(StringRef Val, " << type
911
0
           << " &Out);\n";
912
0
        OS << "  static const char *Convert" << type << "ToStr(" << type
913
0
           << " Val);\n";
914
0
        return;
915
0
      }
916
917
0
      OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << type
918
0
         << "(StringRef Val, " << type << " &Out) {\n";
919
0
      OS << "  Optional<" << type << "> R = llvm::StringSwitch<Optional<";
920
0
      OS << type << ">>(Val)\n";
921
0
      for (size_t I = 0; I < enums.size(); ++I) {
922
0
        OS << "    .Case(\"" << values[I] << "\", ";
923
0
        OS << getAttrName() << "Attr::" << enums[I] << ")\n";
924
0
      }
925
0
      OS << "    .Default(Optional<" << type << ">());\n";
926
0
      OS << "  if (R) {\n";
927
0
      OS << "    Out = *R;\n      return true;\n    }\n";
928
0
      OS << "  return false;\n";
929
0
      OS << "}\n\n";
930
931
      // Mapping from enumeration values back to enumeration strings isn't
932
      // trivial because some enumeration values have multiple named
933
      // enumerators, such as type_visibility(internal) and
934
      // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
935
0
      OS << "const char *" << getAttrName() << "Attr::Convert" << type
936
0
         << "ToStr(" << type << " Val) {\n"
937
0
         << "  switch(Val) {\n";
938
0
      SmallDenseSet<StringRef, 8> Uniques;
939
0
      for (size_t I = 0; I < enums.size(); ++I) {
940
0
        if (Uniques.insert(enums[I]).second)
941
0
          OS << "  case " << getAttrName() << "Attr::" << enums[I]
942
0
             << ": return \"" << values[I] << "\";\n";
943
0
      }
944
0
      OS << "  }\n"
945
0
         << "  llvm_unreachable(\"No enumerator with that value\");\n"
946
0
         << "}\n";
947
0
    }
948
  };
949
950
  class VariadicEnumArgument: public VariadicArgument {
951
    std::string type, QualifiedTypeName;
952
    std::vector<StringRef> values, enums, uniques;
953
954
  protected:
955
0
    void writeValueImpl(raw_ostream &OS) const override {
956
      // FIXME: this isn't 100% correct -- some enum arguments require printing
957
      // as a string literal, while others require printing as an identifier.
958
      // Tablegen currently does not distinguish between the two forms.
959
0
      OS << "    OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
960
0
         << "ToStr(Val)" << "<< \"\\\"\";\n";
961
0
    }
962
963
  public:
964
    VariadicEnumArgument(const Record &Arg, StringRef Attr)
965
        : VariadicArgument(Arg, Attr,
966
                           std::string(Arg.getValueAsString("Type"))),
967
          type(std::string(Arg.getValueAsString("Type"))),
968
          values(Arg.getValueAsListOfStrings("Values")),
969
          enums(Arg.getValueAsListOfStrings("Enums")),
970
0
          uniques(uniqueEnumsInOrder(enums)) {
971
0
      QualifiedTypeName = getAttrName().str() + "Attr::" + type;
972
973
      // FIXME: Emit a proper error
974
0
      assert(!uniques.empty());
975
0
    }
976
977
0
    bool isVariadicEnumArg() const override { return true; }
978
979
0
    void writeDeclarations(raw_ostream &OS) const override {
980
0
      auto i = uniques.cbegin(), e = uniques.cend();
981
      // The last one needs to not have a comma.
982
0
      --e;
983
984
0
      OS << "public:\n";
985
0
      OS << "  enum " << type << " {\n";
986
0
      for (; i != e; ++i)
987
0
        OS << "    " << *i << ",\n";
988
0
      OS << "    " << *e << "\n";
989
0
      OS << "  };\n";
990
0
      OS << "private:\n";
991
992
0
      VariadicArgument::writeDeclarations(OS);
993
0
    }
994
995
0
    void writeDump(raw_ostream &OS) const override {
996
0
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
997
0
         << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
998
0
         << getLowerName() << "_end(); I != E; ++I) {\n";
999
0
      OS << "      switch(*I) {\n";
1000
0
      for (const auto &UI : uniques) {
1001
0
        OS << "    case " << getAttrName() << "Attr::" << UI << ":\n";
1002
0
        OS << "      OS << \" " << UI << "\";\n";
1003
0
        OS << "      break;\n";
1004
0
      }
1005
0
      OS << "      }\n";
1006
0
      OS << "    }\n";
1007
0
    }
1008
1009
0
    void writePCHReadDecls(raw_ostream &OS) const override {
1010
0
      OS << "    unsigned " << getLowerName() << "Size = Record.readInt();\n";
1011
0
      OS << "    SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
1012
0
         << ";\n";
1013
0
      OS << "    " << getLowerName() << ".reserve(" << getLowerName()
1014
0
         << "Size);\n";
1015
0
      OS << "    for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
1016
0
      OS << "      " << getLowerName() << ".push_back(" << "static_cast<"
1017
0
         << QualifiedTypeName << ">(Record.readInt()));\n";
1018
0
    }
1019
1020
0
    void writePCHWrite(raw_ostream &OS) const override {
1021
0
      OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
1022
0
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
1023
0
         << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
1024
0
         << getLowerName() << "_end(); i != e; ++i)\n";
1025
0
      OS << "      " << WritePCHRecord(QualifiedTypeName, "(*i)");
1026
0
    }
1027
1028
0
    void writeConversion(raw_ostream &OS, bool Header) const {
1029
0
      if (Header) {
1030
0
        OS << "  static bool ConvertStrTo" << type << "(StringRef Val, " << type
1031
0
           << " &Out);\n";
1032
0
        OS << "  static const char *Convert" << type << "ToStr(" << type
1033
0
           << " Val);\n";
1034
0
        return;
1035
0
      }
1036
1037
0
      OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << type
1038
0
         << "(StringRef Val, ";
1039
0
      OS << type << " &Out) {\n";
1040
0
      OS << "  Optional<" << type << "> R = llvm::StringSwitch<Optional<";
1041
0
      OS << type << ">>(Val)\n";
1042
0
      for (size_t I = 0; I < enums.size(); ++I) {
1043
0
        OS << "    .Case(\"" << values[I] << "\", ";
1044
0
        OS << getAttrName() << "Attr::" << enums[I] << ")\n";
1045
0
      }
1046
0
      OS << "    .Default(Optional<" << type << ">());\n";
1047
0
      OS << "  if (R) {\n";
1048
0
      OS << "    Out = *R;\n      return true;\n    }\n";
1049
0
      OS << "  return false;\n";
1050
0
      OS << "}\n\n";
1051
1052
0
      OS << "const char *" << getAttrName() << "Attr::Convert" << type
1053
0
         << "ToStr(" << type << " Val) {\n"
1054
0
         << "  switch(Val) {\n";
1055
0
      SmallDenseSet<StringRef, 8> Uniques;
1056
0
      for (size_t I = 0; I < enums.size(); ++I) {
1057
0
        if (Uniques.insert(enums[I]).second)
1058
0
          OS << "  case " << getAttrName() << "Attr::" << enums[I]
1059
0
             << ": return \"" << values[I] << "\";\n";
1060
0
      }
1061
0
      OS << "  }\n"
1062
0
         << "  llvm_unreachable(\"No enumerator with that value\");\n"
1063
0
         << "}\n";
1064
0
    }
1065
  };
1066
1067
  class VersionArgument : public Argument {
1068
  public:
1069
    VersionArgument(const Record &Arg, StringRef Attr)
1070
      : Argument(Arg, Attr)
1071
0
    {}
1072
1073
0
    void writeAccessors(raw_ostream &OS) const override {
1074
0
      OS << "  VersionTuple get" << getUpperName() << "() const {\n";
1075
0
      OS << "    return " << getLowerName() << ";\n";
1076
0
      OS << "  }\n";
1077
0
      OS << "  void set" << getUpperName()
1078
0
         << "(ASTContext &C, VersionTuple V) {\n";
1079
0
      OS << "    " << getLowerName() << " = V;\n";
1080
0
      OS << "  }";
1081
0
    }
1082
1083
0
    void writeCloneArgs(raw_ostream &OS) const override {
1084
0
      OS << "get" << getUpperName() << "()";
1085
0
    }
1086
1087
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1088
0
      OS << "A->get" << getUpperName() << "()";
1089
0
    }
1090
1091
0
    void writeCtorInitializers(raw_ostream &OS) const override {
1092
0
      OS << getLowerName() << "(" << getUpperName() << ")";
1093
0
    }
1094
1095
0
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
1096
0
      OS << getLowerName() << "()";
1097
0
    }
1098
1099
0
    void writeCtorParameters(raw_ostream &OS) const override {
1100
0
      OS << "VersionTuple " << getUpperName();
1101
0
    }
1102
1103
0
    void writeDeclarations(raw_ostream &OS) const override {
1104
0
      OS << "VersionTuple " << getLowerName() << ";\n";
1105
0
    }
1106
1107
0
    void writePCHReadDecls(raw_ostream &OS) const override {
1108
0
      OS << "    VersionTuple " << getLowerName()
1109
0
         << "= Record.readVersionTuple();\n";
1110
0
    }
1111
1112
0
    void writePCHReadArgs(raw_ostream &OS) const override {
1113
0
      OS << getLowerName();
1114
0
    }
1115
1116
0
    void writePCHWrite(raw_ostream &OS) const override {
1117
0
      OS << "    Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
1118
0
    }
1119
1120
0
    void writeValue(raw_ostream &OS) const override {
1121
0
      OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1122
0
    }
1123
1124
0
    void writeDump(raw_ostream &OS) const override {
1125
0
      OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
1126
0
    }
1127
  };
1128
1129
  class ExprArgument : public SimpleArgument {
1130
  public:
1131
    ExprArgument(const Record &Arg, StringRef Attr)
1132
      : SimpleArgument(Arg, Attr, "Expr *")
1133
0
    {}
1134
1135
0
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
1136
0
      OS << "  if (!"
1137
0
         << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1138
0
      OS << "    return false;\n";
1139
0
    }
1140
1141
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1142
0
      OS << "tempInst" << getUpperName();
1143
0
    }
1144
1145
0
    void writeTemplateInstantiation(raw_ostream &OS) const override {
1146
0
      OS << "      " << getType() << " tempInst" << getUpperName() << ";\n";
1147
0
      OS << "      {\n";
1148
0
      OS << "        EnterExpressionEvaluationContext "
1149
0
         << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1150
0
      OS << "        ExprResult " << "Result = S.SubstExpr("
1151
0
         << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1152
0
      OS << "        tempInst" << getUpperName() << " = "
1153
0
         << "Result.getAs<Expr>();\n";
1154
0
      OS << "      }\n";
1155
0
    }
1156
1157
0
    void writeDump(raw_ostream &OS) const override {}
1158
1159
0
    void writeDumpChildren(raw_ostream &OS) const override {
1160
0
      OS << "    Visit(SA->get" << getUpperName() << "());\n";
1161
0
    }
1162
1163
0
    void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
1164
  };
1165
1166
  class VariadicExprArgument : public VariadicArgument {
1167
  public:
1168
    VariadicExprArgument(const Record &Arg, StringRef Attr)
1169
      : VariadicArgument(Arg, Attr, "Expr *")
1170
0
    {}
1171
1172
0
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
1173
0
      OS << "  {\n";
1174
0
      OS << "    " << getType() << " *I = A->" << getLowerName()
1175
0
         << "_begin();\n";
1176
0
      OS << "    " << getType() << " *E = A->" << getLowerName()
1177
0
         << "_end();\n";
1178
0
      OS << "    for (; I != E; ++I) {\n";
1179
0
      OS << "      if (!getDerived().TraverseStmt(*I))\n";
1180
0
      OS << "        return false;\n";
1181
0
      OS << "    }\n";
1182
0
      OS << "  }\n";
1183
0
    }
1184
1185
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1186
0
      OS << "tempInst" << getUpperName() << ", "
1187
0
         << "A->" << getLowerName() << "_size()";
1188
0
    }
1189
1190
0
    void writeTemplateInstantiation(raw_ostream &OS) const override {
1191
0
      OS << "      auto *tempInst" << getUpperName()
1192
0
         << " = new (C, 16) " << getType()
1193
0
         << "[A->" << getLowerName() << "_size()];\n";
1194
0
      OS << "      {\n";
1195
0
      OS << "        EnterExpressionEvaluationContext "
1196
0
         << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1197
0
      OS << "        " << getType() << " *TI = tempInst" << getUpperName()
1198
0
         << ";\n";
1199
0
      OS << "        " << getType() << " *I = A->" << getLowerName()
1200
0
         << "_begin();\n";
1201
0
      OS << "        " << getType() << " *E = A->" << getLowerName()
1202
0
         << "_end();\n";
1203
0
      OS << "        for (; I != E; ++I, ++TI) {\n";
1204
0
      OS << "          ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
1205
0
      OS << "          *TI = Result.getAs<Expr>();\n";
1206
0
      OS << "        }\n";
1207
0
      OS << "      }\n";
1208
0
    }
1209
1210
0
    void writeDump(raw_ostream &OS) const override {}
1211
1212
0
    void writeDumpChildren(raw_ostream &OS) const override {
1213
0
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
1214
0
         << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1215
0
         << getLowerName() << "_end(); I != E; ++I)\n";
1216
0
      OS << "      Visit(*I);\n";
1217
0
    }
1218
1219
0
    void writeHasChildren(raw_ostream &OS) const override {
1220
0
      OS << "SA->" << getLowerName() << "_begin() != "
1221
0
         << "SA->" << getLowerName() << "_end()";
1222
0
    }
1223
  };
1224
1225
  class VariadicIdentifierArgument : public VariadicArgument {
1226
  public:
1227
    VariadicIdentifierArgument(const Record &Arg, StringRef Attr)
1228
      : VariadicArgument(Arg, Attr, "IdentifierInfo *")
1229
0
    {}
1230
  };
1231
1232
  class VariadicStringArgument : public VariadicArgument {
1233
  public:
1234
    VariadicStringArgument(const Record &Arg, StringRef Attr)
1235
      : VariadicArgument(Arg, Attr, "StringRef")
1236
0
    {}
1237
1238
0
    void writeCtorBody(raw_ostream &OS) const override {
1239
0
      OS << "  for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1240
0
            "       ++I) {\n"
1241
0
            "    StringRef Ref = " << getUpperName() << "[I];\n"
1242
0
            "    if (!Ref.empty()) {\n"
1243
0
            "      char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1244
0
            "      std::memcpy(Mem, Ref.data(), Ref.size());\n"
1245
0
            "      " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1246
0
            "    }\n"
1247
0
            "  }\n";
1248
0
    }
1249
1250
0
    void writeValueImpl(raw_ostream &OS) const override {
1251
0
      OS << "    OS << \"\\\"\" << Val << \"\\\"\";\n";
1252
0
    }
1253
  };
1254
1255
  class TypeArgument : public SimpleArgument {
1256
  public:
1257
    TypeArgument(const Record &Arg, StringRef Attr)
1258
      : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1259
0
    {}
1260
1261
0
    void writeAccessors(raw_ostream &OS) const override {
1262
0
      OS << "  QualType get" << getUpperName() << "() const {\n";
1263
0
      OS << "    return " << getLowerName() << "->getType();\n";
1264
0
      OS << "  }";
1265
0
      OS << "  " << getType() << " get" << getUpperName() << "Loc() const {\n";
1266
0
      OS << "    return " << getLowerName() << ";\n";
1267
0
      OS << "  }";
1268
0
    }
1269
1270
0
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
1271
0
      OS << "  if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
1272
0
      OS << "    if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
1273
0
      OS << "      return false;\n";
1274
0
    }
1275
1276
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1277
0
      OS << "A->get" << getUpperName() << "Loc()";
1278
0
    }
1279
1280
0
    void writePCHWrite(raw_ostream &OS) const override {
1281
0
      OS << "    "
1282
0
         << WritePCHRecord(getType(),
1283
0
                           "SA->get" + std::string(getUpperName()) + "Loc()");
1284
0
    }
1285
  };
1286
1287
} // end anonymous namespace
1288
1289
static std::unique_ptr<Argument>
1290
createArgument(const Record &Arg, StringRef Attr,
1291
0
               const Record *Search = nullptr) {
1292
0
  if (!Search)
1293
0
    Search = &Arg;
1294
1295
0
  std::unique_ptr<Argument> Ptr;
1296
0
  llvm::StringRef ArgName = Search->getName();
1297
1298
0
  if (ArgName == "AlignedArgument")
1299
0
    Ptr = std::make_unique<AlignedArgument>(Arg, Attr);
1300
0
  else if (ArgName == "EnumArgument")
1301
0
    Ptr = std::make_unique<EnumArgument>(Arg, Attr);
1302
0
  else if (ArgName == "ExprArgument")
1303
0
    Ptr = std::make_unique<ExprArgument>(Arg, Attr);
1304
0
  else if (ArgName == "DeclArgument")
1305
0
    Ptr = std::make_unique<SimpleArgument>(
1306
0
        Arg, Attr, (Arg.getValueAsDef("Kind")->getName() + "Decl *").str());
1307
0
  else if (ArgName == "IdentifierArgument")
1308
0
    Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
1309
0
  else if (ArgName == "DefaultBoolArgument")
1310
0
    Ptr = std::make_unique<DefaultSimpleArgument>(
1311
0
        Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1312
0
  else if (ArgName == "BoolArgument")
1313
0
    Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "bool");
1314
0
  else if (ArgName == "DefaultIntArgument")
1315
0
    Ptr = std::make_unique<DefaultSimpleArgument>(
1316
0
        Arg, Attr, "int", Arg.getValueAsInt("Default"));
1317
0
  else if (ArgName == "IntArgument")
1318
0
    Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "int");
1319
0
  else if (ArgName == "StringArgument")
1320
0
    Ptr = std::make_unique<StringArgument>(Arg, Attr);
1321
0
  else if (ArgName == "TypeArgument")
1322
0
    Ptr = std::make_unique<TypeArgument>(Arg, Attr);
1323
0
  else if (ArgName == "UnsignedArgument")
1324
0
    Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
1325
0
  else if (ArgName == "VariadicUnsignedArgument")
1326
0
    Ptr = std::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
1327
0
  else if (ArgName == "VariadicStringArgument")
1328
0
    Ptr = std::make_unique<VariadicStringArgument>(Arg, Attr);
1329
0
  else if (ArgName == "VariadicEnumArgument")
1330
0
    Ptr = std::make_unique<VariadicEnumArgument>(Arg, Attr);
1331
0
  else if (ArgName == "VariadicExprArgument")
1332
0
    Ptr = std::make_unique<VariadicExprArgument>(Arg, Attr);
1333
0
  else if (ArgName == "VariadicParamIdxArgument")
1334
0
    Ptr = std::make_unique<VariadicParamIdxArgument>(Arg, Attr);
1335
0
  else if (ArgName == "VariadicParamOrParamIdxArgument")
1336
0
    Ptr = std::make_unique<VariadicParamOrParamIdxArgument>(Arg, Attr);
1337
0
  else if (ArgName == "ParamIdxArgument")
1338
0
    Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "ParamIdx");
1339
0
  else if (ArgName == "VariadicIdentifierArgument")
1340
0
    Ptr = std::make_unique<VariadicIdentifierArgument>(Arg, Attr);
1341
0
  else if (ArgName == "VersionArgument")
1342
0
    Ptr = std::make_unique<VersionArgument>(Arg, Attr);
1343
0
  else if (ArgName == "OMPTraitInfoArgument")
1344
0
    Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "OMPTraitInfo *");
1345
1346
0
  if (!Ptr) {
1347
    // Search in reverse order so that the most-derived type is handled first.
1348
0
    ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
1349
0
    for (const auto &Base : llvm::reverse(Bases)) {
1350
0
      if ((Ptr = createArgument(Arg, Attr, Base.first)))
1351
0
        break;
1352
0
    }
1353
0
  }
1354
1355
0
  if (Ptr && Arg.getValueAsBit("Optional"))
1356
0
    Ptr->setOptional(true);
1357
1358
0
  if (Ptr && Arg.getValueAsBit("Fake"))
1359
0
    Ptr->setFake(true);
1360
1361
0
  return Ptr;
1362
0
}
1363
1364
0
static void writeAvailabilityValue(raw_ostream &OS) {
1365
0
  OS << "\" << getPlatform()->getName();\n"
1366
0
     << "  if (getStrict()) OS << \", strict\";\n"
1367
0
     << "  if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1368
0
     << "  if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1369
0
     << "  if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1370
0
     << "  if (getUnavailable()) OS << \", unavailable\";\n"
1371
0
     << "  OS << \"";
1372
0
}
1373
1374
0
static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
1375
0
  OS << "\\\"\" << getMessage() << \"\\\"\";\n";
1376
  // Only GNU deprecated has an optional fixit argument at the second position.
1377
0
  if (Variety == "GNU")
1378
0
     OS << "    if (!getReplacement().empty()) OS << \", \\\"\""
1379
0
           " << getReplacement() << \"\\\"\";\n";
1380
0
  OS << "    OS << \"";
1381
0
}
1382
1383
0
static void writeGetSpellingFunction(const Record &R, raw_ostream &OS) {
1384
0
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1385
1386
0
  OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1387
0
  if (Spellings.empty()) {
1388
0
    OS << "  return \"(No spelling)\";\n}\n\n";
1389
0
    return;
1390
0
  }
1391
1392
0
  OS << "  switch (getAttributeSpellingListIndex()) {\n"
1393
0
        "  default:\n"
1394
0
        "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
1395
0
        "    return \"(No spelling)\";\n";
1396
1397
0
  for (unsigned I = 0; I < Spellings.size(); ++I)
1398
0
    OS << "  case " << I << ":\n"
1399
0
          "    return \"" << Spellings[I].name() << "\";\n";
1400
  // End of the switch statement.
1401
0
  OS << "  }\n";
1402
  // End of the getSpelling function.
1403
0
  OS << "}\n\n";
1404
0
}
1405
1406
static void
1407
writePrettyPrintFunction(const Record &R,
1408
                         const std::vector<std::unique_ptr<Argument>> &Args,
1409
0
                         raw_ostream &OS) {
1410
0
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1411
1412
0
  OS << "void " << R.getName() << "Attr::printPretty("
1413
0
    << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1414
1415
0
  if (Spellings.empty()) {
1416
0
    OS << "}\n\n";
1417
0
    return;
1418
0
  }
1419
1420
0
  OS << "  switch (getAttributeSpellingListIndex()) {\n"
1421
0
        "  default:\n"
1422
0
        "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
1423
0
        "    break;\n";
1424
1425
0
  for (unsigned I = 0; I < Spellings.size(); ++ I) {
1426
0
    llvm::SmallString<16> Prefix;
1427
0
    llvm::SmallString<8> Suffix;
1428
    // The actual spelling of the name and namespace (if applicable)
1429
    // of an attribute without considering prefix and suffix.
1430
0
    llvm::SmallString<64> Spelling;
1431
0
    std::string Name = Spellings[I].name();
1432
0
    std::string Variety = Spellings[I].variety();
1433
1434
0
    if (Variety == "GNU") {
1435
0
      Prefix = " __attribute__((";
1436
0
      Suffix = "))";
1437
0
    } else if (Variety == "CXX11" || Variety == "C2x") {
1438
0
      Prefix = " [[";
1439
0
      Suffix = "]]";
1440
0
      std::string Namespace = Spellings[I].nameSpace();
1441
0
      if (!Namespace.empty()) {
1442
0
        Spelling += Namespace;
1443
0
        Spelling += "::";
1444
0
      }
1445
0
    } else if (Variety == "Declspec") {
1446
0
      Prefix = " __declspec(";
1447
0
      Suffix = ")";
1448
0
    } else if (Variety == "Microsoft") {
1449
0
      Prefix = "[";
1450
0
      Suffix = "]";
1451
0
    } else if (Variety == "Keyword") {
1452
0
      Prefix = " ";
1453
0
      Suffix = "";
1454
0
    } else if (Variety == "Pragma") {
1455
0
      Prefix = "#pragma ";
1456
0
      Suffix = "\n";
1457
0
      std::string Namespace = Spellings[I].nameSpace();
1458
0
      if (!Namespace.empty()) {
1459
0
        Spelling += Namespace;
1460
0
        Spelling += " ";
1461
0
      }
1462
0
    } else {
1463
0
      llvm_unreachable("Unknown attribute syntax variety!");
1464
0
    }
1465
1466
0
    Spelling += Name;
1467
1468
0
    OS <<
1469
0
      "  case " << I << " : {\n"
1470
0
      "    OS << \"" << Prefix << Spelling;
1471
1472
0
    if (Variety == "Pragma") {
1473
0
      OS << "\";\n";
1474
0
      OS << "    printPrettyPragma(OS, Policy);\n";
1475
0
      OS << "    OS << \"\\n\";";
1476
0
      OS << "    break;\n";
1477
0
      OS << "  }\n";
1478
0
      continue;
1479
0
    }
1480
1481
0
    if (Spelling == "availability") {
1482
0
      OS << "(";
1483
0
      writeAvailabilityValue(OS);
1484
0
      OS << ")";
1485
0
    } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
1486
0
      OS << "(";
1487
0
      writeDeprecatedAttrValue(OS, Variety);
1488
0
      OS << ")";
1489
0
    } else {
1490
      // To avoid printing parentheses around an empty argument list or
1491
      // printing spurious commas at the end of an argument list, we need to
1492
      // determine where the last provided non-fake argument is.
1493
0
      unsigned NonFakeArgs = 0;
1494
0
      unsigned TrailingOptArgs = 0;
1495
0
      bool FoundNonOptArg = false;
1496
0
      for (const auto &arg : llvm::reverse(Args)) {
1497
0
        if (arg->isFake())
1498
0
          continue;
1499
0
        ++NonFakeArgs;
1500
0
        if (FoundNonOptArg)
1501
0
          continue;
1502
        // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
1503
        // any way to detect whether the argument was omitted.
1504
0
        if (!arg->isOptional() || arg->getIsOmitted() == "false") {
1505
0
          FoundNonOptArg = true;
1506
0
          continue;
1507
0
        }
1508
0
        if (!TrailingOptArgs++)
1509
0
          OS << "\";\n"
1510
0
             << "    unsigned TrailingOmittedArgs = 0;\n";
1511
0
        OS << "    if (" << arg->getIsOmitted() << ")\n"
1512
0
           << "      ++TrailingOmittedArgs;\n";
1513
0
      }
1514
0
      if (TrailingOptArgs)
1515
0
        OS << "    OS << \"";
1516
0
      if (TrailingOptArgs < NonFakeArgs)
1517
0
        OS << "(";
1518
0
      else if (TrailingOptArgs)
1519
0
        OS << "\";\n"
1520
0
           << "    if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
1521
0
           << "       OS << \"(\";\n"
1522
0
           << "    OS << \"";
1523
0
      unsigned ArgIndex = 0;
1524
0
      for (const auto &arg : Args) {
1525
0
        if (arg->isFake())
1526
0
          continue;
1527
0
        if (ArgIndex) {
1528
0
          if (ArgIndex >= NonFakeArgs - TrailingOptArgs)
1529
0
            OS << "\";\n"
1530
0
               << "    if (" << ArgIndex << " < " << NonFakeArgs
1531
0
               << " - TrailingOmittedArgs)\n"
1532
0
               << "      OS << \", \";\n"
1533
0
               << "    OS << \"";
1534
0
          else
1535
0
            OS << ", ";
1536
0
        }
1537
0
        std::string IsOmitted = arg->getIsOmitted();
1538
0
        if (arg->isOptional() && IsOmitted != "false")
1539
0
          OS << "\";\n"
1540
0
             << "    if (!(" << IsOmitted << ")) {\n"
1541
0
             << "      OS << \"";
1542
0
        arg->writeValue(OS);
1543
0
        if (arg->isOptional() && IsOmitted != "false")
1544
0
          OS << "\";\n"
1545
0
             << "    }\n"
1546
0
             << "    OS << \"";
1547
0
        ++ArgIndex;
1548
0
      }
1549
0
      if (TrailingOptArgs < NonFakeArgs)
1550
0
        OS << ")";
1551
0
      else if (TrailingOptArgs)
1552
0
        OS << "\";\n"
1553
0
           << "    if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
1554
0
           << "       OS << \")\";\n"
1555
0
           << "    OS << \"";
1556
0
    }
1557
1558
0
    OS << Suffix + "\";\n";
1559
1560
0
    OS <<
1561
0
      "    break;\n"
1562
0
      "  }\n";
1563
0
  }
1564
1565
  // End of the switch statement.
1566
0
  OS << "}\n";
1567
  // End of the print function.
1568
0
  OS << "}\n\n";
1569
0
}
1570
1571
/// Return the index of a spelling in a spelling list.
1572
static unsigned
1573
getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1574
0
                     const FlattenedSpelling &Spelling) {
1575
0
  assert(!SpellingList.empty() && "Spelling list is empty!");
1576
1577
0
  for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
1578
0
    const FlattenedSpelling &S = SpellingList[Index];
1579
0
    if (S.variety() != Spelling.variety())
1580
0
      continue;
1581
0
    if (S.nameSpace() != Spelling.nameSpace())
1582
0
      continue;
1583
0
    if (S.name() != Spelling.name())
1584
0
      continue;
1585
1586
0
    return Index;
1587
0
  }
1588
1589
0
  llvm_unreachable("Unknown spelling!");
1590
0
}
1591
1592
0
static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1593
0
  std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
1594
0
  if (Accessors.empty())
1595
0
    return;
1596
1597
0
  const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1598
0
  assert(!SpellingList.empty() &&
1599
0
         "Attribute with empty spelling list can't have accessors!");
1600
0
  for (const auto *Accessor : Accessors) {
1601
0
    const StringRef Name = Accessor->getValueAsString("Name");
1602
0
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
1603
1604
0
    OS << "  bool " << Name
1605
0
       << "() const { return getAttributeSpellingListIndex() == ";
1606
0
    for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1607
0
      OS << getSpellingListIndex(SpellingList, Spellings[Index]);
1608
0
      if (Index != Spellings.size() - 1)
1609
0
        OS << " ||\n    getAttributeSpellingListIndex() == ";
1610
0
      else
1611
0
        OS << "; }\n";
1612
0
    }
1613
0
  }
1614
0
}
1615
1616
static bool
1617
0
SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1618
0
  assert(!Spellings.empty() && "An empty list of spellings was provided");
1619
0
  std::string FirstName =
1620
0
      std::string(NormalizeNameForSpellingComparison(Spellings.front().name()));
1621
0
  for (const auto &Spelling :
1622
0
       llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
1623
0
    std::string Name =
1624
0
        std::string(NormalizeNameForSpellingComparison(Spelling.name()));
1625
0
    if (Name != FirstName)
1626
0
      return false;
1627
0
  }
1628
0
  return true;
1629
0
}
1630
1631
typedef std::map<unsigned, std::string> SemanticSpellingMap;
1632
static std::string
1633
CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1634
0
                        SemanticSpellingMap &Map) {
1635
  // The enumerants are automatically generated based on the variety,
1636
  // namespace (if present) and name for each attribute spelling. However,
1637
  // care is taken to avoid trampling on the reserved namespace due to
1638
  // underscores.
1639
0
  std::string Ret("  enum Spelling {\n");
1640
0
  std::set<std::string> Uniques;
1641
0
  unsigned Idx = 0;
1642
1643
  // If we have a need to have this many spellings we likely need to add an
1644
  // extra bit to the SpellingIndex in AttributeCommonInfo, then increase the
1645
  // value of SpellingNotCalculated there and here.
1646
0
  assert(Spellings.size() < 15 &&
1647
0
         "Too many spellings, would step on SpellingNotCalculated in "
1648
0
         "AttributeCommonInfo");
1649
0
  for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1650
0
    const FlattenedSpelling &S = *I;
1651
0
    const std::string &Variety = S.variety();
1652
0
    const std::string &Spelling = S.name();
1653
0
    const std::string &Namespace = S.nameSpace();
1654
0
    std::string EnumName;
1655
1656
0
    EnumName += (Variety + "_");
1657
0
    if (!Namespace.empty())
1658
0
      EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1659
0
      "_");
1660
0
    EnumName += NormalizeNameForSpellingComparison(Spelling);
1661
1662
    // Even if the name is not unique, this spelling index corresponds to a
1663
    // particular enumerant name that we've calculated.
1664
0
    Map[Idx] = EnumName;
1665
1666
    // Since we have been stripping underscores to avoid trampling on the
1667
    // reserved namespace, we may have inadvertently created duplicate
1668
    // enumerant names. These duplicates are not considered part of the
1669
    // semantic spelling, and can be elided.
1670
0
    if (Uniques.find(EnumName) != Uniques.end())
1671
0
      continue;
1672
1673
0
    Uniques.insert(EnumName);
1674
0
    if (I != Spellings.begin())
1675
0
      Ret += ",\n";
1676
    // Duplicate spellings are not considered part of the semantic spelling
1677
    // enumeration, but the spelling index and semantic spelling values are
1678
    // meant to be equivalent, so we must specify a concrete value for each
1679
    // enumerator.
1680
0
    Ret += "    " + EnumName + " = " + llvm::utostr(Idx);
1681
0
  }
1682
0
  Ret += ",\n  SpellingNotCalculated = 15\n";
1683
0
  Ret += "\n  };\n\n";
1684
0
  return Ret;
1685
0
}
1686
1687
void WriteSemanticSpellingSwitch(const std::string &VarName,
1688
                                 const SemanticSpellingMap &Map,
1689
0
                                 raw_ostream &OS) {
1690
0
  OS << "  switch (" << VarName << ") {\n    default: "
1691
0
    << "llvm_unreachable(\"Unknown spelling list index\");\n";
1692
0
  for (const auto &I : Map)
1693
0
    OS << "    case " << I.first << ": return " << I.second << ";\n";
1694
0
  OS << "  }\n";
1695
0
}
1696
1697
// Emits the LateParsed property for attributes.
1698
0
static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1699
0
  OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1700
0
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1701
1702
0
  for (const auto *Attr : Attrs) {
1703
0
    bool LateParsed = Attr->getValueAsBit("LateParsed");
1704
1705
0
    if (LateParsed) {
1706
0
      std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1707
1708
      // FIXME: Handle non-GNU attributes
1709
0
      for (const auto &I : Spellings) {
1710
0
        if (I.variety() != "GNU")
1711
0
          continue;
1712
0
        OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
1713
0
      }
1714
0
    }
1715
0
  }
1716
0
  OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1717
0
}
1718
1719
279
static bool hasGNUorCXX11Spelling(const Record &Attribute) {
1720
279
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
1721
300
  for (const auto &I : Spellings) {
1722
300
    if (I.variety() == "GNU" || 
I.variety() == "CXX11"61
)
1723
249
      return true;
1724
300
  }
1725
30
  return false;
1726
279
}
1727
1728
namespace {
1729
1730
struct AttributeSubjectMatchRule {
1731
  const Record *MetaSubject;
1732
  const Record *Constraint;
1733
1734
  AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
1735
50
      : MetaSubject(MetaSubject), Constraint(Constraint) {
1736
50
    assert(MetaSubject && "Missing subject");
1737
50
  }
1738
1739
318
  bool isSubRule() const { return Constraint != nullptr; }
1740
1741
260
  std::vector<Record *> getSubjects() const {
1742
219
    return (Constraint ? 
Constraint41
: MetaSubject)
1743
260
        ->getValueAsListOfDefs("Subjects");
1744
260
  }
1745
1746
0
  std::vector<Record *> getLangOpts() const {
1747
0
    if (Constraint) {
1748
      // Lookup the options in the sub-rule first, in case the sub-rule
1749
      // overrides the rules options.
1750
0
      std::vector<Record *> Opts = Constraint->getValueAsListOfDefs("LangOpts");
1751
0
      if (!Opts.empty())
1752
0
        return Opts;
1753
0
    }
1754
0
    return MetaSubject->getValueAsListOfDefs("LangOpts");
1755
0
  }
1756
1757
  // Abstract rules are used only for sub-rules
1758
260
  bool isAbstractRule() const { return getSubjects().empty(); }
1759
1760
0
  StringRef getName() const {
1761
0
    return (Constraint ? Constraint : MetaSubject)->getValueAsString("Name");
1762
0
  }
1763
1764
41
  bool isNegatedSubRule() const {
1765
41
    assert(isSubRule() && "Not a sub-rule");
1766
41
    return Constraint->getValueAsBit("Negated");
1767
41
  }
1768
1769
0
  std::string getSpelling() const {
1770
0
    std::string Result = std::string(MetaSubject->getValueAsString("Name"));
1771
0
    if (isSubRule()) {
1772
0
      Result += '(';
1773
0
      if (isNegatedSubRule())
1774
0
        Result += "unless(";
1775
0
      Result += getName();
1776
0
      if (isNegatedSubRule())
1777
0
        Result += ')';
1778
0
      Result += ')';
1779
0
    }
1780
0
    return Result;
1781
0
  }
1782
1783
260
  std::string getEnumValueName() const {
1784
260
    SmallString<128> Result;
1785
260
    Result += "SubjectMatchRule_";
1786
260
    Result += MetaSubject->getValueAsString("Name");
1787
260
    if (isSubRule()) {
1788
41
      Result += "_";
1789
41
      if (isNegatedSubRule())
1790
5
        Result += "not_";
1791
41
      Result += Constraint->getValueAsString("Name");
1792
41
    }
1793
260
    if (isAbstractRule())
1794
0
      Result += "_abstract";
1795
260
    return std::string(Result.str());
1796
260
  }
1797
1798
0
  std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
1799
1800
  static const char *EnumName;
1801
};
1802
1803
const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";
1804
1805
struct PragmaClangAttributeSupport {
1806
  std::vector<AttributeSubjectMatchRule> Rules;
1807
1808
  class RuleOrAggregateRuleSet {
1809
    std::vector<AttributeSubjectMatchRule> Rules;
1810
    bool IsRule;
1811
    RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
1812
                           bool IsRule)
1813
26
        : Rules(Rules), IsRule(IsRule) {}
1814
1815
  public:
1816
249
    bool isRule() const { return IsRule; }
1817
1818
262
    const AttributeSubjectMatchRule &getRule() const {
1819
262
      assert(IsRule && "not a rule!");
1820
262
      return Rules[0];
1821
262
    }
1822
1823
2
    ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
1824
2
      return Rules;
1825
2
    }
1826
1827
    static RuleOrAggregateRuleSet
1828
25
    getRule(const AttributeSubjectMatchRule &Rule) {
1829
25
      return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
1830
25
    }
1831
    static RuleOrAggregateRuleSet
1832
1
    getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
1833
1
      return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
1834
1
    }
1835
  };
1836
  llvm::DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;
1837
1838
  PragmaClangAttributeSupport(RecordKeeper &Records);
1839
1840
  bool isAttributedSupported(const Record &Attribute);
1841
1842
  void emitMatchRuleList(raw_ostream &OS);
1843
1844
  void generateStrictConformsTo(const Record &Attr, raw_ostream &OS);
1845
1846
  void generateParsingHelpers(raw_ostream &OS);
1847
};
1848
1849
} // end anonymous namespace
1850
1851
222
static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
1852
222
  const Record *CurrentBase = D->getValueAsOptionalDef(BaseFieldName);
1853
222
  if (!CurrentBase)
1854
24
    return false;
1855
198
  if (CurrentBase == Base)
1856
67
    return true;
1857
131
  return doesDeclDeriveFrom(CurrentBase, Base);
1858
131
}
1859
1860
PragmaClangAttributeSupport::PragmaClangAttributeSupport(
1861
1
    RecordKeeper &Records) {
1862
1
  std::vector<Record *> MetaSubjects =
1863
1
      Records.getAllDerivedDefinitions("AttrSubjectMatcherRule");
1864
1
  auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
1865
1
                                       const Record *MetaSubject,
1866
25
                                       const Record *Constraint) {
1867
25
    Rules.emplace_back(MetaSubject, Constraint);
1868
25
    std::vector<Record *> ApplicableSubjects =
1869
25
        SubjectContainer->getValueAsListOfDefs("Subjects");
1870
25
    for (const auto *Subject : ApplicableSubjects) {
1871
25
      bool Inserted =
1872
25
          SubjectsToRules
1873
25
              .try_emplace(Subject, RuleOrAggregateRuleSet::getRule(
1874
25
                                        AttributeSubjectMatchRule(MetaSubject,
1875
25
                                                                  Constraint)))
1876
25
              .second;
1877
25
      if (!Inserted) {
1878
0
        PrintFatalError("Attribute subject match rules should not represent"
1879
0
                        "same attribute subjects.");
1880
0
      }
1881
25
    }
1882
25
  };
1883
16
  for (const auto *MetaSubject : MetaSubjects) {
1884
16
    MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
1885
16
    std::vector<Record *> Constraints =
1886
16
        MetaSubject->getValueAsListOfDefs("Constraints");
1887
16
    for (const auto *Constraint : Constraints)
1888
9
      MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
1889
16
  }
1890
1891
1
  std::vector<Record *> Aggregates =
1892
1
      Records.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule");
1893
1
  std::vector<Record *> DeclNodes =
1894
1
    Records.getAllDerivedDefinitions(DeclNodeClassName);
1895
1
  for (const auto *Aggregate : Aggregates) {
1896
1
    Record *SubjectDecl = Aggregate->getValueAsDef("Subject");
1897
1898
    // Gather sub-classes of the aggregate subject that act as attribute
1899
    // subject rules.
1900
1
    std::vector<AttributeSubjectMatchRule> Rules;
1901
91
    for (const auto *D : DeclNodes) {
1902
91
      if (doesDeclDeriveFrom(D, SubjectDecl)) {
1903
67
        auto It = SubjectsToRules.find(D);
1904
67
        if (It == SubjectsToRules.end())
1905
50
          continue;
1906
17
        if (!It->second.isRule() || It->second.getRule().isSubRule())
1907
2
          continue; // Assume that the rule will be included as well.
1908
15
        Rules.push_back(It->second.getRule());
1909
15
      }
1910
91
    }
1911
1912
1
    bool Inserted =
1913
1
        SubjectsToRules
1914
1
            .try_emplace(SubjectDecl,
1915
1
                         RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
1916
1
            .second;
1917
1
    if (!Inserted) {
1918
0
      PrintFatalError("Attribute subject match rules should not represent"
1919
0
                      "same attribute subjects.");
1920
0
    }
1921
1
  }
1922
1
}
1923
1924
static PragmaClangAttributeSupport &
1925
1
getPragmaAttributeSupport(RecordKeeper &Records) {
1926
1
  static PragmaClangAttributeSupport Instance(Records);
1927
1
  return Instance;
1928
1
}
1929
1930
0
void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
1931
0
  OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
1932
0
  OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
1933
0
        "IsNegated) "
1934
0
     << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
1935
0
  OS << "#endif\n";
1936
0
  for (const auto &Rule : Rules) {
1937
0
    OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
1938
0
    OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
1939
0
       << Rule.isAbstractRule();
1940
0
    if (Rule.isSubRule())
1941
0
      OS << ", "
1942
0
         << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
1943
0
         << ", " << Rule.isNegatedSubRule();
1944
0
    OS << ")\n";
1945
0
  }
1946
0
  OS << "#undef ATTR_MATCH_SUB_RULE\n";
1947
0
}
1948
1949
bool PragmaClangAttributeSupport::isAttributedSupported(
1950
301
    const Record &Attribute) {
1951
  // If the attribute explicitly specified whether to support #pragma clang
1952
  // attribute, use that setting.
1953
301
  bool Unset;
1954
301
  bool SpecifiedResult =
1955
301
    Attribute.getValueAsBitOrUnset("PragmaAttributeSupport", Unset);
1956
301
  if (!Unset)
1957
6
    return SpecifiedResult;
1958
1959
  // Opt-out rules:
1960
  // An attribute requires delayed parsing (LateParsed is on)
1961
295
  if (Attribute.getValueAsBit("LateParsed"))
1962
16
    return false;
1963
  // An attribute has no GNU/CXX11 spelling
1964
279
  if (!hasGNUorCXX11Spelling(Attribute))
1965
30
    return false;
1966
  // An attribute subject list has a subject that isn't covered by one of the
1967
  // subject match rules or has no subjects at all.
1968
249
  if (Attribute.isValueUnset("Subjects"))
1969
67
    return false;
1970
182
  const Record *SubjectObj = Attribute.getValueAsDef("Subjects");
1971
182
  std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
1972
182
  if (Subjects.empty())
1973
0
    return false;
1974
256
  
for (const auto *Subject : Subjects)182
{
1975
256
    if (SubjectsToRules.find(Subject) == SubjectsToRules.end())
1976
17
      return false;
1977
256
  }
1978
165
  return true;
1979
182
}
1980
1981
0
static std::string GenerateTestExpression(ArrayRef<Record *> LangOpts) {
1982
0
  std::string Test;
1983
1984
0
  for (auto *E : LangOpts) {
1985
0
    if (!Test.empty())
1986
0
      Test += " || ";
1987
1988
0
    const StringRef Code = E->getValueAsString("CustomCode");
1989
0
    if (!Code.empty()) {
1990
0
      Test += "(";
1991
0
      Test += Code;
1992
0
      Test += ")";
1993
0
      if (!E->getValueAsString("Name").empty()) {
1994
0
        PrintWarning(
1995
0
            E->getLoc(),
1996
0
            "non-empty 'Name' field ignored because 'CustomCode' was supplied");
1997
0
      }
1998
0
    } else {
1999
0
      Test += "LangOpts.";
2000
0
      Test += E->getValueAsString("Name");
2001
0
    }
2002
0
  }
2003
2004
0
  if (Test.empty())
2005
0
    return "true";
2006
2007
0
  return Test;
2008
0
}
2009
2010
void
2011
PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
2012
0
                                                      raw_ostream &OS) {
2013
0
  if (!isAttributedSupported(Attr) || Attr.isValueUnset("Subjects"))
2014
0
    return;
2015
  // Generate a function that constructs a set of matching rules that describe
2016
  // to which declarations the attribute should apply to.
2017
0
  OS << "void getPragmaAttributeMatchRules("
2018
0
     << "llvm::SmallVectorImpl<std::pair<"
2019
0
     << AttributeSubjectMatchRule::EnumName
2020
0
     << ", bool>> &MatchRules, const LangOptions &LangOpts) const override {\n";
2021
0
  const Record *SubjectObj = Attr.getValueAsDef("Subjects");
2022
0
  std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
2023
0
  for (const auto *Subject : Subjects) {
2024
0
    auto It = SubjectsToRules.find(Subject);
2025
0
    assert(It != SubjectsToRules.end() &&
2026
0
           "This attribute is unsupported by #pragma clang attribute");
2027
0
    for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
2028
      // The rule might be language specific, so only subtract it from the given
2029
      // rules if the specific language options are specified.
2030
0
      std::vector<Record *> LangOpts = Rule.getLangOpts();
2031
0
      OS << "  MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
2032
0
         << ", /*IsSupported=*/" << GenerateTestExpression(LangOpts)
2033
0
         << "));\n";
2034
0
    }
2035
0
  }
2036
0
  OS << "}\n\n";
2037
0
}
2038
2039
0
void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
2040
  // Generate routines that check the names of sub-rules.
2041
0
  OS << "Optional<attr::SubjectMatchRule> "
2042
0
        "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
2043
0
  OS << "  return None;\n";
2044
0
  OS << "}\n\n";
2045
2046
0
  std::map<const Record *, std::vector<AttributeSubjectMatchRule>>
2047
0
      SubMatchRules;
2048
0
  for (const auto &Rule : Rules) {
2049
0
    if (!Rule.isSubRule())
2050
0
      continue;
2051
0
    SubMatchRules[Rule.MetaSubject].push_back(Rule);
2052
0
  }
2053
2054
0
  for (const auto &SubMatchRule : SubMatchRules) {
2055
0
    OS << "Optional<attr::SubjectMatchRule> isAttributeSubjectMatchSubRuleFor_"
2056
0
       << SubMatchRule.first->getValueAsString("Name")
2057
0
       << "(StringRef Name, bool IsUnless) {\n";
2058
0
    OS << "  if (IsUnless)\n";
2059
0
    OS << "    return "
2060
0
          "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
2061
0
    for (const auto &Rule : SubMatchRule.second) {
2062
0
      if (Rule.isNegatedSubRule())
2063
0
        OS << "    Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2064
0
           << ").\n";
2065
0
    }
2066
0
    OS << "    Default(None);\n";
2067
0
    OS << "  return "
2068
0
          "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
2069
0
    for (const auto &Rule : SubMatchRule.second) {
2070
0
      if (!Rule.isNegatedSubRule())
2071
0
        OS << "  Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2072
0
           << ").\n";
2073
0
    }
2074
0
    OS << "  Default(None);\n";
2075
0
    OS << "}\n\n";
2076
0
  }
2077
2078
  // Generate the function that checks for the top-level rules.
2079
0
  OS << "std::pair<Optional<attr::SubjectMatchRule>, "
2080
0
        "Optional<attr::SubjectMatchRule> (*)(StringRef, "
2081
0
        "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
2082
0
  OS << "  return "
2083
0
        "llvm::StringSwitch<std::pair<Optional<attr::SubjectMatchRule>, "
2084
0
        "Optional<attr::SubjectMatchRule> (*) (StringRef, "
2085
0
        "bool)>>(Name).\n";
2086
0
  for (const auto &Rule : Rules) {
2087
0
    if (Rule.isSubRule())
2088
0
      continue;
2089
0
    std::string SubRuleFunction;
2090
0
    if (SubMatchRules.count(Rule.MetaSubject))
2091
0
      SubRuleFunction =
2092
0
          ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
2093
0
    else
2094
0
      SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
2095
0
    OS << "  Case(\"" << Rule.getName() << "\", std::make_pair("
2096
0
       << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
2097
0
  }
2098
0
  OS << "  Default(std::make_pair(None, "
2099
0
        "defaultIsAttributeSubjectMatchSubRuleFor));\n";
2100
0
  OS << "}\n\n";
2101
2102
  // Generate the function that checks for the submatch rules.
2103
0
  OS << "const char *validAttributeSubjectMatchSubRules("
2104
0
     << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
2105
0
  OS << "  switch (Rule) {\n";
2106
0
  for (const auto &SubMatchRule : SubMatchRules) {
2107
0
    OS << "  case "
2108
0
       << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
2109
0
       << ":\n";
2110
0
    OS << "  return \"'";
2111
0
    bool IsFirst = true;
2112
0
    for (const auto &Rule : SubMatchRule.second) {
2113
0
      if (!IsFirst)
2114
0
        OS << ", '";
2115
0
      IsFirst = false;
2116
0
      if (Rule.isNegatedSubRule())
2117
0
        OS << "unless(";
2118
0
      OS << Rule.getName();
2119
0
      if (Rule.isNegatedSubRule())
2120
0
        OS << ')';
2121
0
      OS << "'";
2122
0
    }
2123
0
    OS << "\";\n";
2124
0
  }
2125
0
  OS << "  default: return nullptr;\n";
2126
0
  OS << "  }\n";
2127
0
  OS << "}\n\n";
2128
0
}
2129
2130
template <typename Fn>
2131
0
static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
2132
0
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2133
0
  SmallDenseSet<StringRef, 8> Seen;
2134
0
  for (const FlattenedSpelling &S : Spellings) {
2135
0
    if (Seen.insert(S.name()).second)
2136
0
      F(S);
2137
0
  }
2138
0
}
Unexecuted instantiation: ClangAttrEmitter.cpp:void forEachUniqueSpelling<emitClangAttrArgContextList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_6>(llvm::Record const&, emitClangAttrArgContextList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_6&&)
Unexecuted instantiation: ClangAttrEmitter.cpp:void forEachUniqueSpelling<emitClangAttrIdentifierArgList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_8>(llvm::Record const&, emitClangAttrIdentifierArgList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_8&&)
Unexecuted instantiation: ClangAttrEmitter.cpp:void forEachUniqueSpelling<emitClangAttrVariadicIdentifierArgList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_7>(llvm::Record const&, emitClangAttrVariadicIdentifierArgList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_7&&)
Unexecuted instantiation: ClangAttrEmitter.cpp:void forEachUniqueSpelling<emitClangAttrThisIsaIdentifierArgList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_9>(llvm::Record const&, emitClangAttrThisIsaIdentifierArgList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_9&&)
Unexecuted instantiation: ClangAttrEmitter.cpp:void forEachUniqueSpelling<emitClangAttrTypeArgList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_5>(llvm::Record const&, emitClangAttrTypeArgList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_5&&)
2139
2140
/// Emits the first-argument-is-type property for attributes.
2141
0
static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
2142
0
  OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
2143
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2144
2145
0
  for (const auto *Attr : Attrs) {
2146
    // Determine whether the first argument is a type.
2147
0
    std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
2148
0
    if (Args.empty())
2149
0
      continue;
2150
2151
0
    if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
2152
0
      continue;
2153
2154
    // All these spellings take a single type argument.
2155
0
    forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2156
0
      OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2157
0
    });
2158
0
  }
2159
0
  OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
2160
0
}
2161
2162
/// Emits the parse-arguments-in-unevaluated-context property for
2163
/// attributes.
2164
0
static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
2165
0
  OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
2166
0
  ParsedAttrMap Attrs = getParsedAttrList(Records);
2167
0
  for (const auto &I : Attrs) {
2168
0
    const Record &Attr = *I.second;
2169
2170
0
    if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
2171
0
      continue;
2172
2173
    // All these spellings take are parsed unevaluated.
2174
0
    forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
2175
0
      OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2176
0
    });
2177
0
  }
2178
0
  OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
2179
0
}
2180
2181
0
static bool isIdentifierArgument(Record *Arg) {
2182
0
  return !Arg->getSuperClasses().empty() &&
2183
0
    llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
2184
0
    .Case("IdentifierArgument", true)
2185
0
    .Case("EnumArgument", true)
2186
0
    .Case("VariadicEnumArgument", true)
2187
0
    .Default(false);
2188
0
}
2189
2190
0
static bool isVariadicIdentifierArgument(Record *Arg) {
2191
0
  return !Arg->getSuperClasses().empty() &&
2192
0
         llvm::StringSwitch<bool>(
2193
0
             Arg->getSuperClasses().back().first->getName())
2194
0
             .Case("VariadicIdentifierArgument", true)
2195
0
             .Case("VariadicParamOrParamIdxArgument", true)
2196
0
             .Default(false);
2197
0
}
2198
2199
static void emitClangAttrVariadicIdentifierArgList(RecordKeeper &Records,
2200
0
                                                   raw_ostream &OS) {
2201
0
  OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
2202
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2203
0
  for (const auto *A : Attrs) {
2204
    // Determine whether the first argument is a variadic identifier.
2205
0
    std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
2206
0
    if (Args.empty() || !isVariadicIdentifierArgument(Args[0]))
2207
0
      continue;
2208
2209
    // All these spellings take an identifier argument.
2210
0
    forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
2211
0
      OS << ".Case(\"" << S.name() << "\", "
2212
0
         << "true"
2213
0
         << ")\n";
2214
0
    });
2215
0
  }
2216
0
  OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
2217
0
}
2218
2219
// Emits the first-argument-is-identifier property for attributes.
2220
0
static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
2221
0
  OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
2222
0
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2223
2224
0
  for (const auto *Attr : Attrs) {
2225
    // Determine whether the first argument is an identifier.
2226
0
    std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
2227
0
    if (Args.empty() || !isIdentifierArgument(Args[0]))
2228
0
      continue;
2229
2230
    // All these spellings take an identifier argument.
2231
0
    forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2232
0
      OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2233
0
    });
2234
0
  }
2235
0
  OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
2236
0
}
2237
2238
0
static bool keywordThisIsaIdentifierInArgument(const Record *Arg) {
2239
0
  return !Arg->getSuperClasses().empty() &&
2240
0
         llvm::StringSwitch<bool>(
2241
0
             Arg->getSuperClasses().back().first->getName())
2242
0
             .Case("VariadicParamOrParamIdxArgument", true)
2243
0
             .Default(false);
2244
0
}
2245
2246
static void emitClangAttrThisIsaIdentifierArgList(RecordKeeper &Records,
2247
0
                                                  raw_ostream &OS) {
2248
0
  OS << "#if defined(CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST)\n";
2249
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2250
0
  for (const auto *A : Attrs) {
2251
    // Determine whether the first argument is a variadic identifier.
2252
0
    std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
2253
0
    if (Args.empty() || !keywordThisIsaIdentifierInArgument(Args[0]))
2254
0
      continue;
2255
2256
    // All these spellings take an identifier argument.
2257
0
    forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
2258
0
      OS << ".Case(\"" << S.name() << "\", "
2259
0
         << "true"
2260
0
         << ")\n";
2261
0
    });
2262
0
  }
2263
0
  OS << "#endif // CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST\n\n";
2264
0
}
2265
2266
static void emitAttributes(RecordKeeper &Records, raw_ostream &OS,
2267
0
                           bool Header) {
2268
0
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2269
0
  ParsedAttrMap AttrMap = getParsedAttrList(Records);
2270
2271
0
  for (const auto *Attr : Attrs) {
2272
0
    const Record &R = *Attr;
2273
2274
    // FIXME: Currently, documentation is generated as-needed due to the fact
2275
    // that there is no way to allow a generated project "reach into" the docs
2276
    // directory (for instance, it may be an out-of-tree build). However, we want
2277
    // to ensure that every attribute has a Documentation field, and produce an
2278
    // error if it has been neglected. Otherwise, the on-demand generation which
2279
    // happens server-side will fail. This code is ensuring that functionality,
2280
    // even though this Emitter doesn't technically need the documentation.
2281
    // When attribute documentation can be generated as part of the build
2282
    // itself, this code can be removed.
2283
0
    (void)R.getValueAsListOfDefs("Documentation");
2284
2285
0
    if (!R.getValueAsBit("ASTNode"))
2286
0
      continue;
2287
2288
0
    ArrayRef<std::pair<Record *, SMRange>> Supers = R.getSuperClasses();
2289
0
    assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
2290
0
    std::string SuperName;
2291
0
    bool Inheritable = false;
2292
0
    for (const auto &Super : llvm::reverse(Supers)) {
2293
0
      const Record *R = Super.first;
2294
0
      if (R->getName() != "TargetSpecificAttr" &&
2295
0
          R->getName() != "DeclOrTypeAttr" && SuperName.empty())
2296
0
        SuperName = std::string(R->getName());
2297
0
      if (R->getName() == "InheritableAttr")
2298
0
        Inheritable = true;
2299
0
    }
2300
2301
0
    if (Header)
2302
0
      OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
2303
0
    else
2304
0
      OS << "\n// " << R.getName() << "Attr implementation\n\n";
2305
2306
0
    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2307
0
    std::vector<std::unique_ptr<Argument>> Args;
2308
0
    Args.reserve(ArgRecords.size());
2309
2310
0
    bool HasOptArg = false;
2311
0
    bool HasFakeArg = false;
2312
0
    for (const auto *ArgRecord : ArgRecords) {
2313
0
      Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2314
0
      if (Header) {
2315
0
        Args.back()->writeDeclarations(OS);
2316
0
        OS << "\n\n";
2317
0
      }
2318
2319
      // For these purposes, fake takes priority over optional.
2320
0
      if (Args.back()->isFake()) {
2321
0
        HasFakeArg = true;
2322
0
      } else if (Args.back()->isOptional()) {
2323
0
        HasOptArg = true;
2324
0
      }
2325
0
    }
2326
2327
0
    if (Header)
2328
0
      OS << "public:\n";
2329
2330
0
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2331
2332
    // If there are zero or one spellings, all spelling-related functionality
2333
    // can be elided. If all of the spellings share the same name, the spelling
2334
    // functionality can also be elided.
2335
0
    bool ElideSpelling = (Spellings.size() <= 1) ||
2336
0
                         SpellingNamesAreCommon(Spellings);
2337
2338
    // This maps spelling index values to semantic Spelling enumerants.
2339
0
    SemanticSpellingMap SemanticToSyntacticMap;
2340
2341
0
    std::string SpellingEnum;
2342
0
    if (Spellings.size() > 1)
2343
0
      SpellingEnum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2344
0
    if (Header)
2345
0
      OS << SpellingEnum;
2346
2347
0
    const auto &ParsedAttrSpellingItr = llvm::find_if(
2348
0
        AttrMap, [R](const std::pair<std::string, const Record *> &P) {
2349
0
          return &R == P.second;
2350
0
        });
2351
2352
    // Emit CreateImplicit factory methods.
2353
0
    auto emitCreate = [&](bool Implicit, bool emitFake) {
2354
0
      if (Header)
2355
0
        OS << "  static ";
2356
0
      OS << R.getName() << "Attr *";
2357
0
      if (!Header)
2358
0
        OS << R.getName() << "Attr::";
2359
0
      OS << "Create";
2360
0
      if (Implicit)
2361
0
        OS << "Implicit";
2362
0
      OS << "(";
2363
0
      OS << "ASTContext &Ctx";
2364
0
      for (auto const &ai : Args) {
2365
0
        if (ai->isFake() && !emitFake) continue;
2366
0
        OS << ", ";
2367
0
        ai->writeCtorParameters(OS);
2368
0
      }
2369
0
      OS << ", const AttributeCommonInfo &CommonInfo";
2370
0
      if (Header)
2371
0
        OS << " = {SourceRange{}}";
2372
0
      OS << ")";
2373
0
      if (Header) {
2374
0
        OS << ";\n";
2375
0
        return;
2376
0
      }
2377
2378
0
      OS << " {\n";
2379
0
      OS << "  auto *A = new (Ctx) " << R.getName();
2380
0
      OS << "Attr(Ctx, CommonInfo";
2381
0
      for (auto const &ai : Args) {
2382
0
        if (ai->isFake() && !emitFake) continue;
2383
0
        OS << ", ";
2384
0
        ai->writeImplicitCtorArgs(OS);
2385
0
      }
2386
0
      OS << ");\n";
2387
0
      if (Implicit) {
2388
0
        OS << "  A->setImplicit(true);\n";
2389
0
      }
2390
0
      if (Implicit || ElideSpelling) {
2391
0
        OS << "  if (!A->isAttributeSpellingListCalculated() && "
2392
0
              "!A->getAttrName())\n";
2393
0
        OS << "    A->setAttributeSpellingListIndex(0);\n";
2394
0
      }
2395
0
      OS << "  return A;\n}\n\n";
2396
0
    };
2397
2398
0
    auto emitCreateNoCI = [&](bool Implicit, bool emitFake) {
2399
0
      if (Header)
2400
0
        OS << "  static ";
2401
0
      OS << R.getName() << "Attr *";
2402
0
      if (!Header)
2403
0
        OS << R.getName() << "Attr::";
2404
0
      OS << "Create";
2405
0
      if (Implicit)
2406
0
        OS << "Implicit";
2407
0
      OS << "(";
2408
0
      OS << "ASTContext &Ctx";
2409
0
      for (auto const &ai : Args) {
2410
0
        if (ai->isFake() && !emitFake) continue;
2411
0
        OS << ", ";
2412
0
        ai->writeCtorParameters(OS);
2413
0
      }
2414
0
      OS << ", SourceRange Range, AttributeCommonInfo::Syntax Syntax";
2415
0
      if (!ElideSpelling) {
2416
0
        OS << ", " << R.getName() << "Attr::Spelling S";
2417
0
        if (Header)
2418
0
          OS << " = static_cast<Spelling>(SpellingNotCalculated)";
2419
0
      }
2420
0
      OS << ")";
2421
0
      if (Header) {
2422
0
        OS << ";\n";
2423
0
        return;
2424
0
      }
2425
2426
0
      OS << " {\n";
2427
0
      OS << "  AttributeCommonInfo I(Range, ";
2428
2429
0
      if (ParsedAttrSpellingItr != std::end(AttrMap))
2430
0
        OS << "AT_" << ParsedAttrSpellingItr->first;
2431
0
      else
2432
0
        OS << "NoSemaHandlerAttribute";
2433
2434
0
      OS << ", Syntax";
2435
0
      if (!ElideSpelling)
2436
0
        OS << ", S";
2437
0
      OS << ");\n";
2438
0
      OS << "  return Create";
2439
0
      if (Implicit)
2440
0
        OS << "Implicit";
2441
0
      OS << "(Ctx";
2442
0
      for (auto const &ai : Args) {
2443
0
        if (ai->isFake() && !emitFake) continue;
2444
0
        OS << ", ";
2445
0
        ai->writeImplicitCtorArgs(OS);
2446
0
      }
2447
0
      OS << ", I);\n";
2448
0
      OS << "}\n\n";
2449
0
    };
2450
2451
0
    auto emitCreates = [&](bool emitFake) {
2452
0
      emitCreate(true, emitFake);
2453
0
      emitCreate(false, emitFake);
2454
0
      emitCreateNoCI(true, emitFake);
2455
0
      emitCreateNoCI(false, emitFake);
2456
0
    };
2457
2458
0
    if (Header)
2459
0
      OS << "  // Factory methods\n";
2460
2461
    // Emit a CreateImplicit that takes all the arguments.
2462
0
    emitCreates(true);
2463
2464
    // Emit a CreateImplicit that takes all the non-fake arguments.
2465
0
    if (HasFakeArg)
2466
0
      emitCreates(false);
2467
2468
    // Emit constructors.
2469
0
    auto emitCtor = [&](bool emitOpt, bool emitFake) {
2470
0
      auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
2471
0
        if (arg->isFake()) return emitFake;
2472
0
        if (arg->isOptional()) return emitOpt;
2473
0
        return true;
2474
0
      };
2475
0
      if (Header)
2476
0
        OS << "  ";
2477
0
      else
2478
0
        OS << R.getName() << "Attr::";
2479
0
      OS << R.getName()
2480
0
         << "Attr(ASTContext &Ctx, const AttributeCommonInfo &CommonInfo";
2481
0
      OS << '\n';
2482
0
      for (auto const &ai : Args) {
2483
0
        if (!shouldEmitArg(ai)) continue;
2484
0
        OS << "              , ";
2485
0
        ai->writeCtorParameters(OS);
2486
0
        OS << "\n";
2487
0
      }
2488
2489
0
      OS << "             )";
2490
0
      if (Header) {
2491
0
        OS << ";\n";
2492
0
        return;
2493
0
      }
2494
0
      OS << "\n  : " << SuperName << "(Ctx, CommonInfo, ";
2495
0
      OS << "attr::" << R.getName() << ", "
2496
0
         << (R.getValueAsBit("LateParsed") ? "true" : "false");
2497
0
      if (Inheritable) {
2498
0
        OS << ", "
2499
0
           << (R.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
2500
0
                                                              : "false");
2501
0
      }
2502
0
      OS << ")\n";
2503
2504
0
      for (auto const &ai : Args) {
2505
0
        OS << "              , ";
2506
0
        if (!shouldEmitArg(ai)) {
2507
0
          ai->writeCtorDefaultInitializers(OS);
2508
0
        } else {
2509
0
          ai->writeCtorInitializers(OS);
2510
0
        }
2511
0
        OS << "\n";
2512
0
      }
2513
2514
0
      OS << "  {\n";
2515
2516
0
      for (auto const &ai : Args) {
2517
0
        if (!shouldEmitArg(ai)) continue;
2518
0
        ai->writeCtorBody(OS);
2519
0
      }
2520
0
      OS << "}\n\n";
2521
0
    };
2522
2523
0
    if (Header)
2524
0
      OS << "\n  // Constructors\n";
2525
2526
    // Emit a constructor that includes all the arguments.
2527
    // This is necessary for cloning.
2528
0
    emitCtor(true, true);
2529
2530
    // Emit a constructor that takes all the non-fake arguments.
2531
0
    if (HasFakeArg)
2532
0
      emitCtor(true, false);
2533
2534
    // Emit a constructor that takes all the non-fake, non-optional arguments.
2535
0
    if (HasOptArg)
2536
0
      emitCtor(false, false);
2537
2538
0
    if (Header) {
2539
0
      OS << '\n';
2540
0
      OS << "  " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
2541
0
      OS << "  void printPretty(raw_ostream &OS,\n"
2542
0
         << "                   const PrintingPolicy &Policy) const;\n";
2543
0
      OS << "  const char *getSpelling() const;\n";
2544
0
    }
2545
2546
0
    if (!ElideSpelling) {
2547
0
      assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
2548
0
      if (Header)
2549
0
        OS << "  Spelling getSemanticSpelling() const;\n";
2550
0
      else {
2551
0
        OS << R.getName() << "Attr::Spelling " << R.getName()
2552
0
           << "Attr::getSemanticSpelling() const {\n";
2553
0
        WriteSemanticSpellingSwitch("getAttributeSpellingListIndex()",
2554
0
                                    SemanticToSyntacticMap, OS);
2555
0
        OS << "}\n";
2556
0
      }
2557
0
    }
2558
2559
0
    if (Header)
2560
0
      writeAttrAccessorDefinition(R, OS);
2561
2562
0
    for (auto const &ai : Args) {
2563
0
      if (Header) {
2564
0
        ai->writeAccessors(OS);
2565
0
      } else {
2566
0
        ai->writeAccessorDefinitions(OS);
2567
0
      }
2568
0
      OS << "\n\n";
2569
2570
      // Don't write conversion routines for fake arguments.
2571
0
      if (ai->isFake()) continue;
2572
2573
0
      if (ai->isEnumArg())
2574
0
        static_cast<const EnumArgument *>(ai.get())->writeConversion(OS,
2575
0
                                                                     Header);
2576
0
      else if (ai->isVariadicEnumArg())
2577
0
        static_cast<const VariadicEnumArgument *>(ai.get())->writeConversion(
2578
0
            OS, Header);
2579
0
    }
2580
2581
0
    if (Header) {
2582
0
      OS << R.getValueAsString("AdditionalMembers");
2583
0
      OS << "\n\n";
2584
2585
0
      OS << "  static bool classof(const Attr *A) { return A->getKind() == "
2586
0
         << "attr::" << R.getName() << "; }\n";
2587
2588
0
      OS << "};\n\n";
2589
0
    } else {
2590
0
      OS << R.getName() << "Attr *" << R.getName()
2591
0
         << "Attr::clone(ASTContext &C) const {\n";
2592
0
      OS << "  auto *A = new (C) " << R.getName() << "Attr(C, *this";
2593
0
      for (auto const &ai : Args) {
2594
0
        OS << ", ";
2595
0
        ai->writeCloneArgs(OS);
2596
0
      }
2597
0
      OS << ");\n";
2598
0
      OS << "  A->Inherited = Inherited;\n";
2599
0
      OS << "  A->IsPackExpansion = IsPackExpansion;\n";
2600
0
      OS << "  A->setImplicit(Implicit);\n";
2601
0
      OS << "  return A;\n}\n\n";
2602
2603
0
      writePrettyPrintFunction(R, Args, OS);
2604
0
      writeGetSpellingFunction(R, OS);
2605
0
    }
2606
0
  }
2607
0
}
2608
// Emits the class definitions for attributes.
2609
0
void clang::EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
2610
0
  emitSourceFileHeader("Attribute classes' definitions", OS);
2611
2612
0
  OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
2613
0
  OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
2614
2615
0
  emitAttributes(Records, OS, true);
2616
2617
0
  OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
2618
0
}
2619
2620
// Emits the class method definitions for attributes.
2621
0
void clang::EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2622
0
  emitSourceFileHeader("Attribute classes' member function definitions", OS);
2623
2624
0
  emitAttributes(Records, OS, false);
2625
2626
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2627
2628
  // Instead of relying on virtual dispatch we just create a huge dispatch
2629
  // switch. This is both smaller and faster than virtual functions.
2630
0
  auto EmitFunc = [&](const char *Method) {
2631
0
    OS << "  switch (getKind()) {\n";
2632
0
    for (const auto *Attr : Attrs) {
2633
0
      const Record &R = *Attr;
2634
0
      if (!R.getValueAsBit("ASTNode"))
2635
0
        continue;
2636
2637
0
      OS << "  case attr::" << R.getName() << ":\n";
2638
0
      OS << "    return cast<" << R.getName() << "Attr>(this)->" << Method
2639
0
         << ";\n";
2640
0
    }
2641
0
    OS << "  }\n";
2642
0
    OS << "  llvm_unreachable(\"Unexpected attribute kind!\");\n";
2643
0
    OS << "}\n\n";
2644
0
  };
2645
2646
0
  OS << "const char *Attr::getSpelling() const {\n";
2647
0
  EmitFunc("getSpelling()");
2648
2649
0
  OS << "Attr *Attr::clone(ASTContext &C) const {\n";
2650
0
  EmitFunc("clone(C)");
2651
2652
0
  OS << "void Attr::printPretty(raw_ostream &OS, "
2653
0
        "const PrintingPolicy &Policy) const {\n";
2654
0
  EmitFunc("printPretty(OS, Policy)");
2655
0
}
2656
2657
static void emitAttrList(raw_ostream &OS, StringRef Class,
2658
0
                         const std::vector<Record*> &AttrList) {
2659
0
  for (auto Cur : AttrList) {
2660
0
    OS << Class << "(" << Cur->getName() << ")\n";
2661
0
  }
2662
0
}
2663
2664
// Determines if an attribute has a Pragma spelling.
2665
0
static bool AttrHasPragmaSpelling(const Record *R) {
2666
0
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
2667
0
  return llvm::find_if(Spellings, [](const FlattenedSpelling &S) {
2668
0
           return S.variety() == "Pragma";
2669
0
         }) != Spellings.end();
2670
0
}
2671
2672
namespace {
2673
2674
  struct AttrClassDescriptor {
2675
    const char * const MacroName;
2676
    const char * const TableGenName;
2677
  };
2678
2679
} // end anonymous namespace
2680
2681
static const AttrClassDescriptor AttrClassDescriptors[] = {
2682
  { "ATTR", "Attr" },
2683
  { "TYPE_ATTR", "TypeAttr" },
2684
  { "STMT_ATTR", "StmtAttr" },
2685
  { "INHERITABLE_ATTR", "InheritableAttr" },
2686
  { "DECL_OR_TYPE_ATTR", "DeclOrTypeAttr" },
2687
  { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
2688
  { "PARAMETER_ABI_ATTR", "ParameterABIAttr" }
2689
};
2690
2691
static void emitDefaultDefine(raw_ostream &OS, StringRef name,
2692
0
                              const char *superName) {
2693
0
  OS << "#ifndef " << name << "\n";
2694
0
  OS << "#define " << name << "(NAME) ";
2695
0
  if (superName) OS << superName << "(NAME)";
2696
0
  OS << "\n#endif\n\n";
2697
0
}
2698
2699
namespace {
2700
2701
  /// A class of attributes.
2702
  struct AttrClass {
2703
    const AttrClassDescriptor &Descriptor;
2704
    Record *TheRecord;
2705
    AttrClass *SuperClass = nullptr;
2706
    std::vector<AttrClass*> SubClasses;
2707
    std::vector<Record*> Attrs;
2708
2709
    AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
2710
0
      : Descriptor(Descriptor), TheRecord(R) {}
2711
2712
0
    void emitDefaultDefines(raw_ostream &OS) const {
2713
      // Default the macro unless this is a root class (i.e. Attr).
2714
0
      if (SuperClass) {
2715
0
        emitDefaultDefine(OS, Descriptor.MacroName,
2716
0
                          SuperClass->Descriptor.MacroName);
2717
0
      }
2718
0
    }
2719
2720
0
    void emitUndefs(raw_ostream &OS) const {
2721
0
      OS << "#undef " << Descriptor.MacroName << "\n";
2722
0
    }
2723
2724
0
    void emitAttrList(raw_ostream &OS) const {
2725
0
      for (auto SubClass : SubClasses) {
2726
0
        SubClass->emitAttrList(OS);
2727
0
      }
2728
2729
0
      ::emitAttrList(OS, Descriptor.MacroName, Attrs);
2730
0
    }
2731
2732
0
    void classifyAttrOnRoot(Record *Attr) {
2733
0
      bool result = classifyAttr(Attr);
2734
0
      assert(result && "failed to classify on root"); (void) result;
2735
0
    }
2736
2737
0
    void emitAttrRange(raw_ostream &OS) const {
2738
0
      OS << "ATTR_RANGE(" << Descriptor.TableGenName
2739
0
         << ", " << getFirstAttr()->getName()
2740
0
         << ", " << getLastAttr()->getName() << ")\n";
2741
0
    }
2742
2743
  private:
2744
0
    bool classifyAttr(Record *Attr) {
2745
      // Check all the subclasses.
2746
0
      for (auto SubClass : SubClasses) {
2747
0
        if (SubClass->classifyAttr(Attr))
2748
0
          return true;
2749
0
      }
2750
2751
      // It's not more specific than this class, but it might still belong here.
2752
0
      if (Attr->isSubClassOf(TheRecord)) {
2753
0
        Attrs.push_back(Attr);
2754
0
        return true;
2755
0
      }
2756
2757
0
      return false;
2758
0
    }
2759
2760
0
    Record *getFirstAttr() const {
2761
0
      if (!SubClasses.empty())
2762
0
        return SubClasses.front()->getFirstAttr();
2763
0
      return Attrs.front();
2764
0
    }
2765
2766
0
    Record *getLastAttr() const {
2767
0
      if (!Attrs.empty())
2768
0
        return Attrs.back();
2769
0
      return SubClasses.back()->getLastAttr();
2770
0
    }
2771
  };
2772
2773
  /// The entire hierarchy of attribute classes.
2774
  class AttrClassHierarchy {
2775
    std::vector<std::unique_ptr<AttrClass>> Classes;
2776
2777
  public:
2778
0
    AttrClassHierarchy(RecordKeeper &Records) {
2779
      // Find records for all the classes.
2780
0
      for (auto &Descriptor : AttrClassDescriptors) {
2781
0
        Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
2782
0
        AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
2783
0
        Classes.emplace_back(Class);
2784
0
      }
2785
2786
      // Link up the hierarchy.
2787
0
      for (auto &Class : Classes) {
2788
0
        if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
2789
0
          Class->SuperClass = SuperClass;
2790
0
          SuperClass->SubClasses.push_back(Class.get());
2791
0
        }
2792
0
      }
2793
2794
0
#ifndef NDEBUG
2795
0
      for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
2796
0
        assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
2797
0
               "only the first class should be a root class!");
2798
0
      }
2799
0
#endif
2800
0
    }
2801
2802
0
    void emitDefaultDefines(raw_ostream &OS) const {
2803
0
      for (auto &Class : Classes) {
2804
0
        Class->emitDefaultDefines(OS);
2805
0
      }
2806
0
    }
2807
2808
0
    void emitUndefs(raw_ostream &OS) const {
2809
0
      for (auto &Class : Classes) {
2810
0
        Class->emitUndefs(OS);
2811
0
      }
2812
0
    }
2813
2814
0
    void emitAttrLists(raw_ostream &OS) const {
2815
      // Just start from the root class.
2816
0
      Classes[0]->emitAttrList(OS);
2817
0
    }
2818
2819
0
    void emitAttrRanges(raw_ostream &OS) const {
2820
0
      for (auto &Class : Classes)
2821
0
        Class->emitAttrRange(OS);
2822
0
    }
2823
2824
0
    void classifyAttr(Record *Attr) {
2825
      // Add the attribute to the root class.
2826
0
      Classes[0]->classifyAttrOnRoot(Attr);
2827
0
    }
2828
2829
  private:
2830
0
    AttrClass *findClassByRecord(Record *R) const {
2831
0
      for (auto &Class : Classes) {
2832
0
        if (Class->TheRecord == R)
2833
0
          return Class.get();
2834
0
      }
2835
0
      return nullptr;
2836
0
    }
2837
2838
0
    AttrClass *findSuperClass(Record *R) const {
2839
      // TableGen flattens the superclass list, so we just need to walk it
2840
      // in reverse.
2841
0
      auto SuperClasses = R->getSuperClasses();
2842
0
      for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
2843
0
        auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
2844
0
        if (SuperClass) return SuperClass;
2845
0
      }
2846
0
      return nullptr;
2847
0
    }
2848
  };
2849
2850
} // end anonymous namespace
2851
2852
namespace clang {
2853
2854
// Emits the enumeration list for attributes.
2855
0
void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
2856
0
  emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
2857
2858
0
  AttrClassHierarchy Hierarchy(Records);
2859
2860
  // Add defaulting macro definitions.
2861
0
  Hierarchy.emitDefaultDefines(OS);
2862
0
  emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
2863
2864
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2865
0
  std::vector<Record *> PragmaAttrs;
2866
0
  for (auto *Attr : Attrs) {
2867
0
    if (!Attr->getValueAsBit("ASTNode"))
2868
0
      continue;
2869
2870
    // Add the attribute to the ad-hoc groups.
2871
0
    if (AttrHasPragmaSpelling(Attr))
2872
0
      PragmaAttrs.push_back(Attr);
2873
2874
    // Place it in the hierarchy.
2875
0
    Hierarchy.classifyAttr(Attr);
2876
0
  }
2877
2878
  // Emit the main attribute list.
2879
0
  Hierarchy.emitAttrLists(OS);
2880
2881
  // Emit the ad hoc groups.
2882
0
  emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
2883
2884
  // Emit the attribute ranges.
2885
0
  OS << "#ifdef ATTR_RANGE\n";
2886
0
  Hierarchy.emitAttrRanges(OS);
2887
0
  OS << "#undef ATTR_RANGE\n";
2888
0
  OS << "#endif\n";
2889
2890
0
  Hierarchy.emitUndefs(OS);
2891
0
  OS << "#undef PRAGMA_SPELLING_ATTR\n";
2892
0
}
2893
2894
// Emits the enumeration list for attributes.
2895
0
void EmitClangAttrSubjectMatchRuleList(RecordKeeper &Records, raw_ostream &OS) {
2896
0
  emitSourceFileHeader(
2897
0
      "List of all attribute subject matching rules that Clang recognizes", OS);
2898
0
  PragmaClangAttributeSupport &PragmaAttributeSupport =
2899
0
      getPragmaAttributeSupport(Records);
2900
0
  emitDefaultDefine(OS, "ATTR_MATCH_RULE", nullptr);
2901
0
  PragmaAttributeSupport.emitMatchRuleList(OS);
2902
0
  OS << "#undef ATTR_MATCH_RULE\n";
2903
0
}
2904
2905
// Emits the code to read an attribute from a precompiled header.
2906
0
void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
2907
0
  emitSourceFileHeader("Attribute deserialization code", OS);
2908
2909
0
  Record *InhClass = Records.getClass("InheritableAttr");
2910
0
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
2911
0
                       ArgRecords;
2912
0
  std::vector<std::unique_ptr<Argument>> Args;
2913
2914
0
  OS << "  switch (Kind) {\n";
2915
0
  for (const auto *Attr : Attrs) {
2916
0
    const Record &R = *Attr;
2917
0
    if (!R.getValueAsBit("ASTNode"))
2918
0
      continue;
2919
2920
0
    OS << "  case attr::" << R.getName() << ": {\n";
2921
0
    if (R.isSubClassOf(InhClass))
2922
0
      OS << "    bool isInherited = Record.readInt();\n";
2923
0
    OS << "    bool isImplicit = Record.readInt();\n";
2924
0
    OS << "    bool isPackExpansion = Record.readInt();\n";
2925
0
    ArgRecords = R.getValueAsListOfDefs("Args");
2926
0
    Args.clear();
2927
0
    for (const auto *Arg : ArgRecords) {
2928
0
      Args.emplace_back(createArgument(*Arg, R.getName()));
2929
0
      Args.back()->writePCHReadDecls(OS);
2930
0
    }
2931
0
    OS << "    New = new (Context) " << R.getName() << "Attr(Context, Info";
2932
0
    for (auto const &ri : Args) {
2933
0
      OS << ", ";
2934
0
      ri->writePCHReadArgs(OS);
2935
0
    }
2936
0
    OS << ");\n";
2937
0
    if (R.isSubClassOf(InhClass))
2938
0
      OS << "    cast<InheritableAttr>(New)->setInherited(isInherited);\n";
2939
0
    OS << "    New->setImplicit(isImplicit);\n";
2940
0
    OS << "    New->setPackExpansion(isPackExpansion);\n";
2941
0
    OS << "    break;\n";
2942
0
    OS << "  }\n";
2943
0
  }
2944
0
  OS << "  }\n";
2945
0
}
2946
2947
// Emits the code to write an attribute to a precompiled header.
2948
0
void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
2949
0
  emitSourceFileHeader("Attribute serialization code", OS);
2950
2951
0
  Record *InhClass = Records.getClass("InheritableAttr");
2952
0
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
2953
2954
0
  OS << "  switch (A->getKind()) {\n";
2955
0
  for (const auto *Attr : Attrs) {
2956
0
    const Record &R = *Attr;
2957
0
    if (!R.getValueAsBit("ASTNode"))
2958
0
      continue;
2959
0
    OS << "  case attr::" << R.getName() << ": {\n";
2960
0
    Args = R.getValueAsListOfDefs("Args");
2961
0
    if (R.isSubClassOf(InhClass) || !Args.empty())
2962
0
      OS << "    const auto *SA = cast<" << R.getName()
2963
0
         << "Attr>(A);\n";
2964
0
    if (R.isSubClassOf(InhClass))
2965
0
      OS << "    Record.push_back(SA->isInherited());\n";
2966
0
    OS << "    Record.push_back(A->isImplicit());\n";
2967
0
    OS << "    Record.push_back(A->isPackExpansion());\n";
2968
2969
0
    for (const auto *Arg : Args)
2970
0
      createArgument(*Arg, R.getName())->writePCHWrite(OS);
2971
0
    OS << "    break;\n";
2972
0
    OS << "  }\n";
2973
0
  }
2974
0
  OS << "  }\n";
2975
0
}
2976
2977
// Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
2978
// parameter with only a single check type, if applicable.
2979
static bool GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
2980
                                            std::string *FnName,
2981
                                            StringRef ListName,
2982
                                            StringRef CheckAgainst,
2983
0
                                            StringRef Scope) {
2984
0
  if (!R->isValueUnset(ListName)) {
2985
0
    Test += " && (";
2986
0
    std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
2987
0
    for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
2988
0
      StringRef Part = *I;
2989
0
      Test += CheckAgainst;
2990
0
      Test += " == ";
2991
0
      Test += Scope;
2992
0
      Test += Part;
2993
0
      if (I + 1 != E)
2994
0
        Test += " || ";
2995
0
      if (FnName)
2996
0
        *FnName += Part;
2997
0
    }
2998
0
    Test += ")";
2999
0
    return true;
3000
0
  }
3001
0
  return false;
3002
0
}
3003
3004
// Generate a conditional expression to check if the current target satisfies
3005
// the conditions for a TargetSpecificAttr record, and append the code for
3006
// those checks to the Test string. If the FnName string pointer is non-null,
3007
// append a unique suffix to distinguish this set of target checks from other
3008
// TargetSpecificAttr records.
3009
static bool GenerateTargetSpecificAttrChecks(const Record *R,
3010
                                             std::vector<StringRef> &Arches,
3011
                                             std::string &Test,
3012
0
                                             std::string *FnName) {
3013
0
  bool AnyTargetChecks = false;
3014
3015
  // It is assumed that there will be an llvm::Triple object
3016
  // named "T" and a TargetInfo object named "Target" within
3017
  // scope that can be used to determine whether the attribute exists in
3018
  // a given target.
3019
0
  Test += "true";
3020
  // If one or more architectures is specified, check those.  Arches are handled
3021
  // differently because GenerateTargetRequirements needs to combine the list
3022
  // with ParseKind.
3023
0
  if (!Arches.empty()) {
3024
0
    AnyTargetChecks = true;
3025
0
    Test += " && (";
3026
0
    for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
3027
0
      StringRef Part = *I;
3028
0
      Test += "T.getArch() == llvm::Triple::";
3029
0
      Test += Part;
3030
0
      if (I + 1 != E)
3031
0
        Test += " || ";
3032
0
      if (FnName)
3033
0
        *FnName += Part;
3034
0
    }
3035
0
    Test += ")";
3036
0
  }
3037
3038
  // If the attribute is specific to particular OSes, check those.
3039
0
  AnyTargetChecks |= GenerateTargetSpecificAttrCheck(
3040
0
      R, Test, FnName, "OSes", "T.getOS()", "llvm::Triple::");
3041
3042
  // If one or more object formats is specified, check those.
3043
0
  AnyTargetChecks |=
3044
0
      GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
3045
0
                                      "T.getObjectFormat()", "llvm::Triple::");
3046
3047
  // If custom code is specified, emit it.
3048
0
  StringRef Code = R->getValueAsString("CustomCode");
3049
0
  if (!Code.empty()) {
3050
0
    AnyTargetChecks = true;
3051
0
    Test += " && (";
3052
0
    Test += Code;
3053
0
    Test += ")";
3054
0
  }
3055
3056
0
  return AnyTargetChecks;
3057
0
}
3058
3059
static void GenerateHasAttrSpellingStringSwitch(
3060
    const std::vector<Record *> &Attrs, raw_ostream &OS,
3061
0
    const std::string &Variety = "", const std::string &Scope = "") {
3062
0
  for (const auto *Attr : Attrs) {
3063
    // C++11-style attributes have specific version information associated with
3064
    // them. If the attribute has no scope, the version information must not
3065
    // have the default value (1), as that's incorrect. Instead, the unscoped
3066
    // attribute version information should be taken from the SD-6 standing
3067
    // document, which can be found at:
3068
    // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
3069
    //
3070
    // C2x-style attributes have the same kind of version information
3071
    // associated with them. The unscoped attribute version information should
3072
    // be taken from the specification of the attribute in the C Standard.
3073
0
    int Version = 1;
3074
3075
0
    if (Variety == "CXX11" || Variety == "C2x") {
3076
0
      std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
3077
0
      for (const auto &Spelling : Spellings) {
3078
0
        if (Spelling->getValueAsString("Variety") == Variety) {
3079
0
          Version = static_cast<int>(Spelling->getValueAsInt("Version"));
3080
0
          if (Scope.empty() && Version == 1)
3081
0
            PrintError(Spelling->getLoc(), "Standard attributes must have "
3082
0
                                           "valid version information.");
3083
0
          break;
3084
0
        }
3085
0
      }
3086
0
    }
3087
3088
0
    std::string Test;
3089
0
    if (Attr->isSubClassOf("TargetSpecificAttr")) {
3090
0
      const Record *R = Attr->getValueAsDef("Target");
3091
0
      std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
3092
0
      GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
3093
3094
      // If this is the C++11 variety, also add in the LangOpts test.
3095
0
      if (Variety == "CXX11")
3096
0
        Test += " && LangOpts.CPlusPlus11";
3097
0
      else if (Variety == "C2x")
3098
0
        Test += " && LangOpts.DoubleSquareBracketAttributes";
3099
0
    } else if (Variety == "CXX11")
3100
      // C++11 mode should be checked against LangOpts, which is presumed to be
3101
      // present in the caller.
3102
0
      Test = "LangOpts.CPlusPlus11";
3103
0
    else if (Variety == "C2x")
3104
0
      Test = "LangOpts.DoubleSquareBracketAttributes";
3105
3106
0
    std::string TestStr =
3107
0
        !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
3108
0
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
3109
0
    for (const auto &S : Spellings)
3110
0
      if (Variety.empty() || (Variety == S.variety() &&
3111
0
                              (Scope.empty() || Scope == S.nameSpace())))
3112
0
        OS << "    .Case(\"" << S.name() << "\", " << TestStr << ")\n";
3113
0
  }
3114
0
  OS << "    .Default(0);\n";
3115
0
}
3116
3117
// Emits the list of spellings for attributes.
3118
0
void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3119
0
  emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
3120
3121
  // Separate all of the attributes out into four group: generic, C++11, GNU,
3122
  // and declspecs. Then generate a big switch statement for each of them.
3123
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3124
0
  std::vector<Record *> Declspec, Microsoft, GNU, Pragma;
3125
0
  std::map<std::string, std::vector<Record *>> CXX, C2x;
3126
3127
  // Walk over the list of all attributes, and split them out based on the
3128
  // spelling variety.
3129
0
  for (auto *R : Attrs) {
3130
0
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
3131
0
    for (const auto &SI : Spellings) {
3132
0
      const std::string &Variety = SI.variety();
3133
0
      if (Variety == "GNU")
3134
0
        GNU.push_back(R);
3135
0
      else if (Variety == "Declspec")
3136
0
        Declspec.push_back(R);
3137
0
      else if (Variety == "Microsoft")
3138
0
        Microsoft.push_back(R);
3139
0
      else if (Variety == "CXX11")
3140
0
        CXX[SI.nameSpace()].push_back(R);
3141
0
      else if (Variety == "C2x")
3142
0
        C2x[SI.nameSpace()].push_back(R);
3143
0
      else if (Variety == "Pragma")
3144
0
        Pragma.push_back(R);
3145
0
    }
3146
0
  }
3147
3148
0
  OS << "const llvm::Triple &T = Target.getTriple();\n";
3149
0
  OS << "switch (Syntax) {\n";
3150
0
  OS << "case AttrSyntax::GNU:\n";
3151
0
  OS << "  return llvm::StringSwitch<int>(Name)\n";
3152
0
  GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
3153
0
  OS << "case AttrSyntax::Declspec:\n";
3154
0
  OS << "  return llvm::StringSwitch<int>(Name)\n";
3155
0
  GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
3156
0
  OS << "case AttrSyntax::Microsoft:\n";
3157
0
  OS << "  return llvm::StringSwitch<int>(Name)\n";
3158
0
  GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
3159
0
  OS << "case AttrSyntax::Pragma:\n";
3160
0
  OS << "  return llvm::StringSwitch<int>(Name)\n";
3161
0
  GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
3162
0
  auto fn = [&OS](const char *Spelling, const char *Variety,
3163
0
                  const std::map<std::string, std::vector<Record *>> &List) {
3164
0
    OS << "case AttrSyntax::" << Variety << ": {\n";
3165
    // C++11-style attributes are further split out based on the Scope.
3166
0
    for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
3167
0
      if (I != List.cbegin())
3168
0
        OS << " else ";
3169
0
      if (I->first.empty())
3170
0
        OS << "if (ScopeName == \"\") {\n";
3171
0
      else
3172
0
        OS << "if (ScopeName == \"" << I->first << "\") {\n";
3173
0
      OS << "  return llvm::StringSwitch<int>(Name)\n";
3174
0
      GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
3175
0
      OS << "}";
3176
0
    }
3177
0
    OS << "\n} break;\n";
3178
0
  };
3179
0
  fn("CXX11", "CXX", CXX);
3180
0
  fn("C2x", "C", C2x);
3181
0
  OS << "}\n";
3182
0
}
3183
3184
0
void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
3185
0
  emitSourceFileHeader("Code to translate different attribute spellings "
3186
0
                       "into internal identifiers", OS);
3187
3188
0
  OS << "  switch (getParsedKind()) {\n";
3189
0
  OS << "    case IgnoredAttribute:\n";
3190
0
  OS << "    case UnknownAttribute:\n";
3191
0
  OS << "    case NoSemaHandlerAttribute:\n";
3192
0
  OS << "      llvm_unreachable(\"Ignored/unknown shouldn't get here\");\n";
3193
3194
0
  ParsedAttrMap Attrs = getParsedAttrList(Records);
3195
0
  for (const auto &I : Attrs) {
3196
0
    const Record &R = *I.second;
3197
0
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
3198
0
    OS << "  case AT_" << I.first << ": {\n";
3199
0
    for (unsigned I = 0; I < Spellings.size(); ++ I) {
3200
0
      OS << "    if (Name == \"" << Spellings[I].name() << "\" && "
3201
0
         << "getSyntax() == AttributeCommonInfo::AS_" << Spellings[I].variety()
3202
0
         << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
3203
0
         << "        return " << I << ";\n";
3204
0
    }
3205
3206
0
    OS << "    break;\n";
3207
0
    OS << "  }\n";
3208
0
  }
3209
3210
0
  OS << "  }\n";
3211
0
  OS << "  return 0;\n";
3212
0
}
3213
3214
// Emits code used by RecursiveASTVisitor to visit attributes
3215
0
void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
3216
0
  emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
3217
3218
0
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3219
3220
  // Write method declarations for Traverse* methods.
3221
  // We emit this here because we only generate methods for attributes that
3222
  // are declared as ASTNodes.
3223
0
  OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
3224
0
  for (const auto *Attr : Attrs) {
3225
0
    const Record &R = *Attr;
3226
0
    if (!R.getValueAsBit("ASTNode"))
3227
0
      continue;
3228
0
    OS << "  bool Traverse"
3229
0
       << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
3230
0
    OS << "  bool Visit"
3231
0
       << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3232
0
       << "    return true; \n"
3233
0
       << "  }\n";
3234
0
  }
3235
0
  OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
3236
3237
  // Write individual Traverse* methods for each attribute class.
3238
0
  for (const auto *Attr : Attrs) {
3239
0
    const Record &R = *Attr;
3240
0
    if (!R.getValueAsBit("ASTNode"))
3241
0
      continue;
3242
3243
0
    OS << "template <typename Derived>\n"
3244
0
       << "bool VISITORCLASS<Derived>::Traverse"
3245
0
       << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3246
0
       << "  if (!getDerived().VisitAttr(A))\n"
3247
0
       << "    return false;\n"
3248
0
       << "  if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
3249
0
       << "    return false;\n";
3250
3251
0
    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
3252
0
    for (const auto *Arg : ArgRecords)
3253
0
      createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
3254
3255
0
    OS << "  return true;\n";
3256
0
    OS << "}\n\n";
3257
0
  }
3258
3259
  // Write generic Traverse routine
3260
0
  OS << "template <typename Derived>\n"
3261
0
     << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
3262
0
     << "  if (!A)\n"
3263
0
     << "    return true;\n"
3264
0
     << "\n"
3265
0
     << "  switch (A->getKind()) {\n";
3266
3267
0
  for (const auto *Attr : Attrs) {
3268
0
    const Record &R = *Attr;
3269
0
    if (!R.getValueAsBit("ASTNode"))
3270
0
      continue;
3271
3272
0
    OS << "    case attr::" << R.getName() << ":\n"
3273
0
       << "      return getDerived().Traverse" << R.getName() << "Attr("
3274
0
       << "cast<" << R.getName() << "Attr>(A));\n";
3275
0
  }
3276
0
  OS << "  }\n";  // end switch
3277
0
  OS << "  llvm_unreachable(\"bad attribute kind\");\n";
3278
0
  OS << "}\n";  // end function
3279
0
  OS << "#endif  // ATTR_VISITOR_DECLS_ONLY\n";
3280
0
}
3281
3282
void EmitClangAttrTemplateInstantiateHelper(const std::vector<Record *> &Attrs,
3283
                                            raw_ostream &OS,
3284
0
                                            bool AppliesToDecl) {
3285
3286
0
  OS << "  switch (At->getKind()) {\n";
3287
0
  for (const auto *Attr : Attrs) {
3288
0
    const Record &R = *Attr;
3289
0
    if (!R.getValueAsBit("ASTNode"))
3290
0
      continue;
3291
0
    OS << "    case attr::" << R.getName() << ": {\n";
3292
0
    bool ShouldClone = R.getValueAsBit("Clone") &&
3293
0
                       (!AppliesToDecl ||
3294
0
                        R.getValueAsBit("MeaningfulToClassTemplateDefinition"));
3295
3296
0
    if (!ShouldClone) {
3297
0
      OS << "      return nullptr;\n";
3298
0
      OS << "    }\n";
3299
0
      continue;
3300
0
    }
3301
3302
0
    OS << "      const auto *A = cast<"
3303
0
       << R.getName() << "Attr>(At);\n";
3304
0
    bool TDependent = R.getValueAsBit("TemplateDependent");
3305
3306
0
    if (!TDependent) {
3307
0
      OS << "      return A->clone(C);\n";
3308
0
      OS << "    }\n";
3309
0
      continue;
3310
0
    }
3311
3312
0
    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
3313
0
    std::vector<std::unique_ptr<Argument>> Args;
3314
0
    Args.reserve(ArgRecords.size());
3315
3316
0
    for (const auto *ArgRecord : ArgRecords)
3317
0
      Args.emplace_back(createArgument(*ArgRecord, R.getName()));
3318
3319
0
    for (auto const &ai : Args)
3320
0
      ai->writeTemplateInstantiation(OS);
3321
3322
0
    OS << "        return new (C) " << R.getName() << "Attr(C, *A";
3323
0
    for (auto const &ai : Args) {
3324
0
      OS << ", ";
3325
0
      ai->writeTemplateInstantiationArgs(OS);
3326
0
    }
3327
0
    OS << ");\n    }\n";
3328
0
  }
3329
0
  OS << "  } // end switch\n"
3330
0
     << "  llvm_unreachable(\"Unknown attribute!\");\n"
3331
0
     << "  return nullptr;\n";
3332
0
}
3333
3334
// Emits code to instantiate dependent attributes on templates.
3335
0
void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
3336
0
  emitSourceFileHeader("Template instantiation code for attributes", OS);
3337
3338
0
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3339
3340
0
  OS << "namespace clang {\n"
3341
0
     << "namespace sema {\n\n"
3342
0
     << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
3343
0
     << "Sema &S,\n"
3344
0
     << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3345
0
  EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
3346
0
  OS << "}\n\n"
3347
0
     << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
3348
0
     << " ASTContext &C, Sema &S,\n"
3349
0
     << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3350
0
  EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
3351
0
  OS << "}\n\n"
3352
0
     << "} // end namespace sema\n"
3353
0
     << "} // end namespace clang\n";
3354
0
}
3355
3356
// Emits the list of parsed attributes.
3357
0
void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
3358
0
  emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
3359
3360
0
  OS << "#ifndef PARSED_ATTR\n";
3361
0
  OS << "#define PARSED_ATTR(NAME) NAME\n";
3362
0
  OS << "#endif\n\n";
3363
3364
0
  ParsedAttrMap Names = getParsedAttrList(Records);
3365
0
  for (const auto &I : Names) {
3366
0
    OS << "PARSED_ATTR(" << I.first << ")\n";
3367
0
  }
3368
0
}
3369
3370
0
static bool isArgVariadic(const Record &R, StringRef AttrName) {
3371
0
  return createArgument(R, AttrName)->isVariadic();
3372
0
}
3373
3374
0
static void emitArgInfo(const Record &R, raw_ostream &OS) {
3375
  // This function will count the number of arguments specified for the
3376
  // attribute and emit the number of required arguments followed by the
3377
  // number of optional arguments.
3378
0
  std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
3379
0
  unsigned ArgCount = 0, OptCount = 0;
3380
0
  bool HasVariadic = false;
3381
0
  for (const auto *Arg : Args) {
3382
    // If the arg is fake, it's the user's job to supply it: general parsing
3383
    // logic shouldn't need to know anything about it.
3384
0
    if (Arg->getValueAsBit("Fake"))
3385
0
      continue;
3386
0
    Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
3387
0
    if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
3388
0
      HasVariadic = true;
3389
0
  }
3390
3391
  // If there is a variadic argument, we will set the optional argument count
3392
  // to its largest value. Since it's currently a 4-bit number, we set it to 15.
3393
0
  OS << "    NumArgs = " << ArgCount << ";\n";
3394
0
  OS << "    OptArgs = " << (HasVariadic ? 15 : OptCount) << ";\n";
3395
0
}
3396
3397
0
static std::string GetDiagnosticSpelling(const Record &R) {
3398
0
  std::string Ret = std::string(R.getValueAsString("DiagSpelling"));
3399
0
  if (!Ret.empty())
3400
0
    return Ret;
3401
3402
  // If we couldn't find the DiagSpelling in this object, we can check to see
3403
  // if the object is one that has a base, and if it is, loop up to the Base
3404
  // member recursively.
3405
0
  if (auto Base = R.getValueAsOptionalDef(BaseFieldName))
3406
0
    return GetDiagnosticSpelling(*Base);
3407
3408
0
  return "";
3409
0
}
3410
3411
0
static std::string CalculateDiagnostic(const Record &S) {
3412
  // If the SubjectList object has a custom diagnostic associated with it,
3413
  // return that directly.
3414
0
  const StringRef CustomDiag = S.getValueAsString("CustomDiag");
3415
0
  if (!CustomDiag.empty())
3416
0
    return ("\"" + Twine(CustomDiag) + "\"").str();
3417
3418
0
  std::vector<std::string> DiagList;
3419
0
  std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
3420
0
  for (const auto *Subject : Subjects) {
3421
0
    const Record &R = *Subject;
3422
    // Get the diagnostic text from the Decl or Stmt node given.
3423
0
    std::string V = GetDiagnosticSpelling(R);
3424
0
    if (V.empty()) {
3425
0
      PrintError(R.getLoc(),
3426
0
                 "Could not determine diagnostic spelling for the node: " +
3427
0
                     R.getName() + "; please add one to DeclNodes.td");
3428
0
    } else {
3429
      // The node may contain a list of elements itself, so split the elements
3430
      // by a comma, and trim any whitespace.
3431
0
      SmallVector<StringRef, 2> Frags;
3432
0
      llvm::SplitString(V, Frags, ",");
3433
0
      for (auto Str : Frags) {
3434
0
        DiagList.push_back(std::string(Str.trim()));
3435
0
      }
3436
0
    }
3437
0
  }
3438
3439
0
  if (DiagList.empty()) {
3440
0
    PrintFatalError(S.getLoc(),
3441
0
                    "Could not deduce diagnostic argument for Attr subjects");
3442
0
    return "";
3443
0
  }
3444
3445
  // FIXME: this is not particularly good for localization purposes and ideally
3446
  // should be part of the diagnostics engine itself with some sort of list
3447
  // specifier.
3448
3449
  // A single member of the list can be returned directly.
3450
0
  if (DiagList.size() == 1)
3451
0
    return '"' + DiagList.front() + '"';
3452
3453
0
  if (DiagList.size() == 2)
3454
0
    return '"' + DiagList[0] + " and " + DiagList[1] + '"';
3455
3456
  // If there are more than two in the list, we serialize the first N - 1
3457
  // elements with a comma. This leaves the string in the state: foo, bar,
3458
  // baz (but misses quux). We can then add ", and " for the last element
3459
  // manually.
3460
0
  std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
3461
0
  return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
3462
0
}
3463
3464
0
static std::string GetSubjectWithSuffix(const Record *R) {
3465
0
  const std::string &B = std::string(R->getName());
3466
0
  if (B == "DeclBase")
3467
0
    return "Decl";
3468
0
  return B + "Decl";
3469
0
}
3470
3471
0
static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
3472
0
  return "is" + Subject.getName().str();
3473
0
}
3474
3475
0
static void GenerateCustomAppertainsTo(const Record &Subject, raw_ostream &OS) {
3476
0
  std::string FnName = functionNameForCustomAppertainsTo(Subject);
3477
3478
  // If this code has already been generated, we don't need to do anything.
3479
0
  static std::set<std::string> CustomSubjectSet;
3480
0
  auto I = CustomSubjectSet.find(FnName);
3481
0
  if (I != CustomSubjectSet.end())
3482
0
    return;
3483
3484
  // This only works with non-root Decls.
3485
0
  Record *Base = Subject.getValueAsDef(BaseFieldName);
3486
3487
  // Not currently support custom subjects within custom subjects.
3488
0
  if (Base->isSubClassOf("SubsetSubject")) {
3489
0
    PrintFatalError(Subject.getLoc(),
3490
0
                    "SubsetSubjects within SubsetSubjects is not supported");
3491
0
    return;
3492
0
  }
3493
3494
0
  OS << "static bool " << FnName << "(const Decl *D) {\n";
3495
0
  OS << "  if (const auto *S = dyn_cast<";
3496
0
  OS << GetSubjectWithSuffix(Base);
3497
0
  OS << ">(D))\n";
3498
0
  OS << "    return " << Subject.getValueAsString("CheckCode") << ";\n";
3499
0
  OS << "  return false;\n";
3500
0
  OS << "}\n\n";
3501
3502
0
  CustomSubjectSet.insert(FnName);
3503
0
}
3504
3505
0
static void GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
3506
  // If the attribute does not contain a Subjects definition, then use the
3507
  // default appertainsTo logic.
3508
0
  if (Attr.isValueUnset("Subjects"))
3509
0
    return;
3510
3511
0
  const Record *SubjectObj = Attr.getValueAsDef("Subjects");
3512
0
  std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
3513
3514
  // If the list of subjects is empty, it is assumed that the attribute
3515
  // appertains to everything.
3516
0
  if (Subjects.empty())
3517
0
    return;
3518
3519
0
  bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
3520
3521
  // Otherwise, generate an appertainsTo check specific to this attribute which
3522
  // checks all of the given subjects against the Decl passed in.
3523
  //
3524
  // If D is null, that means the attribute was not applied to a declaration
3525
  // at all (for instance because it was applied to a type), or that the caller
3526
  // has determined that the check should fail (perhaps prior to the creation
3527
  // of the declaration).
3528
0
  OS << "bool diagAppertainsToDecl(Sema &S, ";
3529
0
  OS << "const ParsedAttr &Attr, const Decl *D) const override {\n";
3530
0
  OS << "  if (";
3531
0
  for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
3532
    // If the subject has custom code associated with it, use the generated
3533
    // function for it. The function cannot be inlined into this check (yet)
3534
    // because it requires the subject to be of a specific type, and were that
3535
    // information inlined here, it would not support an attribute with multiple
3536
    // custom subjects.
3537
0
    if ((*I)->isSubClassOf("SubsetSubject")) {
3538
0
      OS << "!" << functionNameForCustomAppertainsTo(**I) << "(D)";
3539
0
    } else {
3540
0
      OS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3541
0
    }
3542
3543
0
    if (I + 1 != E)
3544
0
      OS << " && ";
3545
0
  }
3546
0
  OS << ") {\n";
3547
0
  OS << "    S.Diag(Attr.getLoc(), diag::";
3548
0
  OS << (Warn ? "warn_attribute_wrong_decl_type_str" :
3549
0
               "err_attribute_wrong_decl_type_str");
3550
0
  OS << ")\n";
3551
0
  OS << "      << Attr << ";
3552
0
  OS << CalculateDiagnostic(*SubjectObj) << ";\n";
3553
0
  OS << "    return false;\n";
3554
0
  OS << "  }\n";
3555
0
  OS << "  return true;\n";
3556
0
  OS << "}\n\n";
3557
0
}
3558
3559
static void
3560
emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
3561
0
                        raw_ostream &OS) {
3562
0
  OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
3563
0
     << AttributeSubjectMatchRule::EnumName << " rule) {\n";
3564
0
  OS << "  switch (rule) {\n";
3565
0
  for (const auto &Rule : PragmaAttributeSupport.Rules) {
3566
0
    if (Rule.isAbstractRule()) {
3567
0
      OS << "  case " << Rule.getEnumValue() << ":\n";
3568
0
      OS << "    assert(false && \"Abstract matcher rule isn't allowed\");\n";
3569
0
      OS << "    return false;\n";
3570
0
      continue;
3571
0
    }
3572
0
    std::vector<Record *> Subjects = Rule.getSubjects();
3573
0
    assert(!Subjects.empty() && "Missing subjects");
3574
0
    OS << "  case " << Rule.getEnumValue() << ":\n";
3575
0
    OS << "    return ";
3576
0
    for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
3577
      // If the subject has custom code associated with it, use the function
3578
      // that was generated for GenerateAppertainsTo to check if the declaration
3579
      // is valid.
3580
0
      if ((*I)->isSubClassOf("SubsetSubject"))
3581
0
        OS << functionNameForCustomAppertainsTo(**I) << "(D)";
3582
0
      else
3583
0
        OS << "isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3584
3585
0
      if (I + 1 != E)
3586
0
        OS << " || ";
3587
0
    }
3588
0
    OS << ";\n";
3589
0
  }
3590
0
  OS << "  }\n";
3591
0
  OS << "  llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
3592
0
  OS << "}\n\n";
3593
0
}
3594
3595
static void GenerateLangOptRequirements(const Record &R,
3596
0
                                        raw_ostream &OS) {
3597
  // If the attribute has an empty or unset list of language requirements,
3598
  // use the default handler.
3599
0
  std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
3600
0
  if (LangOpts.empty())
3601
0
    return;
3602
3603
0
  OS << "bool diagLangOpts(Sema &S, const ParsedAttr &Attr) ";
3604
0
  OS << "const override {\n";
3605
0
  OS << "  auto &LangOpts = S.LangOpts;\n";
3606
0
  OS << "  if (" << GenerateTestExpression(LangOpts) << ")\n";
3607
0
  OS << "    return true;\n\n";
3608
0
  OS << "  S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
3609
0
  OS << "<< Attr;\n";
3610
0
  OS << "  return false;\n";
3611
0
  OS << "}\n\n";
3612
0
}
3613
3614
static void GenerateTargetRequirements(const Record &Attr,
3615
                                       const ParsedAttrMap &Dupes,
3616
0
                                       raw_ostream &OS) {
3617
  // If the attribute is not a target specific attribute, use the default
3618
  // target handler.
3619
0
  if (!Attr.isSubClassOf("TargetSpecificAttr"))
3620
0
    return;
3621
3622
  // Get the list of architectures to be tested for.
3623
0
  const Record *R = Attr.getValueAsDef("Target");
3624
0
  std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
3625
3626
  // If there are other attributes which share the same parsed attribute kind,
3627
  // such as target-specific attributes with a shared spelling, collapse the
3628
  // duplicate architectures. This is required because a shared target-specific
3629
  // attribute has only one ParsedAttr::Kind enumeration value, but it
3630
  // applies to multiple target architectures. In order for the attribute to be
3631
  // considered valid, all of its architectures need to be included.
3632
0
  if (!Attr.isValueUnset("ParseKind")) {
3633
0
    const StringRef APK = Attr.getValueAsString("ParseKind");
3634
0
    for (const auto &I : Dupes) {
3635
0
      if (I.first == APK) {
3636
0
        std::vector<StringRef> DA =
3637
0
            I.second->getValueAsDef("Target")->getValueAsListOfStrings(
3638
0
                "Arches");
3639
0
        Arches.insert(Arches.end(), DA.begin(), DA.end());
3640
0
      }
3641
0
    }
3642
0
  }
3643
3644
0
  std::string FnName = "isTarget";
3645
0
  std::string Test;
3646
0
  bool UsesT = GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
3647
3648
0
  OS << "bool existsInTarget(const TargetInfo &Target) const override {\n";
3649
0
  if (UsesT)
3650
0
    OS << "  const llvm::Triple &T = Target.getTriple(); (void)T;\n";
3651
0
  OS << "  return " << Test << ";\n";
3652
0
  OS << "}\n\n";
3653
0
}
3654
3655
static void GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
3656
0
                                                    raw_ostream &OS) {
3657
  // If the attribute does not have a semantic form, we can bail out early.
3658
0
  if (!Attr.getValueAsBit("ASTNode"))
3659
0
    return;
3660
3661
0
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
3662
3663
  // If there are zero or one spellings, or all of the spellings share the same
3664
  // name, we can also bail out early.
3665
0
  if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
3666
0
    return;
3667
3668
  // Generate the enumeration we will use for the mapping.
3669
0
  SemanticSpellingMap SemanticToSyntacticMap;
3670
0
  std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
3671
0
  std::string Name = Attr.getName().str() + "AttrSpellingMap";
3672
3673
0
  OS << "unsigned spellingIndexToSemanticSpelling(";
3674
0
  OS << "const ParsedAttr &Attr) const override {\n";
3675
0
  OS << Enum;
3676
0
  OS << "  unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
3677
0
  WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
3678
0
  OS << "}\n\n";
3679
0
}
3680
3681
0
static void GenerateHandleDeclAttribute(const Record &Attr, raw_ostream &OS) {
3682
  // Only generate if Attr can be handled simply.
3683
0
  if (!Attr.getValueAsBit("SimpleHandler"))
3684
0
    return;
3685
3686
  // Generate a function which just converts from ParsedAttr to the Attr type.
3687
0
  OS << "AttrHandling handleDeclAttribute(Sema &S, Decl *D,";
3688
0
  OS << "const ParsedAttr &Attr) const override {\n";
3689
0
  OS << "  D->addAttr(::new (S.Context) " << Attr.getName();
3690
0
  OS << "Attr(S.Context, Attr));\n";
3691
0
  OS << "  return AttributeApplied;\n";
3692
0
  OS << "}\n\n";
3693
0
}
3694
3695
0
static bool IsKnownToGCC(const Record &Attr) {
3696
  // Look at the spellings for this subject; if there are any spellings which
3697
  // claim to be known to GCC, the attribute is known to GCC.
3698
0
  return llvm::any_of(
3699
0
      GetFlattenedSpellings(Attr),
3700
0
      [](const FlattenedSpelling &S) { return S.knownToGCC(); });
3701
0
}
3702
3703
/// Emits the parsed attribute helpers
3704
0
void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3705
0
  emitSourceFileHeader("Parsed attribute helpers", OS);
3706
3707
0
  PragmaClangAttributeSupport &PragmaAttributeSupport =
3708
0
      getPragmaAttributeSupport(Records);
3709
3710
  // Get the list of parsed attributes, and accept the optional list of
3711
  // duplicates due to the ParseKind.
3712
0
  ParsedAttrMap Dupes;
3713
0
  ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
3714
3715
  // Generate all of the custom appertainsTo functions that the attributes
3716
  // will be using.
3717
0
  for (auto I : Attrs) {
3718
0
    const Record &Attr = *I.second;
3719
0
    if (Attr.isValueUnset("Subjects"))
3720
0
      continue;
3721
0
    const Record *SubjectObj = Attr.getValueAsDef("Subjects");
3722
0
    for (auto Subject : SubjectObj->getValueAsListOfDefs("Subjects"))
3723
0
      if (Subject->isSubClassOf("SubsetSubject"))
3724
0
        GenerateCustomAppertainsTo(*Subject, OS);
3725
0
  }
3726
3727
  // Generate a ParsedAttrInfo struct for each of the attributes.
3728
0
  for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
3729
    // TODO: If the attribute's kind appears in the list of duplicates, that is
3730
    // because it is a target-specific attribute that appears multiple times.
3731
    // It would be beneficial to test whether the duplicates are "similar
3732
    // enough" to each other to not cause problems. For instance, check that
3733
    // the spellings are identical, and custom parsing rules match, etc.
3734
3735
    // We need to generate struct instances based off ParsedAttrInfo from
3736
    // ParsedAttr.cpp.
3737
0
    const std::string &AttrName = I->first;
3738
0
    const Record &Attr = *I->second;
3739
0
    auto Spellings = GetFlattenedSpellings(Attr);
3740
0
    if (!Spellings.empty()) {
3741
0
      OS << "static constexpr ParsedAttrInfo::Spelling " << I->first
3742
0
         << "Spellings[] = {\n";
3743
0
      for (const auto &S : Spellings) {
3744
0
        const std::string &RawSpelling = S.name();
3745
0
        std::string Spelling;
3746
0
        if (!S.nameSpace().empty())
3747
0
          Spelling += S.nameSpace() + "::";
3748
0
        if (S.variety() == "GNU")
3749
0
          Spelling += NormalizeGNUAttrSpelling(RawSpelling);
3750
0
        else
3751
0
          Spelling += RawSpelling;
3752
0
        OS << "  {AttributeCommonInfo::AS_" << S.variety();
3753
0
        OS << ", \"" << Spelling << "\"},\n";
3754
0
      }
3755
0
      OS << "};\n";
3756
0
    }
3757
0
    OS << "struct ParsedAttrInfo" << I->first
3758
0
       << " final : public ParsedAttrInfo {\n";
3759
0
    OS << "  ParsedAttrInfo" << I->first << "() {\n";
3760
0
    OS << "    AttrKind = ParsedAttr::AT_" << AttrName << ";\n";
3761
0
    emitArgInfo(Attr, OS);
3762
0
    OS << "    HasCustomParsing = ";
3763
0
    OS << Attr.getValueAsBit("HasCustomParsing") << ";\n";
3764
0
    OS << "    IsTargetSpecific = ";
3765
0
    OS << Attr.isSubClassOf("TargetSpecificAttr") << ";\n";
3766
0
    OS << "    IsType = ";
3767
0
    OS << (Attr.isSubClassOf("TypeAttr") ||
3768
0
           Attr.isSubClassOf("DeclOrTypeAttr")) << ";\n";
3769
0
    OS << "    IsStmt = ";
3770
0
    OS << Attr.isSubClassOf("StmtAttr") << ";\n";
3771
0
    OS << "    IsKnownToGCC = ";
3772
0
    OS << IsKnownToGCC(Attr) << ";\n";
3773
0
    OS << "    IsSupportedByPragmaAttribute = ";
3774
0
    OS << PragmaAttributeSupport.isAttributedSupported(*I->second) << ";\n";
3775
0
    if (!Spellings.empty())
3776
0
      OS << "    Spellings = " << I->first << "Spellings;\n";
3777
0
    OS << "  }\n";
3778
0
    GenerateAppertainsTo(Attr, OS);
3779
0
    GenerateLangOptRequirements(Attr, OS);
3780
0
    GenerateTargetRequirements(Attr, Dupes, OS);
3781
0
    GenerateSpellingIndexToSemanticSpelling(Attr, OS);
3782
0
    PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
3783
0
    GenerateHandleDeclAttribute(Attr, OS);
3784
0
    OS << "static const ParsedAttrInfo" << I->first << " Instance;\n";
3785
0
    OS << "};\n";
3786
0
    OS << "const ParsedAttrInfo" << I->first << " ParsedAttrInfo" << I->first
3787
0
       << "::Instance;\n";
3788
0
  }
3789
3790
0
  OS << "static const ParsedAttrInfo *AttrInfoMap[] = {\n";
3791
0
  for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
3792
0
    OS << "&ParsedAttrInfo" << I->first << "::Instance,\n";
3793
0
  }
3794
0
  OS << "};\n\n";
3795
3796
  // Generate the attribute match rules.
3797
0
  emitAttributeMatchRules(PragmaAttributeSupport, OS);
3798
0
}
3799
3800
// Emits the kind list of parsed attributes
3801
0
void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
3802
0
  emitSourceFileHeader("Attribute name matcher", OS);
3803
3804
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3805
0
  std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
3806
0
      Keywords, Pragma, C2x;
3807
0
  std::set<std::string> Seen;
3808
0
  for (const auto *A : Attrs) {
3809
0
    const Record &Attr = *A;
3810
3811
0
    bool SemaHandler = Attr.getValueAsBit("SemaHandler");
3812
0
    bool Ignored = Attr.getValueAsBit("Ignored");
3813
0
    if (SemaHandler || Ignored) {
3814
      // Attribute spellings can be shared between target-specific attributes,
3815
      // and can be shared between syntaxes for the same attribute. For
3816
      // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
3817
      // specific attribute, or MSP430-specific attribute. Additionally, an
3818
      // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
3819
      // for the same semantic attribute. Ultimately, we need to map each of
3820
      // these to a single AttributeCommonInfo::Kind value, but the
3821
      // StringMatcher class cannot handle duplicate match strings. So we
3822
      // generate a list of string to match based on the syntax, and emit
3823
      // multiple string matchers depending on the syntax used.
3824
0
      std::string AttrName;
3825
0
      if (Attr.isSubClassOf("TargetSpecificAttr") &&
3826
0
          !Attr.isValueUnset("ParseKind")) {
3827
0
        AttrName = std::string(Attr.getValueAsString("ParseKind"));
3828
0
        if (Seen.find(AttrName) != Seen.end())
3829
0
          continue;
3830
0
        Seen.insert(AttrName);
3831
0
      } else
3832
0
        AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
3833
3834
0
      std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
3835
0
      for (const auto &S : Spellings) {
3836
0
        const std::string &RawSpelling = S.name();
3837
0
        std::vector<StringMatcher::StringPair> *Matches = nullptr;
3838
0
        std::string Spelling;
3839
0
        const std::string &Variety = S.variety();
3840
0
        if (Variety == "CXX11") {
3841
0
          Matches = &CXX11;
3842
0
          if (!S.nameSpace().empty())
3843
0
            Spelling += S.nameSpace() + "::";
3844
0
        } else if (Variety == "C2x") {
3845
0
          Matches = &C2x;
3846
0
          if (!S.nameSpace().empty())
3847
0
            Spelling += S.nameSpace() + "::";
3848
0
        } else if (Variety == "GNU")
3849
0
          Matches = &GNU;
3850
0
        else if (Variety == "Declspec")
3851
0
          Matches = &Declspec;
3852
0
        else if (Variety == "Microsoft")
3853
0
          Matches = &Microsoft;
3854
0
        else if (Variety == "Keyword")
3855
0
          Matches = &Keywords;
3856
0
        else if (Variety == "Pragma")
3857
0
          Matches = &Pragma;
3858
3859
0
        assert(Matches && "Unsupported spelling variety found");
3860
3861
0
        if (Variety == "GNU")
3862
0
          Spelling += NormalizeGNUAttrSpelling(RawSpelling);
3863
0
        else
3864
0
          Spelling += RawSpelling;
3865
3866
0
        if (SemaHandler)
3867
0
          Matches->push_back(StringMatcher::StringPair(
3868
0
              Spelling, "return AttributeCommonInfo::AT_" + AttrName + ";"));
3869
0
        else
3870
0
          Matches->push_back(StringMatcher::StringPair(
3871
0
              Spelling, "return AttributeCommonInfo::IgnoredAttribute;"));
3872
0
      }
3873
0
    }
3874
0
  }
3875
3876
0
  OS << "static AttributeCommonInfo::Kind getAttrKind(StringRef Name, ";
3877
0
  OS << "AttributeCommonInfo::Syntax Syntax) {\n";
3878
0
  OS << "  if (AttributeCommonInfo::AS_GNU == Syntax) {\n";
3879
0
  StringMatcher("Name", GNU, OS).Emit();
3880
0
  OS << "  } else if (AttributeCommonInfo::AS_Declspec == Syntax) {\n";
3881
0
  StringMatcher("Name", Declspec, OS).Emit();
3882
0
  OS << "  } else if (AttributeCommonInfo::AS_Microsoft == Syntax) {\n";
3883
0
  StringMatcher("Name", Microsoft, OS).Emit();
3884
0
  OS << "  } else if (AttributeCommonInfo::AS_CXX11 == Syntax) {\n";
3885
0
  StringMatcher("Name", CXX11, OS).Emit();
3886
0
  OS << "  } else if (AttributeCommonInfo::AS_C2x == Syntax) {\n";
3887
0
  StringMatcher("Name", C2x, OS).Emit();
3888
0
  OS << "  } else if (AttributeCommonInfo::AS_Keyword == Syntax || ";
3889
0
  OS << "AttributeCommonInfo::AS_ContextSensitiveKeyword == Syntax) {\n";
3890
0
  StringMatcher("Name", Keywords, OS).Emit();
3891
0
  OS << "  } else if (AttributeCommonInfo::AS_Pragma == Syntax) {\n";
3892
0
  StringMatcher("Name", Pragma, OS).Emit();
3893
0
  OS << "  }\n";
3894
0
  OS << "  return AttributeCommonInfo::UnknownAttribute;\n"
3895
0
     << "}\n";
3896
0
}
3897
3898
// Emits the code to dump an attribute.
3899
0
void EmitClangAttrTextNodeDump(RecordKeeper &Records, raw_ostream &OS) {
3900
0
  emitSourceFileHeader("Attribute text node dumper", OS);
3901
3902
0
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
3903
0
  for (const auto *Attr : Attrs) {
3904
0
    const Record &R = *Attr;
3905
0
    if (!R.getValueAsBit("ASTNode"))
3906
0
      continue;
3907
3908
    // If the attribute has a semantically-meaningful name (which is determined
3909
    // by whether there is a Spelling enumeration for it), then write out the
3910
    // spelling used for the attribute.
3911
3912
0
    std::string FunctionContent;
3913
0
    llvm::raw_string_ostream SS(FunctionContent);
3914
3915
0
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
3916
0
    if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
3917
0
      SS << "    OS << \" \" << A->getSpelling();\n";
3918
3919
0
    Args = R.getValueAsListOfDefs("Args");
3920
0
    for (const auto *Arg : Args)
3921
0
      createArgument(*Arg, R.getName())->writeDump(SS);
3922
3923
0
    if (SS.tell()) {
3924
0
      OS << "  void Visit" << R.getName() << "Attr(const " << R.getName()
3925
0
         << "Attr *A) {\n";
3926
0
      if (!Args.empty())
3927
0
        OS << "    const auto *SA = cast<" << R.getName()
3928
0
           << "Attr>(A); (void)SA;\n";
3929
0
      OS << SS.str();
3930
0
      OS << "  }\n";
3931
0
    }
3932
0
  }
3933
0
}
3934
3935
0
void EmitClangAttrNodeTraverse(RecordKeeper &Records, raw_ostream &OS) {
3936
0
  emitSourceFileHeader("Attribute text node traverser", OS);
3937
3938
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
3939
0
  for (const auto *Attr : Attrs) {
3940
0
    const Record &R = *Attr;
3941
0
    if (!R.getValueAsBit("ASTNode"))
3942
0
      continue;
3943
3944
0
    std::string FunctionContent;
3945
0
    llvm::raw_string_ostream SS(FunctionContent);
3946
3947
0
    Args = R.getValueAsListOfDefs("Args");
3948
0
    for (const auto *Arg : Args)
3949
0
      createArgument(*Arg, R.getName())->writeDumpChildren(SS);
3950
0
    if (SS.tell()) {
3951
0
      OS << "  void Visit" << R.getName() << "Attr(const " << R.getName()
3952
0
         << "Attr *A) {\n";
3953
0
      if (!Args.empty())
3954
0
        OS << "    const auto *SA = cast<" << R.getName()
3955
0
           << "Attr>(A); (void)SA;\n";
3956
0
      OS << SS.str();
3957
0
      OS << "  }\n";
3958
0
    }
3959
0
  }
3960
0
}
3961
3962
void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
3963
0
                                       raw_ostream &OS) {
3964
0
  emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
3965
0
  emitClangAttrArgContextList(Records, OS);
3966
0
  emitClangAttrIdentifierArgList(Records, OS);
3967
0
  emitClangAttrVariadicIdentifierArgList(Records, OS);
3968
0
  emitClangAttrThisIsaIdentifierArgList(Records, OS);
3969
0
  emitClangAttrTypeArgList(Records, OS);
3970
0
  emitClangAttrLateParsedList(Records, OS);
3971
0
}
3972
3973
void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper &Records,
3974
0
                                                        raw_ostream &OS) {
3975
0
  getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
3976
0
}
3977
3978
enum class SpellingKind {
3979
  GNU,
3980
  CXX11,
3981
  C2x,
3982
  Declspec,
3983
  Microsoft,
3984
  Keyword,
3985
  Pragma,
3986
};
3987
static const size_t NumSpellingKinds = (size_t)SpellingKind::Pragma + 1;
3988
3989
class SpellingList {
3990
  std::vector<std::string> Spellings[NumSpellingKinds];
3991
3992
public:
3993
0
  ArrayRef<std::string> operator[](SpellingKind K) const {
3994
0
    return Spellings[(size_t)K];
3995
0
  }
3996
3997
0
  void add(const Record &Attr, FlattenedSpelling Spelling) {
3998
0
    SpellingKind Kind = StringSwitch<SpellingKind>(Spelling.variety())
3999
0
                            .Case("GNU", SpellingKind::GNU)
4000
0
                            .Case("CXX11", SpellingKind::CXX11)
4001
0
                            .Case("C2x", SpellingKind::C2x)
4002
0
                            .Case("Declspec", SpellingKind::Declspec)
4003
0
                            .Case("Microsoft", SpellingKind::Microsoft)
4004
0
                            .Case("Keyword", SpellingKind::Keyword)
4005
0
                            .Case("Pragma", SpellingKind::Pragma);
4006
0
    std::string Name;
4007
0
    if (!Spelling.nameSpace().empty()) {
4008
0
      switch (Kind) {
4009
0
      case SpellingKind::CXX11:
4010
0
      case SpellingKind::C2x:
4011
0
        Name = Spelling.nameSpace() + "::";
4012
0
        break;
4013
0
      case SpellingKind::Pragma:
4014
0
        Name = Spelling.nameSpace() + " ";
4015
0
        break;
4016
0
      default:
4017
0
        PrintFatalError(Attr.getLoc(), "Unexpected namespace in spelling");
4018
0
      }
4019
0
    }
4020
0
    Name += Spelling.name();
4021
4022
0
    Spellings[(size_t)Kind].push_back(Name);
4023
0
  }
4024
};
4025
4026
class DocumentationData {
4027
public:
4028
  const Record *Documentation;
4029
  const Record *Attribute;
4030
  std::string Heading;
4031
  SpellingList SupportedSpellings;
4032
4033
  DocumentationData(const Record &Documentation, const Record &Attribute,
4034
                    std::pair<std::string, SpellingList> HeadingAndSpellings)
4035
      : Documentation(&Documentation), Attribute(&Attribute),
4036
        Heading(std::move(HeadingAndSpellings.first)),
4037
0
        SupportedSpellings(std::move(HeadingAndSpellings.second)) {}
4038
};
4039
4040
static void WriteCategoryHeader(const Record *DocCategory,
4041
0
                                raw_ostream &OS) {
4042
0
  const StringRef Name = DocCategory->getValueAsString("Name");
4043
0
  OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
4044
4045
  // If there is content, print that as well.
4046
0
  const StringRef ContentStr = DocCategory->getValueAsString("Content");
4047
  // Trim leading and trailing newlines and spaces.
4048
0
  OS << ContentStr.trim();
4049
4050
0
  OS << "\n\n";
4051
0
}
4052
4053
static std::pair<std::string, SpellingList>
4054
GetAttributeHeadingAndSpellings(const Record &Documentation,
4055
0
                                const Record &Attribute) {
4056
  // FIXME: there is no way to have a per-spelling category for the attribute
4057
  // documentation. This may not be a limiting factor since the spellings
4058
  // should generally be consistently applied across the category.
4059
4060
0
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
4061
0
  if (Spellings.empty())
4062
0
    PrintFatalError(Attribute.getLoc(),
4063
0
                    "Attribute has no supported spellings; cannot be "
4064
0
                    "documented");
4065
4066
  // Determine the heading to be used for this attribute.
4067
0
  std::string Heading = std::string(Documentation.getValueAsString("Heading"));
4068
0
  if (Heading.empty()) {
4069
    // If there's only one spelling, we can simply use that.
4070
0
    if (Spellings.size() == 1)
4071
0
      Heading = Spellings.begin()->name();
4072
0
    else {
4073
0
      std::set<std::string> Uniques;
4074
0
      for (auto I = Spellings.begin(), E = Spellings.end();
4075
0
           I != E && Uniques.size() <= 1; ++I) {
4076
0
        std::string Spelling =
4077
0
            std::string(NormalizeNameForSpellingComparison(I->name()));
4078
0
        Uniques.insert(Spelling);
4079
0
      }
4080
      // If the semantic map has only one spelling, that is sufficient for our
4081
      // needs.
4082
0
      if (Uniques.size() == 1)
4083
0
        Heading = *Uniques.begin();
4084
0
    }
4085
0
  }
4086
4087
  // If the heading is still empty, it is an error.
4088
0
  if (Heading.empty())
4089
0
    PrintFatalError(Attribute.getLoc(),
4090
0
                    "This attribute requires a heading to be specified");
4091
4092
0
  SpellingList SupportedSpellings;
4093
0
  for (const auto &I : Spellings)
4094
0
    SupportedSpellings.add(Attribute, I);
4095
4096
0
  return std::make_pair(std::move(Heading), std::move(SupportedSpellings));
4097
0
}
4098
4099
static void WriteDocumentation(RecordKeeper &Records,
4100
0
                               const DocumentationData &Doc, raw_ostream &OS) {
4101
0
  OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
4102
4103
  // List what spelling syntaxes the attribute supports.
4104
0
  OS << ".. csv-table:: Supported Syntaxes\n";
4105
0
  OS << "   :header: \"GNU\", \"C++11\", \"C2x\", \"``__declspec``\",";
4106
0
  OS << " \"Keyword\", \"``#pragma``\", \"``#pragma clang attribute``\"\n\n";
4107
0
  OS << "   \"";
4108
0
  for (size_t Kind = 0; Kind != NumSpellingKinds; ++Kind) {
4109
0
    SpellingKind K = (SpellingKind)Kind;
4110
    // TODO: List Microsoft (IDL-style attribute) spellings once we fully
4111
    // support them.
4112
0
    if (K == SpellingKind::Microsoft)
4113
0
      continue;
4114
4115
0
    bool PrintedAny = false;
4116
0
    for (StringRef Spelling : Doc.SupportedSpellings[K]) {
4117
0
      if (PrintedAny)
4118
0
        OS << " |br| ";
4119
0
      OS << "``" << Spelling << "``";
4120
0
      PrintedAny = true;
4121
0
    }
4122
4123
0
    OS << "\",\"";
4124
0
  }
4125
4126
0
  if (getPragmaAttributeSupport(Records).isAttributedSupported(
4127
0
          *Doc.Attribute))
4128
0
    OS << "Yes";
4129
0
  OS << "\"\n\n";
4130
4131
  // If the attribute is deprecated, print a message about it, and possibly
4132
  // provide a replacement attribute.
4133
0
  if (!Doc.Documentation->isValueUnset("Deprecated")) {
4134
0
    OS << "This attribute has been deprecated, and may be removed in a future "
4135
0
       << "version of Clang.";
4136
0
    const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
4137
0
    const StringRef Replacement = Deprecated.getValueAsString("Replacement");
4138
0
    if (!Replacement.empty())
4139
0
      OS << "  This attribute has been superseded by ``" << Replacement
4140
0
         << "``.";
4141
0
    OS << "\n\n";
4142
0
  }
4143
4144
0
  const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
4145
  // Trim leading and trailing newlines and spaces.
4146
0
  OS << ContentStr.trim();
4147
4148
0
  OS << "\n\n\n";
4149
0
}
4150
4151
0
void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
4152
  // Get the documentation introduction paragraph.
4153
0
  const Record *Documentation = Records.getDef("GlobalDocumentation");
4154
0
  if (!Documentation) {
4155
0
    PrintFatalError("The Documentation top-level definition is missing, "
4156
0
                    "no documentation will be generated.");
4157
0
    return;
4158
0
  }
4159
4160
0
  OS << Documentation->getValueAsString("Intro") << "\n";
4161
4162
  // Gather the Documentation lists from each of the attributes, based on the
4163
  // category provided.
4164
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
4165
0
  std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
4166
0
  for (const auto *A : Attrs) {
4167
0
    const Record &Attr = *A;
4168
0
    std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
4169
0
    for (const auto *D : Docs) {
4170
0
      const Record &Doc = *D;
4171
0
      const Record *Category = Doc.getValueAsDef("Category");
4172
      // If the category is "undocumented", then there cannot be any other
4173
      // documentation categories (otherwise, the attribute would become
4174
      // documented).
4175
0
      const StringRef Cat = Category->getValueAsString("Name");
4176
0
      bool Undocumented = Cat == "Undocumented";
4177
0
      if (Undocumented && Docs.size() > 1)
4178
0
        PrintFatalError(Doc.getLoc(),
4179
0
                        "Attribute is \"Undocumented\", but has multiple "
4180
0
                        "documentation categories");
4181
4182
0
      if (!Undocumented)
4183
0
        SplitDocs[Category].push_back(DocumentationData(
4184
0
            Doc, Attr, GetAttributeHeadingAndSpellings(Doc, Attr)));
4185
0
    }
4186
0
  }
4187
4188
  // Having split the attributes out based on what documentation goes where,
4189
  // we can begin to generate sections of documentation.
4190
0
  for (auto &I : SplitDocs) {
4191
0
    WriteCategoryHeader(I.first, OS);
4192
4193
0
    llvm::sort(I.second,
4194
0
               [](const DocumentationData &D1, const DocumentationData &D2) {
4195
0
                 return D1.Heading < D2.Heading;
4196
0
               });
4197
4198
    // Walk over each of the attributes in the category and write out their
4199
    // documentation.
4200
0
    for (const auto &Doc : I.second)
4201
0
      WriteDocumentation(Records, Doc, OS);
4202
0
  }
4203
0
}
4204
4205
void EmitTestPragmaAttributeSupportedAttributes(RecordKeeper &Records,
4206
1
                                                raw_ostream &OS) {
4207
1
  PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
4208
1
  ParsedAttrMap Attrs = getParsedAttrList(Records);
4209
1
  OS << "#pragma clang attribute supports the following attributes:\n";
4210
301
  for (const auto &I : Attrs) {
4211
301
    if (!Support.isAttributedSupported(*I.second))
4212
134
      continue;
4213
167
    OS << I.first;
4214
167
    if (I.second->isValueUnset("Subjects")) {
4215
1
      OS << " ()\n";
4216
1
      continue;
4217
1
    }
4218
166
    const Record *SubjectObj = I.second->getValueAsDef("Subjects");
4219
166
    std::vector<Record *> Subjects =
4220
166
        SubjectObj->getValueAsListOfDefs("Subjects");
4221
166
    OS << " (";
4222
232
    for (const auto &Subject : llvm::enumerate(Subjects)) {
4223
232
      if (Subject.index())
4224
66
        OS << ", ";
4225
232
      PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
4226
232
          Support.SubjectsToRules.find(Subject.value())->getSecond();
4227
232
      if (RuleSet.isRule()) {
4228
230
        OS << RuleSet.getRule().getEnumValueName();
4229
230
        continue;
4230
230
      }
4231
2
      OS << "(";
4232
30
      for (const auto &Rule : llvm::enumerate(RuleSet.getAggregateRuleSet())) {
4233
30
        if (Rule.index())
4234
28
          OS << ", ";
4235
30
        OS << Rule.value().getEnumValueName();
4236
30
      }
4237
2
      OS << ")";
4238
2
    }
4239
166
    OS << ")\n";
4240
166
  }
4241
1
  OS << "End of supported attributes.\n";
4242
1
}
4243
4244
} // end namespace clang