blob: 1b9fd2d29bf90604b3f93a7304438593b7261e84 [file] [log] [blame]
Peter Collingbournebee583f2011-10-06 13:03:08 +00001//===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Peter Collingbournebee583f2011-10-06 13:03:08 +00006//
7//===----------------------------------------------------------------------===//
8//
9// These tablegen backends emit Clang attribute processing code
10//
11//===----------------------------------------------------------------------===//
12
John McCallc45f8d42019-10-01 23:12:57 +000013#include "TableGenBackends.h"
John McCallb6f03a52019-10-25 18:38:07 -070014#include "ASTTableGen.h"
John McCallc45f8d42019-10-01 23:12:57 +000015
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000016#include "llvm/ADT/ArrayRef.h"
Alex Lorenz9e7bf162017-04-18 14:33:39 +000017#include "llvm/ADT/DenseMap.h"
George Burgess IV1881a572016-12-01 00:13:18 +000018#include "llvm/ADT/DenseSet.h"
Alex Lorenz3bfe9622017-04-18 10:46:41 +000019#include "llvm/ADT/STLExtras.h"
Alex Lorenz9e7bf162017-04-18 14:33:39 +000020#include "llvm/ADT/SmallString.h"
Aaron Ballman28afa182014-11-17 18:17:19 +000021#include "llvm/ADT/StringExtras.h"
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000022#include "llvm/ADT/StringRef.h"
Alex Lorenz9e7bf162017-04-18 14:33:39 +000023#include "llvm/ADT/StringSet.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000024#include "llvm/ADT/StringSwitch.h"
Alex Lorenz9e7bf162017-04-18 14:33:39 +000025#include "llvm/ADT/iterator_range.h"
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000026#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/raw_ostream.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000028#include "llvm/TableGen/Error.h"
Peter Collingbournebee583f2011-10-06 13:03:08 +000029#include "llvm/TableGen/Record.h"
Douglas Gregor377f99b2012-05-02 17:33:51 +000030#include "llvm/TableGen/StringMatcher.h"
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +000031#include "llvm/TableGen/TableGenBackend.h"
Peter Collingbournebee583f2011-10-06 13:03:08 +000032#include <algorithm>
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000033#include <cassert>
Peter Collingbournebee583f2011-10-06 13:03:08 +000034#include <cctype>
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000035#include <cstddef>
36#include <cstdint>
37#include <map>
Aaron Ballman8f1439b2014-03-05 16:49:55 +000038#include <memory>
Aaron Ballman80469032013-11-29 14:57:58 +000039#include <set>
Chandler Carruth5553d0d2014-01-07 11:51:46 +000040#include <sstream>
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000041#include <string>
42#include <utility>
43#include <vector>
Peter Collingbournebee583f2011-10-06 13:03:08 +000044
45using namespace llvm;
46
Benjamin Kramerd910d162015-03-10 18:24:01 +000047namespace {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000048
Aaron Ballmanc669cc02014-01-27 22:10:04 +000049class FlattenedSpelling {
50 std::string V, N, NS;
Aaron Ballman522934d2020-06-01 10:39:38 -040051 bool K = false;
Aaron Ballmanc669cc02014-01-27 22:10:04 +000052
53public:
54 FlattenedSpelling(const std::string &Variety, const std::string &Name,
55 const std::string &Namespace, bool KnownToGCC) :
56 V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
Benjamin Krameradcd0262020-01-28 20:23:46 +010057 explicit FlattenedSpelling(const Record &Spelling)
58 : V(std::string(Spelling.getValueAsString("Variety"))),
59 N(std::string(Spelling.getValueAsString("Name"))) {
Aaron Ballmanffc43362017-10-26 12:19:02 +000060 assert(V != "GCC" && V != "Clang" &&
61 "Given a GCC spelling, which means this hasn't been flattened!");
Aaron Ballman606093a2017-10-15 15:01:42 +000062 if (V == "CXX11" || V == "C2x" || V == "Pragma")
Benjamin Krameradcd0262020-01-28 20:23:46 +010063 NS = std::string(Spelling.getValueAsString("Namespace"));
Aaron Ballmanc669cc02014-01-27 22:10:04 +000064 }
65
66 const std::string &variety() const { return V; }
67 const std::string &name() const { return N; }
68 const std::string &nameSpace() const { return NS; }
69 bool knownToGCC() const { return K; }
70};
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000071
Hans Wennborgdcfba332015-10-06 23:40:43 +000072} // end anonymous namespace
Aaron Ballmanc669cc02014-01-27 22:10:04 +000073
Benjamin Kramerd910d162015-03-10 18:24:01 +000074static std::vector<FlattenedSpelling>
75GetFlattenedSpellings(const Record &Attr) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +000076 std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
77 std::vector<FlattenedSpelling> Ret;
78
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +000079 for (const auto &Spelling : Spellings) {
Aaron Ballmanffc43362017-10-26 12:19:02 +000080 StringRef Variety = Spelling->getValueAsString("Variety");
81 StringRef Name = Spelling->getValueAsString("Name");
82 if (Variety == "GCC") {
Benjamin Krameradcd0262020-01-28 20:23:46 +010083 Ret.emplace_back("GNU", std::string(Name), "", true);
84 Ret.emplace_back("CXX11", std::string(Name), "gnu", true);
Aaron Ballman522934d2020-06-01 10:39:38 -040085 if (Spelling->getValueAsBit("AllowInC"))
86 Ret.emplace_back("C2x", std::string(Name), "gnu", true);
Aaron Ballmanffc43362017-10-26 12:19:02 +000087 } else if (Variety == "Clang") {
Benjamin Krameradcd0262020-01-28 20:23:46 +010088 Ret.emplace_back("GNU", std::string(Name), "", false);
89 Ret.emplace_back("CXX11", std::string(Name), "clang", false);
Aaron Ballman10007812018-01-03 22:22:48 +000090 if (Spelling->getValueAsBit("AllowInC"))
Benjamin Krameradcd0262020-01-28 20:23:46 +010091 Ret.emplace_back("C2x", std::string(Name), "clang", false);
Aaron Ballmanc669cc02014-01-27 22:10:04 +000092 } else
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +000093 Ret.push_back(FlattenedSpelling(*Spelling));
Aaron Ballmanc669cc02014-01-27 22:10:04 +000094 }
95
96 return Ret;
97}
98
Peter Collingbournebee583f2011-10-06 13:03:08 +000099static std::string ReadPCHRecord(StringRef type) {
100 return StringSwitch<std::string>(type)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100101 .EndsWith("Decl *", "Record.GetLocalDeclAs<" +
102 std::string(type.data(), 0, type.size() - 1) +
103 ">(Record.readInt())")
104 .Case("TypeSourceInfo *", "Record.readTypeSourceInfo()")
105 .Case("Expr *", "Record.readExpr()")
106 .Case("IdentifierInfo *", "Record.readIdentifier()")
107 .Case("StringRef", "Record.readString()")
108 .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
Johannes Doerfert55eca282020-03-13 23:42:05 -0500109 .Case("OMPTraitInfo *", "Record.readOMPTraitInfo()")
Benjamin Krameradcd0262020-01-28 20:23:46 +0100110 .Default("Record.readInt()");
Peter Collingbournebee583f2011-10-06 13:03:08 +0000111}
112
Richard Smith19978562016-05-18 00:16:51 +0000113// Get a type that is suitable for storing an object of the specified type.
114static StringRef getStorageType(StringRef type) {
115 return StringSwitch<StringRef>(type)
116 .Case("StringRef", "std::string")
117 .Default(type);
118}
119
Peter Collingbournebee583f2011-10-06 13:03:08 +0000120// Assumes that the way to get the value is SA->getname()
121static std::string WritePCHRecord(StringRef type, StringRef name) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100122 return "Record." +
123 StringSwitch<std::string>(type)
124 .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
125 .Case("TypeSourceInfo *",
126 "AddTypeSourceInfo(" + std::string(name) + ");\n")
127 .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
128 .Case("IdentifierInfo *",
129 "AddIdentifierRef(" + std::string(name) + ");\n")
130 .Case("StringRef", "AddString(" + std::string(name) + ");\n")
131 .Case("ParamIdx",
132 "push_back(" + std::string(name) + ".serialize());\n")
Johannes Doerfert55eca282020-03-13 23:42:05 -0500133 .Case("OMPTraitInfo *",
Johannes Doerfert1228d422019-12-19 20:42:12 -0600134 "writeOMPTraitInfo(" + std::string(name) + ");\n")
Benjamin Krameradcd0262020-01-28 20:23:46 +0100135 .Default("push_back(" + std::string(name) + ");\n");
Peter Collingbournebee583f2011-10-06 13:03:08 +0000136}
137
Michael Han4a045172012-03-07 00:12:16 +0000138// Normalize attribute name by removing leading and trailing
139// underscores. For example, __foo, foo__, __foo__ would
140// become foo.
141static StringRef NormalizeAttrName(StringRef AttrName) {
George Burgess IV1881a572016-12-01 00:13:18 +0000142 AttrName.consume_front("__");
143 AttrName.consume_back("__");
Michael Han4a045172012-03-07 00:12:16 +0000144 return AttrName;
145}
146
Aaron Ballman36a53502014-01-16 13:03:14 +0000147// Normalize the name by removing any and all leading and trailing underscores.
148// This is different from NormalizeAttrName in that it also handles names like
149// _pascal and __pascal.
150static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
Benjamin Kramer5c404072015-04-10 21:37:21 +0000151 return Name.trim("_");
Aaron Ballman36a53502014-01-16 13:03:14 +0000152}
153
Justin Lebar4086fe52017-01-05 16:51:54 +0000154// Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
155// removing "__" if it appears at the beginning and end of the attribute's name.
156static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
Michael Han4a045172012-03-07 00:12:16 +0000157 if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
158 AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
159 }
160
161 return AttrSpelling;
162}
163
Aaron Ballman2f22b942014-05-20 19:47:14 +0000164typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
Aaron Ballman64e69862013-12-15 13:05:48 +0000165
Aaron Ballmanab7691c2014-01-09 22:48:32 +0000166static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
Craig Topper8ae12032014-05-07 06:21:57 +0000167 ParsedAttrMap *Dupes = nullptr) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000168 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Aaron Ballman64e69862013-12-15 13:05:48 +0000169 std::set<std::string> Seen;
170 ParsedAttrMap R;
Aaron Ballman2f22b942014-05-20 19:47:14 +0000171 for (const auto *Attr : Attrs) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000172 if (Attr->getValueAsBit("SemaHandler")) {
Aaron Ballman64e69862013-12-15 13:05:48 +0000173 std::string AN;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000174 if (Attr->isSubClassOf("TargetSpecificAttr") &&
175 !Attr->isValueUnset("ParseKind")) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100176 AN = std::string(Attr->getValueAsString("ParseKind"));
Aaron Ballman64e69862013-12-15 13:05:48 +0000177
178 // If this attribute has already been handled, it does not need to be
179 // handled again.
Aaron Ballmanab7691c2014-01-09 22:48:32 +0000180 if (Seen.find(AN) != Seen.end()) {
181 if (Dupes)
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000182 Dupes->push_back(std::make_pair(AN, Attr));
Aaron Ballman64e69862013-12-15 13:05:48 +0000183 continue;
Aaron Ballmanab7691c2014-01-09 22:48:32 +0000184 }
Aaron Ballman64e69862013-12-15 13:05:48 +0000185 Seen.insert(AN);
186 } else
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000187 AN = NormalizeAttrName(Attr->getName()).str();
Aaron Ballman64e69862013-12-15 13:05:48 +0000188
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000189 R.push_back(std::make_pair(AN, Attr));
Aaron Ballman64e69862013-12-15 13:05:48 +0000190 }
191 }
192 return R;
193}
194
Peter Collingbournebee583f2011-10-06 13:03:08 +0000195namespace {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000196
Peter Collingbournebee583f2011-10-06 13:03:08 +0000197 class Argument {
198 std::string lowerName, upperName;
199 StringRef attrName;
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000200 bool isOpt;
John McCalla62c1a92015-10-28 00:17:34 +0000201 bool Fake;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000202
203 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000204 Argument(const Record &Arg, StringRef Attr)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100205 : lowerName(std::string(Arg.getValueAsString("Name"))),
206 upperName(lowerName), attrName(Attr), isOpt(false), Fake(false) {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000207 if (!lowerName.empty()) {
208 lowerName[0] = std::tolower(lowerName[0]);
209 upperName[0] = std::toupper(upperName[0]);
210 }
Reid Klecknerebeb0ca2016-05-31 17:42:56 +0000211 // Work around MinGW's macro definition of 'interface' to 'struct'. We
212 // have an attribute argument called 'Interface', so only the lower case
213 // name conflicts with the macro definition.
214 if (lowerName == "interface")
215 lowerName = "interface_";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000216 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000217 virtual ~Argument() = default;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000218
219 StringRef getLowerName() const { return lowerName; }
220 StringRef getUpperName() const { return upperName; }
221 StringRef getAttrName() const { return attrName; }
222
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000223 bool isOptional() const { return isOpt; }
224 void setOptional(bool set) { isOpt = set; }
225
John McCalla62c1a92015-10-28 00:17:34 +0000226 bool isFake() const { return Fake; }
227 void setFake(bool fake) { Fake = fake; }
228
Peter Collingbournebee583f2011-10-06 13:03:08 +0000229 // These functions print the argument contents formatted in different ways.
230 virtual void writeAccessors(raw_ostream &OS) const = 0;
231 virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +0000232 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000233 virtual void writeCloneArgs(raw_ostream &OS) const = 0;
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000234 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
Daniel Dunbardc51baa2012-02-10 06:00:29 +0000235 virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000236 virtual void writeCtorBody(raw_ostream &OS) const {}
237 virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000238 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000239 virtual void writeCtorParameters(raw_ostream &OS) const = 0;
240 virtual void writeDeclarations(raw_ostream &OS) const = 0;
241 virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
242 virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
243 virtual void writePCHWrite(raw_ostream &OS) const = 0;
Aaron Ballman48a533d2018-02-27 23:49:28 +0000244 virtual std::string getIsOmitted() const { return "false"; }
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000245 virtual void writeValue(raw_ostream &OS) const = 0;
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000246 virtual void writeDump(raw_ostream &OS) const = 0;
247 virtual void writeDumpChildren(raw_ostream &OS) const {}
Richard Trieude5cc7d2013-01-31 01:44:26 +0000248 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
Aaron Ballman682ee422013-09-11 19:47:58 +0000249
250 virtual bool isEnumArg() const { return false; }
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000251 virtual bool isVariadicEnumArg() const { return false; }
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000252 virtual bool isVariadic() const { return false; }
Aaron Ballman36a53502014-01-16 13:03:14 +0000253
254 virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
255 OS << getUpperName();
256 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000257 };
258
259 class SimpleArgument : public Argument {
260 std::string type;
261
262 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000263 SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000264 : Argument(Arg, Attr), type(std::move(T)) {}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000265
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000266 std::string getType() const { return type; }
267
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000268 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000269 OS << " " << type << " get" << getUpperName() << "() const {\n";
270 OS << " return " << getLowerName() << ";\n";
271 OS << " }";
272 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000273
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000274 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000275 OS << getLowerName();
276 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000277
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000278 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000279 OS << "A->get" << getUpperName() << "()";
280 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000281
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000282 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000283 OS << getLowerName() << "(" << getUpperName() << ")";
284 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000285
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000286 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000287 OS << getLowerName() << "()";
288 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000289
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000290 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000291 OS << type << " " << getUpperName();
292 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000293
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000294 void writeDeclarations(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000295 OS << type << " " << getLowerName() << ";";
296 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000297
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000298 void writePCHReadDecls(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000299 std::string read = ReadPCHRecord(type);
300 OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
301 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000302
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000303 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000304 OS << getLowerName();
305 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000306
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000307 void writePCHWrite(raw_ostream &OS) const override {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100308 OS << " "
309 << WritePCHRecord(type,
310 "SA->get" + std::string(getUpperName()) + "()");
Peter Collingbournebee583f2011-10-06 13:03:08 +0000311 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000312
Aaron Ballman48a533d2018-02-27 23:49:28 +0000313 std::string getIsOmitted() const override {
314 if (type == "IdentifierInfo *")
315 return "!get" + getUpperName().str() + "()";
Matthias Gehred293cbd2019-07-25 17:50:51 +0000316 if (type == "TypeSourceInfo *")
317 return "!get" + getUpperName().str() + "Loc()";
Joel E. Denny81508102018-03-13 14:51:22 +0000318 if (type == "ParamIdx")
319 return "!get" + getUpperName().str() + "().isValid()";
Aaron Ballman48a533d2018-02-27 23:49:28 +0000320 return "false";
321 }
322
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000323 void writeValue(raw_ostream &OS) const override {
Aaron Ballman48a533d2018-02-27 23:49:28 +0000324 if (type == "FunctionDecl *")
Richard Smithb87c4652013-10-31 21:23:20 +0000325 OS << "\" << get" << getUpperName()
326 << "()->getNameInfo().getAsString() << \"";
Aaron Ballman48a533d2018-02-27 23:49:28 +0000327 else if (type == "IdentifierInfo *")
328 // Some non-optional (comma required) identifier arguments can be the
329 // empty string but are then recorded as a nullptr.
330 OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
331 << "()->getName() : \"\") << \"";
332 else if (type == "TypeSourceInfo *")
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000333 OS << "\" << get" << getUpperName() << "().getAsString() << \"";
Joel E. Denny81508102018-03-13 14:51:22 +0000334 else if (type == "ParamIdx")
335 OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
Aaron Ballman48a533d2018-02-27 23:49:28 +0000336 else
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000337 OS << "\" << get" << getUpperName() << "() << \"";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000338 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000339
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000340 void writeDump(raw_ostream &OS) const override {
Richard Smithb09ee882020-04-14 23:28:33 -0700341 if (StringRef(type).endswith("Decl *")) {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000342 OS << " OS << \" \";\n";
Johannes Doerfert1228d422019-12-19 20:42:12 -0600343 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000344 } else if (type == "IdentifierInfo *") {
Aaron Ballman48a533d2018-02-27 23:49:28 +0000345 // Some non-optional (comma required) identifier arguments can be the
346 // empty string but are then recorded as a nullptr.
347 OS << " if (SA->get" << getUpperName() << "())\n"
348 << " OS << \" \" << SA->get" << getUpperName()
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000349 << "()->getName();\n";
Richard Smithb87c4652013-10-31 21:23:20 +0000350 } else if (type == "TypeSourceInfo *") {
Matthias Gehred293cbd2019-07-25 17:50:51 +0000351 if (isOptional())
352 OS << " if (SA->get" << getUpperName() << "Loc())";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000353 OS << " OS << \" \" << SA->get" << getUpperName()
354 << "().getAsString();\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000355 } else if (type == "bool") {
356 OS << " if (SA->get" << getUpperName() << "()) OS << \" "
357 << getUpperName() << "\";\n";
358 } else if (type == "int" || type == "unsigned") {
359 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
Joel E. Denny81508102018-03-13 14:51:22 +0000360 } else if (type == "ParamIdx") {
361 if (isOptional())
362 OS << " if (SA->get" << getUpperName() << "().isValid())\n ";
363 OS << " OS << \" \" << SA->get" << getUpperName()
364 << "().getSourceIndex();\n";
Johannes Doerfert55eca282020-03-13 23:42:05 -0500365 } else if (type == "OMPTraitInfo *") {
Johannes Doerfertb86bf832020-02-15 18:07:42 -0600366 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000367 } else {
368 llvm_unreachable("Unknown SimpleArgument type!");
369 }
370 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000371 };
372
Aaron Ballman18a78382013-11-21 00:28:23 +0000373 class DefaultSimpleArgument : public SimpleArgument {
374 int64_t Default;
375
376 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000377 DefaultSimpleArgument(const Record &Arg, StringRef Attr,
Aaron Ballman18a78382013-11-21 00:28:23 +0000378 std::string T, int64_t Default)
379 : SimpleArgument(Arg, Attr, T), Default(Default) {}
380
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000381 void writeAccessors(raw_ostream &OS) const override {
Aaron Ballman18a78382013-11-21 00:28:23 +0000382 SimpleArgument::writeAccessors(OS);
383
384 OS << "\n\n static const " << getType() << " Default" << getUpperName()
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000385 << " = ";
386 if (getType() == "bool")
387 OS << (Default != 0 ? "true" : "false");
388 else
389 OS << Default;
390 OS << ";";
Aaron Ballman18a78382013-11-21 00:28:23 +0000391 }
392 };
393
Peter Collingbournebee583f2011-10-06 13:03:08 +0000394 class StringArgument : public Argument {
395 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000396 StringArgument(const Record &Arg, StringRef Attr)
Peter Collingbournebee583f2011-10-06 13:03:08 +0000397 : Argument(Arg, Attr)
398 {}
399
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000400 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000401 OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
402 OS << " return llvm::StringRef(" << getLowerName() << ", "
403 << getLowerName() << "Length);\n";
404 OS << " }\n";
405 OS << " unsigned get" << getUpperName() << "Length() const {\n";
406 OS << " return " << getLowerName() << "Length;\n";
407 OS << " }\n";
408 OS << " void set" << getUpperName()
409 << "(ASTContext &C, llvm::StringRef S) {\n";
410 OS << " " << getLowerName() << "Length = S.size();\n";
411 OS << " this->" << getLowerName() << " = new (C, 1) char ["
412 << getLowerName() << "Length];\n";
Chandler Carruth38a45cc2015-08-04 03:53:01 +0000413 OS << " if (!S.empty())\n";
414 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
Peter Collingbournebee583f2011-10-06 13:03:08 +0000415 << getLowerName() << "Length);\n";
416 OS << " }";
417 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000418
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000419 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000420 OS << "get" << getUpperName() << "()";
421 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000422
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000423 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000424 OS << "A->get" << getUpperName() << "()";
425 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000426
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000427 void writeCtorBody(raw_ostream &OS) const override {
Reid Kleckner7420f962020-03-11 19:43:37 -0700428 OS << " if (!" << getUpperName() << ".empty())\n";
429 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000430 << ".data(), " << getLowerName() << "Length);\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000431 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000432
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000433 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000434 OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
435 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
436 << "Length])";
437 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000438
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000439 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Hans Wennborg59dbe862015-09-29 20:56:43 +0000440 OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000441 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000442
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000443 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000444 OS << "llvm::StringRef " << getUpperName();
445 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000446
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000447 void writeDeclarations(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000448 OS << "unsigned " << getLowerName() << "Length;\n";
449 OS << "char *" << getLowerName() << ";";
450 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000451
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000452 void writePCHReadDecls(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000453 OS << " std::string " << getLowerName()
David L. Jones267b8842017-01-24 01:04:30 +0000454 << "= Record.readString();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000455 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000456
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000457 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000458 OS << getLowerName();
459 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000460
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000461 void writePCHWrite(raw_ostream &OS) const override {
Richard Smith290d8012016-04-06 17:06:00 +0000462 OS << " Record.AddString(SA->get" << getUpperName() << "());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000463 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000464
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000465 void writeValue(raw_ostream &OS) const override {
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000466 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
467 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000468
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000469 void writeDump(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000470 OS << " OS << \" \\\"\" << SA->get" << getUpperName()
471 << "() << \"\\\"\";\n";
472 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000473 };
474
475 class AlignedArgument : public Argument {
476 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000477 AlignedArgument(const Record &Arg, StringRef Attr)
Peter Collingbournebee583f2011-10-06 13:03:08 +0000478 : Argument(Arg, Attr)
479 {}
480
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000481 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000482 OS << " bool is" << getUpperName() << "Dependent() const;\n";
Haojian Wu17198df2020-04-12 23:06:00 +0200483 OS << " bool is" << getUpperName() << "ErrorDependent() const;\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000484
485 OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
486
487 OS << " bool is" << getUpperName() << "Expr() const {\n";
488 OS << " return is" << getLowerName() << "Expr;\n";
489 OS << " }\n";
490
491 OS << " Expr *get" << getUpperName() << "Expr() const {\n";
492 OS << " assert(is" << getLowerName() << "Expr);\n";
493 OS << " return " << getLowerName() << "Expr;\n";
494 OS << " }\n";
495
496 OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
497 OS << " assert(!is" << getLowerName() << "Expr);\n";
498 OS << " return " << getLowerName() << "Type;\n";
499 OS << " }";
500 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000501
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000502 void writeAccessorDefinitions(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000503 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
504 << "Dependent() const {\n";
505 OS << " if (is" << getLowerName() << "Expr)\n";
506 OS << " return " << getLowerName() << "Expr && (" << getLowerName()
507 << "Expr->isValueDependent() || " << getLowerName()
Johannes Doerfert1228d422019-12-19 20:42:12 -0600508 << "Expr->isTypeDependent());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000509 OS << " else\n";
510 OS << " return " << getLowerName()
511 << "Type->getType()->isDependentType();\n";
512 OS << "}\n";
513
Haojian Wu17198df2020-04-12 23:06:00 +0200514 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
515 << "ErrorDependent() const {\n";
516 OS << " if (is" << getLowerName() << "Expr)\n";
517 OS << " return " << getLowerName() << "Expr && " << getLowerName()
518 << "Expr->containsErrors();\n";
519 OS << " return " << getLowerName()
520 << "Type->getType()->containsErrors();\n";
521 OS << "}\n";
522
Peter Collingbournebee583f2011-10-06 13:03:08 +0000523 // FIXME: Do not do the calculation here
524 // FIXME: Handle types correctly
525 // A null pointer means maximum alignment
Peter Collingbournebee583f2011-10-06 13:03:08 +0000526 OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
527 << "(ASTContext &Ctx) const {\n";
528 OS << " assert(!is" << getUpperName() << "Dependent());\n";
529 OS << " if (is" << getLowerName() << "Expr)\n";
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +0000530 OS << " return " << getLowerName() << "Expr ? " << getLowerName()
531 << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
532 << " * Ctx.getCharWidth() : "
533 << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000534 OS << " else\n";
535 OS << " return 0; // FIXME\n";
536 OS << "}\n";
537 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000538
Richard Smithf26d5512017-08-15 22:58:45 +0000539 void writeASTVisitorTraversal(raw_ostream &OS) const override {
540 StringRef Name = getUpperName();
541 OS << " if (A->is" << Name << "Expr()) {\n"
Johannes Doerfert1228d422019-12-19 20:42:12 -0600542 << " if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n"
543 << " return false;\n"
Richard Smithf26d5512017-08-15 22:58:45 +0000544 << " } else if (auto *TSI = A->get" << Name << "Type()) {\n"
545 << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
Johannes Doerfert1228d422019-12-19 20:42:12 -0600546 << " return false;\n"
Richard Smithf26d5512017-08-15 22:58:45 +0000547 << " }\n";
548 }
549
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000550 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000551 OS << "is" << getLowerName() << "Expr, is" << getLowerName()
552 << "Expr ? static_cast<void*>(" << getLowerName()
553 << "Expr) : " << getLowerName()
554 << "Type";
555 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000556
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000557 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000558 // FIXME: move the definition in Sema::InstantiateAttrs to here.
559 // In the meantime, aligned attributes are cloned.
560 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000561
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000562 void writeCtorBody(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000563 OS << " if (is" << getLowerName() << "Expr)\n";
564 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
565 << getUpperName() << ");\n";
566 OS << " else\n";
567 OS << " " << getLowerName()
568 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000569 << ");\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000570 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000571
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000572 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000573 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
574 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000575
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000576 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000577 OS << "is" << getLowerName() << "Expr(false)";
578 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000579
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000580 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000581 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
582 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000583
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000584 void writeImplicitCtorArgs(raw_ostream &OS) const override {
Aaron Ballman36a53502014-01-16 13:03:14 +0000585 OS << "Is" << getUpperName() << "Expr, " << getUpperName();
586 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000587
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000588 void writeDeclarations(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000589 OS << "bool is" << getLowerName() << "Expr;\n";
590 OS << "union {\n";
591 OS << "Expr *" << getLowerName() << "Expr;\n";
592 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
593 OS << "};";
594 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000595
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000596 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000597 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
598 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000599
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000600 void writePCHReadDecls(raw_ostream &OS) const override {
David L. Jones267b8842017-01-24 01:04:30 +0000601 OS << " bool is" << getLowerName() << "Expr = Record.readInt();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000602 OS << " void *" << getLowerName() << "Ptr;\n";
603 OS << " if (is" << getLowerName() << "Expr)\n";
David L. Jones267b8842017-01-24 01:04:30 +0000604 OS << " " << getLowerName() << "Ptr = Record.readExpr();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000605 OS << " else\n";
606 OS << " " << getLowerName()
John McCall3ce3d232019-12-13 03:37:23 -0500607 << "Ptr = Record.readTypeSourceInfo();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000608 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000609
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000610 void writePCHWrite(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000611 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
612 OS << " if (SA->is" << getUpperName() << "Expr())\n";
Richard Smith290d8012016-04-06 17:06:00 +0000613 OS << " Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000614 OS << " else\n";
Richard Smith290d8012016-04-06 17:06:00 +0000615 OS << " Record.AddTypeSourceInfo(SA->get" << getUpperName()
616 << "Type());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000617 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000618
Aaron Ballman48a533d2018-02-27 23:49:28 +0000619 std::string getIsOmitted() const override {
620 return "!is" + getLowerName().str() + "Expr || !" + getLowerName().str()
621 + "Expr";
622 }
623
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000624 void writeValue(raw_ostream &OS) const override {
Richard Trieuddd01ce2014-06-09 22:53:25 +0000625 OS << "\";\n";
Aaron Ballman48a533d2018-02-27 23:49:28 +0000626 OS << " " << getLowerName()
627 << "Expr->printPretty(OS, nullptr, Policy);\n";
Richard Trieuddd01ce2014-06-09 22:53:25 +0000628 OS << " OS << \"";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000629 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000630
Stephen Kellydb8fac12019-01-11 19:16:01 +0000631 void writeDump(raw_ostream &OS) const override {
632 OS << " if (!SA->is" << getUpperName() << "Expr())\n";
633 OS << " dumpType(SA->get" << getUpperName()
634 << "Type()->getType());\n";
635 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000636
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000637 void writeDumpChildren(raw_ostream &OS) const override {
Richard Smithf7514452014-10-30 21:02:37 +0000638 OS << " if (SA->is" << getUpperName() << "Expr())\n";
Stephen Kelly6d110d62019-01-30 19:49:49 +0000639 OS << " Visit(SA->get" << getUpperName() << "Expr());\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000640 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000641
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000642 void writeHasChildren(raw_ostream &OS) const override {
Richard Trieude5cc7d2013-01-31 01:44:26 +0000643 OS << "SA->is" << getUpperName() << "Expr()";
644 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000645 };
646
647 class VariadicArgument : public Argument {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000648 std::string Type, ArgName, ArgSizeName, RangeName;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000649
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000650 protected:
651 // Assumed to receive a parameter: raw_ostream OS.
652 virtual void writeValueImpl(raw_ostream &OS) const {
653 OS << " OS << Val;\n";
654 }
Joel E. Denny81508102018-03-13 14:51:22 +0000655 // Assumed to receive a parameter: raw_ostream OS.
656 virtual void writeDumpImpl(raw_ostream &OS) const {
657 OS << " OS << \" \" << Val;\n";
658 }
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000659
Peter Collingbournebee583f2011-10-06 13:03:08 +0000660 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000661 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000662 : Argument(Arg, Attr), Type(std::move(T)),
663 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
Benjamin Krameradcd0262020-01-28 20:23:46 +0100664 RangeName(std::string(getLowerName())) {}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000665
Benjamin Kramer1b582012016-02-13 18:11:49 +0000666 const std::string &getType() const { return Type; }
667 const std::string &getArgName() const { return ArgName; }
668 const std::string &getArgSizeName() const { return ArgSizeName; }
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000669 bool isVariadic() const override { return true; }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000670
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000671 void writeAccessors(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000672 std::string IteratorType = getLowerName().str() + "_iterator";
673 std::string BeginFn = getLowerName().str() + "_begin()";
674 std::string EndFn = getLowerName().str() + "_end()";
Johannes Doerfert1228d422019-12-19 20:42:12 -0600675
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000676 OS << " typedef " << Type << "* " << IteratorType << ";\n";
677 OS << " " << IteratorType << " " << BeginFn << " const {"
678 << " return " << ArgName << "; }\n";
679 OS << " " << IteratorType << " " << EndFn << " const {"
680 << " return " << ArgName << " + " << ArgSizeName << "; }\n";
681 OS << " unsigned " << getLowerName() << "_size() const {"
682 << " return " << ArgSizeName << "; }\n";
683 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
684 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
685 << "); }\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000686 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000687
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000688 void writeCloneArgs(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000689 OS << ArgName << ", " << ArgSizeName;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000690 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000691
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000692 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000693 // This isn't elegant, but we have to go through public methods...
694 OS << "A->" << getLowerName() << "_begin(), "
695 << "A->" << getLowerName() << "_size()";
696 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000697
Richard Smithf26d5512017-08-15 22:58:45 +0000698 void writeASTVisitorTraversal(raw_ostream &OS) const override {
699 // FIXME: Traverse the elements.
700 }
701
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000702 void writeCtorBody(raw_ostream &OS) const override {
Reid Kleckner7420f962020-03-11 19:43:37 -0700703 OS << " std::copy(" << getUpperName() << ", " << getUpperName() << " + "
704 << ArgSizeName << ", " << ArgName << ");\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000705 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000706
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000707 void writeCtorInitializers(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000708 OS << ArgSizeName << "(" << getUpperName() << "Size), "
709 << ArgName << "(new (Ctx, 16) " << getType() << "["
710 << ArgSizeName << "])";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000711 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000712
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000713 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000714 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000715 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000716
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000717 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000718 OS << getType() << " *" << getUpperName() << ", unsigned "
719 << getUpperName() << "Size";
720 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000721
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000722 void writeImplicitCtorArgs(raw_ostream &OS) const override {
Aaron Ballman36a53502014-01-16 13:03:14 +0000723 OS << getUpperName() << ", " << getUpperName() << "Size";
724 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000725
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000726 void writeDeclarations(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000727 OS << " unsigned " << ArgSizeName << ";\n";
728 OS << " " << getType() << " *" << ArgName << ";";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000729 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000730
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000731 void writePCHReadDecls(raw_ostream &OS) const override {
David L. Jones267b8842017-01-24 01:04:30 +0000732 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
Richard Smith19978562016-05-18 00:16:51 +0000733 OS << " SmallVector<" << getType() << ", 4> "
734 << getLowerName() << ";\n";
735 OS << " " << getLowerName() << ".reserve(" << getLowerName()
Peter Collingbournebee583f2011-10-06 13:03:08 +0000736 << "Size);\n";
Richard Smith19978562016-05-18 00:16:51 +0000737
738 // If we can't store the values in the current type (if it's something
739 // like StringRef), store them in a different type and convert the
740 // container afterwards.
Benjamin Krameradcd0262020-01-28 20:23:46 +0100741 std::string StorageType = std::string(getStorageType(getType()));
742 std::string StorageName = std::string(getLowerName());
Richard Smith19978562016-05-18 00:16:51 +0000743 if (StorageType != getType()) {
744 StorageName += "Storage";
745 OS << " SmallVector<" << StorageType << ", 4> "
746 << StorageName << ";\n";
747 OS << " " << StorageName << ".reserve(" << getLowerName()
748 << "Size);\n";
749 }
750
751 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000752 std::string read = ReadPCHRecord(Type);
Richard Smith19978562016-05-18 00:16:51 +0000753 OS << " " << StorageName << ".push_back(" << read << ");\n";
754
755 if (StorageType != getType()) {
756 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
757 OS << " " << getLowerName() << ".push_back("
758 << StorageName << "[i]);\n";
759 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000760 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000761
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000762 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000763 OS << getLowerName() << ".data(), " << getLowerName() << "Size";
764 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000765
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000766 void writePCHWrite(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000767 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000768 OS << " for (auto &Val : SA->" << RangeName << "())\n";
769 OS << " " << WritePCHRecord(Type, "Val");
Peter Collingbournebee583f2011-10-06 13:03:08 +0000770 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000771
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000772 void writeValue(raw_ostream &OS) const override {
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000773 OS << "\";\n";
774 OS << " bool isFirst = true;\n"
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000775 << " for (const auto &Val : " << RangeName << "()) {\n"
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000776 << " if (isFirst) isFirst = false;\n"
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000777 << " else OS << \", \";\n";
778 writeValueImpl(OS);
779 OS << " }\n";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000780 OS << " OS << \"";
781 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000782
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000783 void writeDump(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000784 OS << " for (const auto &Val : SA->" << RangeName << "())\n";
Joel E. Denny81508102018-03-13 14:51:22 +0000785 writeDumpImpl(OS);
786 }
787 };
788
789 class VariadicParamIdxArgument : public VariadicArgument {
790 public:
791 VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
792 : VariadicArgument(Arg, Attr, "ParamIdx") {}
793
794 public:
795 void writeValueImpl(raw_ostream &OS) const override {
796 OS << " OS << Val.getSourceIndex();\n";
797 }
798
799 void writeDumpImpl(raw_ostream &OS) const override {
800 OS << " OS << \" \" << Val.getSourceIndex();\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000801 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000802 };
803
Johannes Doerfertac991bb2019-01-19 05:36:54 +0000804 struct VariadicParamOrParamIdxArgument : public VariadicArgument {
805 VariadicParamOrParamIdxArgument(const Record &Arg, StringRef Attr)
806 : VariadicArgument(Arg, Attr, "int") {}
807 };
808
Reid Klecknerf526b9482014-02-12 18:22:18 +0000809 // Unique the enums, but maintain the original declaration ordering.
Craig Topper00648582017-05-31 19:01:22 +0000810 std::vector<StringRef>
811 uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
812 std::vector<StringRef> uniques;
George Burgess IV1881a572016-12-01 00:13:18 +0000813 SmallDenseSet<StringRef, 8> unique_set;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000814 for (const auto &i : enums) {
George Burgess IV1881a572016-12-01 00:13:18 +0000815 if (unique_set.insert(i).second)
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000816 uniques.push_back(i);
Reid Klecknerf526b9482014-02-12 18:22:18 +0000817 }
818 return uniques;
819 }
820
Peter Collingbournebee583f2011-10-06 13:03:08 +0000821 class EnumArgument : public Argument {
822 std::string type;
Craig Topper00648582017-05-31 19:01:22 +0000823 std::vector<StringRef> values, enums, uniques;
824
Peter Collingbournebee583f2011-10-06 13:03:08 +0000825 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000826 EnumArgument(const Record &Arg, StringRef Attr)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100827 : Argument(Arg, Attr), type(std::string(Arg.getValueAsString("Type"))),
828 values(Arg.getValueAsListOfStrings("Values")),
829 enums(Arg.getValueAsListOfStrings("Enums")),
830 uniques(uniqueEnumsInOrder(enums)) {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000831 // FIXME: Emit a proper error
832 assert(!uniques.empty());
833 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000834
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000835 bool isEnumArg() const override { return true; }
Aaron Ballman682ee422013-09-11 19:47:58 +0000836
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000837 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000838 OS << " " << type << " get" << getUpperName() << "() const {\n";
839 OS << " return " << getLowerName() << ";\n";
840 OS << " }";
841 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000842
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000843 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000844 OS << getLowerName();
845 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000846
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000847 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000848 OS << "A->get" << getUpperName() << "()";
849 }
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000850 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000851 OS << getLowerName() << "(" << getUpperName() << ")";
852 }
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000853 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000854 OS << getLowerName() << "(" << type << "(0))";
855 }
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000856 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000857 OS << type << " " << getUpperName();
858 }
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000859 void writeDeclarations(raw_ostream &OS) const override {
Eugene Zelenko5f02b772015-12-08 18:49:01 +0000860 auto i = uniques.cbegin(), e = uniques.cend();
Peter Collingbournebee583f2011-10-06 13:03:08 +0000861 // The last one needs to not have a comma.
862 --e;
863
864 OS << "public:\n";
865 OS << " enum " << type << " {\n";
866 for (; i != e; ++i)
867 OS << " " << *i << ",\n";
868 OS << " " << *e << "\n";
869 OS << " };\n";
870 OS << "private:\n";
871 OS << " " << type << " " << getLowerName() << ";";
872 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000873
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000874 void writePCHReadDecls(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000875 OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
876 << "(static_cast<" << getAttrName() << "Attr::" << type
David L. Jones267b8842017-01-24 01:04:30 +0000877 << ">(Record.readInt()));\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000878 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000879
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000880 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000881 OS << getLowerName();
882 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000883
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000884 void writePCHWrite(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000885 OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
886 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000887
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000888 void writeValue(raw_ostream &OS) const override {
Aaron Ballman36d79102014-09-15 16:16:14 +0000889 // FIXME: this isn't 100% correct -- some enum arguments require printing
890 // as a string literal, while others require printing as an identifier.
891 // Tablegen currently does not distinguish between the two forms.
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000892 OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
893 << getUpperName() << "()) << \"\\\"";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000894 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000895
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000896 void writeDump(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000897 OS << " switch(SA->get" << getUpperName() << "()) {\n";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000898 for (const auto &I : uniques) {
899 OS << " case " << getAttrName() << "Attr::" << I << ":\n";
900 OS << " OS << \" " << I << "\";\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000901 OS << " break;\n";
902 }
903 OS << " }\n";
904 }
Aaron Ballman682ee422013-09-11 19:47:58 +0000905
Reid Kleckner7420f962020-03-11 19:43:37 -0700906 void writeConversion(raw_ostream &OS, bool Header) const {
907 if (Header) {
908 OS << " static bool ConvertStrTo" << type << "(StringRef Val, " << type
909 << " &Out);\n";
910 OS << " static const char *Convert" << type << "ToStr(" << type
911 << " Val);\n";
912 return;
913 }
914
915 OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << type
916 << "(StringRef Val, " << type << " &Out) {\n";
917 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000918 OS << type << ">>(Val)\n";
Aaron Ballman682ee422013-09-11 19:47:58 +0000919 for (size_t I = 0; I < enums.size(); ++I) {
Reid Kleckner7420f962020-03-11 19:43:37 -0700920 OS << " .Case(\"" << values[I] << "\", ";
Aaron Ballman682ee422013-09-11 19:47:58 +0000921 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
922 }
Reid Kleckner7420f962020-03-11 19:43:37 -0700923 OS << " .Default(Optional<" << type << ">());\n";
924 OS << " if (R) {\n";
925 OS << " Out = *R;\n return true;\n }\n";
926 OS << " return false;\n";
927 OS << "}\n\n";
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000928
929 // Mapping from enumeration values back to enumeration strings isn't
930 // trivial because some enumeration values have multiple named
931 // enumerators, such as type_visibility(internal) and
932 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
Reid Kleckner7420f962020-03-11 19:43:37 -0700933 OS << "const char *" << getAttrName() << "Attr::Convert" << type
934 << "ToStr(" << type << " Val) {\n"
935 << " switch(Val) {\n";
George Burgess IV1881a572016-12-01 00:13:18 +0000936 SmallDenseSet<StringRef, 8> Uniques;
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000937 for (size_t I = 0; I < enums.size(); ++I) {
938 if (Uniques.insert(enums[I]).second)
Reid Kleckner7420f962020-03-11 19:43:37 -0700939 OS << " case " << getAttrName() << "Attr::" << enums[I]
Johannes Doerfert1228d422019-12-19 20:42:12 -0600940 << ": return \"" << values[I] << "\";\n";
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000941 }
Reid Kleckner7420f962020-03-11 19:43:37 -0700942 OS << " }\n"
943 << " llvm_unreachable(\"No enumerator with that value\");\n"
944 << "}\n";
Aaron Ballman682ee422013-09-11 19:47:58 +0000945 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000946 };
Johannes Doerfert1228d422019-12-19 20:42:12 -0600947
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000948 class VariadicEnumArgument: public VariadicArgument {
949 std::string type, QualifiedTypeName;
Craig Topper00648582017-05-31 19:01:22 +0000950 std::vector<StringRef> values, enums, uniques;
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000951
952 protected:
953 void writeValueImpl(raw_ostream &OS) const override {
Aaron Ballman36d79102014-09-15 16:16:14 +0000954 // FIXME: this isn't 100% correct -- some enum arguments require printing
955 // as a string literal, while others require printing as an identifier.
956 // Tablegen currently does not distinguish between the two forms.
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000957 OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
958 << "ToStr(Val)" << "<< \"\\\"\";\n";
959 }
960
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000961 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000962 VariadicEnumArgument(const Record &Arg, StringRef Attr)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100963 : VariadicArgument(Arg, Attr,
964 std::string(Arg.getValueAsString("Type"))),
965 type(std::string(Arg.getValueAsString("Type"))),
966 values(Arg.getValueAsListOfStrings("Values")),
967 enums(Arg.getValueAsListOfStrings("Enums")),
968 uniques(uniqueEnumsInOrder(enums)) {
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000969 QualifiedTypeName = getAttrName().str() + "Attr::" + type;
Johannes Doerfert1228d422019-12-19 20:42:12 -0600970
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000971 // FIXME: Emit a proper error
972 assert(!uniques.empty());
973 }
974
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000975 bool isVariadicEnumArg() const override { return true; }
Johannes Doerfert1228d422019-12-19 20:42:12 -0600976
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000977 void writeDeclarations(raw_ostream &OS) const override {
Eugene Zelenko5f02b772015-12-08 18:49:01 +0000978 auto i = uniques.cbegin(), e = uniques.cend();
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000979 // The last one needs to not have a comma.
980 --e;
981
982 OS << "public:\n";
983 OS << " enum " << type << " {\n";
984 for (; i != e; ++i)
985 OS << " " << *i << ",\n";
986 OS << " " << *e << "\n";
987 OS << " };\n";
988 OS << "private:\n";
Johannes Doerfert1228d422019-12-19 20:42:12 -0600989
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000990 VariadicArgument::writeDeclarations(OS);
991 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000992
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000993 void writeDump(raw_ostream &OS) const override {
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000994 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
995 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
996 << getLowerName() << "_end(); I != E; ++I) {\n";
997 OS << " switch(*I) {\n";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000998 for (const auto &UI : uniques) {
999 OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
1000 OS << " OS << \" " << UI << "\";\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001001 OS << " break;\n";
1002 }
1003 OS << " }\n";
1004 OS << " }\n";
1005 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001006
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001007 void writePCHReadDecls(raw_ostream &OS) const override {
David L. Jones267b8842017-01-24 01:04:30 +00001008 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001009 OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
1010 << ";\n";
1011 OS << " " << getLowerName() << ".reserve(" << getLowerName()
1012 << "Size);\n";
1013 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
1014 OS << " " << getLowerName() << ".push_back(" << "static_cast<"
David L. Jones267b8842017-01-24 01:04:30 +00001015 << QualifiedTypeName << ">(Record.readInt()));\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001016 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001017
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001018 void writePCHWrite(raw_ostream &OS) const override {
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001019 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
1020 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1021 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
1022 << getLowerName() << "_end(); i != e; ++i)\n";
1023 OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
1024 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001025
Reid Kleckner7420f962020-03-11 19:43:37 -07001026 void writeConversion(raw_ostream &OS, bool Header) const {
1027 if (Header) {
1028 OS << " static bool ConvertStrTo" << type << "(StringRef Val, " << type
1029 << " &Out);\n";
1030 OS << " static const char *Convert" << type << "ToStr(" << type
1031 << " Val);\n";
1032 return;
1033 }
1034
1035 OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << type
1036 << "(StringRef Val, ";
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001037 OS << type << " &Out) {\n";
Reid Kleckner7420f962020-03-11 19:43:37 -07001038 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001039 OS << type << ">>(Val)\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001040 for (size_t I = 0; I < enums.size(); ++I) {
Reid Kleckner7420f962020-03-11 19:43:37 -07001041 OS << " .Case(\"" << values[I] << "\", ";
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001042 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
1043 }
Reid Kleckner7420f962020-03-11 19:43:37 -07001044 OS << " .Default(Optional<" << type << ">());\n";
1045 OS << " if (R) {\n";
1046 OS << " Out = *R;\n return true;\n }\n";
1047 OS << " return false;\n";
1048 OS << "}\n\n";
Aaron Ballman25a2cb92014-09-15 15:14:13 +00001049
Reid Kleckner7420f962020-03-11 19:43:37 -07001050 OS << "const char *" << getAttrName() << "Attr::Convert" << type
1051 << "ToStr(" << type << " Val) {\n"
1052 << " switch(Val) {\n";
George Burgess IV1881a572016-12-01 00:13:18 +00001053 SmallDenseSet<StringRef, 8> Uniques;
Aaron Ballman25a2cb92014-09-15 15:14:13 +00001054 for (size_t I = 0; I < enums.size(); ++I) {
1055 if (Uniques.insert(enums[I]).second)
Reid Kleckner7420f962020-03-11 19:43:37 -07001056 OS << " case " << getAttrName() << "Attr::" << enums[I]
1057 << ": return \"" << values[I] << "\";\n";
Aaron Ballman25a2cb92014-09-15 15:14:13 +00001058 }
Reid Kleckner7420f962020-03-11 19:43:37 -07001059 OS << " }\n"
1060 << " llvm_unreachable(\"No enumerator with that value\");\n"
1061 << "}\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001062 }
1063 };
Peter Collingbournebee583f2011-10-06 13:03:08 +00001064
1065 class VersionArgument : public Argument {
1066 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +00001067 VersionArgument(const Record &Arg, StringRef Attr)
Peter Collingbournebee583f2011-10-06 13:03:08 +00001068 : Argument(Arg, Attr)
1069 {}
1070
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001071 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001072 OS << " VersionTuple get" << getUpperName() << "() const {\n";
1073 OS << " return " << getLowerName() << ";\n";
1074 OS << " }\n";
Johannes Doerfert1228d422019-12-19 20:42:12 -06001075 OS << " void set" << getUpperName()
Peter Collingbournebee583f2011-10-06 13:03:08 +00001076 << "(ASTContext &C, VersionTuple V) {\n";
1077 OS << " " << getLowerName() << " = V;\n";
1078 OS << " }";
1079 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001080
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001081 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001082 OS << "get" << getUpperName() << "()";
1083 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001084
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001085 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001086 OS << "A->get" << getUpperName() << "()";
1087 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001088
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001089 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001090 OS << getLowerName() << "(" << getUpperName() << ")";
1091 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001092
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001093 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballman8ee40b72013-09-09 23:33:17 +00001094 OS << getLowerName() << "()";
1095 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001096
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001097 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001098 OS << "VersionTuple " << getUpperName();
1099 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001100
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001101 void writeDeclarations(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001102 OS << "VersionTuple " << getLowerName() << ";\n";
1103 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001104
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001105 void writePCHReadDecls(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001106 OS << " VersionTuple " << getLowerName()
David L. Jones267b8842017-01-24 01:04:30 +00001107 << "= Record.readVersionTuple();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001108 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001109
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001110 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001111 OS << getLowerName();
1112 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001113
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001114 void writePCHWrite(raw_ostream &OS) const override {
Richard Smith290d8012016-04-06 17:06:00 +00001115 OS << " Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001116 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001117
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001118 void writeValue(raw_ostream &OS) const override {
Douglas Gregor49ccfaa2011-11-19 19:22:57 +00001119 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1120 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001121
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001122 void writeDump(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001123 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
1124 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001125 };
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001126
1127 class ExprArgument : public SimpleArgument {
1128 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +00001129 ExprArgument(const Record &Arg, StringRef Attr)
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001130 : SimpleArgument(Arg, Attr, "Expr *")
1131 {}
1132
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001133 void writeASTVisitorTraversal(raw_ostream &OS) const override {
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00001134 OS << " if (!"
1135 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1136 OS << " return false;\n";
1137 }
1138
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001139 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001140 OS << "tempInst" << getUpperName();
1141 }
1142
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001143 void writeTemplateInstantiation(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001144 OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
1145 OS << " {\n";
1146 OS << " EnterExpressionEvaluationContext "
Faisal Valid143a0c2017-04-01 21:30:49 +00001147 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001148 OS << " ExprResult " << "Result = S.SubstExpr("
1149 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1150 OS << " tempInst" << getUpperName() << " = "
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001151 << "Result.getAs<Expr>();\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001152 OS << " }\n";
1153 }
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001154
Craig Topper3164f332014-03-11 03:39:26 +00001155 void writeDump(raw_ostream &OS) const override {}
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001156
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001157 void writeDumpChildren(raw_ostream &OS) const override {
Stephen Kelly6d110d62019-01-30 19:49:49 +00001158 OS << " Visit(SA->get" << getUpperName() << "());\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001159 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001160
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001161 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001162 };
1163
1164 class VariadicExprArgument : public VariadicArgument {
1165 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +00001166 VariadicExprArgument(const Record &Arg, StringRef Attr)
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001167 : VariadicArgument(Arg, Attr, "Expr *")
1168 {}
1169
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001170 void writeASTVisitorTraversal(raw_ostream &OS) const override {
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00001171 OS << " {\n";
1172 OS << " " << getType() << " *I = A->" << getLowerName()
1173 << "_begin();\n";
1174 OS << " " << getType() << " *E = A->" << getLowerName()
1175 << "_end();\n";
1176 OS << " for (; I != E; ++I) {\n";
1177 OS << " if (!getDerived().TraverseStmt(*I))\n";
1178 OS << " return false;\n";
1179 OS << " }\n";
1180 OS << " }\n";
1181 }
1182
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001183 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001184 OS << "tempInst" << getUpperName() << ", "
1185 << "A->" << getLowerName() << "_size()";
1186 }
1187
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001188 void writeTemplateInstantiation(raw_ostream &OS) const override {
Eugene Zelenko5f02b772015-12-08 18:49:01 +00001189 OS << " auto *tempInst" << getUpperName()
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001190 << " = new (C, 16) " << getType()
1191 << "[A->" << getLowerName() << "_size()];\n";
1192 OS << " {\n";
1193 OS << " EnterExpressionEvaluationContext "
Faisal Valid143a0c2017-04-01 21:30:49 +00001194 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001195 OS << " " << getType() << " *TI = tempInst" << getUpperName()
1196 << ";\n";
1197 OS << " " << getType() << " *I = A->" << getLowerName()
1198 << "_begin();\n";
1199 OS << " " << getType() << " *E = A->" << getLowerName()
1200 << "_end();\n";
1201 OS << " for (; I != E; ++I, ++TI) {\n";
1202 OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001203 OS << " *TI = Result.getAs<Expr>();\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001204 OS << " }\n";
1205 OS << " }\n";
1206 }
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001207
Craig Topper3164f332014-03-11 03:39:26 +00001208 void writeDump(raw_ostream &OS) const override {}
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001209
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001210 void writeDumpChildren(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001211 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1212 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
Richard Smithf7514452014-10-30 21:02:37 +00001213 << getLowerName() << "_end(); I != E; ++I)\n";
Stephen Kelly6d110d62019-01-30 19:49:49 +00001214 OS << " Visit(*I);\n";
Richard Trieude5cc7d2013-01-31 01:44:26 +00001215 }
1216
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001217 void writeHasChildren(raw_ostream &OS) const override {
Richard Trieude5cc7d2013-01-31 01:44:26 +00001218 OS << "SA->" << getLowerName() << "_begin() != "
1219 << "SA->" << getLowerName() << "_end()";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001220 }
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001221 };
Richard Smithb87c4652013-10-31 21:23:20 +00001222
Erich Keane3efe0022018-07-20 14:13:28 +00001223 class VariadicIdentifierArgument : public VariadicArgument {
1224 public:
1225 VariadicIdentifierArgument(const Record &Arg, StringRef Attr)
1226 : VariadicArgument(Arg, Attr, "IdentifierInfo *")
1227 {}
1228 };
1229
Peter Collingbourne915df992015-05-15 18:33:32 +00001230 class VariadicStringArgument : public VariadicArgument {
1231 public:
1232 VariadicStringArgument(const Record &Arg, StringRef Attr)
Benjamin Kramer1b582012016-02-13 18:11:49 +00001233 : VariadicArgument(Arg, Attr, "StringRef")
Peter Collingbourne915df992015-05-15 18:33:32 +00001234 {}
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001235
Benjamin Kramer1b582012016-02-13 18:11:49 +00001236 void writeCtorBody(raw_ostream &OS) const override {
Reid Kleckner7420f962020-03-11 19:43:37 -07001237 OS << " for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1238 " ++I) {\n"
1239 " StringRef Ref = " << getUpperName() << "[I];\n"
1240 " if (!Ref.empty()) {\n"
1241 " char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1242 " std::memcpy(Mem, Ref.data(), Ref.size());\n"
1243 " " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1244 " }\n"
1245 " }\n";
Benjamin Kramer1b582012016-02-13 18:11:49 +00001246 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001247
Peter Collingbourne915df992015-05-15 18:33:32 +00001248 void writeValueImpl(raw_ostream &OS) const override {
1249 OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
1250 }
1251 };
1252
Richard Smithb87c4652013-10-31 21:23:20 +00001253 class TypeArgument : public SimpleArgument {
1254 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +00001255 TypeArgument(const Record &Arg, StringRef Attr)
Richard Smithb87c4652013-10-31 21:23:20 +00001256 : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1257 {}
1258
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001259 void writeAccessors(raw_ostream &OS) const override {
Richard Smithb87c4652013-10-31 21:23:20 +00001260 OS << " QualType get" << getUpperName() << "() const {\n";
1261 OS << " return " << getLowerName() << "->getType();\n";
1262 OS << " }";
1263 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1264 OS << " return " << getLowerName() << ";\n";
1265 OS << " }";
1266 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001267
Richard Smithf26d5512017-08-15 22:58:45 +00001268 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1269 OS << " if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
1270 OS << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
1271 OS << " return false;\n";
1272 }
1273
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001274 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
Richard Smithb87c4652013-10-31 21:23:20 +00001275 OS << "A->get" << getUpperName() << "Loc()";
1276 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001277
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001278 void writePCHWrite(raw_ostream &OS) const override {
Benjamin Krameradcd0262020-01-28 20:23:46 +01001279 OS << " "
1280 << WritePCHRecord(getType(),
1281 "SA->get" + std::string(getUpperName()) + "Loc()");
Richard Smithb87c4652013-10-31 21:23:20 +00001282 }
1283 };
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001284
Hans Wennborgdcfba332015-10-06 23:40:43 +00001285} // end anonymous namespace
Peter Collingbournebee583f2011-10-06 13:03:08 +00001286
Aaron Ballman2f22b942014-05-20 19:47:14 +00001287static std::unique_ptr<Argument>
1288createArgument(const Record &Arg, StringRef Attr,
1289 const Record *Search = nullptr) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001290 if (!Search)
1291 Search = &Arg;
1292
David Blaikie28f30ca2014-08-08 23:59:38 +00001293 std::unique_ptr<Argument> Ptr;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001294 llvm::StringRef ArgName = Search->getName();
1295
David Blaikie28f30ca2014-08-08 23:59:38 +00001296 if (ArgName == "AlignedArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001297 Ptr = std::make_unique<AlignedArgument>(Arg, Attr);
David Blaikie28f30ca2014-08-08 23:59:38 +00001298 else if (ArgName == "EnumArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001299 Ptr = std::make_unique<EnumArgument>(Arg, Attr);
David Blaikie28f30ca2014-08-08 23:59:38 +00001300 else if (ArgName == "ExprArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001301 Ptr = std::make_unique<ExprArgument>(Arg, Attr);
Richard Smithb09ee882020-04-14 23:28:33 -07001302 else if (ArgName == "DeclArgument")
1303 Ptr = std::make_unique<SimpleArgument>(
1304 Arg, Attr, (Arg.getValueAsDef("Kind")->getName() + "Decl *").str());
Peter Collingbournebee583f2011-10-06 13:03:08 +00001305 else if (ArgName == "IdentifierArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001306 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
David Majnemer4bb09802014-02-10 19:50:15 +00001307 else if (ArgName == "DefaultBoolArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001308 Ptr = std::make_unique<DefaultSimpleArgument>(
David Blaikie28f30ca2014-08-08 23:59:38 +00001309 Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1310 else if (ArgName == "BoolArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001311 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "bool");
Aaron Ballman18a78382013-11-21 00:28:23 +00001312 else if (ArgName == "DefaultIntArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001313 Ptr = std::make_unique<DefaultSimpleArgument>(
David Blaikie28f30ca2014-08-08 23:59:38 +00001314 Arg, Attr, "int", Arg.getValueAsInt("Default"));
1315 else if (ArgName == "IntArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001316 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "int");
David Blaikie28f30ca2014-08-08 23:59:38 +00001317 else if (ArgName == "StringArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001318 Ptr = std::make_unique<StringArgument>(Arg, Attr);
David Blaikie28f30ca2014-08-08 23:59:38 +00001319 else if (ArgName == "TypeArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001320 Ptr = std::make_unique<TypeArgument>(Arg, Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001321 else if (ArgName == "UnsignedArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001322 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
Peter Collingbournebee583f2011-10-06 13:03:08 +00001323 else if (ArgName == "VariadicUnsignedArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001324 Ptr = std::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
Peter Collingbourne915df992015-05-15 18:33:32 +00001325 else if (ArgName == "VariadicStringArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001326 Ptr = std::make_unique<VariadicStringArgument>(Arg, Attr);
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001327 else if (ArgName == "VariadicEnumArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001328 Ptr = std::make_unique<VariadicEnumArgument>(Arg, Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001329 else if (ArgName == "VariadicExprArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001330 Ptr = std::make_unique<VariadicExprArgument>(Arg, Attr);
Joel E. Denny81508102018-03-13 14:51:22 +00001331 else if (ArgName == "VariadicParamIdxArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001332 Ptr = std::make_unique<VariadicParamIdxArgument>(Arg, Attr);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00001333 else if (ArgName == "VariadicParamOrParamIdxArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001334 Ptr = std::make_unique<VariadicParamOrParamIdxArgument>(Arg, Attr);
Joel E. Denny81508102018-03-13 14:51:22 +00001335 else if (ArgName == "ParamIdxArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001336 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "ParamIdx");
Erich Keane3efe0022018-07-20 14:13:28 +00001337 else if (ArgName == "VariadicIdentifierArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001338 Ptr = std::make_unique<VariadicIdentifierArgument>(Arg, Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001339 else if (ArgName == "VersionArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001340 Ptr = std::make_unique<VersionArgument>(Arg, Attr);
Johannes Doerfert1228d422019-12-19 20:42:12 -06001341 else if (ArgName == "OMPTraitInfoArgument")
Johannes Doerfert55eca282020-03-13 23:42:05 -05001342 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "OMPTraitInfo *");
Peter Collingbournebee583f2011-10-06 13:03:08 +00001343
1344 if (!Ptr) {
Aaron Ballman18a78382013-11-21 00:28:23 +00001345 // Search in reverse order so that the most-derived type is handled first.
Craig Topper25761242016-01-18 19:52:54 +00001346 ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
David Majnemerf7e36092016-06-23 00:15:04 +00001347 for (const auto &Base : llvm::reverse(Bases)) {
Craig Topper25761242016-01-18 19:52:54 +00001348 if ((Ptr = createArgument(Arg, Attr, Base.first)))
Peter Collingbournebee583f2011-10-06 13:03:08 +00001349 break;
1350 }
1351 }
Aaron Ballman8ee40b72013-09-09 23:33:17 +00001352
1353 if (Ptr && Arg.getValueAsBit("Optional"))
1354 Ptr->setOptional(true);
1355
John McCalla62c1a92015-10-28 00:17:34 +00001356 if (Ptr && Arg.getValueAsBit("Fake"))
1357 Ptr->setFake(true);
1358
David Blaikie28f30ca2014-08-08 23:59:38 +00001359 return Ptr;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001360}
1361
Douglas Gregor49ccfaa2011-11-19 19:22:57 +00001362static void writeAvailabilityValue(raw_ostream &OS) {
1363 OS << "\" << getPlatform()->getName();\n"
Manman Ren42e09eb2016-03-10 23:54:12 +00001364 << " if (getStrict()) OS << \", strict\";\n"
Douglas Gregor49ccfaa2011-11-19 19:22:57 +00001365 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1366 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1367 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1368 << " if (getUnavailable()) OS << \", unavailable\";\n"
1369 << " OS << \"";
1370}
1371
Manman Renc7890fe2016-03-16 18:50:49 +00001372static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
1373 OS << "\\\"\" << getMessage() << \"\\\"\";\n";
1374 // Only GNU deprecated has an optional fixit argument at the second position.
1375 if (Variety == "GNU")
1376 OS << " if (!getReplacement().empty()) OS << \", \\\"\""
1377 " << getReplacement() << \"\\\"\";\n";
1378 OS << " OS << \"";
1379}
1380
Reid Kleckner7420f962020-03-11 19:43:37 -07001381static void writeGetSpellingFunction(const Record &R, raw_ostream &OS) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001382 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Aaron Ballman3e424b52013-12-26 18:30:57 +00001383
1384 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1385 if (Spellings.empty()) {
1386 OS << " return \"(No spelling)\";\n}\n\n";
1387 return;
1388 }
1389
Erich Keane6a24e802019-09-13 17:39:31 +00001390 OS << " switch (getAttributeSpellingListIndex()) {\n"
Aaron Ballman3e424b52013-12-26 18:30:57 +00001391 " default:\n"
1392 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1393 " return \"(No spelling)\";\n";
1394
1395 for (unsigned I = 0; I < Spellings.size(); ++I)
1396 OS << " case " << I << ":\n"
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001397 " return \"" << Spellings[I].name() << "\";\n";
Aaron Ballman3e424b52013-12-26 18:30:57 +00001398 // End of the switch statement.
1399 OS << " }\n";
1400 // End of the getSpelling function.
1401 OS << "}\n\n";
1402}
1403
Aaron Ballman8f1439b2014-03-05 16:49:55 +00001404static void
Reid Kleckner7420f962020-03-11 19:43:37 -07001405writePrettyPrintFunction(const Record &R,
Aaron Ballman8f1439b2014-03-05 16:49:55 +00001406 const std::vector<std::unique_ptr<Argument>> &Args,
1407 raw_ostream &OS) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001408 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Michael Han99315932013-01-24 16:46:58 +00001409
1410 OS << "void " << R.getName() << "Attr::printPretty("
1411 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1412
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001413 if (Spellings.empty()) {
Michael Han99315932013-01-24 16:46:58 +00001414 OS << "}\n\n";
1415 return;
1416 }
1417
Erich Keane6a24e802019-09-13 17:39:31 +00001418 OS << " switch (getAttributeSpellingListIndex()) {\n"
1419 " default:\n"
1420 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1421 " break;\n";
Michael Han99315932013-01-24 16:46:58 +00001422
1423 for (unsigned I = 0; I < Spellings.size(); ++ I) {
1424 llvm::SmallString<16> Prefix;
1425 llvm::SmallString<8> Suffix;
1426 // The actual spelling of the name and namespace (if applicable)
1427 // of an attribute without considering prefix and suffix.
1428 llvm::SmallString<64> Spelling;
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001429 std::string Name = Spellings[I].name();
1430 std::string Variety = Spellings[I].variety();
Michael Han99315932013-01-24 16:46:58 +00001431
1432 if (Variety == "GNU") {
1433 Prefix = " __attribute__((";
1434 Suffix = "))";
Aaron Ballman606093a2017-10-15 15:01:42 +00001435 } else if (Variety == "CXX11" || Variety == "C2x") {
Michael Han99315932013-01-24 16:46:58 +00001436 Prefix = " [[";
1437 Suffix = "]]";
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001438 std::string Namespace = Spellings[I].nameSpace();
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001439 if (!Namespace.empty()) {
Michael Han99315932013-01-24 16:46:58 +00001440 Spelling += Namespace;
1441 Spelling += "::";
1442 }
1443 } else if (Variety == "Declspec") {
1444 Prefix = " __declspec(";
1445 Suffix = ")";
Nico Weber20e08042016-09-03 02:55:10 +00001446 } else if (Variety == "Microsoft") {
1447 Prefix = "[";
1448 Suffix = "]";
Richard Smith0cdcc982013-01-29 01:24:26 +00001449 } else if (Variety == "Keyword") {
1450 Prefix = " ";
1451 Suffix = "";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001452 } else if (Variety == "Pragma") {
1453 Prefix = "#pragma ";
1454 Suffix = "\n";
1455 std::string Namespace = Spellings[I].nameSpace();
1456 if (!Namespace.empty()) {
1457 Spelling += Namespace;
1458 Spelling += " ";
1459 }
Michael Han99315932013-01-24 16:46:58 +00001460 } else {
Richard Smith0cdcc982013-01-29 01:24:26 +00001461 llvm_unreachable("Unknown attribute syntax variety!");
Michael Han99315932013-01-24 16:46:58 +00001462 }
1463
1464 Spelling += Name;
1465
1466 OS <<
1467 " case " << I << " : {\n"
Yaron Keren09fb7c62015-03-10 07:33:23 +00001468 " OS << \"" << Prefix << Spelling;
Michael Han99315932013-01-24 16:46:58 +00001469
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001470 if (Variety == "Pragma") {
Alexey Bataevcbecfdf2018-02-14 17:38:47 +00001471 OS << "\";\n";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001472 OS << " printPrettyPragma(OS, Policy);\n";
Alexey Bataev6d455322015-10-12 06:59:48 +00001473 OS << " OS << \"\\n\";";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001474 OS << " break;\n";
1475 OS << " }\n";
1476 continue;
1477 }
1478
Michael Han99315932013-01-24 16:46:58 +00001479 if (Spelling == "availability") {
Aaron Ballman48a533d2018-02-27 23:49:28 +00001480 OS << "(";
Michael Han99315932013-01-24 16:46:58 +00001481 writeAvailabilityValue(OS);
Aaron Ballman48a533d2018-02-27 23:49:28 +00001482 OS << ")";
Manman Renc7890fe2016-03-16 18:50:49 +00001483 } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
Aaron Ballman48a533d2018-02-27 23:49:28 +00001484 OS << "(";
1485 writeDeprecatedAttrValue(OS, Variety);
1486 OS << ")";
Michael Han99315932013-01-24 16:46:58 +00001487 } else {
Aaron Ballman48a533d2018-02-27 23:49:28 +00001488 // To avoid printing parentheses around an empty argument list or
1489 // printing spurious commas at the end of an argument list, we need to
1490 // determine where the last provided non-fake argument is.
1491 unsigned NonFakeArgs = 0;
1492 unsigned TrailingOptArgs = 0;
1493 bool FoundNonOptArg = false;
1494 for (const auto &arg : llvm::reverse(Args)) {
1495 if (arg->isFake())
1496 continue;
1497 ++NonFakeArgs;
1498 if (FoundNonOptArg)
1499 continue;
1500 // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
1501 // any way to detect whether the argument was omitted.
1502 if (!arg->isOptional() || arg->getIsOmitted() == "false") {
1503 FoundNonOptArg = true;
1504 continue;
1505 }
1506 if (!TrailingOptArgs++)
1507 OS << "\";\n"
1508 << " unsigned TrailingOmittedArgs = 0;\n";
1509 OS << " if (" << arg->getIsOmitted() << ")\n"
1510 << " ++TrailingOmittedArgs;\n";
Michael Han99315932013-01-24 16:46:58 +00001511 }
Aaron Ballman48a533d2018-02-27 23:49:28 +00001512 if (TrailingOptArgs)
1513 OS << " OS << \"";
1514 if (TrailingOptArgs < NonFakeArgs)
1515 OS << "(";
1516 else if (TrailingOptArgs)
1517 OS << "\";\n"
1518 << " if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
1519 << " OS << \"(\";\n"
1520 << " OS << \"";
1521 unsigned ArgIndex = 0;
1522 for (const auto &arg : Args) {
1523 if (arg->isFake())
1524 continue;
1525 if (ArgIndex) {
1526 if (ArgIndex >= NonFakeArgs - TrailingOptArgs)
1527 OS << "\";\n"
1528 << " if (" << ArgIndex << " < " << NonFakeArgs
1529 << " - TrailingOmittedArgs)\n"
1530 << " OS << \", \";\n"
1531 << " OS << \"";
1532 else
1533 OS << ", ";
1534 }
1535 std::string IsOmitted = arg->getIsOmitted();
1536 if (arg->isOptional() && IsOmitted != "false")
1537 OS << "\";\n"
1538 << " if (!(" << IsOmitted << ")) {\n"
1539 << " OS << \"";
1540 arg->writeValue(OS);
1541 if (arg->isOptional() && IsOmitted != "false")
1542 OS << "\";\n"
1543 << " }\n"
1544 << " OS << \"";
1545 ++ArgIndex;
1546 }
1547 if (TrailingOptArgs < NonFakeArgs)
1548 OS << ")";
1549 else if (TrailingOptArgs)
1550 OS << "\";\n"
1551 << " if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
1552 << " OS << \")\";\n"
1553 << " OS << \"";
Michael Han99315932013-01-24 16:46:58 +00001554 }
1555
Yaron Keren09fb7c62015-03-10 07:33:23 +00001556 OS << Suffix + "\";\n";
Michael Han99315932013-01-24 16:46:58 +00001557
1558 OS <<
1559 " break;\n"
1560 " }\n";
1561 }
1562
1563 // End of the switch statement.
1564 OS << "}\n";
1565 // End of the print function.
1566 OS << "}\n\n";
1567}
1568
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001569/// Return the index of a spelling in a spelling list.
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001570static unsigned
1571getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1572 const FlattenedSpelling &Spelling) {
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00001573 assert(!SpellingList.empty() && "Spelling list is empty!");
Michael Hanaf02bbe2013-02-01 01:19:17 +00001574
1575 for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001576 const FlattenedSpelling &S = SpellingList[Index];
1577 if (S.variety() != Spelling.variety())
Michael Hanaf02bbe2013-02-01 01:19:17 +00001578 continue;
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001579 if (S.nameSpace() != Spelling.nameSpace())
Michael Hanaf02bbe2013-02-01 01:19:17 +00001580 continue;
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001581 if (S.name() != Spelling.name())
Michael Hanaf02bbe2013-02-01 01:19:17 +00001582 continue;
1583
1584 return Index;
1585 }
1586
1587 llvm_unreachable("Unknown spelling!");
1588}
1589
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001590static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
Michael Hanaf02bbe2013-02-01 01:19:17 +00001591 std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
George Burgess IV1881a572016-12-01 00:13:18 +00001592 if (Accessors.empty())
1593 return;
1594
1595 const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1596 assert(!SpellingList.empty() &&
1597 "Attribute with empty spelling list can't have accessors!");
Aaron Ballman2f22b942014-05-20 19:47:14 +00001598 for (const auto *Accessor : Accessors) {
Erich Keane3bff4142017-10-16 23:25:24 +00001599 const StringRef Name = Accessor->getValueAsString("Name");
George Burgess IV1881a572016-12-01 00:13:18 +00001600 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
Michael Hanaf02bbe2013-02-01 01:19:17 +00001601
Erich Keane6a24e802019-09-13 17:39:31 +00001602 OS << " bool " << Name
1603 << "() const { return getAttributeSpellingListIndex() == ";
Michael Hanaf02bbe2013-02-01 01:19:17 +00001604 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001605 OS << getSpellingListIndex(SpellingList, Spellings[Index]);
George Burgess IV1881a572016-12-01 00:13:18 +00001606 if (Index != Spellings.size() - 1)
Erich Keane6a24e802019-09-13 17:39:31 +00001607 OS << " ||\n getAttributeSpellingListIndex() == ";
Michael Hanaf02bbe2013-02-01 01:19:17 +00001608 else
1609 OS << "; }\n";
1610 }
1611 }
1612}
1613
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001614static bool
1615SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
Aaron Ballman36a53502014-01-16 13:03:14 +00001616 assert(!Spellings.empty() && "An empty list of spellings was provided");
Benjamin Krameradcd0262020-01-28 20:23:46 +01001617 std::string FirstName =
1618 std::string(NormalizeNameForSpellingComparison(Spellings.front().name()));
Aaron Ballman2f22b942014-05-20 19:47:14 +00001619 for (const auto &Spelling :
1620 llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01001621 std::string Name =
1622 std::string(NormalizeNameForSpellingComparison(Spelling.name()));
Aaron Ballman36a53502014-01-16 13:03:14 +00001623 if (Name != FirstName)
1624 return false;
1625 }
1626 return true;
1627}
1628
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001629typedef std::map<unsigned, std::string> SemanticSpellingMap;
1630static std::string
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001631CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001632 SemanticSpellingMap &Map) {
1633 // The enumerants are automatically generated based on the variety,
1634 // namespace (if present) and name for each attribute spelling. However,
1635 // care is taken to avoid trampling on the reserved namespace due to
1636 // underscores.
1637 std::string Ret(" enum Spelling {\n");
1638 std::set<std::string> Uniques;
1639 unsigned Idx = 0;
Erich Keane68b09772019-09-17 14:11:51 +00001640
1641 // If we have a need to have this many spellings we likely need to add an
1642 // extra bit to the SpellingIndex in AttributeCommonInfo, then increase the
1643 // value of SpellingNotCalculated there and here.
1644 assert(Spellings.size() < 15 &&
1645 "Too many spellings, would step on SpellingNotCalculated in "
1646 "AttributeCommonInfo");
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001647 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001648 const FlattenedSpelling &S = *I;
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00001649 const std::string &Variety = S.variety();
1650 const std::string &Spelling = S.name();
1651 const std::string &Namespace = S.nameSpace();
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001652 std::string EnumName;
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001653
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001654 EnumName += (Variety + "_");
1655 if (!Namespace.empty())
1656 EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1657 "_");
1658 EnumName += NormalizeNameForSpellingComparison(Spelling);
1659
1660 // Even if the name is not unique, this spelling index corresponds to a
1661 // particular enumerant name that we've calculated.
1662 Map[Idx] = EnumName;
1663
1664 // Since we have been stripping underscores to avoid trampling on the
1665 // reserved namespace, we may have inadvertently created duplicate
1666 // enumerant names. These duplicates are not considered part of the
1667 // semantic spelling, and can be elided.
1668 if (Uniques.find(EnumName) != Uniques.end())
1669 continue;
1670
1671 Uniques.insert(EnumName);
1672 if (I != Spellings.begin())
1673 Ret += ",\n";
Aaron Ballman9bf6b752015-03-10 17:19:18 +00001674 // Duplicate spellings are not considered part of the semantic spelling
1675 // enumeration, but the spelling index and semantic spelling values are
1676 // meant to be equivalent, so we must specify a concrete value for each
1677 // enumerator.
1678 Ret += " " + EnumName + " = " + llvm::utostr(Idx);
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001679 }
Erich Keane68b09772019-09-17 14:11:51 +00001680 Ret += ",\n SpellingNotCalculated = 15\n";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001681 Ret += "\n };\n\n";
1682 return Ret;
1683}
1684
1685void WriteSemanticSpellingSwitch(const std::string &VarName,
1686 const SemanticSpellingMap &Map,
1687 raw_ostream &OS) {
1688 OS << " switch (" << VarName << ") {\n default: "
1689 << "llvm_unreachable(\"Unknown spelling list index\");\n";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001690 for (const auto &I : Map)
1691 OS << " case " << I.first << ": return " << I.second << ";\n";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001692 OS << " }\n";
1693}
1694
Aaron Ballman35db2b32014-01-29 22:13:45 +00001695// Emits the LateParsed property for attributes.
1696static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1697 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1698 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1699
Aaron Ballman2f22b942014-05-20 19:47:14 +00001700 for (const auto *Attr : Attrs) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001701 bool LateParsed = Attr->getValueAsBit("LateParsed");
Aaron Ballman35db2b32014-01-29 22:13:45 +00001702
1703 if (LateParsed) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001704 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
Aaron Ballman35db2b32014-01-29 22:13:45 +00001705
1706 // FIXME: Handle non-GNU attributes
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001707 for (const auto &I : Spellings) {
1708 if (I.variety() != "GNU")
Aaron Ballman35db2b32014-01-29 22:13:45 +00001709 continue;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001710 OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
Aaron Ballman35db2b32014-01-29 22:13:45 +00001711 }
1712 }
1713 }
1714 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1715}
1716
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001717static bool hasGNUorCXX11Spelling(const Record &Attribute) {
1718 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
1719 for (const auto &I : Spellings) {
1720 if (I.variety() == "GNU" || I.variety() == "CXX11")
1721 return true;
1722 }
1723 return false;
1724}
1725
1726namespace {
1727
1728struct AttributeSubjectMatchRule {
1729 const Record *MetaSubject;
1730 const Record *Constraint;
1731
1732 AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
1733 : MetaSubject(MetaSubject), Constraint(Constraint) {
1734 assert(MetaSubject && "Missing subject");
1735 }
1736
1737 bool isSubRule() const { return Constraint != nullptr; }
1738
1739 std::vector<Record *> getSubjects() const {
1740 return (Constraint ? Constraint : MetaSubject)
1741 ->getValueAsListOfDefs("Subjects");
1742 }
1743
1744 std::vector<Record *> getLangOpts() const {
1745 if (Constraint) {
1746 // Lookup the options in the sub-rule first, in case the sub-rule
1747 // overrides the rules options.
1748 std::vector<Record *> Opts = Constraint->getValueAsListOfDefs("LangOpts");
1749 if (!Opts.empty())
1750 return Opts;
1751 }
1752 return MetaSubject->getValueAsListOfDefs("LangOpts");
1753 }
1754
1755 // Abstract rules are used only for sub-rules
1756 bool isAbstractRule() const { return getSubjects().empty(); }
1757
Erich Keane3bff4142017-10-16 23:25:24 +00001758 StringRef getName() const {
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001759 return (Constraint ? Constraint : MetaSubject)->getValueAsString("Name");
1760 }
1761
1762 bool isNegatedSubRule() const {
1763 assert(isSubRule() && "Not a sub-rule");
1764 return Constraint->getValueAsBit("Negated");
1765 }
1766
1767 std::string getSpelling() const {
Benjamin Krameradcd0262020-01-28 20:23:46 +01001768 std::string Result = std::string(MetaSubject->getValueAsString("Name"));
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001769 if (isSubRule()) {
1770 Result += '(';
1771 if (isNegatedSubRule())
1772 Result += "unless(";
1773 Result += getName();
1774 if (isNegatedSubRule())
1775 Result += ')';
1776 Result += ')';
1777 }
1778 return Result;
1779 }
1780
1781 std::string getEnumValueName() const {
Craig Topper00648582017-05-31 19:01:22 +00001782 SmallString<128> Result;
1783 Result += "SubjectMatchRule_";
1784 Result += MetaSubject->getValueAsString("Name");
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001785 if (isSubRule()) {
1786 Result += "_";
1787 if (isNegatedSubRule())
1788 Result += "not_";
1789 Result += Constraint->getValueAsString("Name");
1790 }
1791 if (isAbstractRule())
1792 Result += "_abstract";
Benjamin Krameradcd0262020-01-28 20:23:46 +01001793 return std::string(Result.str());
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001794 }
1795
1796 std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
1797
1798 static const char *EnumName;
1799};
1800
1801const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";
1802
1803struct PragmaClangAttributeSupport {
1804 std::vector<AttributeSubjectMatchRule> Rules;
Alex Lorenz24952fb2017-04-19 15:52:11 +00001805
1806 class RuleOrAggregateRuleSet {
1807 std::vector<AttributeSubjectMatchRule> Rules;
1808 bool IsRule;
1809 RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
1810 bool IsRule)
1811 : Rules(Rules), IsRule(IsRule) {}
1812
1813 public:
1814 bool isRule() const { return IsRule; }
1815
1816 const AttributeSubjectMatchRule &getRule() const {
1817 assert(IsRule && "not a rule!");
1818 return Rules[0];
1819 }
1820
1821 ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
1822 return Rules;
1823 }
1824
1825 static RuleOrAggregateRuleSet
1826 getRule(const AttributeSubjectMatchRule &Rule) {
1827 return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
1828 }
1829 static RuleOrAggregateRuleSet
1830 getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
1831 return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
1832 }
1833 };
1834 llvm::DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001835
1836 PragmaClangAttributeSupport(RecordKeeper &Records);
1837
1838 bool isAttributedSupported(const Record &Attribute);
1839
1840 void emitMatchRuleList(raw_ostream &OS);
1841
John Brawn590dc8d2020-02-26 16:31:24 +00001842 void generateStrictConformsTo(const Record &Attr, raw_ostream &OS);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001843
1844 void generateParsingHelpers(raw_ostream &OS);
1845};
1846
1847} // end anonymous namespace
1848
Alex Lorenz24952fb2017-04-19 15:52:11 +00001849static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
John McCallbaf91d02019-10-25 16:28:03 -07001850 const Record *CurrentBase = D->getValueAsOptionalDef(BaseFieldName);
Alex Lorenz24952fb2017-04-19 15:52:11 +00001851 if (!CurrentBase)
1852 return false;
1853 if (CurrentBase == Base)
1854 return true;
1855 return doesDeclDeriveFrom(CurrentBase, Base);
1856}
1857
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001858PragmaClangAttributeSupport::PragmaClangAttributeSupport(
1859 RecordKeeper &Records) {
1860 std::vector<Record *> MetaSubjects =
1861 Records.getAllDerivedDefinitions("AttrSubjectMatcherRule");
1862 auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
1863 const Record *MetaSubject,
Saleem Abdulrasoolbe4773c2017-05-01 00:26:59 +00001864 const Record *Constraint) {
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001865 Rules.emplace_back(MetaSubject, Constraint);
1866 std::vector<Record *> ApplicableSubjects =
1867 SubjectContainer->getValueAsListOfDefs("Subjects");
1868 for (const auto *Subject : ApplicableSubjects) {
1869 bool Inserted =
Alex Lorenz24952fb2017-04-19 15:52:11 +00001870 SubjectsToRules
1871 .try_emplace(Subject, RuleOrAggregateRuleSet::getRule(
1872 AttributeSubjectMatchRule(MetaSubject,
1873 Constraint)))
1874 .second;
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001875 if (!Inserted) {
1876 PrintFatalError("Attribute subject match rules should not represent"
1877 "same attribute subjects.");
1878 }
1879 }
1880 };
1881 for (const auto *MetaSubject : MetaSubjects) {
Saleem Abdulrasoolbe4773c2017-05-01 00:26:59 +00001882 MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001883 std::vector<Record *> Constraints =
1884 MetaSubject->getValueAsListOfDefs("Constraints");
1885 for (const auto *Constraint : Constraints)
1886 MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
1887 }
Alex Lorenz24952fb2017-04-19 15:52:11 +00001888
1889 std::vector<Record *> Aggregates =
1890 Records.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule");
John McCallbaf91d02019-10-25 16:28:03 -07001891 std::vector<Record *> DeclNodes =
1892 Records.getAllDerivedDefinitions(DeclNodeClassName);
Alex Lorenz24952fb2017-04-19 15:52:11 +00001893 for (const auto *Aggregate : Aggregates) {
1894 Record *SubjectDecl = Aggregate->getValueAsDef("Subject");
1895
1896 // Gather sub-classes of the aggregate subject that act as attribute
1897 // subject rules.
1898 std::vector<AttributeSubjectMatchRule> Rules;
1899 for (const auto *D : DeclNodes) {
1900 if (doesDeclDeriveFrom(D, SubjectDecl)) {
1901 auto It = SubjectsToRules.find(D);
1902 if (It == SubjectsToRules.end())
1903 continue;
1904 if (!It->second.isRule() || It->second.getRule().isSubRule())
1905 continue; // Assume that the rule will be included as well.
1906 Rules.push_back(It->second.getRule());
1907 }
1908 }
1909
1910 bool Inserted =
1911 SubjectsToRules
1912 .try_emplace(SubjectDecl,
1913 RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
1914 .second;
1915 if (!Inserted) {
1916 PrintFatalError("Attribute subject match rules should not represent"
1917 "same attribute subjects.");
1918 }
1919 }
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001920}
1921
1922static PragmaClangAttributeSupport &
1923getPragmaAttributeSupport(RecordKeeper &Records) {
1924 static PragmaClangAttributeSupport Instance(Records);
1925 return Instance;
1926}
1927
1928void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
1929 OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
1930 OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
1931 "IsNegated) "
1932 << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
1933 OS << "#endif\n";
1934 for (const auto &Rule : Rules) {
1935 OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
1936 OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
1937 << Rule.isAbstractRule();
1938 if (Rule.isSubRule())
1939 OS << ", "
1940 << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
1941 << ", " << Rule.isNegatedSubRule();
1942 OS << ")\n";
1943 }
1944 OS << "#undef ATTR_MATCH_SUB_RULE\n";
1945}
1946
1947bool PragmaClangAttributeSupport::isAttributedSupported(
1948 const Record &Attribute) {
Richard Smith1bb64532018-08-30 01:01:07 +00001949 // If the attribute explicitly specified whether to support #pragma clang
1950 // attribute, use that setting.
1951 bool Unset;
1952 bool SpecifiedResult =
1953 Attribute.getValueAsBitOrUnset("PragmaAttributeSupport", Unset);
1954 if (!Unset)
1955 return SpecifiedResult;
1956
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001957 // Opt-out rules:
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001958 // An attribute requires delayed parsing (LateParsed is on)
1959 if (Attribute.getValueAsBit("LateParsed"))
1960 return false;
1961 // An attribute has no GNU/CXX11 spelling
1962 if (!hasGNUorCXX11Spelling(Attribute))
1963 return false;
1964 // An attribute subject list has a subject that isn't covered by one of the
1965 // subject match rules or has no subjects at all.
1966 if (Attribute.isValueUnset("Subjects"))
1967 return false;
1968 const Record *SubjectObj = Attribute.getValueAsDef("Subjects");
1969 std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
1970 if (Subjects.empty())
1971 return false;
1972 for (const auto *Subject : Subjects) {
1973 if (SubjectsToRules.find(Subject) == SubjectsToRules.end())
1974 return false;
1975 }
1976 return true;
1977}
1978
John McCall2c91c3b2019-05-30 04:09:01 +00001979static std::string GenerateTestExpression(ArrayRef<Record *> LangOpts) {
1980 std::string Test;
1981
1982 for (auto *E : LangOpts) {
1983 if (!Test.empty())
1984 Test += " || ";
1985
1986 const StringRef Code = E->getValueAsString("CustomCode");
1987 if (!Code.empty()) {
1988 Test += "(";
1989 Test += Code;
1990 Test += ")";
Aaron Ballmaneda58ac2020-03-14 15:57:28 -04001991 if (!E->getValueAsString("Name").empty()) {
1992 PrintWarning(
1993 E->getLoc(),
1994 "non-empty 'Name' field ignored because 'CustomCode' was supplied");
1995 }
John McCall2c91c3b2019-05-30 04:09:01 +00001996 } else {
1997 Test += "LangOpts.";
1998 Test += E->getValueAsString("Name");
1999 }
2000 }
2001
2002 if (Test.empty())
2003 return "true";
2004
2005 return Test;
2006}
2007
John Brawn590dc8d2020-02-26 16:31:24 +00002008void
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002009PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
2010 raw_ostream &OS) {
John Brawn590dc8d2020-02-26 16:31:24 +00002011 if (!isAttributedSupported(Attr) || Attr.isValueUnset("Subjects"))
2012 return;
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002013 // Generate a function that constructs a set of matching rules that describe
2014 // to which declarations the attribute should apply to.
John Brawn590dc8d2020-02-26 16:31:24 +00002015 OS << "virtual void getPragmaAttributeMatchRules("
2016 << "llvm::SmallVectorImpl<std::pair<"
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002017 << AttributeSubjectMatchRule::EnumName
John Brawn590dc8d2020-02-26 16:31:24 +00002018 << ", bool>> &MatchRules, const LangOptions &LangOpts) const {\n";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002019 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
2020 std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
2021 for (const auto *Subject : Subjects) {
2022 auto It = SubjectsToRules.find(Subject);
2023 assert(It != SubjectsToRules.end() &&
2024 "This attribute is unsupported by #pragma clang attribute");
Alex Lorenz24952fb2017-04-19 15:52:11 +00002025 for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
2026 // The rule might be language specific, so only subtract it from the given
2027 // rules if the specific language options are specified.
2028 std::vector<Record *> LangOpts = Rule.getLangOpts();
Erich Keane3bff4142017-10-16 23:25:24 +00002029 OS << " MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
John McCall2c91c3b2019-05-30 04:09:01 +00002030 << ", /*IsSupported=*/" << GenerateTestExpression(LangOpts)
2031 << "));\n";
Alex Lorenz24952fb2017-04-19 15:52:11 +00002032 }
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002033 }
Erich Keane3bff4142017-10-16 23:25:24 +00002034 OS << "}\n\n";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002035}
2036
2037void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
2038 // Generate routines that check the names of sub-rules.
2039 OS << "Optional<attr::SubjectMatchRule> "
2040 "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
2041 OS << " return None;\n";
2042 OS << "}\n\n";
2043
2044 std::map<const Record *, std::vector<AttributeSubjectMatchRule>>
2045 SubMatchRules;
2046 for (const auto &Rule : Rules) {
2047 if (!Rule.isSubRule())
2048 continue;
2049 SubMatchRules[Rule.MetaSubject].push_back(Rule);
2050 }
2051
2052 for (const auto &SubMatchRule : SubMatchRules) {
2053 OS << "Optional<attr::SubjectMatchRule> isAttributeSubjectMatchSubRuleFor_"
2054 << SubMatchRule.first->getValueAsString("Name")
2055 << "(StringRef Name, bool IsUnless) {\n";
2056 OS << " if (IsUnless)\n";
2057 OS << " return "
2058 "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
2059 for (const auto &Rule : SubMatchRule.second) {
2060 if (Rule.isNegatedSubRule())
2061 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2062 << ").\n";
2063 }
2064 OS << " Default(None);\n";
2065 OS << " return "
2066 "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
2067 for (const auto &Rule : SubMatchRule.second) {
2068 if (!Rule.isNegatedSubRule())
2069 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2070 << ").\n";
2071 }
2072 OS << " Default(None);\n";
2073 OS << "}\n\n";
2074 }
2075
2076 // Generate the function that checks for the top-level rules.
2077 OS << "std::pair<Optional<attr::SubjectMatchRule>, "
2078 "Optional<attr::SubjectMatchRule> (*)(StringRef, "
2079 "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
2080 OS << " return "
2081 "llvm::StringSwitch<std::pair<Optional<attr::SubjectMatchRule>, "
2082 "Optional<attr::SubjectMatchRule> (*) (StringRef, "
2083 "bool)>>(Name).\n";
2084 for (const auto &Rule : Rules) {
2085 if (Rule.isSubRule())
2086 continue;
2087 std::string SubRuleFunction;
2088 if (SubMatchRules.count(Rule.MetaSubject))
Erich Keane3bff4142017-10-16 23:25:24 +00002089 SubRuleFunction =
2090 ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002091 else
2092 SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
2093 OS << " Case(\"" << Rule.getName() << "\", std::make_pair("
2094 << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
2095 }
2096 OS << " Default(std::make_pair(None, "
2097 "defaultIsAttributeSubjectMatchSubRuleFor));\n";
2098 OS << "}\n\n";
2099
2100 // Generate the function that checks for the submatch rules.
2101 OS << "const char *validAttributeSubjectMatchSubRules("
2102 << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
2103 OS << " switch (Rule) {\n";
2104 for (const auto &SubMatchRule : SubMatchRules) {
2105 OS << " case "
2106 << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
2107 << ":\n";
2108 OS << " return \"'";
2109 bool IsFirst = true;
2110 for (const auto &Rule : SubMatchRule.second) {
2111 if (!IsFirst)
2112 OS << ", '";
2113 IsFirst = false;
2114 if (Rule.isNegatedSubRule())
2115 OS << "unless(";
2116 OS << Rule.getName();
2117 if (Rule.isNegatedSubRule())
2118 OS << ')';
2119 OS << "'";
2120 }
2121 OS << "\";\n";
2122 }
2123 OS << " default: return nullptr;\n";
2124 OS << " }\n";
2125 OS << "}\n\n";
2126}
2127
George Burgess IV1881a572016-12-01 00:13:18 +00002128template <typename Fn>
2129static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
2130 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2131 SmallDenseSet<StringRef, 8> Seen;
2132 for (const FlattenedSpelling &S : Spellings) {
2133 if (Seen.insert(S.name()).second)
2134 F(S);
2135 }
2136}
2137
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002138/// Emits the first-argument-is-type property for attributes.
Aaron Ballman35db2b32014-01-29 22:13:45 +00002139static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
2140 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
2141 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2142
Aaron Ballman2f22b942014-05-20 19:47:14 +00002143 for (const auto *Attr : Attrs) {
Aaron Ballman35db2b32014-01-29 22:13:45 +00002144 // Determine whether the first argument is a type.
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002145 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
Aaron Ballman35db2b32014-01-29 22:13:45 +00002146 if (Args.empty())
2147 continue;
2148
Craig Topper25761242016-01-18 19:52:54 +00002149 if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
Aaron Ballman35db2b32014-01-29 22:13:45 +00002150 continue;
2151
2152 // All these spellings take a single type argument.
George Burgess IV1881a572016-12-01 00:13:18 +00002153 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2154 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2155 });
Aaron Ballman35db2b32014-01-29 22:13:45 +00002156 }
2157 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
2158}
2159
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002160/// Emits the parse-arguments-in-unevaluated-context property for
Aaron Ballman35db2b32014-01-29 22:13:45 +00002161/// attributes.
2162static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
2163 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
2164 ParsedAttrMap Attrs = getParsedAttrList(Records);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002165 for (const auto &I : Attrs) {
2166 const Record &Attr = *I.second;
Aaron Ballman35db2b32014-01-29 22:13:45 +00002167
2168 if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
2169 continue;
2170
2171 // All these spellings take are parsed unevaluated.
George Burgess IV1881a572016-12-01 00:13:18 +00002172 forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
2173 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2174 });
Aaron Ballman35db2b32014-01-29 22:13:45 +00002175 }
2176 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
2177}
2178
2179static bool isIdentifierArgument(Record *Arg) {
2180 return !Arg->getSuperClasses().empty() &&
Craig Topper25761242016-01-18 19:52:54 +00002181 llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
Aaron Ballman35db2b32014-01-29 22:13:45 +00002182 .Case("IdentifierArgument", true)
2183 .Case("EnumArgument", true)
Aaron Ballman55ef1512014-12-19 16:42:04 +00002184 .Case("VariadicEnumArgument", true)
Aaron Ballman35db2b32014-01-29 22:13:45 +00002185 .Default(false);
2186}
2187
Erich Keane3efe0022018-07-20 14:13:28 +00002188static bool isVariadicIdentifierArgument(Record *Arg) {
2189 return !Arg->getSuperClasses().empty() &&
2190 llvm::StringSwitch<bool>(
2191 Arg->getSuperClasses().back().first->getName())
2192 .Case("VariadicIdentifierArgument", true)
Johannes Doerfertac991bb2019-01-19 05:36:54 +00002193 .Case("VariadicParamOrParamIdxArgument", true)
Erich Keane3efe0022018-07-20 14:13:28 +00002194 .Default(false);
2195}
2196
2197static void emitClangAttrVariadicIdentifierArgList(RecordKeeper &Records,
2198 raw_ostream &OS) {
2199 OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
2200 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2201 for (const auto *A : Attrs) {
2202 // Determine whether the first argument is a variadic identifier.
2203 std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
2204 if (Args.empty() || !isVariadicIdentifierArgument(Args[0]))
2205 continue;
2206
2207 // All these spellings take an identifier argument.
2208 forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
2209 OS << ".Case(\"" << S.name() << "\", "
2210 << "true"
2211 << ")\n";
2212 });
2213 }
2214 OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
2215}
2216
Aaron Ballman35db2b32014-01-29 22:13:45 +00002217// Emits the first-argument-is-identifier property for attributes.
2218static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
2219 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
2220 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2221
Aaron Ballman2f22b942014-05-20 19:47:14 +00002222 for (const auto *Attr : Attrs) {
Aaron Ballman35db2b32014-01-29 22:13:45 +00002223 // Determine whether the first argument is an identifier.
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002224 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
Aaron Ballman35db2b32014-01-29 22:13:45 +00002225 if (Args.empty() || !isIdentifierArgument(Args[0]))
2226 continue;
2227
2228 // All these spellings take an identifier argument.
George Burgess IV1881a572016-12-01 00:13:18 +00002229 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2230 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2231 });
Aaron Ballman35db2b32014-01-29 22:13:45 +00002232 }
2233 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
2234}
2235
Johannes Doerfertac991bb2019-01-19 05:36:54 +00002236static bool keywordThisIsaIdentifierInArgument(const Record *Arg) {
2237 return !Arg->getSuperClasses().empty() &&
2238 llvm::StringSwitch<bool>(
2239 Arg->getSuperClasses().back().first->getName())
2240 .Case("VariadicParamOrParamIdxArgument", true)
2241 .Default(false);
2242}
2243
2244static void emitClangAttrThisIsaIdentifierArgList(RecordKeeper &Records,
2245 raw_ostream &OS) {
2246 OS << "#if defined(CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST)\n";
2247 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2248 for (const auto *A : Attrs) {
2249 // Determine whether the first argument is a variadic identifier.
2250 std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
2251 if (Args.empty() || !keywordThisIsaIdentifierInArgument(Args[0]))
2252 continue;
2253
2254 // All these spellings take an identifier argument.
2255 forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
2256 OS << ".Case(\"" << S.name() << "\", "
2257 << "true"
2258 << ")\n";
2259 });
2260 }
2261 OS << "#endif // CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST\n\n";
2262}
2263
Reid Kleckner7420f962020-03-11 19:43:37 -07002264static void emitAttributes(RecordKeeper &Records, raw_ostream &OS,
2265 bool Header) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00002266 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
Erich Keane6a24e802019-09-13 17:39:31 +00002267 ParsedAttrMap AttrMap = getParsedAttrList(Records);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002268
Aaron Ballman2f22b942014-05-20 19:47:14 +00002269 for (const auto *Attr : Attrs) {
2270 const Record &R = *Attr;
Aaron Ballman06bd44b2014-02-17 18:23:02 +00002271
2272 // FIXME: Currently, documentation is generated as-needed due to the fact
2273 // that there is no way to allow a generated project "reach into" the docs
2274 // directory (for instance, it may be an out-of-tree build). However, we want
2275 // to ensure that every attribute has a Documentation field, and produce an
2276 // error if it has been neglected. Otherwise, the on-demand generation which
2277 // happens server-side will fail. This code is ensuring that functionality,
2278 // even though this Emitter doesn't technically need the documentation.
2279 // When attribute documentation can be generated as part of the build
2280 // itself, this code can be removed.
2281 (void)R.getValueAsListOfDefs("Documentation");
Johannes Doerfert1228d422019-12-19 20:42:12 -06002282
Douglas Gregorb2daf842012-05-02 15:56:52 +00002283 if (!R.getValueAsBit("ASTNode"))
2284 continue;
Johannes Doerfert1228d422019-12-19 20:42:12 -06002285
Craig Topper25761242016-01-18 19:52:54 +00002286 ArrayRef<std::pair<Record *, SMRange>> Supers = R.getSuperClasses();
Aaron Ballman0979e9e2013-07-30 01:44:15 +00002287 assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
Aaron Ballman0979e9e2013-07-30 01:44:15 +00002288 std::string SuperName;
Richard Smith33bddbd2018-01-04 23:42:29 +00002289 bool Inheritable = false;
David Majnemerf7e36092016-06-23 00:15:04 +00002290 for (const auto &Super : llvm::reverse(Supers)) {
Craig Topper25761242016-01-18 19:52:54 +00002291 const Record *R = Super.first;
Aaron Ballmanb9a457a2018-05-03 15:33:50 +00002292 if (R->getName() != "TargetSpecificAttr" &&
2293 R->getName() != "DeclOrTypeAttr" && SuperName.empty())
Benjamin Krameradcd0262020-01-28 20:23:46 +01002294 SuperName = std::string(R->getName());
Richard Smith33bddbd2018-01-04 23:42:29 +00002295 if (R->getName() == "InheritableAttr")
2296 Inheritable = true;
Aaron Ballman0979e9e2013-07-30 01:44:15 +00002297 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00002298
Reid Kleckner7420f962020-03-11 19:43:37 -07002299 if (Header)
2300 OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
2301 else
2302 OS << "\n// " << R.getName() << "Attr implementation\n\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002303
2304 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002305 std::vector<std::unique_ptr<Argument>> Args;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002306 Args.reserve(ArgRecords.size());
2307
John McCalla62c1a92015-10-28 00:17:34 +00002308 bool HasOptArg = false;
2309 bool HasFakeArg = false;
Aaron Ballman2f22b942014-05-20 19:47:14 +00002310 for (const auto *ArgRecord : ArgRecords) {
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002311 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
Reid Kleckner7420f962020-03-11 19:43:37 -07002312 if (Header) {
2313 Args.back()->writeDeclarations(OS);
2314 OS << "\n\n";
2315 }
John McCalla62c1a92015-10-28 00:17:34 +00002316
2317 // For these purposes, fake takes priority over optional.
2318 if (Args.back()->isFake()) {
2319 HasFakeArg = true;
2320 } else if (Args.back()->isOptional()) {
2321 HasOptArg = true;
2322 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00002323 }
2324
Reid Kleckner7420f962020-03-11 19:43:37 -07002325 if (Header)
2326 OS << "public:\n";
Aaron Ballman36a53502014-01-16 13:03:14 +00002327
Aaron Ballmanc669cc02014-01-27 22:10:04 +00002328 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Aaron Ballman36a53502014-01-16 13:03:14 +00002329
2330 // If there are zero or one spellings, all spelling-related functionality
2331 // can be elided. If all of the spellings share the same name, the spelling
2332 // functionality can also be elided.
2333 bool ElideSpelling = (Spellings.size() <= 1) ||
2334 SpellingNamesAreCommon(Spellings);
2335
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00002336 // This maps spelling index values to semantic Spelling enumerants.
2337 SemanticSpellingMap SemanticToSyntacticMap;
Aaron Ballman36a53502014-01-16 13:03:14 +00002338
Reid Kleckner7420f962020-03-11 19:43:37 -07002339 std::string SpellingEnum;
Erich Keane661c9502020-03-17 08:23:45 -07002340 if (Spellings.size() > 1)
Reid Kleckner7420f962020-03-11 19:43:37 -07002341 SpellingEnum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2342 if (Header)
2343 OS << SpellingEnum;
Aaron Ballman36a53502014-01-16 13:03:14 +00002344
Erich Keane6a24e802019-09-13 17:39:31 +00002345 const auto &ParsedAttrSpellingItr = llvm::find_if(
2346 AttrMap, [R](const std::pair<std::string, const Record *> &P) {
2347 return &R == P.second;
2348 });
2349
John McCalla62c1a92015-10-28 00:17:34 +00002350 // Emit CreateImplicit factory methods.
Erich Keane6a24e802019-09-13 17:39:31 +00002351 auto emitCreate = [&](bool Implicit, bool emitFake) {
Reid Kleckner7420f962020-03-11 19:43:37 -07002352 if (Header)
2353 OS << " static ";
2354 OS << R.getName() << "Attr *";
2355 if (!Header)
2356 OS << R.getName() << "Attr::";
2357 OS << "Create";
2358 if (Implicit)
2359 OS << "Implicit";
Erich Keane6a24e802019-09-13 17:39:31 +00002360 OS << "(";
John McCalla62c1a92015-10-28 00:17:34 +00002361 OS << "ASTContext &Ctx";
John McCalla62c1a92015-10-28 00:17:34 +00002362 for (auto const &ai : Args) {
2363 if (ai->isFake() && !emitFake) continue;
2364 OS << ", ";
2365 ai->writeCtorParameters(OS);
2366 }
Reid Kleckner7420f962020-03-11 19:43:37 -07002367 OS << ", const AttributeCommonInfo &CommonInfo";
2368 if (Header)
2369 OS << " = {SourceRange{}}";
2370 OS << ")";
2371 if (Header) {
2372 OS << ";\n";
2373 return;
2374 }
2375
2376 OS << " {\n";
2377 OS << " auto *A = new (Ctx) " << R.getName();
Erich Keane6a24e802019-09-13 17:39:31 +00002378 OS << "Attr(Ctx, CommonInfo";
John McCalla62c1a92015-10-28 00:17:34 +00002379 for (auto const &ai : Args) {
2380 if (ai->isFake() && !emitFake) continue;
John McCalla62c1a92015-10-28 00:17:34 +00002381 OS << ", ";
Erich Keane6a24e802019-09-13 17:39:31 +00002382 ai->writeImplicitCtorArgs(OS);
John McCalla62c1a92015-10-28 00:17:34 +00002383 }
Erich Keane6a24e802019-09-13 17:39:31 +00002384 OS << ");\n";
2385 if (Implicit) {
Reid Kleckner7420f962020-03-11 19:43:37 -07002386 OS << " A->setImplicit(true);\n";
Erich Keane6a24e802019-09-13 17:39:31 +00002387 }
2388 if (Implicit || ElideSpelling) {
Reid Kleckner7420f962020-03-11 19:43:37 -07002389 OS << " if (!A->isAttributeSpellingListCalculated() && "
Erich Keane6a24e802019-09-13 17:39:31 +00002390 "!A->getAttrName())\n";
Reid Kleckner7420f962020-03-11 19:43:37 -07002391 OS << " A->setAttributeSpellingListIndex(0);\n";
Erich Keane6a24e802019-09-13 17:39:31 +00002392 }
Reid Kleckner7420f962020-03-11 19:43:37 -07002393 OS << " return A;\n}\n\n";
John McCalla62c1a92015-10-28 00:17:34 +00002394 };
Aaron Ballman36a53502014-01-16 13:03:14 +00002395
Erich Keane6a24e802019-09-13 17:39:31 +00002396 auto emitCreateNoCI = [&](bool Implicit, bool emitFake) {
Reid Kleckner7420f962020-03-11 19:43:37 -07002397 if (Header)
2398 OS << " static ";
2399 OS << R.getName() << "Attr *";
2400 if (!Header)
2401 OS << R.getName() << "Attr::";
2402 OS << "Create";
Erich Keane6a24e802019-09-13 17:39:31 +00002403 if (Implicit)
2404 OS << "Implicit";
2405 OS << "(";
2406 OS << "ASTContext &Ctx";
2407 for (auto const &ai : Args) {
2408 if (ai->isFake() && !emitFake) continue;
2409 OS << ", ";
2410 ai->writeCtorParameters(OS);
2411 }
2412 OS << ", SourceRange Range, AttributeCommonInfo::Syntax Syntax";
Reid Kleckner7420f962020-03-11 19:43:37 -07002413 if (!ElideSpelling) {
2414 OS << ", " << R.getName() << "Attr::Spelling S";
2415 if (Header)
2416 OS << " = static_cast<Spelling>(SpellingNotCalculated)";
2417 }
2418 OS << ")";
2419 if (Header) {
2420 OS << ";\n";
2421 return;
2422 }
2423
2424 OS << " {\n";
2425 OS << " AttributeCommonInfo I(Range, ";
Erich Keane6a24e802019-09-13 17:39:31 +00002426
2427 if (ParsedAttrSpellingItr != std::end(AttrMap))
2428 OS << "AT_" << ParsedAttrSpellingItr->first;
2429 else
2430 OS << "NoSemaHandlerAttribute";
2431
2432 OS << ", Syntax";
2433 if (!ElideSpelling)
Erich Keanef9cd3812019-09-13 17:56:38 +00002434 OS << ", S";
Erich Keane6a24e802019-09-13 17:39:31 +00002435 OS << ");\n";
Reid Kleckner7420f962020-03-11 19:43:37 -07002436 OS << " return Create";
Erich Keane6a24e802019-09-13 17:39:31 +00002437 if (Implicit)
2438 OS << "Implicit";
2439 OS << "(Ctx";
2440 for (auto const &ai : Args) {
2441 if (ai->isFake() && !emitFake) continue;
2442 OS << ", ";
2443 ai->writeImplicitCtorArgs(OS);
2444 }
2445 OS << ", I);\n";
Reid Kleckner7420f962020-03-11 19:43:37 -07002446 OS << "}\n\n";
Erich Keane6a24e802019-09-13 17:39:31 +00002447 };
2448
2449 auto emitCreates = [&](bool emitFake) {
2450 emitCreate(true, emitFake);
2451 emitCreate(false, emitFake);
2452 emitCreateNoCI(true, emitFake);
2453 emitCreateNoCI(false, emitFake);
2454 };
2455
Reid Kleckner7420f962020-03-11 19:43:37 -07002456 if (Header)
2457 OS << " // Factory methods\n";
2458
John McCalla62c1a92015-10-28 00:17:34 +00002459 // Emit a CreateImplicit that takes all the arguments.
Erich Keane6a24e802019-09-13 17:39:31 +00002460 emitCreates(true);
John McCalla62c1a92015-10-28 00:17:34 +00002461
2462 // Emit a CreateImplicit that takes all the non-fake arguments.
Erich Keane6a24e802019-09-13 17:39:31 +00002463 if (HasFakeArg)
2464 emitCreates(false);
Michael Han99315932013-01-24 16:46:58 +00002465
John McCalla62c1a92015-10-28 00:17:34 +00002466 // Emit constructors.
2467 auto emitCtor = [&](bool emitOpt, bool emitFake) {
2468 auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
2469 if (arg->isFake()) return emitFake;
2470 if (arg->isOptional()) return emitOpt;
2471 return true;
2472 };
Reid Kleckner7420f962020-03-11 19:43:37 -07002473 if (Header)
2474 OS << " ";
2475 else
2476 OS << R.getName() << "Attr::";
2477 OS << R.getName()
Erich Keane6a24e802019-09-13 17:39:31 +00002478 << "Attr(ASTContext &Ctx, const AttributeCommonInfo &CommonInfo";
2479 OS << '\n';
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002480 for (auto const &ai : Args) {
John McCalla62c1a92015-10-28 00:17:34 +00002481 if (!shouldEmitArg(ai)) continue;
2482 OS << " , ";
2483 ai->writeCtorParameters(OS);
2484 OS << "\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002485 }
2486
Reid Kleckner7420f962020-03-11 19:43:37 -07002487 OS << " )";
2488 if (Header) {
2489 OS << ";\n";
2490 return;
2491 }
2492 OS << "\n : " << SuperName << "(Ctx, CommonInfo, ";
Erich Keane6a24e802019-09-13 17:39:31 +00002493 OS << "attr::" << R.getName() << ", "
2494 << (R.getValueAsBit("LateParsed") ? "true" : "false");
Richard Smith33bddbd2018-01-04 23:42:29 +00002495 if (Inheritable) {
2496 OS << ", "
2497 << (R.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
2498 : "false");
2499 }
2500 OS << ")\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002501
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002502 for (auto const &ai : Args) {
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002503 OS << " , ";
John McCalla62c1a92015-10-28 00:17:34 +00002504 if (!shouldEmitArg(ai)) {
2505 ai->writeCtorDefaultInitializers(OS);
2506 } else {
2507 ai->writeCtorInitializers(OS);
2508 }
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002509 OS << "\n";
2510 }
2511
2512 OS << " {\n";
Johannes Doerfert1228d422019-12-19 20:42:12 -06002513
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002514 for (auto const &ai : Args) {
John McCalla62c1a92015-10-28 00:17:34 +00002515 if (!shouldEmitArg(ai)) continue;
2516 ai->writeCtorBody(OS);
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002517 }
Reid Kleckner7420f962020-03-11 19:43:37 -07002518 OS << "}\n\n";
John McCalla62c1a92015-10-28 00:17:34 +00002519 };
2520
Reid Kleckner7420f962020-03-11 19:43:37 -07002521 if (Header)
2522 OS << "\n // Constructors\n";
2523
John McCalla62c1a92015-10-28 00:17:34 +00002524 // Emit a constructor that includes all the arguments.
2525 // This is necessary for cloning.
2526 emitCtor(true, true);
2527
2528 // Emit a constructor that takes all the non-fake arguments.
Erich Keane6a24e802019-09-13 17:39:31 +00002529 if (HasFakeArg)
John McCalla62c1a92015-10-28 00:17:34 +00002530 emitCtor(true, false);
Johannes Doerfert1228d422019-12-19 20:42:12 -06002531
John McCalla62c1a92015-10-28 00:17:34 +00002532 // Emit a constructor that takes all the non-fake, non-optional arguments.
Erich Keane6a24e802019-09-13 17:39:31 +00002533 if (HasOptArg)
John McCalla62c1a92015-10-28 00:17:34 +00002534 emitCtor(false, false);
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002535
Reid Kleckner7420f962020-03-11 19:43:37 -07002536 if (Header) {
2537 OS << '\n';
2538 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
2539 OS << " void printPretty(raw_ostream &OS,\n"
2540 << " const PrintingPolicy &Policy) const;\n";
2541 OS << " const char *getSpelling() const;\n";
2542 }
Johannes Doerfert1228d422019-12-19 20:42:12 -06002543
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00002544 if (!ElideSpelling) {
2545 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
Reid Kleckner7420f962020-03-11 19:43:37 -07002546 if (Header)
2547 OS << " Spelling getSemanticSpelling() const;\n";
2548 else {
2549 OS << R.getName() << "Attr::Spelling " << R.getName()
2550 << "Attr::getSemanticSpelling() const {\n";
2551 WriteSemanticSpellingSwitch("getAttributeSpellingListIndex()",
2552 SemanticToSyntacticMap, OS);
2553 OS << "}\n";
2554 }
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00002555 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00002556
Reid Kleckner7420f962020-03-11 19:43:37 -07002557 if (Header)
2558 writeAttrAccessorDefinition(R, OS);
Michael Hanaf02bbe2013-02-01 01:19:17 +00002559
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002560 for (auto const &ai : Args) {
Reid Kleckner7420f962020-03-11 19:43:37 -07002561 if (Header) {
2562 ai->writeAccessors(OS);
2563 } else {
2564 ai->writeAccessorDefinitions(OS);
2565 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00002566 OS << "\n\n";
Aaron Ballman682ee422013-09-11 19:47:58 +00002567
John McCalla62c1a92015-10-28 00:17:34 +00002568 // Don't write conversion routines for fake arguments.
2569 if (ai->isFake()) continue;
2570
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002571 if (ai->isEnumArg())
Reid Kleckner7420f962020-03-11 19:43:37 -07002572 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS,
2573 Header);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002574 else if (ai->isVariadicEnumArg())
Reid Kleckner7420f962020-03-11 19:43:37 -07002575 static_cast<const VariadicEnumArgument *>(ai.get())->writeConversion(
2576 OS, Header);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002577 }
2578
Reid Kleckner7420f962020-03-11 19:43:37 -07002579 if (Header) {
2580 OS << R.getValueAsString("AdditionalMembers");
2581 OS << "\n\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002582
Reid Kleckner7420f962020-03-11 19:43:37 -07002583 OS << " static bool classof(const Attr *A) { return A->getKind() == "
2584 << "attr::" << R.getName() << "; }\n";
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002585
Reid Kleckner7420f962020-03-11 19:43:37 -07002586 OS << "};\n\n";
2587 } else {
2588 OS << R.getName() << "Attr *" << R.getName()
2589 << "Attr::clone(ASTContext &C) const {\n";
2590 OS << " auto *A = new (C) " << R.getName() << "Attr(C, *this";
2591 for (auto const &ai : Args) {
2592 OS << ", ";
2593 ai->writeCloneArgs(OS);
2594 }
2595 OS << ");\n";
2596 OS << " A->Inherited = Inherited;\n";
2597 OS << " A->IsPackExpansion = IsPackExpansion;\n";
2598 OS << " A->setImplicit(Implicit);\n";
2599 OS << " return A;\n}\n\n";
2600
2601 writePrettyPrintFunction(R, Args, OS);
2602 writeGetSpellingFunction(R, OS);
2603 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00002604 }
Reid Kleckner7420f962020-03-11 19:43:37 -07002605}
2606// Emits the class definitions for attributes.
2607void clang::EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
2608 emitSourceFileHeader("Attribute classes' definitions", OS);
2609
2610 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
2611 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
2612
2613 emitAttributes(Records, OS, true);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002614
Eugene Zelenko5f02b772015-12-08 18:49:01 +00002615 OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002616}
2617
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002618// Emits the class method definitions for attributes.
John McCallc45f8d42019-10-01 23:12:57 +00002619void clang::EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002620 emitSourceFileHeader("Attribute classes' member function definitions", OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002621
Reid Kleckner7420f962020-03-11 19:43:37 -07002622 emitAttributes(Records, OS, false);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002623
Reid Kleckner7420f962020-03-11 19:43:37 -07002624 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Benjamin Kramer845e32c2015-03-19 16:06:49 +00002625
2626 // Instead of relying on virtual dispatch we just create a huge dispatch
2627 // switch. This is both smaller and faster than virtual functions.
2628 auto EmitFunc = [&](const char *Method) {
2629 OS << " switch (getKind()) {\n";
2630 for (const auto *Attr : Attrs) {
2631 const Record &R = *Attr;
2632 if (!R.getValueAsBit("ASTNode"))
2633 continue;
2634
2635 OS << " case attr::" << R.getName() << ":\n";
2636 OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
2637 << ";\n";
2638 }
Benjamin Kramer845e32c2015-03-19 16:06:49 +00002639 OS << " }\n";
2640 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
2641 OS << "}\n\n";
2642 };
2643
2644 OS << "const char *Attr::getSpelling() const {\n";
2645 EmitFunc("getSpelling()");
2646
2647 OS << "Attr *Attr::clone(ASTContext &C) const {\n";
2648 EmitFunc("clone(C)");
2649
2650 OS << "void Attr::printPretty(raw_ostream &OS, "
2651 "const PrintingPolicy &Policy) const {\n";
2652 EmitFunc("printPretty(OS, Policy)");
Peter Collingbournebee583f2011-10-06 13:03:08 +00002653}
2654
John McCall2225c8b2016-03-01 00:18:05 +00002655static void emitAttrList(raw_ostream &OS, StringRef Class,
Peter Collingbournebee583f2011-10-06 13:03:08 +00002656 const std::vector<Record*> &AttrList) {
John McCall2225c8b2016-03-01 00:18:05 +00002657 for (auto Cur : AttrList) {
2658 OS << Class << "(" << Cur->getName() << ")\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002659 }
2660}
2661
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002662// Determines if an attribute has a Pragma spelling.
2663static bool AttrHasPragmaSpelling(const Record *R) {
2664 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
George Burgess IV1881a572016-12-01 00:13:18 +00002665 return llvm::find_if(Spellings, [](const FlattenedSpelling &S) {
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002666 return S.variety() == "Pragma";
2667 }) != Spellings.end();
2668}
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002669
John McCall2225c8b2016-03-01 00:18:05 +00002670namespace {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002671
John McCall2225c8b2016-03-01 00:18:05 +00002672 struct AttrClassDescriptor {
2673 const char * const MacroName;
2674 const char * const TableGenName;
2675 };
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002676
2677} // end anonymous namespace
John McCall2225c8b2016-03-01 00:18:05 +00002678
2679static const AttrClassDescriptor AttrClassDescriptors[] = {
2680 { "ATTR", "Attr" },
Richard Smithe43e2b32018-08-20 21:47:29 +00002681 { "TYPE_ATTR", "TypeAttr" },
Richard Smith4f902c72016-03-08 00:32:55 +00002682 { "STMT_ATTR", "StmtAttr" },
John McCall2225c8b2016-03-01 00:18:05 +00002683 { "INHERITABLE_ATTR", "InheritableAttr" },
Richard Smithe43e2b32018-08-20 21:47:29 +00002684 { "DECL_OR_TYPE_ATTR", "DeclOrTypeAttr" },
John McCall477f2bb2016-03-03 06:39:32 +00002685 { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
2686 { "PARAMETER_ABI_ATTR", "ParameterABIAttr" }
John McCall2225c8b2016-03-01 00:18:05 +00002687};
2688
2689static void emitDefaultDefine(raw_ostream &OS, StringRef name,
2690 const char *superName) {
2691 OS << "#ifndef " << name << "\n";
2692 OS << "#define " << name << "(NAME) ";
2693 if (superName) OS << superName << "(NAME)";
2694 OS << "\n#endif\n\n";
2695}
2696
2697namespace {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002698
John McCall2225c8b2016-03-01 00:18:05 +00002699 /// A class of attributes.
2700 struct AttrClass {
2701 const AttrClassDescriptor &Descriptor;
2702 Record *TheRecord;
2703 AttrClass *SuperClass = nullptr;
2704 std::vector<AttrClass*> SubClasses;
2705 std::vector<Record*> Attrs;
2706
2707 AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
2708 : Descriptor(Descriptor), TheRecord(R) {}
2709
2710 void emitDefaultDefines(raw_ostream &OS) const {
2711 // Default the macro unless this is a root class (i.e. Attr).
2712 if (SuperClass) {
2713 emitDefaultDefine(OS, Descriptor.MacroName,
2714 SuperClass->Descriptor.MacroName);
2715 }
2716 }
2717
2718 void emitUndefs(raw_ostream &OS) const {
2719 OS << "#undef " << Descriptor.MacroName << "\n";
2720 }
2721
2722 void emitAttrList(raw_ostream &OS) const {
2723 for (auto SubClass : SubClasses) {
2724 SubClass->emitAttrList(OS);
2725 }
2726
2727 ::emitAttrList(OS, Descriptor.MacroName, Attrs);
2728 }
2729
2730 void classifyAttrOnRoot(Record *Attr) {
2731 bool result = classifyAttr(Attr);
2732 assert(result && "failed to classify on root"); (void) result;
2733 }
2734
2735 void emitAttrRange(raw_ostream &OS) const {
2736 OS << "ATTR_RANGE(" << Descriptor.TableGenName
2737 << ", " << getFirstAttr()->getName()
2738 << ", " << getLastAttr()->getName() << ")\n";
2739 }
2740
2741 private:
2742 bool classifyAttr(Record *Attr) {
2743 // Check all the subclasses.
2744 for (auto SubClass : SubClasses) {
2745 if (SubClass->classifyAttr(Attr))
2746 return true;
2747 }
2748
2749 // It's not more specific than this class, but it might still belong here.
2750 if (Attr->isSubClassOf(TheRecord)) {
2751 Attrs.push_back(Attr);
2752 return true;
2753 }
2754
2755 return false;
2756 }
2757
2758 Record *getFirstAttr() const {
2759 if (!SubClasses.empty())
2760 return SubClasses.front()->getFirstAttr();
2761 return Attrs.front();
2762 }
2763
2764 Record *getLastAttr() const {
2765 if (!Attrs.empty())
2766 return Attrs.back();
2767 return SubClasses.back()->getLastAttr();
2768 }
2769 };
2770
2771 /// The entire hierarchy of attribute classes.
2772 class AttrClassHierarchy {
2773 std::vector<std::unique_ptr<AttrClass>> Classes;
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002774
John McCall2225c8b2016-03-01 00:18:05 +00002775 public:
2776 AttrClassHierarchy(RecordKeeper &Records) {
2777 // Find records for all the classes.
2778 for (auto &Descriptor : AttrClassDescriptors) {
2779 Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
2780 AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
2781 Classes.emplace_back(Class);
2782 }
2783
2784 // Link up the hierarchy.
2785 for (auto &Class : Classes) {
2786 if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
2787 Class->SuperClass = SuperClass;
2788 SuperClass->SubClasses.push_back(Class.get());
2789 }
2790 }
2791
2792#ifndef NDEBUG
2793 for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
2794 assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
2795 "only the first class should be a root class!");
2796 }
2797#endif
2798 }
2799
2800 void emitDefaultDefines(raw_ostream &OS) const {
2801 for (auto &Class : Classes) {
2802 Class->emitDefaultDefines(OS);
2803 }
2804 }
2805
2806 void emitUndefs(raw_ostream &OS) const {
2807 for (auto &Class : Classes) {
2808 Class->emitUndefs(OS);
2809 }
2810 }
2811
2812 void emitAttrLists(raw_ostream &OS) const {
2813 // Just start from the root class.
2814 Classes[0]->emitAttrList(OS);
2815 }
2816
2817 void emitAttrRanges(raw_ostream &OS) const {
2818 for (auto &Class : Classes)
2819 Class->emitAttrRange(OS);
2820 }
2821
2822 void classifyAttr(Record *Attr) {
2823 // Add the attribute to the root class.
2824 Classes[0]->classifyAttrOnRoot(Attr);
2825 }
2826
2827 private:
2828 AttrClass *findClassByRecord(Record *R) const {
2829 for (auto &Class : Classes) {
2830 if (Class->TheRecord == R)
2831 return Class.get();
2832 }
2833 return nullptr;
2834 }
2835
2836 AttrClass *findSuperClass(Record *R) const {
2837 // TableGen flattens the superclass list, so we just need to walk it
2838 // in reverse.
2839 auto SuperClasses = R->getSuperClasses();
2840 for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
2841 auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
2842 if (SuperClass) return SuperClass;
2843 }
2844 return nullptr;
2845 }
2846 };
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002847
2848} // end anonymous namespace
John McCall2225c8b2016-03-01 00:18:05 +00002849
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002850namespace clang {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002851
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002852// Emits the enumeration list for attributes.
2853void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002854 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002855
John McCall2225c8b2016-03-01 00:18:05 +00002856 AttrClassHierarchy Hierarchy(Records);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002857
John McCall2225c8b2016-03-01 00:18:05 +00002858 // Add defaulting macro definitions.
2859 Hierarchy.emitDefaultDefines(OS);
2860 emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002861
John McCall2225c8b2016-03-01 00:18:05 +00002862 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2863 std::vector<Record *> PragmaAttrs;
Aaron Ballman2f22b942014-05-20 19:47:14 +00002864 for (auto *Attr : Attrs) {
2865 if (!Attr->getValueAsBit("ASTNode"))
Douglas Gregorb2daf842012-05-02 15:56:52 +00002866 continue;
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002867
John McCall2225c8b2016-03-01 00:18:05 +00002868 // Add the attribute to the ad-hoc groups.
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002869 if (AttrHasPragmaSpelling(Attr))
2870 PragmaAttrs.push_back(Attr);
2871
John McCall2225c8b2016-03-01 00:18:05 +00002872 // Place it in the hierarchy.
2873 Hierarchy.classifyAttr(Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002874 }
2875
John McCall2225c8b2016-03-01 00:18:05 +00002876 // Emit the main attribute list.
2877 Hierarchy.emitAttrLists(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002878
John McCall2225c8b2016-03-01 00:18:05 +00002879 // Emit the ad hoc groups.
2880 emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
2881
2882 // Emit the attribute ranges.
2883 OS << "#ifdef ATTR_RANGE\n";
2884 Hierarchy.emitAttrRanges(OS);
2885 OS << "#undef ATTR_RANGE\n";
2886 OS << "#endif\n";
2887
2888 Hierarchy.emitUndefs(OS);
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002889 OS << "#undef PRAGMA_SPELLING_ATTR\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002890}
2891
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002892// Emits the enumeration list for attributes.
2893void EmitClangAttrSubjectMatchRuleList(RecordKeeper &Records, raw_ostream &OS) {
2894 emitSourceFileHeader(
2895 "List of all attribute subject matching rules that Clang recognizes", OS);
2896 PragmaClangAttributeSupport &PragmaAttributeSupport =
2897 getPragmaAttributeSupport(Records);
2898 emitDefaultDefine(OS, "ATTR_MATCH_RULE", nullptr);
2899 PragmaAttributeSupport.emitMatchRuleList(OS);
2900 OS << "#undef ATTR_MATCH_RULE\n";
2901}
2902
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002903// Emits the code to read an attribute from a precompiled header.
2904void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002905 emitSourceFileHeader("Attribute deserialization code", OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002906
2907 Record *InhClass = Records.getClass("InheritableAttr");
2908 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
2909 ArgRecords;
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002910 std::vector<std::unique_ptr<Argument>> Args;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002911
2912 OS << " switch (Kind) {\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00002913 for (const auto *Attr : Attrs) {
2914 const Record &R = *Attr;
Douglas Gregorb2daf842012-05-02 15:56:52 +00002915 if (!R.getValueAsBit("ASTNode"))
2916 continue;
Erich Keane6a24e802019-09-13 17:39:31 +00002917
Peter Collingbournebee583f2011-10-06 13:03:08 +00002918 OS << " case attr::" << R.getName() << ": {\n";
2919 if (R.isSubClassOf(InhClass))
David L. Jones267b8842017-01-24 01:04:30 +00002920 OS << " bool isInherited = Record.readInt();\n";
2921 OS << " bool isImplicit = Record.readInt();\n";
Nathan Ridge8b3b7552020-04-01 01:29:58 -04002922 OS << " bool isPackExpansion = Record.readInt();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002923 ArgRecords = R.getValueAsListOfDefs("Args");
2924 Args.clear();
Aaron Ballman2f22b942014-05-20 19:47:14 +00002925 for (const auto *Arg : ArgRecords) {
2926 Args.emplace_back(createArgument(*Arg, R.getName()));
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002927 Args.back()->writePCHReadDecls(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002928 }
Erich Keane6a24e802019-09-13 17:39:31 +00002929 OS << " New = new (Context) " << R.getName() << "Attr(Context, Info";
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002930 for (auto const &ri : Args) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00002931 OS << ", ";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002932 ri->writePCHReadArgs(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002933 }
Erich Keane6a24e802019-09-13 17:39:31 +00002934 OS << ");\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002935 if (R.isSubClassOf(InhClass))
2936 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
Aaron Ballman36a53502014-01-16 13:03:14 +00002937 OS << " New->setImplicit(isImplicit);\n";
Nathan Ridge8b3b7552020-04-01 01:29:58 -04002938 OS << " New->setPackExpansion(isPackExpansion);\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002939 OS << " break;\n";
2940 OS << " }\n";
2941 }
2942 OS << " }\n";
2943}
2944
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002945// Emits the code to write an attribute to a precompiled header.
2946void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002947 emitSourceFileHeader("Attribute serialization code", OS);
2948
Peter Collingbournebee583f2011-10-06 13:03:08 +00002949 Record *InhClass = Records.getClass("InheritableAttr");
2950 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002951
2952 OS << " switch (A->getKind()) {\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00002953 for (const auto *Attr : Attrs) {
2954 const Record &R = *Attr;
Douglas Gregorb2daf842012-05-02 15:56:52 +00002955 if (!R.getValueAsBit("ASTNode"))
2956 continue;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002957 OS << " case attr::" << R.getName() << ": {\n";
2958 Args = R.getValueAsListOfDefs("Args");
2959 if (R.isSubClassOf(InhClass) || !Args.empty())
Eugene Zelenko5f02b772015-12-08 18:49:01 +00002960 OS << " const auto *SA = cast<" << R.getName()
Peter Collingbournebee583f2011-10-06 13:03:08 +00002961 << "Attr>(A);\n";
2962 if (R.isSubClassOf(InhClass))
2963 OS << " Record.push_back(SA->isInherited());\n";
Aaron Ballman36a53502014-01-16 13:03:14 +00002964 OS << " Record.push_back(A->isImplicit());\n";
Nathan Ridge8b3b7552020-04-01 01:29:58 -04002965 OS << " Record.push_back(A->isPackExpansion());\n";
Aaron Ballman36a53502014-01-16 13:03:14 +00002966
Aaron Ballman2f22b942014-05-20 19:47:14 +00002967 for (const auto *Arg : Args)
2968 createArgument(*Arg, R.getName())->writePCHWrite(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002969 OS << " break;\n";
2970 OS << " }\n";
2971 }
2972 OS << " }\n";
2973}
2974
Erich Keane75449672017-12-20 18:51:08 +00002975// Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
2976// parameter with only a single check type, if applicable.
Richard Smith78b239e2019-06-20 20:44:45 +00002977static bool GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
Erich Keane75449672017-12-20 18:51:08 +00002978 std::string *FnName,
2979 StringRef ListName,
2980 StringRef CheckAgainst,
2981 StringRef Scope) {
2982 if (!R->isValueUnset(ListName)) {
2983 Test += " && (";
2984 std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
2985 for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
2986 StringRef Part = *I;
2987 Test += CheckAgainst;
2988 Test += " == ";
2989 Test += Scope;
2990 Test += Part;
2991 if (I + 1 != E)
2992 Test += " || ";
2993 if (FnName)
2994 *FnName += Part;
2995 }
2996 Test += ")";
Richard Smith78b239e2019-06-20 20:44:45 +00002997 return true;
Erich Keane75449672017-12-20 18:51:08 +00002998 }
Richard Smith78b239e2019-06-20 20:44:45 +00002999 return false;
Erich Keane75449672017-12-20 18:51:08 +00003000}
3001
Bob Wilson0058b822015-07-20 22:57:36 +00003002// Generate a conditional expression to check if the current target satisfies
3003// the conditions for a TargetSpecificAttr record, and append the code for
3004// those checks to the Test string. If the FnName string pointer is non-null,
3005// append a unique suffix to distinguish this set of target checks from other
3006// TargetSpecificAttr records.
Richard Smith78b239e2019-06-20 20:44:45 +00003007static bool GenerateTargetSpecificAttrChecks(const Record *R,
Craig Topper00648582017-05-31 19:01:22 +00003008 std::vector<StringRef> &Arches,
Bob Wilson0058b822015-07-20 22:57:36 +00003009 std::string &Test,
3010 std::string *FnName) {
Richard Smith78b239e2019-06-20 20:44:45 +00003011 bool AnyTargetChecks = false;
3012
Bob Wilson0058b822015-07-20 22:57:36 +00003013 // It is assumed that there will be an llvm::Triple object
3014 // named "T" and a TargetInfo object named "Target" within
3015 // scope that can be used to determine whether the attribute exists in
3016 // a given target.
Erich Keane75449672017-12-20 18:51:08 +00003017 Test += "true";
3018 // If one or more architectures is specified, check those. Arches are handled
3019 // differently because GenerateTargetRequirements needs to combine the list
3020 // with ParseKind.
3021 if (!Arches.empty()) {
Richard Smith78b239e2019-06-20 20:44:45 +00003022 AnyTargetChecks = true;
Erich Keane75449672017-12-20 18:51:08 +00003023 Test += " && (";
3024 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
3025 StringRef Part = *I;
3026 Test += "T.getArch() == llvm::Triple::";
3027 Test += Part;
3028 if (I + 1 != E)
3029 Test += " || ";
3030 if (FnName)
3031 *FnName += Part;
3032 }
3033 Test += ")";
Bob Wilson0058b822015-07-20 22:57:36 +00003034 }
Bob Wilson0058b822015-07-20 22:57:36 +00003035
3036 // If the attribute is specific to particular OSes, check those.
Richard Smith78b239e2019-06-20 20:44:45 +00003037 AnyTargetChecks |= GenerateTargetSpecificAttrCheck(
3038 R, Test, FnName, "OSes", "T.getOS()", "llvm::Triple::");
Bob Wilson0058b822015-07-20 22:57:36 +00003039
Erich Keane75449672017-12-20 18:51:08 +00003040 // If one or more object formats is specified, check those.
Richard Smith78b239e2019-06-20 20:44:45 +00003041 AnyTargetChecks |=
3042 GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
3043 "T.getObjectFormat()", "llvm::Triple::");
3044
3045 // If custom code is specified, emit it.
3046 StringRef Code = R->getValueAsString("CustomCode");
3047 if (!Code.empty()) {
3048 AnyTargetChecks = true;
3049 Test += " && (";
3050 Test += Code;
3051 Test += ")";
3052 }
3053
3054 return AnyTargetChecks;
Bob Wilson0058b822015-07-20 22:57:36 +00003055}
3056
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003057static void GenerateHasAttrSpellingStringSwitch(
3058 const std::vector<Record *> &Attrs, raw_ostream &OS,
3059 const std::string &Variety = "", const std::string &Scope = "") {
3060 for (const auto *Attr : Attrs) {
Aaron Ballmana0344c52014-11-14 13:44:02 +00003061 // C++11-style attributes have specific version information associated with
3062 // them. If the attribute has no scope, the version information must not
3063 // have the default value (1), as that's incorrect. Instead, the unscoped
3064 // attribute version information should be taken from the SD-6 standing
Johannes Doerfert1228d422019-12-19 20:42:12 -06003065 // document, which can be found at:
Aaron Ballmana0344c52014-11-14 13:44:02 +00003066 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
3067 int Version = 1;
3068
3069 if (Variety == "CXX11") {
3070 std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
3071 for (const auto &Spelling : Spellings) {
3072 if (Spelling->getValueAsString("Variety") == "CXX11") {
3073 Version = static_cast<int>(Spelling->getValueAsInt("Version"));
3074 if (Scope.empty() && Version == 1)
3075 PrintError(Spelling->getLoc(), "C++ standard attributes must "
3076 "have valid version information.");
3077 break;
3078 }
3079 }
3080 }
3081
Aaron Ballman0fa06d82014-01-09 22:57:44 +00003082 std::string Test;
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003083 if (Attr->isSubClassOf("TargetSpecificAttr")) {
3084 const Record *R = Attr->getValueAsDef("Target");
Craig Topper00648582017-05-31 19:01:22 +00003085 std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
Hans Wennborgdcfba332015-10-06 23:40:43 +00003086 GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
Bob Wilson7c730832015-07-20 22:57:31 +00003087
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003088 // If this is the C++11 variety, also add in the LangOpts test.
3089 if (Variety == "CXX11")
3090 Test += " && LangOpts.CPlusPlus11";
Aaron Ballman606093a2017-10-15 15:01:42 +00003091 else if (Variety == "C2x")
3092 Test += " && LangOpts.DoubleSquareBracketAttributes";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003093 } else if (Variety == "CXX11")
3094 // C++11 mode should be checked against LangOpts, which is presumed to be
3095 // present in the caller.
3096 Test = "LangOpts.CPlusPlus11";
Aaron Ballman606093a2017-10-15 15:01:42 +00003097 else if (Variety == "C2x")
3098 Test = "LangOpts.DoubleSquareBracketAttributes";
Aaron Ballman0fa06d82014-01-09 22:57:44 +00003099
Aaron Ballmana0344c52014-11-14 13:44:02 +00003100 std::string TestStr =
Aaron Ballman28afa182014-11-17 18:17:19 +00003101 !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003102 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003103 for (const auto &S : Spellings)
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003104 if (Variety.empty() || (Variety == S.variety() &&
3105 (Scope.empty() || Scope == S.nameSpace())))
Aaron Ballmana0344c52014-11-14 13:44:02 +00003106 OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00003107 }
Aaron Ballmana0344c52014-11-14 13:44:02 +00003108 OS << " .Default(0);\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003109}
3110
3111// Emits the list of spellings for attributes.
3112void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3113 emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
3114
3115 // Separate all of the attributes out into four group: generic, C++11, GNU,
3116 // and declspecs. Then generate a big switch statement for each of them.
3117 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Nico Weber20e08042016-09-03 02:55:10 +00003118 std::vector<Record *> Declspec, Microsoft, GNU, Pragma;
Aaron Ballman606093a2017-10-15 15:01:42 +00003119 std::map<std::string, std::vector<Record *>> CXX, C2x;
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003120
3121 // Walk over the list of all attributes, and split them out based on the
3122 // spelling variety.
3123 for (auto *R : Attrs) {
3124 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
3125 for (const auto &SI : Spellings) {
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00003126 const std::string &Variety = SI.variety();
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003127 if (Variety == "GNU")
3128 GNU.push_back(R);
3129 else if (Variety == "Declspec")
3130 Declspec.push_back(R);
Nico Weber20e08042016-09-03 02:55:10 +00003131 else if (Variety == "Microsoft")
3132 Microsoft.push_back(R);
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003133 else if (Variety == "CXX11")
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003134 CXX[SI.nameSpace()].push_back(R);
Aaron Ballman606093a2017-10-15 15:01:42 +00003135 else if (Variety == "C2x")
3136 C2x[SI.nameSpace()].push_back(R);
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003137 else if (Variety == "Pragma")
3138 Pragma.push_back(R);
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003139 }
3140 }
3141
Bob Wilson7c730832015-07-20 22:57:31 +00003142 OS << "const llvm::Triple &T = Target.getTriple();\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003143 OS << "switch (Syntax) {\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003144 OS << "case AttrSyntax::GNU:\n";
Aaron Ballmana0344c52014-11-14 13:44:02 +00003145 OS << " return llvm::StringSwitch<int>(Name)\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003146 GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
3147 OS << "case AttrSyntax::Declspec:\n";
Aaron Ballmana0344c52014-11-14 13:44:02 +00003148 OS << " return llvm::StringSwitch<int>(Name)\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003149 GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
Nico Weber20e08042016-09-03 02:55:10 +00003150 OS << "case AttrSyntax::Microsoft:\n";
3151 OS << " return llvm::StringSwitch<int>(Name)\n";
3152 GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003153 OS << "case AttrSyntax::Pragma:\n";
Aaron Ballmana0344c52014-11-14 13:44:02 +00003154 OS << " return llvm::StringSwitch<int>(Name)\n";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003155 GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
Aaron Ballman606093a2017-10-15 15:01:42 +00003156 auto fn = [&OS](const char *Spelling, const char *Variety,
3157 const std::map<std::string, std::vector<Record *>> &List) {
3158 OS << "case AttrSyntax::" << Variety << ": {\n";
3159 // C++11-style attributes are further split out based on the Scope.
3160 for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
Stephen Kellydb8fac12019-01-11 19:16:01 +00003161 if (I != List.cbegin())
3162 OS << " else ";
3163 if (I->first.empty())
3164 OS << "if (ScopeName == \"\") {\n";
3165 else
3166 OS << "if (ScopeName == \"" << I->first << "\") {\n";
3167 OS << " return llvm::StringSwitch<int>(Name)\n";
3168 GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
3169 OS << "}";
Aaron Ballman606093a2017-10-15 15:01:42 +00003170 }
Aaron Ballman4ff3b5ab2017-10-18 12:11:58 +00003171 OS << "\n} break;\n";
Aaron Ballman606093a2017-10-15 15:01:42 +00003172 };
3173 fn("CXX11", "CXX", CXX);
3174 fn("C2x", "C", C2x);
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003175 OS << "}\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00003176}
3177
Michael Han99315932013-01-24 16:46:58 +00003178void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00003179 emitSourceFileHeader("Code to translate different attribute spellings "
3180 "into internal identifiers", OS);
Michael Han99315932013-01-24 16:46:58 +00003181
Erich Keane6a24e802019-09-13 17:39:31 +00003182 OS << " switch (getParsedKind()) {\n";
3183 OS << " case IgnoredAttribute:\n";
3184 OS << " case UnknownAttribute:\n";
3185 OS << " case NoSemaHandlerAttribute:\n";
3186 OS << " llvm_unreachable(\"Ignored/unknown shouldn't get here\");\n";
Michael Han99315932013-01-24 16:46:58 +00003187
Aaron Ballman64e69862013-12-15 13:05:48 +00003188 ParsedAttrMap Attrs = getParsedAttrList(Records);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003189 for (const auto &I : Attrs) {
Aaron Ballman2f22b942014-05-20 19:47:14 +00003190 const Record &R = *I.second;
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003191 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003192 OS << " case AT_" << I.first << ": {\n";
Richard Smith852e9ce2013-11-27 01:46:48 +00003193 for (unsigned I = 0; I < Spellings.size(); ++ I) {
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003194 OS << " if (Name == \"" << Spellings[I].name() << "\" && "
Erich Keane6a24e802019-09-13 17:39:31 +00003195 << "getSyntax() == AttributeCommonInfo::AS_" << Spellings[I].variety()
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003196 << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
3197 << " return " << I << ";\n";
Michael Han99315932013-01-24 16:46:58 +00003198 }
Richard Smith852e9ce2013-11-27 01:46:48 +00003199
3200 OS << " break;\n";
3201 OS << " }\n";
Michael Han99315932013-01-24 16:46:58 +00003202 }
3203
3204 OS << " }\n";
Aaron Ballman64e69862013-12-15 13:05:48 +00003205 OS << " return 0;\n";
Michael Han99315932013-01-24 16:46:58 +00003206}
3207
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003208// Emits code used by RecursiveASTVisitor to visit attributes
3209void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
3210 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
3211
3212 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3213
3214 // Write method declarations for Traverse* methods.
3215 // We emit this here because we only generate methods for attributes that
3216 // are declared as ASTNodes.
3217 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00003218 for (const auto *Attr : Attrs) {
3219 const Record &R = *Attr;
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003220 if (!R.getValueAsBit("ASTNode"))
3221 continue;
3222 OS << " bool Traverse"
3223 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
3224 OS << " bool Visit"
3225 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3226 << " return true; \n"
Hans Wennborg4afe5042015-07-22 20:46:26 +00003227 << " }\n";
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003228 }
3229 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
3230
3231 // Write individual Traverse* methods for each attribute class.
Aaron Ballman2f22b942014-05-20 19:47:14 +00003232 for (const auto *Attr : Attrs) {
3233 const Record &R = *Attr;
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003234 if (!R.getValueAsBit("ASTNode"))
3235 continue;
3236
3237 OS << "template <typename Derived>\n"
DeLesley Hutchinsbb79c332013-12-30 21:03:02 +00003238 << "bool VISITORCLASS<Derived>::Traverse"
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003239 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3240 << " if (!getDerived().VisitAttr(A))\n"
3241 << " return false;\n"
3242 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
3243 << " return false;\n";
3244
3245 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
Aaron Ballman2f22b942014-05-20 19:47:14 +00003246 for (const auto *Arg : ArgRecords)
3247 createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003248
3249 OS << " return true;\n";
3250 OS << "}\n\n";
3251 }
3252
3253 // Write generic Traverse routine
3254 OS << "template <typename Derived>\n"
DeLesley Hutchinsbb79c332013-12-30 21:03:02 +00003255 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003256 << " if (!A)\n"
3257 << " return true;\n"
3258 << "\n"
John McCall2225c8b2016-03-01 00:18:05 +00003259 << " switch (A->getKind()) {\n";
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003260
Aaron Ballman2f22b942014-05-20 19:47:14 +00003261 for (const auto *Attr : Attrs) {
3262 const Record &R = *Attr;
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003263 if (!R.getValueAsBit("ASTNode"))
3264 continue;
3265
3266 OS << " case attr::" << R.getName() << ":\n"
3267 << " return getDerived().Traverse" << R.getName() << "Attr("
3268 << "cast<" << R.getName() << "Attr>(A));\n";
3269 }
John McCall5d7cf772016-03-01 02:09:20 +00003270 OS << " }\n"; // end switch
3271 OS << " llvm_unreachable(\"bad attribute kind\");\n";
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003272 OS << "}\n"; // end function
3273 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
3274}
3275
Erich Keanea32910d2017-03-23 18:51:54 +00003276void EmitClangAttrTemplateInstantiateHelper(const std::vector<Record *> &Attrs,
3277 raw_ostream &OS,
3278 bool AppliesToDecl) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003279
Erich Keanea32910d2017-03-23 18:51:54 +00003280 OS << " switch (At->getKind()) {\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00003281 for (const auto *Attr : Attrs) {
3282 const Record &R = *Attr;
Douglas Gregorb2daf842012-05-02 15:56:52 +00003283 if (!R.getValueAsBit("ASTNode"))
3284 continue;
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003285 OS << " case attr::" << R.getName() << ": {\n";
Erich Keanea32910d2017-03-23 18:51:54 +00003286 bool ShouldClone = R.getValueAsBit("Clone") &&
3287 (!AppliesToDecl ||
3288 R.getValueAsBit("MeaningfulToClassTemplateDefinition"));
Rafael Espindola7f90b7d2012-05-15 14:09:55 +00003289
3290 if (!ShouldClone) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00003291 OS << " return nullptr;\n";
Rafael Espindola7f90b7d2012-05-15 14:09:55 +00003292 OS << " }\n";
3293 continue;
3294 }
3295
Eugene Zelenko5f02b772015-12-08 18:49:01 +00003296 OS << " const auto *A = cast<"
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003297 << R.getName() << "Attr>(At);\n";
3298 bool TDependent = R.getValueAsBit("TemplateDependent");
3299
3300 if (!TDependent) {
3301 OS << " return A->clone(C);\n";
3302 OS << " }\n";
3303 continue;
3304 }
3305
3306 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003307 std::vector<std::unique_ptr<Argument>> Args;
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003308 Args.reserve(ArgRecords.size());
3309
Aaron Ballman2f22b942014-05-20 19:47:14 +00003310 for (const auto *ArgRecord : ArgRecords)
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003311 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003312
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003313 for (auto const &ai : Args)
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003314 ai->writeTemplateInstantiation(OS);
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003315
Erich Keane6a24e802019-09-13 17:39:31 +00003316 OS << " return new (C) " << R.getName() << "Attr(C, *A";
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003317 for (auto const &ai : Args) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003318 OS << ", ";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003319 ai->writeTemplateInstantiationArgs(OS);
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003320 }
Erich Keane6a24e802019-09-13 17:39:31 +00003321 OS << ");\n }\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003322 }
3323 OS << " } // end switch\n"
3324 << " llvm_unreachable(\"Unknown attribute!\");\n"
Erich Keanea32910d2017-03-23 18:51:54 +00003325 << " return nullptr;\n";
3326}
3327
3328// Emits code to instantiate dependent attributes on templates.
3329void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
3330 emitSourceFileHeader("Template instantiation code for attributes", OS);
3331
3332 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3333
3334 OS << "namespace clang {\n"
3335 << "namespace sema {\n\n"
3336 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
3337 << "Sema &S,\n"
3338 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3339 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
3340 OS << "}\n\n"
3341 << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
3342 << " ASTContext &C, Sema &S,\n"
3343 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3344 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
3345 OS << "}\n\n"
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00003346 << "} // end namespace sema\n"
3347 << "} // end namespace clang\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003348}
3349
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003350// Emits the list of parsed attributes.
3351void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
3352 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
3353
3354 OS << "#ifndef PARSED_ATTR\n";
3355 OS << "#define PARSED_ATTR(NAME) NAME\n";
3356 OS << "#endif\n\n";
Johannes Doerfert1228d422019-12-19 20:42:12 -06003357
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003358 ParsedAttrMap Names = getParsedAttrList(Records);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003359 for (const auto &I : Names) {
3360 OS << "PARSED_ATTR(" << I.first << ")\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003361 }
3362}
3363
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00003364static bool isArgVariadic(const Record &R, StringRef AttrName) {
3365 return createArgument(R, AttrName)->isVariadic();
3366}
3367
Erich Keanedf9e8ae2017-10-16 22:47:26 +00003368static void emitArgInfo(const Record &R, raw_ostream &OS) {
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003369 // This function will count the number of arguments specified for the
3370 // attribute and emit the number of required arguments followed by the
3371 // number of optional arguments.
3372 std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
3373 unsigned ArgCount = 0, OptCount = 0;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00003374 bool HasVariadic = false;
Aaron Ballman2f22b942014-05-20 19:47:14 +00003375 for (const auto *Arg : Args) {
George Burgess IV8a36ace2016-12-01 17:52:39 +00003376 // If the arg is fake, it's the user's job to supply it: general parsing
3377 // logic shouldn't need to know anything about it.
3378 if (Arg->getValueAsBit("Fake"))
3379 continue;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003380 Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00003381 if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
3382 HasVariadic = true;
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003383 }
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00003384
3385 // If there is a variadic argument, we will set the optional argument count
3386 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
John Brawn590dc8d2020-02-26 16:31:24 +00003387 OS << " NumArgs = " << ArgCount << ";\n";
3388 OS << " OptArgs = " << (HasVariadic ? 15 : OptCount) << ";\n";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003389}
3390
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003391static std::string GetDiagnosticSpelling(const Record &R) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01003392 std::string Ret = std::string(R.getValueAsString("DiagSpelling"));
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003393 if (!Ret.empty())
3394 return Ret;
3395
3396 // If we couldn't find the DiagSpelling in this object, we can check to see
3397 // if the object is one that has a base, and if it is, loop up to the Base
3398 // member recursively.
John McCallbaf91d02019-10-25 16:28:03 -07003399 if (auto Base = R.getValueAsOptionalDef(BaseFieldName))
3400 return GetDiagnosticSpelling(*Base);
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003401
3402 return "";
3403}
3404
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003405static std::string CalculateDiagnostic(const Record &S) {
3406 // If the SubjectList object has a custom diagnostic associated with it,
3407 // return that directly.
Erich Keane3bff4142017-10-16 23:25:24 +00003408 const StringRef CustomDiag = S.getValueAsString("CustomDiag");
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003409 if (!CustomDiag.empty())
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003410 return ("\"" + Twine(CustomDiag) + "\"").str();
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003411
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003412 std::vector<std::string> DiagList;
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003413 std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
Aaron Ballman2f22b942014-05-20 19:47:14 +00003414 for (const auto *Subject : Subjects) {
3415 const Record &R = *Subject;
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003416 // Get the diagnostic text from the Decl or Stmt node given.
3417 std::string V = GetDiagnosticSpelling(R);
3418 if (V.empty()) {
3419 PrintError(R.getLoc(),
3420 "Could not determine diagnostic spelling for the node: " +
3421 R.getName() + "; please add one to DeclNodes.td");
3422 } else {
3423 // The node may contain a list of elements itself, so split the elements
3424 // by a comma, and trim any whitespace.
3425 SmallVector<StringRef, 2> Frags;
3426 llvm::SplitString(V, Frags, ",");
3427 for (auto Str : Frags) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01003428 DiagList.push_back(std::string(Str.trim()));
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003429 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003430 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003431 }
3432
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003433 if (DiagList.empty()) {
3434 PrintFatalError(S.getLoc(),
3435 "Could not deduce diagnostic argument for Attr subjects");
3436 return "";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003437 }
3438
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003439 // FIXME: this is not particularly good for localization purposes and ideally
3440 // should be part of the diagnostics engine itself with some sort of list
3441 // specifier.
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003442
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003443 // A single member of the list can be returned directly.
3444 if (DiagList.size() == 1)
3445 return '"' + DiagList.front() + '"';
3446
3447 if (DiagList.size() == 2)
3448 return '"' + DiagList[0] + " and " + DiagList[1] + '"';
3449
3450 // If there are more than two in the list, we serialize the first N - 1
3451 // elements with a comma. This leaves the string in the state: foo, bar,
3452 // baz (but misses quux). We can then add ", and " for the last element
3453 // manually.
3454 std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
3455 return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003456}
3457
Aaron Ballman12b9f652014-01-16 13:55:42 +00003458static std::string GetSubjectWithSuffix(const Record *R) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01003459 const std::string &B = std::string(R->getName());
Aaron Ballman12b9f652014-01-16 13:55:42 +00003460 if (B == "DeclBase")
3461 return "Decl";
3462 return B + "Decl";
3463}
Hans Wennborgdcfba332015-10-06 23:40:43 +00003464
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003465static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
3466 return "is" + Subject.getName().str();
3467}
3468
John Brawn590dc8d2020-02-26 16:31:24 +00003469static void GenerateCustomAppertainsTo(const Record &Subject, raw_ostream &OS) {
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003470 std::string FnName = functionNameForCustomAppertainsTo(Subject);
Aaron Ballmana358c902013-12-02 14:58:17 +00003471
John Brawn590dc8d2020-02-26 16:31:24 +00003472 // If this code has already been generated, we don't need to do anything.
Aaron Ballman80469032013-11-29 14:57:58 +00003473 static std::set<std::string> CustomSubjectSet;
Eugene Zelenko5f02b772015-12-08 18:49:01 +00003474 auto I = CustomSubjectSet.find(FnName);
Aaron Ballman80469032013-11-29 14:57:58 +00003475 if (I != CustomSubjectSet.end())
John Brawn590dc8d2020-02-26 16:31:24 +00003476 return;
Aaron Ballman80469032013-11-29 14:57:58 +00003477
John McCallbaf91d02019-10-25 16:28:03 -07003478 // This only works with non-root Decls.
3479 Record *Base = Subject.getValueAsDef(BaseFieldName);
Aaron Ballman80469032013-11-29 14:57:58 +00003480
3481 // Not currently support custom subjects within custom subjects.
3482 if (Base->isSubClassOf("SubsetSubject")) {
3483 PrintFatalError(Subject.getLoc(),
3484 "SubsetSubjects within SubsetSubjects is not supported");
John Brawn590dc8d2020-02-26 16:31:24 +00003485 return;
Aaron Ballman80469032013-11-29 14:57:58 +00003486 }
3487
Aaron Ballman80469032013-11-29 14:57:58 +00003488 OS << "static bool " << FnName << "(const Decl *D) {\n";
Erich Keane873de982018-08-03 14:24:34 +00003489 OS << " if (const auto *S = dyn_cast<";
3490 OS << GetSubjectWithSuffix(Base);
3491 OS << ">(D))\n";
3492 OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
Aaron Ballman47553042014-01-16 14:32:03 +00003493 OS << " return false;\n";
Aaron Ballman80469032013-11-29 14:57:58 +00003494 OS << "}\n\n";
3495
3496 CustomSubjectSet.insert(FnName);
Aaron Ballman80469032013-11-29 14:57:58 +00003497}
3498
John Brawn590dc8d2020-02-26 16:31:24 +00003499static void GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003500 // If the attribute does not contain a Subjects definition, then use the
3501 // default appertainsTo logic.
3502 if (Attr.isValueUnset("Subjects"))
John Brawn590dc8d2020-02-26 16:31:24 +00003503 return;
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003504
3505 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
3506 std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
3507
3508 // If the list of subjects is empty, it is assumed that the attribute
3509 // appertains to everything.
3510 if (Subjects.empty())
John Brawn590dc8d2020-02-26 16:31:24 +00003511 return;
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003512
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003513 bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
3514
3515 // Otherwise, generate an appertainsTo check specific to this attribute which
John Brawn590dc8d2020-02-26 16:31:24 +00003516 // checks all of the given subjects against the Decl passed in.
Richard Smithf4e248c2018-08-01 00:33:25 +00003517 //
3518 // If D is null, that means the attribute was not applied to a declaration
3519 // at all (for instance because it was applied to a type), or that the caller
3520 // has determined that the check should fail (perhaps prior to the creation
3521 // of the declaration).
John Brawn590dc8d2020-02-26 16:31:24 +00003522 OS << "virtual bool diagAppertainsToDecl(Sema &S, ";
3523 OS << "const ParsedAttr &Attr, const Decl *D) const {\n";
Aaron Ballman920d90f2020-03-21 15:46:40 -04003524 OS << " if (";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003525 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
John Brawn590dc8d2020-02-26 16:31:24 +00003526 // If the subject has custom code associated with it, use the generated
3527 // function for it. The function cannot be inlined into this check (yet)
3528 // because it requires the subject to be of a specific type, and were that
3529 // information inlined here, it would not support an attribute with multiple
3530 // custom subjects.
Aaron Ballman80469032013-11-29 14:57:58 +00003531 if ((*I)->isSubClassOf("SubsetSubject")) {
John Brawn590dc8d2020-02-26 16:31:24 +00003532 OS << "!" << functionNameForCustomAppertainsTo(**I) << "(D)";
Aaron Ballman80469032013-11-29 14:57:58 +00003533 } else {
John Brawn590dc8d2020-02-26 16:31:24 +00003534 OS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
Aaron Ballman80469032013-11-29 14:57:58 +00003535 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003536
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003537 if (I + 1 != E)
John Brawn590dc8d2020-02-26 16:31:24 +00003538 OS << " && ";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003539 }
Aaron Ballman920d90f2020-03-21 15:46:40 -04003540 OS << ") {\n";
John Brawn590dc8d2020-02-26 16:31:24 +00003541 OS << " S.Diag(Attr.getLoc(), diag::";
3542 OS << (Warn ? "warn_attribute_wrong_decl_type_str" :
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003543 "err_attribute_wrong_decl_type_str");
John Brawn590dc8d2020-02-26 16:31:24 +00003544 OS << ")\n";
3545 OS << " << Attr << ";
3546 OS << CalculateDiagnostic(*SubjectObj) << ";\n";
3547 OS << " return false;\n";
3548 OS << " }\n";
3549 OS << " return true;\n";
3550 OS << "}\n\n";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003551}
3552
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003553static void
3554emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
3555 raw_ostream &OS) {
3556 OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
3557 << AttributeSubjectMatchRule::EnumName << " rule) {\n";
3558 OS << " switch (rule) {\n";
3559 for (const auto &Rule : PragmaAttributeSupport.Rules) {
3560 if (Rule.isAbstractRule()) {
3561 OS << " case " << Rule.getEnumValue() << ":\n";
3562 OS << " assert(false && \"Abstract matcher rule isn't allowed\");\n";
3563 OS << " return false;\n";
3564 continue;
3565 }
3566 std::vector<Record *> Subjects = Rule.getSubjects();
3567 assert(!Subjects.empty() && "Missing subjects");
3568 OS << " case " << Rule.getEnumValue() << ":\n";
3569 OS << " return ";
3570 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
3571 // If the subject has custom code associated with it, use the function
3572 // that was generated for GenerateAppertainsTo to check if the declaration
3573 // is valid.
3574 if ((*I)->isSubClassOf("SubsetSubject"))
3575 OS << functionNameForCustomAppertainsTo(**I) << "(D)";
3576 else
3577 OS << "isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3578
3579 if (I + 1 != E)
3580 OS << " || ";
3581 }
3582 OS << ";\n";
3583 }
3584 OS << " }\n";
3585 OS << " llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
3586 OS << "}\n\n";
3587}
3588
John Brawn590dc8d2020-02-26 16:31:24 +00003589static void GenerateLangOptRequirements(const Record &R,
3590 raw_ostream &OS) {
Aaron Ballman3aff6332013-12-02 19:30:36 +00003591 // If the attribute has an empty or unset list of language requirements,
John Brawn590dc8d2020-02-26 16:31:24 +00003592 // use the default handler.
Aaron Ballman3aff6332013-12-02 19:30:36 +00003593 std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
3594 if (LangOpts.empty())
John Brawn590dc8d2020-02-26 16:31:24 +00003595 return;
Aaron Ballman3aff6332013-12-02 19:30:36 +00003596
John Brawn590dc8d2020-02-26 16:31:24 +00003597 OS << "virtual bool diagLangOpts(Sema &S, const ParsedAttr &Attr) ";
3598 OS << "const {\n";
John McCall2c91c3b2019-05-30 04:09:01 +00003599 OS << " auto &LangOpts = S.LangOpts;\n";
3600 OS << " if (" << GenerateTestExpression(LangOpts) << ")\n";
Aaron Ballman3aff6332013-12-02 19:30:36 +00003601 OS << " return true;\n\n";
3602 OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
Erich Keane6a24e802019-09-13 17:39:31 +00003603 OS << "<< Attr;\n";
Aaron Ballman3aff6332013-12-02 19:30:36 +00003604 OS << " return false;\n";
3605 OS << "}\n\n";
Aaron Ballman3aff6332013-12-02 19:30:36 +00003606}
3607
John Brawn590dc8d2020-02-26 16:31:24 +00003608static void GenerateTargetRequirements(const Record &Attr,
3609 const ParsedAttrMap &Dupes,
3610 raw_ostream &OS) {
3611 // If the attribute is not a target specific attribute, use the default
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003612 // target handler.
3613 if (!Attr.isSubClassOf("TargetSpecificAttr"))
John Brawn590dc8d2020-02-26 16:31:24 +00003614 return;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003615
3616 // Get the list of architectures to be tested for.
3617 const Record *R = Attr.getValueAsDef("Target");
Craig Topper00648582017-05-31 19:01:22 +00003618 std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003619
3620 // If there are other attributes which share the same parsed attribute kind,
3621 // such as target-specific attributes with a shared spelling, collapse the
3622 // duplicate architectures. This is required because a shared target-specific
Erich Keanee891aa92018-07-13 15:07:47 +00003623 // attribute has only one ParsedAttr::Kind enumeration value, but it
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003624 // applies to multiple target architectures. In order for the attribute to be
3625 // considered valid, all of its architectures need to be included.
3626 if (!Attr.isValueUnset("ParseKind")) {
Erich Keane3bff4142017-10-16 23:25:24 +00003627 const StringRef APK = Attr.getValueAsString("ParseKind");
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003628 for (const auto &I : Dupes) {
3629 if (I.first == APK) {
Craig Topper00648582017-05-31 19:01:22 +00003630 std::vector<StringRef> DA =
3631 I.second->getValueAsDef("Target")->getValueAsListOfStrings(
3632 "Arches");
3633 Arches.insert(Arches.end(), DA.begin(), DA.end());
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003634 }
3635 }
3636 }
3637
Bob Wilson0058b822015-07-20 22:57:36 +00003638 std::string FnName = "isTarget";
3639 std::string Test;
Richard Smith78b239e2019-06-20 20:44:45 +00003640 bool UsesT = GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
Bob Wilson7c730832015-07-20 22:57:31 +00003641
John Brawn590dc8d2020-02-26 16:31:24 +00003642 OS << "virtual bool existsInTarget(const TargetInfo &Target) const {\n";
Richard Smith78b239e2019-06-20 20:44:45 +00003643 if (UsesT)
3644 OS << " const llvm::Triple &T = Target.getTriple(); (void)T;\n";
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003645 OS << " return " << Test << ";\n";
3646 OS << "}\n\n";
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003647}
3648
John Brawn590dc8d2020-02-26 16:31:24 +00003649static void GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
3650 raw_ostream &OS) {
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003651 // If the attribute does not have a semantic form, we can bail out early.
3652 if (!Attr.getValueAsBit("ASTNode"))
John Brawn590dc8d2020-02-26 16:31:24 +00003653 return;
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003654
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003655 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003656
3657 // If there are zero or one spellings, or all of the spellings share the same
3658 // name, we can also bail out early.
3659 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
John Brawn590dc8d2020-02-26 16:31:24 +00003660 return;
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003661
3662 // Generate the enumeration we will use for the mapping.
3663 SemanticSpellingMap SemanticToSyntacticMap;
3664 std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
Matthias Braunbbbf5d42016-12-04 05:55:09 +00003665 std::string Name = Attr.getName().str() + "AttrSpellingMap";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003666
John Brawn590dc8d2020-02-26 16:31:24 +00003667 OS << "virtual unsigned spellingIndexToSemanticSpelling(";
3668 OS << "const ParsedAttr &Attr) const {\n";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003669 OS << Enum;
3670 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
3671 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
3672 OS << "}\n\n";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003673}
3674
John Brawnfa0320d2020-02-28 14:51:30 +00003675static void GenerateHandleDeclAttribute(const Record &Attr, raw_ostream &OS) {
3676 // Only generate if Attr can be handled simply.
3677 if (!Attr.getValueAsBit("SimpleHandler"))
3678 return;
3679
3680 // Generate a function which just converts from ParsedAttr to the Attr type.
3681 OS << "virtual AttrHandling handleDeclAttribute(Sema &S, Decl *D,";
3682 OS << "const ParsedAttr &Attr) const {\n";
3683 OS << " D->addAttr(::new (S.Context) " << Attr.getName();
3684 OS << "Attr(S.Context, Attr));\n";
3685 OS << " return AttributeApplied;\n";
3686 OS << "}\n\n";
3687}
3688
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003689static bool IsKnownToGCC(const Record &Attr) {
3690 // Look at the spellings for this subject; if there are any spellings which
3691 // claim to be known to GCC, the attribute is known to GCC.
George Burgess IV1881a572016-12-01 00:13:18 +00003692 return llvm::any_of(
3693 GetFlattenedSpellings(Attr),
3694 [](const FlattenedSpelling &S) { return S.knownToGCC(); });
Aaron Ballman9a99e0d2014-01-20 17:18:35 +00003695}
3696
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003697/// Emits the parsed attribute helpers
3698void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3699 emitSourceFileHeader("Parsed attribute helpers", OS);
3700
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003701 PragmaClangAttributeSupport &PragmaAttributeSupport =
3702 getPragmaAttributeSupport(Records);
3703
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003704 // Get the list of parsed attributes, and accept the optional list of
3705 // duplicates due to the ParseKind.
3706 ParsedAttrMap Dupes;
3707 ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003708
John Brawn590dc8d2020-02-26 16:31:24 +00003709 // Generate all of the custom appertainsTo functions that the attributes
3710 // will be using.
3711 for (auto I : Attrs) {
3712 const Record &Attr = *I.second;
3713 if (Attr.isValueUnset("Subjects"))
3714 continue;
3715 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
3716 for (auto Subject : SubjectObj->getValueAsListOfDefs("Subjects"))
3717 if (Subject->isSubClassOf("SubsetSubject"))
3718 GenerateCustomAppertainsTo(*Subject, OS);
3719 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003720
John Brawn590dc8d2020-02-26 16:31:24 +00003721 // Generate a ParsedAttrInfo struct for each of the attributes.
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003722 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003723 // TODO: If the attribute's kind appears in the list of duplicates, that is
3724 // because it is a target-specific attribute that appears multiple times.
3725 // It would be beneficial to test whether the duplicates are "similar
3726 // enough" to each other to not cause problems. For instance, check that
Alp Toker96cf7582014-01-18 21:49:37 +00003727 // the spellings are identical, and custom parsing rules match, etc.
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003728
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003729 // We need to generate struct instances based off ParsedAttrInfo from
Erich Keanee891aa92018-07-13 15:07:47 +00003730 // ParsedAttr.cpp.
John Brawn75d4d4b2020-02-07 14:21:13 +00003731 const std::string &AttrName = I->first;
John Brawn590dc8d2020-02-26 16:31:24 +00003732 const Record &Attr = *I->second;
Benjamin Kramere8743c02020-03-28 18:12:28 +01003733 auto Spellings = GetFlattenedSpellings(Attr);
3734 if (!Spellings.empty()) {
3735 OS << "static constexpr ParsedAttrInfo::Spelling " << I->first
3736 << "Spellings[] = {\n";
3737 for (const auto &S : Spellings) {
3738 const std::string &RawSpelling = S.name();
3739 std::string Spelling;
3740 if (!S.nameSpace().empty())
3741 Spelling += S.nameSpace() + "::";
3742 if (S.variety() == "GNU")
3743 Spelling += NormalizeGNUAttrSpelling(RawSpelling);
3744 else
3745 Spelling += RawSpelling;
3746 OS << " {AttributeCommonInfo::AS_" << S.variety();
3747 OS << ", \"" << Spelling << "\"},\n";
3748 }
3749 OS << "};\n";
3750 }
3751 OS << "struct ParsedAttrInfo" << I->first
3752 << " final : public ParsedAttrInfo {\n";
Benjamin Kramer347e31c2020-03-28 19:21:56 +01003753 OS << " ParsedAttrInfo" << I->first << "() {\n";
John Brawn75d4d4b2020-02-07 14:21:13 +00003754 OS << " AttrKind = ParsedAttr::AT_" << AttrName << ";\n";
John Brawn590dc8d2020-02-26 16:31:24 +00003755 emitArgInfo(Attr, OS);
3756 OS << " HasCustomParsing = ";
3757 OS << Attr.getValueAsBit("HasCustomParsing") << ";\n";
3758 OS << " IsTargetSpecific = ";
3759 OS << Attr.isSubClassOf("TargetSpecificAttr") << ";\n";
3760 OS << " IsType = ";
3761 OS << (Attr.isSubClassOf("TypeAttr") ||
3762 Attr.isSubClassOf("DeclOrTypeAttr")) << ";\n";
3763 OS << " IsStmt = ";
3764 OS << Attr.isSubClassOf("StmtAttr") << ";\n";
3765 OS << " IsKnownToGCC = ";
3766 OS << IsKnownToGCC(Attr) << ";\n";
3767 OS << " IsSupportedByPragmaAttribute = ";
3768 OS << PragmaAttributeSupport.isAttributedSupported(*I->second) << ";\n";
Benjamin Kramere8743c02020-03-28 18:12:28 +01003769 if (!Spellings.empty())
3770 OS << " Spellings = " << I->first << "Spellings;\n";
John Brawn590dc8d2020-02-26 16:31:24 +00003771 OS << " }\n";
3772 GenerateAppertainsTo(Attr, OS);
3773 GenerateLangOptRequirements(Attr, OS);
3774 GenerateTargetRequirements(Attr, Dupes, OS);
3775 GenerateSpellingIndexToSemanticSpelling(Attr, OS);
3776 PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
John Brawnfa0320d2020-02-28 14:51:30 +00003777 GenerateHandleDeclAttribute(Attr, OS);
John Brawn590dc8d2020-02-26 16:31:24 +00003778 OS << "static const ParsedAttrInfo" << I->first << " Instance;\n";
3779 OS << "};\n";
3780 OS << "const ParsedAttrInfo" << I->first << " ParsedAttrInfo" << I->first
3781 << "::Instance;\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003782 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003783
John Brawn590dc8d2020-02-26 16:31:24 +00003784 OS << "static const ParsedAttrInfo *AttrInfoMap[] = {\n";
3785 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
3786 OS << "&ParsedAttrInfo" << I->first << "::Instance,\n";
3787 }
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003788 OS << "};\n\n";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003789
3790 // Generate the attribute match rules.
3791 emitAttributeMatchRules(PragmaAttributeSupport, OS);
Michael Han4a045172012-03-07 00:12:16 +00003792}
3793
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00003794// Emits the kind list of parsed attributes
3795void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00003796 emitSourceFileHeader("Attribute name matcher", OS);
3797
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003798 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Nico Weber20e08042016-09-03 02:55:10 +00003799 std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
Aaron Ballman606093a2017-10-15 15:01:42 +00003800 Keywords, Pragma, C2x;
Aaron Ballman64e69862013-12-15 13:05:48 +00003801 std::set<std::string> Seen;
Aaron Ballman2f22b942014-05-20 19:47:14 +00003802 for (const auto *A : Attrs) {
3803 const Record &Attr = *A;
Richard Smith852e9ce2013-11-27 01:46:48 +00003804
Michael Han4a045172012-03-07 00:12:16 +00003805 bool SemaHandler = Attr.getValueAsBit("SemaHandler");
Douglas Gregor19fbb8f2012-05-02 16:18:45 +00003806 bool Ignored = Attr.getValueAsBit("Ignored");
Douglas Gregor19fbb8f2012-05-02 16:18:45 +00003807 if (SemaHandler || Ignored) {
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003808 // Attribute spellings can be shared between target-specific attributes,
3809 // and can be shared between syntaxes for the same attribute. For
3810 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
3811 // specific attribute, or MSP430-specific attribute. Additionally, an
3812 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
3813 // for the same semantic attribute. Ultimately, we need to map each of
Erich Keaneb79f3312019-09-16 13:58:59 +00003814 // these to a single AttributeCommonInfo::Kind value, but the
3815 // StringMatcher class cannot handle duplicate match strings. So we
3816 // generate a list of string to match based on the syntax, and emit
3817 // multiple string matchers depending on the syntax used.
Aaron Ballman64e69862013-12-15 13:05:48 +00003818 std::string AttrName;
3819 if (Attr.isSubClassOf("TargetSpecificAttr") &&
3820 !Attr.isValueUnset("ParseKind")) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01003821 AttrName = std::string(Attr.getValueAsString("ParseKind"));
Aaron Ballman64e69862013-12-15 13:05:48 +00003822 if (Seen.find(AttrName) != Seen.end())
3823 continue;
3824 Seen.insert(AttrName);
3825 } else
3826 AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
3827
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003828 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003829 for (const auto &S : Spellings) {
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00003830 const std::string &RawSpelling = S.name();
Craig Topper8ae12032014-05-07 06:21:57 +00003831 std::vector<StringMatcher::StringPair> *Matches = nullptr;
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00003832 std::string Spelling;
3833 const std::string &Variety = S.variety();
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003834 if (Variety == "CXX11") {
3835 Matches = &CXX11;
John Brawnbc3f1712020-03-25 10:53:30 +00003836 if (!S.nameSpace().empty())
3837 Spelling += S.nameSpace() + "::";
Aaron Ballman606093a2017-10-15 15:01:42 +00003838 } else if (Variety == "C2x") {
3839 Matches = &C2x;
John Brawnbc3f1712020-03-25 10:53:30 +00003840 if (!S.nameSpace().empty())
3841 Spelling += S.nameSpace() + "::";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003842 } else if (Variety == "GNU")
3843 Matches = &GNU;
3844 else if (Variety == "Declspec")
3845 Matches = &Declspec;
Nico Weber20e08042016-09-03 02:55:10 +00003846 else if (Variety == "Microsoft")
3847 Matches = &Microsoft;
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003848 else if (Variety == "Keyword")
3849 Matches = &Keywords;
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003850 else if (Variety == "Pragma")
3851 Matches = &Pragma;
Alexis Hunta0e54d42012-06-18 16:13:52 +00003852
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003853 assert(Matches && "Unsupported spelling variety found");
3854
Justin Lebar4086fe52017-01-05 16:51:54 +00003855 if (Variety == "GNU")
3856 Spelling += NormalizeGNUAttrSpelling(RawSpelling);
3857 else
3858 Spelling += RawSpelling;
3859
Douglas Gregor19fbb8f2012-05-02 16:18:45 +00003860 if (SemaHandler)
Erich Keanee891aa92018-07-13 15:07:47 +00003861 Matches->push_back(StringMatcher::StringPair(
Erich Keaneb79f3312019-09-16 13:58:59 +00003862 Spelling, "return AttributeCommonInfo::AT_" + AttrName + ";"));
Douglas Gregor19fbb8f2012-05-02 16:18:45 +00003863 else
Erich Keanee891aa92018-07-13 15:07:47 +00003864 Matches->push_back(StringMatcher::StringPair(
Erich Keaneb79f3312019-09-16 13:58:59 +00003865 Spelling, "return AttributeCommonInfo::IgnoredAttribute;"));
Michael Han4a045172012-03-07 00:12:16 +00003866 }
3867 }
3868 }
Erich Keanee891aa92018-07-13 15:07:47 +00003869
Erich Keaneb79f3312019-09-16 13:58:59 +00003870 OS << "static AttributeCommonInfo::Kind getAttrKind(StringRef Name, ";
3871 OS << "AttributeCommonInfo::Syntax Syntax) {\n";
3872 OS << " if (AttributeCommonInfo::AS_GNU == Syntax) {\n";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003873 StringMatcher("Name", GNU, OS).Emit();
Erich Keaneb79f3312019-09-16 13:58:59 +00003874 OS << " } else if (AttributeCommonInfo::AS_Declspec == Syntax) {\n";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003875 StringMatcher("Name", Declspec, OS).Emit();
Erich Keaneb79f3312019-09-16 13:58:59 +00003876 OS << " } else if (AttributeCommonInfo::AS_Microsoft == Syntax) {\n";
Nico Weber20e08042016-09-03 02:55:10 +00003877 StringMatcher("Name", Microsoft, OS).Emit();
Erich Keaneb79f3312019-09-16 13:58:59 +00003878 OS << " } else if (AttributeCommonInfo::AS_CXX11 == Syntax) {\n";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003879 StringMatcher("Name", CXX11, OS).Emit();
Erich Keaneb79f3312019-09-16 13:58:59 +00003880 OS << " } else if (AttributeCommonInfo::AS_C2x == Syntax) {\n";
Aaron Ballman606093a2017-10-15 15:01:42 +00003881 StringMatcher("Name", C2x, OS).Emit();
Erich Keaneb79f3312019-09-16 13:58:59 +00003882 OS << " } else if (AttributeCommonInfo::AS_Keyword == Syntax || ";
3883 OS << "AttributeCommonInfo::AS_ContextSensitiveKeyword == Syntax) {\n";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003884 StringMatcher("Name", Keywords, OS).Emit();
Erich Keaneb79f3312019-09-16 13:58:59 +00003885 OS << " } else if (AttributeCommonInfo::AS_Pragma == Syntax) {\n";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003886 StringMatcher("Name", Pragma, OS).Emit();
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003887 OS << " }\n";
Erich Keaneb79f3312019-09-16 13:58:59 +00003888 OS << " return AttributeCommonInfo::UnknownAttribute;\n"
Douglas Gregor377f99b2012-05-02 17:33:51 +00003889 << "}\n";
Michael Han4a045172012-03-07 00:12:16 +00003890}
3891
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003892// Emits the code to dump an attribute.
Stephen Kellydb8fac12019-01-11 19:16:01 +00003893void EmitClangAttrTextNodeDump(RecordKeeper &Records, raw_ostream &OS) {
3894 emitSourceFileHeader("Attribute text node dumper", OS);
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00003895
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003896 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
Aaron Ballman2f22b942014-05-20 19:47:14 +00003897 for (const auto *Attr : Attrs) {
3898 const Record &R = *Attr;
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003899 if (!R.getValueAsBit("ASTNode"))
3900 continue;
Aaron Ballmanbc909612014-01-22 21:51:20 +00003901
3902 // If the attribute has a semantically-meaningful name (which is determined
3903 // by whether there is a Spelling enumeration for it), then write out the
3904 // spelling used for the attribute.
Stephen Kellydb8fac12019-01-11 19:16:01 +00003905
3906 std::string FunctionContent;
3907 llvm::raw_string_ostream SS(FunctionContent);
3908
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003909 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Aaron Ballmanbc909612014-01-22 21:51:20 +00003910 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
Stephen Kellydb8fac12019-01-11 19:16:01 +00003911 SS << " OS << \" \" << A->getSpelling();\n";
Aaron Ballmanbc909612014-01-22 21:51:20 +00003912
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003913 Args = R.getValueAsListOfDefs("Args");
Stephen Kellydb8fac12019-01-11 19:16:01 +00003914 for (const auto *Arg : Args)
3915 createArgument(*Arg, R.getName())->writeDump(SS);
Richard Trieude5cc7d2013-01-31 01:44:26 +00003916
Stephen Kellydb8fac12019-01-11 19:16:01 +00003917 if (SS.tell()) {
3918 OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
3919 << "Attr *A) {\n";
3920 if (!Args.empty())
3921 OS << " const auto *SA = cast<" << R.getName()
3922 << "Attr>(A); (void)SA;\n";
3923 OS << SS.str();
3924 OS << " }\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003925 }
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003926 }
Stephen Kellydb8fac12019-01-11 19:16:01 +00003927}
3928
3929void EmitClangAttrNodeTraverse(RecordKeeper &Records, raw_ostream &OS) {
3930 emitSourceFileHeader("Attribute text node traverser", OS);
3931
3932 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
3933 for (const auto *Attr : Attrs) {
3934 const Record &R = *Attr;
3935 if (!R.getValueAsBit("ASTNode"))
3936 continue;
3937
3938 std::string FunctionContent;
3939 llvm::raw_string_ostream SS(FunctionContent);
3940
3941 Args = R.getValueAsListOfDefs("Args");
3942 for (const auto *Arg : Args)
3943 createArgument(*Arg, R.getName())->writeDumpChildren(SS);
3944 if (SS.tell()) {
3945 OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
3946 << "Attr *A) {\n";
3947 if (!Args.empty())
3948 OS << " const auto *SA = cast<" << R.getName()
3949 << "Attr>(A); (void)SA;\n";
3950 OS << SS.str();
3951 OS << " }\n";
3952 }
3953 }
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003954}
3955
Aaron Ballman35db2b32014-01-29 22:13:45 +00003956void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
3957 raw_ostream &OS) {
3958 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
3959 emitClangAttrArgContextList(Records, OS);
3960 emitClangAttrIdentifierArgList(Records, OS);
Erich Keane3efe0022018-07-20 14:13:28 +00003961 emitClangAttrVariadicIdentifierArgList(Records, OS);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00003962 emitClangAttrThisIsaIdentifierArgList(Records, OS);
Aaron Ballman35db2b32014-01-29 22:13:45 +00003963 emitClangAttrTypeArgList(Records, OS);
3964 emitClangAttrLateParsedList(Records, OS);
3965}
3966
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003967void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper &Records,
3968 raw_ostream &OS) {
3969 getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
3970}
3971
Richard Smith09ac4a12018-08-30 19:16:33 +00003972enum class SpellingKind {
3973 GNU,
3974 CXX11,
3975 C2x,
3976 Declspec,
3977 Microsoft,
3978 Keyword,
3979 Pragma,
3980};
3981static const size_t NumSpellingKinds = (size_t)SpellingKind::Pragma + 1;
3982
3983class SpellingList {
3984 std::vector<std::string> Spellings[NumSpellingKinds];
3985
3986public:
3987 ArrayRef<std::string> operator[](SpellingKind K) const {
3988 return Spellings[(size_t)K];
3989 }
3990
3991 void add(const Record &Attr, FlattenedSpelling Spelling) {
3992 SpellingKind Kind = StringSwitch<SpellingKind>(Spelling.variety())
3993 .Case("GNU", SpellingKind::GNU)
3994 .Case("CXX11", SpellingKind::CXX11)
3995 .Case("C2x", SpellingKind::C2x)
3996 .Case("Declspec", SpellingKind::Declspec)
3997 .Case("Microsoft", SpellingKind::Microsoft)
3998 .Case("Keyword", SpellingKind::Keyword)
3999 .Case("Pragma", SpellingKind::Pragma);
4000 std::string Name;
4001 if (!Spelling.nameSpace().empty()) {
4002 switch (Kind) {
4003 case SpellingKind::CXX11:
4004 case SpellingKind::C2x:
4005 Name = Spelling.nameSpace() + "::";
4006 break;
4007 case SpellingKind::Pragma:
4008 Name = Spelling.nameSpace() + " ";
4009 break;
4010 default:
4011 PrintFatalError(Attr.getLoc(), "Unexpected namespace in spelling");
4012 }
4013 }
4014 Name += Spelling.name();
4015
4016 Spellings[(size_t)Kind].push_back(Name);
4017 }
4018};
4019
Aaron Ballman97dba042014-02-17 15:27:10 +00004020class DocumentationData {
4021public:
Aaron Ballman1a3e5852014-02-17 16:18:32 +00004022 const Record *Documentation;
4023 const Record *Attribute;
Erich Keanea98a2be2017-10-16 20:31:05 +00004024 std::string Heading;
Richard Smith09ac4a12018-08-30 19:16:33 +00004025 SpellingList SupportedSpellings;
Aaron Ballman97dba042014-02-17 15:27:10 +00004026
Erich Keanea98a2be2017-10-16 20:31:05 +00004027 DocumentationData(const Record &Documentation, const Record &Attribute,
Richard Smith09ac4a12018-08-30 19:16:33 +00004028 std::pair<std::string, SpellingList> HeadingAndSpellings)
Erich Keanea98a2be2017-10-16 20:31:05 +00004029 : Documentation(&Documentation), Attribute(&Attribute),
Richard Smith09ac4a12018-08-30 19:16:33 +00004030 Heading(std::move(HeadingAndSpellings.first)),
4031 SupportedSpellings(std::move(HeadingAndSpellings.second)) {}
Aaron Ballman97dba042014-02-17 15:27:10 +00004032};
4033
Aaron Ballman4de1b582014-02-19 22:59:32 +00004034static void WriteCategoryHeader(const Record *DocCategory,
Aaron Ballman97dba042014-02-17 15:27:10 +00004035 raw_ostream &OS) {
Erich Keane3bff4142017-10-16 23:25:24 +00004036 const StringRef Name = DocCategory->getValueAsString("Name");
4037 OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
Aaron Ballman4de1b582014-02-19 22:59:32 +00004038
4039 // If there is content, print that as well.
Erich Keane3bff4142017-10-16 23:25:24 +00004040 const StringRef ContentStr = DocCategory->getValueAsString("Content");
Benjamin Kramer5c404072015-04-10 21:37:21 +00004041 // Trim leading and trailing newlines and spaces.
Erich Keane3bff4142017-10-16 23:25:24 +00004042 OS << ContentStr.trim();
Benjamin Kramer5c404072015-04-10 21:37:21 +00004043
Aaron Ballman4de1b582014-02-19 22:59:32 +00004044 OS << "\n\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00004045}
4046
Richard Smith09ac4a12018-08-30 19:16:33 +00004047static std::pair<std::string, SpellingList>
4048GetAttributeHeadingAndSpellings(const Record &Documentation,
4049 const Record &Attribute) {
Aaron Ballman97dba042014-02-17 15:27:10 +00004050 // FIXME: there is no way to have a per-spelling category for the attribute
4051 // documentation. This may not be a limiting factor since the spellings
4052 // should generally be consistently applied across the category.
4053
Erich Keanea98a2be2017-10-16 20:31:05 +00004054 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
Richard Smith09ac4a12018-08-30 19:16:33 +00004055 if (Spellings.empty())
4056 PrintFatalError(Attribute.getLoc(),
4057 "Attribute has no supported spellings; cannot be "
4058 "documented");
Aaron Ballman97dba042014-02-17 15:27:10 +00004059
4060 // Determine the heading to be used for this attribute.
Benjamin Krameradcd0262020-01-28 20:23:46 +01004061 std::string Heading = std::string(Documentation.getValueAsString("Heading"));
Aaron Ballman97dba042014-02-17 15:27:10 +00004062 if (Heading.empty()) {
4063 // If there's only one spelling, we can simply use that.
4064 if (Spellings.size() == 1)
4065 Heading = Spellings.begin()->name();
4066 else {
4067 std::set<std::string> Uniques;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00004068 for (auto I = Spellings.begin(), E = Spellings.end();
4069 I != E && Uniques.size() <= 1; ++I) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01004070 std::string Spelling =
4071 std::string(NormalizeNameForSpellingComparison(I->name()));
Aaron Ballman97dba042014-02-17 15:27:10 +00004072 Uniques.insert(Spelling);
4073 }
4074 // If the semantic map has only one spelling, that is sufficient for our
4075 // needs.
4076 if (Uniques.size() == 1)
4077 Heading = *Uniques.begin();
4078 }
4079 }
4080
4081 // If the heading is still empty, it is an error.
4082 if (Heading.empty())
Erich Keanea98a2be2017-10-16 20:31:05 +00004083 PrintFatalError(Attribute.getLoc(),
Aaron Ballman97dba042014-02-17 15:27:10 +00004084 "This attribute requires a heading to be specified");
4085
Richard Smith09ac4a12018-08-30 19:16:33 +00004086 SpellingList SupportedSpellings;
4087 for (const auto &I : Spellings)
4088 SupportedSpellings.add(Attribute, I);
Aaron Ballman97dba042014-02-17 15:27:10 +00004089
Richard Smith09ac4a12018-08-30 19:16:33 +00004090 return std::make_pair(std::move(Heading), std::move(SupportedSpellings));
Erich Keanea98a2be2017-10-16 20:31:05 +00004091}
4092
4093static void WriteDocumentation(RecordKeeper &Records,
4094 const DocumentationData &Doc, raw_ostream &OS) {
4095 OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00004096
4097 // List what spelling syntaxes the attribute supports.
4098 OS << ".. csv-table:: Supported Syntaxes\n";
Richard Smith09ac4a12018-08-30 19:16:33 +00004099 OS << " :header: \"GNU\", \"C++11\", \"C2x\", \"``__declspec``\",";
4100 OS << " \"Keyword\", \"``#pragma``\", \"``#pragma clang attribute``\"\n\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00004101 OS << " \"";
Richard Smith09ac4a12018-08-30 19:16:33 +00004102 for (size_t Kind = 0; Kind != NumSpellingKinds; ++Kind) {
4103 SpellingKind K = (SpellingKind)Kind;
Richard Smith23ff7e82018-08-30 19:19:15 +00004104 // TODO: List Microsoft (IDL-style attribute) spellings once we fully
4105 // support them.
Richard Smith09ac4a12018-08-30 19:16:33 +00004106 if (K == SpellingKind::Microsoft)
4107 continue;
4108
4109 bool PrintedAny = false;
4110 for (StringRef Spelling : Doc.SupportedSpellings[K]) {
4111 if (PrintedAny)
4112 OS << " |br| ";
4113 OS << "``" << Spelling << "``";
4114 PrintedAny = true;
4115 }
4116
4117 OS << "\",\"";
4118 }
4119
4120 if (getPragmaAttributeSupport(Records).isAttributedSupported(
4121 *Doc.Attribute))
4122 OS << "Yes";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00004123 OS << "\"\n\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00004124
4125 // If the attribute is deprecated, print a message about it, and possibly
4126 // provide a replacement attribute.
Aaron Ballman1a3e5852014-02-17 16:18:32 +00004127 if (!Doc.Documentation->isValueUnset("Deprecated")) {
Aaron Ballman97dba042014-02-17 15:27:10 +00004128 OS << "This attribute has been deprecated, and may be removed in a future "
4129 << "version of Clang.";
Aaron Ballman1a3e5852014-02-17 16:18:32 +00004130 const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
Erich Keane3bff4142017-10-16 23:25:24 +00004131 const StringRef Replacement = Deprecated.getValueAsString("Replacement");
Aaron Ballman97dba042014-02-17 15:27:10 +00004132 if (!Replacement.empty())
Joel E. Denny6053ec22018-02-28 16:57:33 +00004133 OS << " This attribute has been superseded by ``" << Replacement
4134 << "``.";
Aaron Ballman97dba042014-02-17 15:27:10 +00004135 OS << "\n\n";
4136 }
4137
Erich Keane3bff4142017-10-16 23:25:24 +00004138 const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
Aaron Ballman97dba042014-02-17 15:27:10 +00004139 // Trim leading and trailing newlines and spaces.
Erich Keane3bff4142017-10-16 23:25:24 +00004140 OS << ContentStr.trim();
Aaron Ballman97dba042014-02-17 15:27:10 +00004141
4142 OS << "\n\n\n";
4143}
4144
4145void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
4146 // Get the documentation introduction paragraph.
4147 const Record *Documentation = Records.getDef("GlobalDocumentation");
4148 if (!Documentation) {
4149 PrintFatalError("The Documentation top-level definition is missing, "
4150 "no documentation will be generated.");
4151 return;
4152 }
4153
Aaron Ballman4de1b582014-02-19 22:59:32 +00004154 OS << Documentation->getValueAsString("Intro") << "\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00004155
Aaron Ballman97dba042014-02-17 15:27:10 +00004156 // Gather the Documentation lists from each of the attributes, based on the
4157 // category provided.
4158 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00004159 std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
Aaron Ballman2f22b942014-05-20 19:47:14 +00004160 for (const auto *A : Attrs) {
4161 const Record &Attr = *A;
Aaron Ballman97dba042014-02-17 15:27:10 +00004162 std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
Aaron Ballman2f22b942014-05-20 19:47:14 +00004163 for (const auto *D : Docs) {
4164 const Record &Doc = *D;
Aaron Ballman4de1b582014-02-19 22:59:32 +00004165 const Record *Category = Doc.getValueAsDef("Category");
Aaron Ballman97dba042014-02-17 15:27:10 +00004166 // If the category is "undocumented", then there cannot be any other
4167 // documentation categories (otherwise, the attribute would become
4168 // documented).
Erich Keane3bff4142017-10-16 23:25:24 +00004169 const StringRef Cat = Category->getValueAsString("Name");
Aaron Ballman4de1b582014-02-19 22:59:32 +00004170 bool Undocumented = Cat == "Undocumented";
Aaron Ballman97dba042014-02-17 15:27:10 +00004171 if (Undocumented && Docs.size() > 1)
4172 PrintFatalError(Doc.getLoc(),
4173 "Attribute is \"Undocumented\", but has multiple "
Erich Keanea98a2be2017-10-16 20:31:05 +00004174 "documentation categories");
Aaron Ballman97dba042014-02-17 15:27:10 +00004175
4176 if (!Undocumented)
Erich Keanea98a2be2017-10-16 20:31:05 +00004177 SplitDocs[Category].push_back(DocumentationData(
Richard Smith09ac4a12018-08-30 19:16:33 +00004178 Doc, Attr, GetAttributeHeadingAndSpellings(Doc, Attr)));
Aaron Ballman97dba042014-02-17 15:27:10 +00004179 }
4180 }
4181
4182 // Having split the attributes out based on what documentation goes where,
4183 // we can begin to generate sections of documentation.
Erich Keanea98a2be2017-10-16 20:31:05 +00004184 for (auto &I : SplitDocs) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00004185 WriteCategoryHeader(I.first, OS);
Aaron Ballman97dba042014-02-17 15:27:10 +00004186
Fangrui Song1d38c132018-09-30 21:41:11 +00004187 llvm::sort(I.second,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00004188 [](const DocumentationData &D1, const DocumentationData &D2) {
4189 return D1.Heading < D2.Heading;
Fangrui Song1d38c132018-09-30 21:41:11 +00004190 });
Erich Keanea98a2be2017-10-16 20:31:05 +00004191
Aaron Ballman97dba042014-02-17 15:27:10 +00004192 // Walk over each of the attributes in the category and write out their
4193 // documentation.
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00004194 for (const auto &Doc : I.second)
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004195 WriteDocumentation(Records, Doc, OS);
4196 }
4197}
4198
4199void EmitTestPragmaAttributeSupportedAttributes(RecordKeeper &Records,
4200 raw_ostream &OS) {
4201 PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
4202 ParsedAttrMap Attrs = getParsedAttrList(Records);
Erik Pilkington23c48c22018-12-04 00:31:31 +00004203 OS << "#pragma clang attribute supports the following attributes:\n";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004204 for (const auto &I : Attrs) {
4205 if (!Support.isAttributedSupported(*I.second))
4206 continue;
4207 OS << I.first;
4208 if (I.second->isValueUnset("Subjects")) {
4209 OS << " ()\n";
4210 continue;
4211 }
4212 const Record *SubjectObj = I.second->getValueAsDef("Subjects");
4213 std::vector<Record *> Subjects =
4214 SubjectObj->getValueAsListOfDefs("Subjects");
4215 OS << " (";
4216 for (const auto &Subject : llvm::enumerate(Subjects)) {
4217 if (Subject.index())
4218 OS << ", ";
Alex Lorenz24952fb2017-04-19 15:52:11 +00004219 PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
4220 Support.SubjectsToRules.find(Subject.value())->getSecond();
4221 if (RuleSet.isRule()) {
4222 OS << RuleSet.getRule().getEnumValueName();
4223 continue;
4224 }
4225 OS << "(";
4226 for (const auto &Rule : llvm::enumerate(RuleSet.getAggregateRuleSet())) {
4227 if (Rule.index())
4228 OS << ", ";
4229 OS << Rule.value().getEnumValueName();
4230 }
4231 OS << ")";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004232 }
4233 OS << ")\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00004234 }
Erik Pilkington23c48c22018-12-04 00:31:31 +00004235 OS << "End of supported attributes.\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00004236}
4237
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00004238} // end namespace clang