Coverage Report

Created: 2020-02-15 09:57

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