blob: 486799eb81baa35287514ad09eac6cba9597a685 [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;
51 bool K;
52
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 bool Unset;
65 K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
66 }
67
68 const std::string &variety() const { return V; }
69 const std::string &name() const { return N; }
70 const std::string &nameSpace() const { return NS; }
71 bool knownToGCC() const { return K; }
72};
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000073
Hans Wennborgdcfba332015-10-06 23:40:43 +000074} // end anonymous namespace
Aaron Ballmanc669cc02014-01-27 22:10:04 +000075
Benjamin Kramerd910d162015-03-10 18:24:01 +000076static std::vector<FlattenedSpelling>
77GetFlattenedSpellings(const Record &Attr) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +000078 std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
79 std::vector<FlattenedSpelling> Ret;
80
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +000081 for (const auto &Spelling : Spellings) {
Aaron Ballmanffc43362017-10-26 12:19:02 +000082 StringRef Variety = Spelling->getValueAsString("Variety");
83 StringRef Name = Spelling->getValueAsString("Name");
84 if (Variety == "GCC") {
Aaron Ballmanc669cc02014-01-27 22:10:04 +000085 // Gin up two new spelling objects to add into the list.
Benjamin Krameradcd0262020-01-28 20:23:46 +010086 Ret.emplace_back("GNU", std::string(Name), "", true);
87 Ret.emplace_back("CXX11", std::string(Name), "gnu", true);
Aaron Ballmanffc43362017-10-26 12:19:02 +000088 } else if (Variety == "Clang") {
Benjamin Krameradcd0262020-01-28 20:23:46 +010089 Ret.emplace_back("GNU", std::string(Name), "", false);
90 Ret.emplace_back("CXX11", std::string(Name), "clang", false);
Aaron Ballman10007812018-01-03 22:22:48 +000091 if (Spelling->getValueAsBit("AllowInC"))
Benjamin Krameradcd0262020-01-28 20:23:46 +010092 Ret.emplace_back("C2x", std::string(Name), "clang", false);
Aaron Ballmanc669cc02014-01-27 22:10:04 +000093 } else
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +000094 Ret.push_back(FlattenedSpelling(*Spelling));
Aaron Ballmanc669cc02014-01-27 22:10:04 +000095 }
96
97 return Ret;
98}
99
Peter Collingbournebee583f2011-10-06 13:03:08 +0000100static std::string ReadPCHRecord(StringRef type) {
101 return StringSwitch<std::string>(type)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100102 .EndsWith("Decl *", "Record.GetLocalDeclAs<" +
103 std::string(type.data(), 0, type.size() - 1) +
104 ">(Record.readInt())")
105 .Case("TypeSourceInfo *", "Record.readTypeSourceInfo()")
106 .Case("Expr *", "Record.readExpr()")
107 .Case("IdentifierInfo *", "Record.readIdentifier()")
108 .Case("StringRef", "Record.readString()")
109 .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
Johannes Doerfert55eca282020-03-13 23:42:05 -0500110 .Case("OMPTraitInfo *", "Record.readOMPTraitInfo()")
Benjamin Krameradcd0262020-01-28 20:23:46 +0100111 .Default("Record.readInt()");
Peter Collingbournebee583f2011-10-06 13:03:08 +0000112}
113
Richard Smith19978562016-05-18 00:16:51 +0000114// Get a type that is suitable for storing an object of the specified type.
115static StringRef getStorageType(StringRef type) {
116 return StringSwitch<StringRef>(type)
117 .Case("StringRef", "std::string")
118 .Default(type);
119}
120
Peter Collingbournebee583f2011-10-06 13:03:08 +0000121// Assumes that the way to get the value is SA->getname()
122static std::string WritePCHRecord(StringRef type, StringRef name) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100123 return "Record." +
124 StringSwitch<std::string>(type)
125 .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
126 .Case("TypeSourceInfo *",
127 "AddTypeSourceInfo(" + std::string(name) + ");\n")
128 .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
129 .Case("IdentifierInfo *",
130 "AddIdentifierRef(" + std::string(name) + ");\n")
131 .Case("StringRef", "AddString(" + std::string(name) + ");\n")
132 .Case("ParamIdx",
133 "push_back(" + std::string(name) + ".serialize());\n")
Johannes Doerfert55eca282020-03-13 23:42:05 -0500134 .Case("OMPTraitInfo *",
Johannes Doerfert1228d422019-12-19 20:42:12 -0600135 "writeOMPTraitInfo(" + std::string(name) + ");\n")
Benjamin Krameradcd0262020-01-28 20:23:46 +0100136 .Default("push_back(" + std::string(name) + ");\n");
Peter Collingbournebee583f2011-10-06 13:03:08 +0000137}
138
Michael Han4a045172012-03-07 00:12:16 +0000139// Normalize attribute name by removing leading and trailing
140// underscores. For example, __foo, foo__, __foo__ would
141// become foo.
142static StringRef NormalizeAttrName(StringRef AttrName) {
George Burgess IV1881a572016-12-01 00:13:18 +0000143 AttrName.consume_front("__");
144 AttrName.consume_back("__");
Michael Han4a045172012-03-07 00:12:16 +0000145 return AttrName;
146}
147
Aaron Ballman36a53502014-01-16 13:03:14 +0000148// Normalize the name by removing any and all leading and trailing underscores.
149// This is different from NormalizeAttrName in that it also handles names like
150// _pascal and __pascal.
151static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
Benjamin Kramer5c404072015-04-10 21:37:21 +0000152 return Name.trim("_");
Aaron Ballman36a53502014-01-16 13:03:14 +0000153}
154
Justin Lebar4086fe52017-01-05 16:51:54 +0000155// Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
156// removing "__" if it appears at the beginning and end of the attribute's name.
157static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
Michael Han4a045172012-03-07 00:12:16 +0000158 if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
159 AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
160 }
161
162 return AttrSpelling;
163}
164
Aaron Ballman2f22b942014-05-20 19:47:14 +0000165typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
Aaron Ballman64e69862013-12-15 13:05:48 +0000166
Aaron Ballmanab7691c2014-01-09 22:48:32 +0000167static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
Craig Topper8ae12032014-05-07 06:21:57 +0000168 ParsedAttrMap *Dupes = nullptr) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000169 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Aaron Ballman64e69862013-12-15 13:05:48 +0000170 std::set<std::string> Seen;
171 ParsedAttrMap R;
Aaron Ballman2f22b942014-05-20 19:47:14 +0000172 for (const auto *Attr : Attrs) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000173 if (Attr->getValueAsBit("SemaHandler")) {
Aaron Ballman64e69862013-12-15 13:05:48 +0000174 std::string AN;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000175 if (Attr->isSubClassOf("TargetSpecificAttr") &&
176 !Attr->isValueUnset("ParseKind")) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100177 AN = std::string(Attr->getValueAsString("ParseKind"));
Aaron Ballman64e69862013-12-15 13:05:48 +0000178
179 // If this attribute has already been handled, it does not need to be
180 // handled again.
Aaron Ballmanab7691c2014-01-09 22:48:32 +0000181 if (Seen.find(AN) != Seen.end()) {
182 if (Dupes)
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000183 Dupes->push_back(std::make_pair(AN, Attr));
Aaron Ballman64e69862013-12-15 13:05:48 +0000184 continue;
Aaron Ballmanab7691c2014-01-09 22:48:32 +0000185 }
Aaron Ballman64e69862013-12-15 13:05:48 +0000186 Seen.insert(AN);
187 } else
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000188 AN = NormalizeAttrName(Attr->getName()).str();
Aaron Ballman64e69862013-12-15 13:05:48 +0000189
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000190 R.push_back(std::make_pair(AN, Attr));
Aaron Ballman64e69862013-12-15 13:05:48 +0000191 }
192 }
193 return R;
194}
195
Peter Collingbournebee583f2011-10-06 13:03:08 +0000196namespace {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000197
Peter Collingbournebee583f2011-10-06 13:03:08 +0000198 class Argument {
199 std::string lowerName, upperName;
200 StringRef attrName;
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000201 bool isOpt;
John McCalla62c1a92015-10-28 00:17:34 +0000202 bool Fake;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000203
204 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000205 Argument(const Record &Arg, StringRef Attr)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100206 : lowerName(std::string(Arg.getValueAsString("Name"))),
207 upperName(lowerName), attrName(Attr), isOpt(false), Fake(false) {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000208 if (!lowerName.empty()) {
209 lowerName[0] = std::tolower(lowerName[0]);
210 upperName[0] = std::toupper(upperName[0]);
211 }
Reid Klecknerebeb0ca2016-05-31 17:42:56 +0000212 // Work around MinGW's macro definition of 'interface' to 'struct'. We
213 // have an attribute argument called 'Interface', so only the lower case
214 // name conflicts with the macro definition.
215 if (lowerName == "interface")
216 lowerName = "interface_";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000217 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000218 virtual ~Argument() = default;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000219
220 StringRef getLowerName() const { return lowerName; }
221 StringRef getUpperName() const { return upperName; }
222 StringRef getAttrName() const { return attrName; }
223
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000224 bool isOptional() const { return isOpt; }
225 void setOptional(bool set) { isOpt = set; }
226
John McCalla62c1a92015-10-28 00:17:34 +0000227 bool isFake() const { return Fake; }
228 void setFake(bool fake) { Fake = fake; }
229
Peter Collingbournebee583f2011-10-06 13:03:08 +0000230 // These functions print the argument contents formatted in different ways.
231 virtual void writeAccessors(raw_ostream &OS) const = 0;
232 virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +0000233 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000234 virtual void writeCloneArgs(raw_ostream &OS) const = 0;
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000235 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
Daniel Dunbardc51baa2012-02-10 06:00:29 +0000236 virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000237 virtual void writeCtorBody(raw_ostream &OS) const {}
238 virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000239 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000240 virtual void writeCtorParameters(raw_ostream &OS) const = 0;
241 virtual void writeDeclarations(raw_ostream &OS) const = 0;
242 virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
243 virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
244 virtual void writePCHWrite(raw_ostream &OS) const = 0;
Aaron Ballman48a533d2018-02-27 23:49:28 +0000245 virtual std::string getIsOmitted() const { return "false"; }
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000246 virtual void writeValue(raw_ostream &OS) const = 0;
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000247 virtual void writeDump(raw_ostream &OS) const = 0;
248 virtual void writeDumpChildren(raw_ostream &OS) const {}
Richard Trieude5cc7d2013-01-31 01:44:26 +0000249 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
Aaron Ballman682ee422013-09-11 19:47:58 +0000250
251 virtual bool isEnumArg() const { return false; }
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000252 virtual bool isVariadicEnumArg() const { return false; }
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000253 virtual bool isVariadic() const { return false; }
Aaron Ballman36a53502014-01-16 13:03:14 +0000254
255 virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
256 OS << getUpperName();
257 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000258 };
259
260 class SimpleArgument : public Argument {
261 std::string type;
262
263 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000264 SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000265 : Argument(Arg, Attr), type(std::move(T)) {}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000266
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000267 std::string getType() const { return type; }
268
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000269 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000270 OS << " " << type << " get" << getUpperName() << "() const {\n";
271 OS << " return " << getLowerName() << ";\n";
272 OS << " }";
273 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000274
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000275 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000276 OS << getLowerName();
277 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000278
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000279 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000280 OS << "A->get" << getUpperName() << "()";
281 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000282
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000283 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000284 OS << getLowerName() << "(" << getUpperName() << ")";
285 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000286
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000287 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000288 OS << getLowerName() << "()";
289 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000290
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000291 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000292 OS << type << " " << getUpperName();
293 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000294
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000295 void writeDeclarations(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000296 OS << type << " " << getLowerName() << ";";
297 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000298
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000299 void writePCHReadDecls(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000300 std::string read = ReadPCHRecord(type);
301 OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
302 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000303
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000304 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000305 OS << getLowerName();
306 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000307
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000308 void writePCHWrite(raw_ostream &OS) const override {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100309 OS << " "
310 << WritePCHRecord(type,
311 "SA->get" + std::string(getUpperName()) + "()");
Peter Collingbournebee583f2011-10-06 13:03:08 +0000312 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000313
Aaron Ballman48a533d2018-02-27 23:49:28 +0000314 std::string getIsOmitted() const override {
315 if (type == "IdentifierInfo *")
316 return "!get" + getUpperName().str() + "()";
Matthias Gehred293cbd2019-07-25 17:50:51 +0000317 if (type == "TypeSourceInfo *")
318 return "!get" + getUpperName().str() + "Loc()";
Joel E. Denny81508102018-03-13 14:51:22 +0000319 if (type == "ParamIdx")
320 return "!get" + getUpperName().str() + "().isValid()";
Aaron Ballman48a533d2018-02-27 23:49:28 +0000321 return "false";
322 }
323
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000324 void writeValue(raw_ostream &OS) const override {
Aaron Ballman48a533d2018-02-27 23:49:28 +0000325 if (type == "FunctionDecl *")
Richard Smithb87c4652013-10-31 21:23:20 +0000326 OS << "\" << get" << getUpperName()
327 << "()->getNameInfo().getAsString() << \"";
Aaron Ballman48a533d2018-02-27 23:49:28 +0000328 else if (type == "IdentifierInfo *")
329 // Some non-optional (comma required) identifier arguments can be the
330 // empty string but are then recorded as a nullptr.
331 OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
332 << "()->getName() : \"\") << \"";
333 else if (type == "TypeSourceInfo *")
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000334 OS << "\" << get" << getUpperName() << "().getAsString() << \"";
Joel E. Denny81508102018-03-13 14:51:22 +0000335 else if (type == "ParamIdx")
336 OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
Aaron Ballman48a533d2018-02-27 23:49:28 +0000337 else
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000338 OS << "\" << get" << getUpperName() << "() << \"";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000339 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000340
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000341 void writeDump(raw_ostream &OS) const override {
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +0000342 if (type == "FunctionDecl *" || type == "NamedDecl *") {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000343 OS << " OS << \" \";\n";
Johannes Doerfert1228d422019-12-19 20:42:12 -0600344 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000345 } else if (type == "IdentifierInfo *") {
Aaron Ballman48a533d2018-02-27 23:49:28 +0000346 // Some non-optional (comma required) identifier arguments can be the
347 // empty string but are then recorded as a nullptr.
348 OS << " if (SA->get" << getUpperName() << "())\n"
349 << " OS << \" \" << SA->get" << getUpperName()
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000350 << "()->getName();\n";
Richard Smithb87c4652013-10-31 21:23:20 +0000351 } else if (type == "TypeSourceInfo *") {
Matthias Gehred293cbd2019-07-25 17:50:51 +0000352 if (isOptional())
353 OS << " if (SA->get" << getUpperName() << "Loc())";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000354 OS << " OS << \" \" << SA->get" << getUpperName()
355 << "().getAsString();\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000356 } else if (type == "bool") {
357 OS << " if (SA->get" << getUpperName() << "()) OS << \" "
358 << getUpperName() << "\";\n";
359 } else if (type == "int" || type == "unsigned") {
360 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
Joel E. Denny81508102018-03-13 14:51:22 +0000361 } else if (type == "ParamIdx") {
362 if (isOptional())
363 OS << " if (SA->get" << getUpperName() << "().isValid())\n ";
364 OS << " OS << \" \" << SA->get" << getUpperName()
365 << "().getSourceIndex();\n";
Johannes Doerfert55eca282020-03-13 23:42:05 -0500366 } else if (type == "OMPTraitInfo *") {
Johannes Doerfertb86bf832020-02-15 18:07:42 -0600367 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000368 } else {
369 llvm_unreachable("Unknown SimpleArgument type!");
370 }
371 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000372 };
373
Aaron Ballman18a78382013-11-21 00:28:23 +0000374 class DefaultSimpleArgument : public SimpleArgument {
375 int64_t Default;
376
377 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000378 DefaultSimpleArgument(const Record &Arg, StringRef Attr,
Aaron Ballman18a78382013-11-21 00:28:23 +0000379 std::string T, int64_t Default)
380 : SimpleArgument(Arg, Attr, T), Default(Default) {}
381
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000382 void writeAccessors(raw_ostream &OS) const override {
Aaron Ballman18a78382013-11-21 00:28:23 +0000383 SimpleArgument::writeAccessors(OS);
384
385 OS << "\n\n static const " << getType() << " Default" << getUpperName()
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000386 << " = ";
387 if (getType() == "bool")
388 OS << (Default != 0 ? "true" : "false");
389 else
390 OS << Default;
391 OS << ";";
Aaron Ballman18a78382013-11-21 00:28:23 +0000392 }
393 };
394
Peter Collingbournebee583f2011-10-06 13:03:08 +0000395 class StringArgument : public Argument {
396 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000397 StringArgument(const Record &Arg, StringRef Attr)
Peter Collingbournebee583f2011-10-06 13:03:08 +0000398 : Argument(Arg, Attr)
399 {}
400
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000401 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000402 OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
403 OS << " return llvm::StringRef(" << getLowerName() << ", "
404 << getLowerName() << "Length);\n";
405 OS << " }\n";
406 OS << " unsigned get" << getUpperName() << "Length() const {\n";
407 OS << " return " << getLowerName() << "Length;\n";
408 OS << " }\n";
409 OS << " void set" << getUpperName()
410 << "(ASTContext &C, llvm::StringRef S) {\n";
411 OS << " " << getLowerName() << "Length = S.size();\n";
412 OS << " this->" << getLowerName() << " = new (C, 1) char ["
413 << getLowerName() << "Length];\n";
Chandler Carruth38a45cc2015-08-04 03:53:01 +0000414 OS << " if (!S.empty())\n";
415 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
Peter Collingbournebee583f2011-10-06 13:03:08 +0000416 << getLowerName() << "Length);\n";
417 OS << " }";
418 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000419
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000420 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000421 OS << "get" << getUpperName() << "()";
422 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000423
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000424 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000425 OS << "A->get" << getUpperName() << "()";
426 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000427
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000428 void writeCtorBody(raw_ostream &OS) const override {
Reid Kleckner7420f962020-03-11 19:43:37 -0700429 OS << " if (!" << getUpperName() << ".empty())\n";
430 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000431 << ".data(), " << getLowerName() << "Length);\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000432 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000433
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000434 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000435 OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
436 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
437 << "Length])";
438 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000439
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000440 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Hans Wennborg59dbe862015-09-29 20:56:43 +0000441 OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000442 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000443
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000444 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000445 OS << "llvm::StringRef " << getUpperName();
446 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000447
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000448 void writeDeclarations(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000449 OS << "unsigned " << getLowerName() << "Length;\n";
450 OS << "char *" << getLowerName() << ";";
451 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000452
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000453 void writePCHReadDecls(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000454 OS << " std::string " << getLowerName()
David L. Jones267b8842017-01-24 01:04:30 +0000455 << "= Record.readString();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000456 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000457
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000458 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000459 OS << getLowerName();
460 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000461
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000462 void writePCHWrite(raw_ostream &OS) const override {
Richard Smith290d8012016-04-06 17:06:00 +0000463 OS << " Record.AddString(SA->get" << getUpperName() << "());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000464 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000465
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000466 void writeValue(raw_ostream &OS) const override {
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000467 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
468 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000469
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000470 void writeDump(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000471 OS << " OS << \" \\\"\" << SA->get" << getUpperName()
472 << "() << \"\\\"\";\n";
473 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000474 };
475
476 class AlignedArgument : public Argument {
477 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000478 AlignedArgument(const Record &Arg, StringRef Attr)
Peter Collingbournebee583f2011-10-06 13:03:08 +0000479 : Argument(Arg, Attr)
480 {}
481
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000482 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000483 OS << " bool is" << getUpperName() << "Dependent() const;\n";
484
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
514 // FIXME: Do not do the calculation here
515 // FIXME: Handle types correctly
516 // A null pointer means maximum alignment
Peter Collingbournebee583f2011-10-06 13:03:08 +0000517 OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
518 << "(ASTContext &Ctx) const {\n";
519 OS << " assert(!is" << getUpperName() << "Dependent());\n";
520 OS << " if (is" << getLowerName() << "Expr)\n";
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +0000521 OS << " return " << getLowerName() << "Expr ? " << getLowerName()
522 << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
523 << " * Ctx.getCharWidth() : "
524 << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000525 OS << " else\n";
526 OS << " return 0; // FIXME\n";
527 OS << "}\n";
528 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000529
Richard Smithf26d5512017-08-15 22:58:45 +0000530 void writeASTVisitorTraversal(raw_ostream &OS) const override {
531 StringRef Name = getUpperName();
532 OS << " if (A->is" << Name << "Expr()) {\n"
Johannes Doerfert1228d422019-12-19 20:42:12 -0600533 << " if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n"
534 << " return false;\n"
Richard Smithf26d5512017-08-15 22:58:45 +0000535 << " } else if (auto *TSI = A->get" << Name << "Type()) {\n"
536 << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
Johannes Doerfert1228d422019-12-19 20:42:12 -0600537 << " return false;\n"
Richard Smithf26d5512017-08-15 22:58:45 +0000538 << " }\n";
539 }
540
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000541 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000542 OS << "is" << getLowerName() << "Expr, is" << getLowerName()
543 << "Expr ? static_cast<void*>(" << getLowerName()
544 << "Expr) : " << getLowerName()
545 << "Type";
546 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000547
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000548 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000549 // FIXME: move the definition in Sema::InstantiateAttrs to here.
550 // In the meantime, aligned attributes are cloned.
551 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000552
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000553 void writeCtorBody(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000554 OS << " if (is" << getLowerName() << "Expr)\n";
555 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
556 << getUpperName() << ");\n";
557 OS << " else\n";
558 OS << " " << getLowerName()
559 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000560 << ");\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000561 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000562
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000563 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000564 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
565 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000566
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000567 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000568 OS << "is" << getLowerName() << "Expr(false)";
569 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000570
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000571 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000572 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
573 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000574
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000575 void writeImplicitCtorArgs(raw_ostream &OS) const override {
Aaron Ballman36a53502014-01-16 13:03:14 +0000576 OS << "Is" << getUpperName() << "Expr, " << getUpperName();
577 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000578
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000579 void writeDeclarations(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000580 OS << "bool is" << getLowerName() << "Expr;\n";
581 OS << "union {\n";
582 OS << "Expr *" << getLowerName() << "Expr;\n";
583 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
584 OS << "};";
585 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000586
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000587 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000588 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
589 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000590
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000591 void writePCHReadDecls(raw_ostream &OS) const override {
David L. Jones267b8842017-01-24 01:04:30 +0000592 OS << " bool is" << getLowerName() << "Expr = Record.readInt();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000593 OS << " void *" << getLowerName() << "Ptr;\n";
594 OS << " if (is" << getLowerName() << "Expr)\n";
David L. Jones267b8842017-01-24 01:04:30 +0000595 OS << " " << getLowerName() << "Ptr = Record.readExpr();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000596 OS << " else\n";
597 OS << " " << getLowerName()
John McCall3ce3d232019-12-13 03:37:23 -0500598 << "Ptr = Record.readTypeSourceInfo();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000599 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000600
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000601 void writePCHWrite(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000602 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
603 OS << " if (SA->is" << getUpperName() << "Expr())\n";
Richard Smith290d8012016-04-06 17:06:00 +0000604 OS << " Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000605 OS << " else\n";
Richard Smith290d8012016-04-06 17:06:00 +0000606 OS << " Record.AddTypeSourceInfo(SA->get" << getUpperName()
607 << "Type());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000608 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000609
Aaron Ballman48a533d2018-02-27 23:49:28 +0000610 std::string getIsOmitted() const override {
611 return "!is" + getLowerName().str() + "Expr || !" + getLowerName().str()
612 + "Expr";
613 }
614
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000615 void writeValue(raw_ostream &OS) const override {
Richard Trieuddd01ce2014-06-09 22:53:25 +0000616 OS << "\";\n";
Aaron Ballman48a533d2018-02-27 23:49:28 +0000617 OS << " " << getLowerName()
618 << "Expr->printPretty(OS, nullptr, Policy);\n";
Richard Trieuddd01ce2014-06-09 22:53:25 +0000619 OS << " OS << \"";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000620 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000621
Stephen Kellydb8fac12019-01-11 19:16:01 +0000622 void writeDump(raw_ostream &OS) const override {
623 OS << " if (!SA->is" << getUpperName() << "Expr())\n";
624 OS << " dumpType(SA->get" << getUpperName()
625 << "Type()->getType());\n";
626 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000627
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000628 void writeDumpChildren(raw_ostream &OS) const override {
Richard Smithf7514452014-10-30 21:02:37 +0000629 OS << " if (SA->is" << getUpperName() << "Expr())\n";
Stephen Kelly6d110d62019-01-30 19:49:49 +0000630 OS << " Visit(SA->get" << getUpperName() << "Expr());\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000631 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000632
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000633 void writeHasChildren(raw_ostream &OS) const override {
Richard Trieude5cc7d2013-01-31 01:44:26 +0000634 OS << "SA->is" << getUpperName() << "Expr()";
635 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000636 };
637
638 class VariadicArgument : public Argument {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000639 std::string Type, ArgName, ArgSizeName, RangeName;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000640
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000641 protected:
642 // Assumed to receive a parameter: raw_ostream OS.
643 virtual void writeValueImpl(raw_ostream &OS) const {
644 OS << " OS << Val;\n";
645 }
Joel E. Denny81508102018-03-13 14:51:22 +0000646 // Assumed to receive a parameter: raw_ostream OS.
647 virtual void writeDumpImpl(raw_ostream &OS) const {
648 OS << " OS << \" \" << Val;\n";
649 }
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000650
Peter Collingbournebee583f2011-10-06 13:03:08 +0000651 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000652 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000653 : Argument(Arg, Attr), Type(std::move(T)),
654 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
Benjamin Krameradcd0262020-01-28 20:23:46 +0100655 RangeName(std::string(getLowerName())) {}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000656
Benjamin Kramer1b582012016-02-13 18:11:49 +0000657 const std::string &getType() const { return Type; }
658 const std::string &getArgName() const { return ArgName; }
659 const std::string &getArgSizeName() const { return ArgSizeName; }
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000660 bool isVariadic() const override { return true; }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000661
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000662 void writeAccessors(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000663 std::string IteratorType = getLowerName().str() + "_iterator";
664 std::string BeginFn = getLowerName().str() + "_begin()";
665 std::string EndFn = getLowerName().str() + "_end()";
Johannes Doerfert1228d422019-12-19 20:42:12 -0600666
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000667 OS << " typedef " << Type << "* " << IteratorType << ";\n";
668 OS << " " << IteratorType << " " << BeginFn << " const {"
669 << " return " << ArgName << "; }\n";
670 OS << " " << IteratorType << " " << EndFn << " const {"
671 << " return " << ArgName << " + " << ArgSizeName << "; }\n";
672 OS << " unsigned " << getLowerName() << "_size() const {"
673 << " return " << ArgSizeName << "; }\n";
674 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
675 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
676 << "); }\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000677 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000678
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000679 void writeCloneArgs(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000680 OS << ArgName << ", " << ArgSizeName;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000681 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000682
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000683 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000684 // This isn't elegant, but we have to go through public methods...
685 OS << "A->" << getLowerName() << "_begin(), "
686 << "A->" << getLowerName() << "_size()";
687 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000688
Richard Smithf26d5512017-08-15 22:58:45 +0000689 void writeASTVisitorTraversal(raw_ostream &OS) const override {
690 // FIXME: Traverse the elements.
691 }
692
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000693 void writeCtorBody(raw_ostream &OS) const override {
Reid Kleckner7420f962020-03-11 19:43:37 -0700694 OS << " std::copy(" << getUpperName() << ", " << getUpperName() << " + "
695 << ArgSizeName << ", " << ArgName << ");\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000696 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000697
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000698 void writeCtorInitializers(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000699 OS << ArgSizeName << "(" << getUpperName() << "Size), "
700 << ArgName << "(new (Ctx, 16) " << getType() << "["
701 << ArgSizeName << "])";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000702 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000703
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000704 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000705 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000706 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000707
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000708 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000709 OS << getType() << " *" << getUpperName() << ", unsigned "
710 << getUpperName() << "Size";
711 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000712
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000713 void writeImplicitCtorArgs(raw_ostream &OS) const override {
Aaron Ballman36a53502014-01-16 13:03:14 +0000714 OS << getUpperName() << ", " << getUpperName() << "Size";
715 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000716
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000717 void writeDeclarations(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000718 OS << " unsigned " << ArgSizeName << ";\n";
719 OS << " " << getType() << " *" << ArgName << ";";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000720 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000721
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000722 void writePCHReadDecls(raw_ostream &OS) const override {
David L. Jones267b8842017-01-24 01:04:30 +0000723 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
Richard Smith19978562016-05-18 00:16:51 +0000724 OS << " SmallVector<" << getType() << ", 4> "
725 << getLowerName() << ";\n";
726 OS << " " << getLowerName() << ".reserve(" << getLowerName()
Peter Collingbournebee583f2011-10-06 13:03:08 +0000727 << "Size);\n";
Richard Smith19978562016-05-18 00:16:51 +0000728
729 // If we can't store the values in the current type (if it's something
730 // like StringRef), store them in a different type and convert the
731 // container afterwards.
Benjamin Krameradcd0262020-01-28 20:23:46 +0100732 std::string StorageType = std::string(getStorageType(getType()));
733 std::string StorageName = std::string(getLowerName());
Richard Smith19978562016-05-18 00:16:51 +0000734 if (StorageType != getType()) {
735 StorageName += "Storage";
736 OS << " SmallVector<" << StorageType << ", 4> "
737 << StorageName << ";\n";
738 OS << " " << StorageName << ".reserve(" << getLowerName()
739 << "Size);\n";
740 }
741
742 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000743 std::string read = ReadPCHRecord(Type);
Richard Smith19978562016-05-18 00:16:51 +0000744 OS << " " << StorageName << ".push_back(" << read << ");\n";
745
746 if (StorageType != getType()) {
747 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
748 OS << " " << getLowerName() << ".push_back("
749 << StorageName << "[i]);\n";
750 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000751 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000752
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000753 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000754 OS << getLowerName() << ".data(), " << getLowerName() << "Size";
755 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000756
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000757 void writePCHWrite(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000758 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000759 OS << " for (auto &Val : SA->" << RangeName << "())\n";
760 OS << " " << WritePCHRecord(Type, "Val");
Peter Collingbournebee583f2011-10-06 13:03:08 +0000761 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000762
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000763 void writeValue(raw_ostream &OS) const override {
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000764 OS << "\";\n";
765 OS << " bool isFirst = true;\n"
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000766 << " for (const auto &Val : " << RangeName << "()) {\n"
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000767 << " if (isFirst) isFirst = false;\n"
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000768 << " else OS << \", \";\n";
769 writeValueImpl(OS);
770 OS << " }\n";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000771 OS << " OS << \"";
772 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000773
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000774 void writeDump(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000775 OS << " for (const auto &Val : SA->" << RangeName << "())\n";
Joel E. Denny81508102018-03-13 14:51:22 +0000776 writeDumpImpl(OS);
777 }
778 };
779
780 class VariadicParamIdxArgument : public VariadicArgument {
781 public:
782 VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
783 : VariadicArgument(Arg, Attr, "ParamIdx") {}
784
785 public:
786 void writeValueImpl(raw_ostream &OS) const override {
787 OS << " OS << Val.getSourceIndex();\n";
788 }
789
790 void writeDumpImpl(raw_ostream &OS) const override {
791 OS << " OS << \" \" << Val.getSourceIndex();\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000792 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000793 };
794
Johannes Doerfertac991bb2019-01-19 05:36:54 +0000795 struct VariadicParamOrParamIdxArgument : public VariadicArgument {
796 VariadicParamOrParamIdxArgument(const Record &Arg, StringRef Attr)
797 : VariadicArgument(Arg, Attr, "int") {}
798 };
799
Reid Klecknerf526b9482014-02-12 18:22:18 +0000800 // Unique the enums, but maintain the original declaration ordering.
Craig Topper00648582017-05-31 19:01:22 +0000801 std::vector<StringRef>
802 uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
803 std::vector<StringRef> uniques;
George Burgess IV1881a572016-12-01 00:13:18 +0000804 SmallDenseSet<StringRef, 8> unique_set;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000805 for (const auto &i : enums) {
George Burgess IV1881a572016-12-01 00:13:18 +0000806 if (unique_set.insert(i).second)
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000807 uniques.push_back(i);
Reid Klecknerf526b9482014-02-12 18:22:18 +0000808 }
809 return uniques;
810 }
811
Peter Collingbournebee583f2011-10-06 13:03:08 +0000812 class EnumArgument : public Argument {
813 std::string type;
Craig Topper00648582017-05-31 19:01:22 +0000814 std::vector<StringRef> values, enums, uniques;
815
Peter Collingbournebee583f2011-10-06 13:03:08 +0000816 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000817 EnumArgument(const Record &Arg, StringRef Attr)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100818 : Argument(Arg, Attr), type(std::string(Arg.getValueAsString("Type"))),
819 values(Arg.getValueAsListOfStrings("Values")),
820 enums(Arg.getValueAsListOfStrings("Enums")),
821 uniques(uniqueEnumsInOrder(enums)) {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000822 // FIXME: Emit a proper error
823 assert(!uniques.empty());
824 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000825
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000826 bool isEnumArg() const override { return true; }
Aaron Ballman682ee422013-09-11 19:47:58 +0000827
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000828 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000829 OS << " " << type << " get" << getUpperName() << "() const {\n";
830 OS << " return " << getLowerName() << ";\n";
831 OS << " }";
832 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000833
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000834 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000835 OS << getLowerName();
836 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000837
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000838 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000839 OS << "A->get" << getUpperName() << "()";
840 }
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000841 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000842 OS << getLowerName() << "(" << getUpperName() << ")";
843 }
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000844 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000845 OS << getLowerName() << "(" << type << "(0))";
846 }
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000847 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000848 OS << type << " " << getUpperName();
849 }
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000850 void writeDeclarations(raw_ostream &OS) const override {
Eugene Zelenko5f02b772015-12-08 18:49:01 +0000851 auto i = uniques.cbegin(), e = uniques.cend();
Peter Collingbournebee583f2011-10-06 13:03:08 +0000852 // The last one needs to not have a comma.
853 --e;
854
855 OS << "public:\n";
856 OS << " enum " << type << " {\n";
857 for (; i != e; ++i)
858 OS << " " << *i << ",\n";
859 OS << " " << *e << "\n";
860 OS << " };\n";
861 OS << "private:\n";
862 OS << " " << type << " " << getLowerName() << ";";
863 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000864
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000865 void writePCHReadDecls(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000866 OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
867 << "(static_cast<" << getAttrName() << "Attr::" << type
David L. Jones267b8842017-01-24 01:04:30 +0000868 << ">(Record.readInt()));\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000869 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000870
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000871 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000872 OS << getLowerName();
873 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000874
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000875 void writePCHWrite(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000876 OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
877 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000878
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000879 void writeValue(raw_ostream &OS) const override {
Aaron Ballman36d79102014-09-15 16:16:14 +0000880 // FIXME: this isn't 100% correct -- some enum arguments require printing
881 // as a string literal, while others require printing as an identifier.
882 // Tablegen currently does not distinguish between the two forms.
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000883 OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
884 << getUpperName() << "()) << \"\\\"";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000885 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000886
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000887 void writeDump(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000888 OS << " switch(SA->get" << getUpperName() << "()) {\n";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000889 for (const auto &I : uniques) {
890 OS << " case " << getAttrName() << "Attr::" << I << ":\n";
891 OS << " OS << \" " << I << "\";\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000892 OS << " break;\n";
893 }
894 OS << " }\n";
895 }
Aaron Ballman682ee422013-09-11 19:47:58 +0000896
Reid Kleckner7420f962020-03-11 19:43:37 -0700897 void writeConversion(raw_ostream &OS, bool Header) const {
898 if (Header) {
899 OS << " static bool ConvertStrTo" << type << "(StringRef Val, " << type
900 << " &Out);\n";
901 OS << " static const char *Convert" << type << "ToStr(" << type
902 << " Val);\n";
903 return;
904 }
905
906 OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << type
907 << "(StringRef Val, " << type << " &Out) {\n";
908 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000909 OS << type << ">>(Val)\n";
Aaron Ballman682ee422013-09-11 19:47:58 +0000910 for (size_t I = 0; I < enums.size(); ++I) {
Reid Kleckner7420f962020-03-11 19:43:37 -0700911 OS << " .Case(\"" << values[I] << "\", ";
Aaron Ballman682ee422013-09-11 19:47:58 +0000912 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
913 }
Reid Kleckner7420f962020-03-11 19:43:37 -0700914 OS << " .Default(Optional<" << type << ">());\n";
915 OS << " if (R) {\n";
916 OS << " Out = *R;\n return true;\n }\n";
917 OS << " return false;\n";
918 OS << "}\n\n";
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000919
920 // Mapping from enumeration values back to enumeration strings isn't
921 // trivial because some enumeration values have multiple named
922 // enumerators, such as type_visibility(internal) and
923 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
Reid Kleckner7420f962020-03-11 19:43:37 -0700924 OS << "const char *" << getAttrName() << "Attr::Convert" << type
925 << "ToStr(" << type << " Val) {\n"
926 << " switch(Val) {\n";
George Burgess IV1881a572016-12-01 00:13:18 +0000927 SmallDenseSet<StringRef, 8> Uniques;
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000928 for (size_t I = 0; I < enums.size(); ++I) {
929 if (Uniques.insert(enums[I]).second)
Reid Kleckner7420f962020-03-11 19:43:37 -0700930 OS << " case " << getAttrName() << "Attr::" << enums[I]
Johannes Doerfert1228d422019-12-19 20:42:12 -0600931 << ": return \"" << values[I] << "\";\n";
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000932 }
Reid Kleckner7420f962020-03-11 19:43:37 -0700933 OS << " }\n"
934 << " llvm_unreachable(\"No enumerator with that value\");\n"
935 << "}\n";
Aaron Ballman682ee422013-09-11 19:47:58 +0000936 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000937 };
Johannes Doerfert1228d422019-12-19 20:42:12 -0600938
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000939 class VariadicEnumArgument: public VariadicArgument {
940 std::string type, QualifiedTypeName;
Craig Topper00648582017-05-31 19:01:22 +0000941 std::vector<StringRef> values, enums, uniques;
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000942
943 protected:
944 void writeValueImpl(raw_ostream &OS) const override {
Aaron Ballman36d79102014-09-15 16:16:14 +0000945 // FIXME: this isn't 100% correct -- some enum arguments require printing
946 // as a string literal, while others require printing as an identifier.
947 // Tablegen currently does not distinguish between the two forms.
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000948 OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
949 << "ToStr(Val)" << "<< \"\\\"\";\n";
950 }
951
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000952 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000953 VariadicEnumArgument(const Record &Arg, StringRef Attr)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100954 : VariadicArgument(Arg, Attr,
955 std::string(Arg.getValueAsString("Type"))),
956 type(std::string(Arg.getValueAsString("Type"))),
957 values(Arg.getValueAsListOfStrings("Values")),
958 enums(Arg.getValueAsListOfStrings("Enums")),
959 uniques(uniqueEnumsInOrder(enums)) {
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000960 QualifiedTypeName = getAttrName().str() + "Attr::" + type;
Johannes Doerfert1228d422019-12-19 20:42:12 -0600961
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000962 // FIXME: Emit a proper error
963 assert(!uniques.empty());
964 }
965
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000966 bool isVariadicEnumArg() const override { return true; }
Johannes Doerfert1228d422019-12-19 20:42:12 -0600967
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000968 void writeDeclarations(raw_ostream &OS) const override {
Eugene Zelenko5f02b772015-12-08 18:49:01 +0000969 auto i = uniques.cbegin(), e = uniques.cend();
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000970 // The last one needs to not have a comma.
971 --e;
972
973 OS << "public:\n";
974 OS << " enum " << type << " {\n";
975 for (; i != e; ++i)
976 OS << " " << *i << ",\n";
977 OS << " " << *e << "\n";
978 OS << " };\n";
979 OS << "private:\n";
Johannes Doerfert1228d422019-12-19 20:42:12 -0600980
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000981 VariadicArgument::writeDeclarations(OS);
982 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000983
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000984 void writeDump(raw_ostream &OS) const override {
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000985 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
986 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
987 << getLowerName() << "_end(); I != E; ++I) {\n";
988 OS << " switch(*I) {\n";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000989 for (const auto &UI : uniques) {
990 OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
991 OS << " OS << \" " << UI << "\";\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000992 OS << " break;\n";
993 }
994 OS << " }\n";
995 OS << " }\n";
996 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000997
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000998 void writePCHReadDecls(raw_ostream &OS) const override {
David L. Jones267b8842017-01-24 01:04:30 +0000999 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001000 OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
1001 << ";\n";
1002 OS << " " << getLowerName() << ".reserve(" << getLowerName()
1003 << "Size);\n";
1004 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
1005 OS << " " << getLowerName() << ".push_back(" << "static_cast<"
David L. Jones267b8842017-01-24 01:04:30 +00001006 << QualifiedTypeName << ">(Record.readInt()));\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001007 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001008
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001009 void writePCHWrite(raw_ostream &OS) const override {
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001010 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
1011 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1012 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
1013 << getLowerName() << "_end(); i != e; ++i)\n";
1014 OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
1015 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001016
Reid Kleckner7420f962020-03-11 19:43:37 -07001017 void writeConversion(raw_ostream &OS, bool Header) const {
1018 if (Header) {
1019 OS << " static bool ConvertStrTo" << type << "(StringRef Val, " << type
1020 << " &Out);\n";
1021 OS << " static const char *Convert" << type << "ToStr(" << type
1022 << " Val);\n";
1023 return;
1024 }
1025
1026 OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << type
1027 << "(StringRef Val, ";
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001028 OS << type << " &Out) {\n";
Reid Kleckner7420f962020-03-11 19:43:37 -07001029 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001030 OS << type << ">>(Val)\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001031 for (size_t I = 0; I < enums.size(); ++I) {
Reid Kleckner7420f962020-03-11 19:43:37 -07001032 OS << " .Case(\"" << values[I] << "\", ";
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001033 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
1034 }
Reid Kleckner7420f962020-03-11 19:43:37 -07001035 OS << " .Default(Optional<" << type << ">());\n";
1036 OS << " if (R) {\n";
1037 OS << " Out = *R;\n return true;\n }\n";
1038 OS << " return false;\n";
1039 OS << "}\n\n";
Aaron Ballman25a2cb92014-09-15 15:14:13 +00001040
Reid Kleckner7420f962020-03-11 19:43:37 -07001041 OS << "const char *" << getAttrName() << "Attr::Convert" << type
1042 << "ToStr(" << type << " Val) {\n"
1043 << " switch(Val) {\n";
George Burgess IV1881a572016-12-01 00:13:18 +00001044 SmallDenseSet<StringRef, 8> Uniques;
Aaron Ballman25a2cb92014-09-15 15:14:13 +00001045 for (size_t I = 0; I < enums.size(); ++I) {
1046 if (Uniques.insert(enums[I]).second)
Reid Kleckner7420f962020-03-11 19:43:37 -07001047 OS << " case " << getAttrName() << "Attr::" << enums[I]
1048 << ": return \"" << values[I] << "\";\n";
Aaron Ballman25a2cb92014-09-15 15:14:13 +00001049 }
Reid Kleckner7420f962020-03-11 19:43:37 -07001050 OS << " }\n"
1051 << " llvm_unreachable(\"No enumerator with that value\");\n"
1052 << "}\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001053 }
1054 };
Peter Collingbournebee583f2011-10-06 13:03:08 +00001055
1056 class VersionArgument : public Argument {
1057 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +00001058 VersionArgument(const Record &Arg, StringRef Attr)
Peter Collingbournebee583f2011-10-06 13:03:08 +00001059 : Argument(Arg, Attr)
1060 {}
1061
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001062 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001063 OS << " VersionTuple get" << getUpperName() << "() const {\n";
1064 OS << " return " << getLowerName() << ";\n";
1065 OS << " }\n";
Johannes Doerfert1228d422019-12-19 20:42:12 -06001066 OS << " void set" << getUpperName()
Peter Collingbournebee583f2011-10-06 13:03:08 +00001067 << "(ASTContext &C, VersionTuple V) {\n";
1068 OS << " " << getLowerName() << " = V;\n";
1069 OS << " }";
1070 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001071
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001072 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001073 OS << "get" << getUpperName() << "()";
1074 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001075
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001076 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001077 OS << "A->get" << getUpperName() << "()";
1078 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001079
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001080 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001081 OS << getLowerName() << "(" << getUpperName() << ")";
1082 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001083
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001084 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballman8ee40b72013-09-09 23:33:17 +00001085 OS << getLowerName() << "()";
1086 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001087
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001088 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001089 OS << "VersionTuple " << getUpperName();
1090 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001091
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001092 void writeDeclarations(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001093 OS << "VersionTuple " << getLowerName() << ";\n";
1094 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001095
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001096 void writePCHReadDecls(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001097 OS << " VersionTuple " << getLowerName()
David L. Jones267b8842017-01-24 01:04:30 +00001098 << "= Record.readVersionTuple();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001099 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001100
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001101 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001102 OS << getLowerName();
1103 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001104
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001105 void writePCHWrite(raw_ostream &OS) const override {
Richard Smith290d8012016-04-06 17:06:00 +00001106 OS << " Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001107 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001108
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001109 void writeValue(raw_ostream &OS) const override {
Douglas Gregor49ccfaa2011-11-19 19:22:57 +00001110 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1111 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001112
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001113 void writeDump(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001114 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
1115 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001116 };
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001117
1118 class ExprArgument : public SimpleArgument {
1119 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +00001120 ExprArgument(const Record &Arg, StringRef Attr)
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001121 : SimpleArgument(Arg, Attr, "Expr *")
1122 {}
1123
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001124 void writeASTVisitorTraversal(raw_ostream &OS) const override {
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00001125 OS << " if (!"
1126 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1127 OS << " return false;\n";
1128 }
1129
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001130 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001131 OS << "tempInst" << getUpperName();
1132 }
1133
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001134 void writeTemplateInstantiation(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001135 OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
1136 OS << " {\n";
1137 OS << " EnterExpressionEvaluationContext "
Faisal Valid143a0c2017-04-01 21:30:49 +00001138 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001139 OS << " ExprResult " << "Result = S.SubstExpr("
1140 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1141 OS << " tempInst" << getUpperName() << " = "
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001142 << "Result.getAs<Expr>();\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001143 OS << " }\n";
1144 }
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001145
Craig Topper3164f332014-03-11 03:39:26 +00001146 void writeDump(raw_ostream &OS) const override {}
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001147
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001148 void writeDumpChildren(raw_ostream &OS) const override {
Stephen Kelly6d110d62019-01-30 19:49:49 +00001149 OS << " Visit(SA->get" << getUpperName() << "());\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001150 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001151
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001152 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001153 };
1154
1155 class VariadicExprArgument : public VariadicArgument {
1156 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +00001157 VariadicExprArgument(const Record &Arg, StringRef Attr)
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001158 : VariadicArgument(Arg, Attr, "Expr *")
1159 {}
1160
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001161 void writeASTVisitorTraversal(raw_ostream &OS) const override {
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00001162 OS << " {\n";
1163 OS << " " << getType() << " *I = A->" << getLowerName()
1164 << "_begin();\n";
1165 OS << " " << getType() << " *E = A->" << getLowerName()
1166 << "_end();\n";
1167 OS << " for (; I != E; ++I) {\n";
1168 OS << " if (!getDerived().TraverseStmt(*I))\n";
1169 OS << " return false;\n";
1170 OS << " }\n";
1171 OS << " }\n";
1172 }
1173
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001174 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001175 OS << "tempInst" << getUpperName() << ", "
1176 << "A->" << getLowerName() << "_size()";
1177 }
1178
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001179 void writeTemplateInstantiation(raw_ostream &OS) const override {
Eugene Zelenko5f02b772015-12-08 18:49:01 +00001180 OS << " auto *tempInst" << getUpperName()
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001181 << " = new (C, 16) " << getType()
1182 << "[A->" << getLowerName() << "_size()];\n";
1183 OS << " {\n";
1184 OS << " EnterExpressionEvaluationContext "
Faisal Valid143a0c2017-04-01 21:30:49 +00001185 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001186 OS << " " << getType() << " *TI = tempInst" << getUpperName()
1187 << ";\n";
1188 OS << " " << getType() << " *I = A->" << getLowerName()
1189 << "_begin();\n";
1190 OS << " " << getType() << " *E = A->" << getLowerName()
1191 << "_end();\n";
1192 OS << " for (; I != E; ++I, ++TI) {\n";
1193 OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001194 OS << " *TI = Result.getAs<Expr>();\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001195 OS << " }\n";
1196 OS << " }\n";
1197 }
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001198
Craig Topper3164f332014-03-11 03:39:26 +00001199 void writeDump(raw_ostream &OS) const override {}
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001200
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001201 void writeDumpChildren(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001202 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1203 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
Richard Smithf7514452014-10-30 21:02:37 +00001204 << getLowerName() << "_end(); I != E; ++I)\n";
Stephen Kelly6d110d62019-01-30 19:49:49 +00001205 OS << " Visit(*I);\n";
Richard Trieude5cc7d2013-01-31 01:44:26 +00001206 }
1207
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001208 void writeHasChildren(raw_ostream &OS) const override {
Richard Trieude5cc7d2013-01-31 01:44:26 +00001209 OS << "SA->" << getLowerName() << "_begin() != "
1210 << "SA->" << getLowerName() << "_end()";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001211 }
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001212 };
Richard Smithb87c4652013-10-31 21:23:20 +00001213
Erich Keane3efe0022018-07-20 14:13:28 +00001214 class VariadicIdentifierArgument : public VariadicArgument {
1215 public:
1216 VariadicIdentifierArgument(const Record &Arg, StringRef Attr)
1217 : VariadicArgument(Arg, Attr, "IdentifierInfo *")
1218 {}
1219 };
1220
Peter Collingbourne915df992015-05-15 18:33:32 +00001221 class VariadicStringArgument : public VariadicArgument {
1222 public:
1223 VariadicStringArgument(const Record &Arg, StringRef Attr)
Benjamin Kramer1b582012016-02-13 18:11:49 +00001224 : VariadicArgument(Arg, Attr, "StringRef")
Peter Collingbourne915df992015-05-15 18:33:32 +00001225 {}
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001226
Benjamin Kramer1b582012016-02-13 18:11:49 +00001227 void writeCtorBody(raw_ostream &OS) const override {
Reid Kleckner7420f962020-03-11 19:43:37 -07001228 OS << " for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1229 " ++I) {\n"
1230 " StringRef Ref = " << getUpperName() << "[I];\n"
1231 " if (!Ref.empty()) {\n"
1232 " char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1233 " std::memcpy(Mem, Ref.data(), Ref.size());\n"
1234 " " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1235 " }\n"
1236 " }\n";
Benjamin Kramer1b582012016-02-13 18:11:49 +00001237 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001238
Peter Collingbourne915df992015-05-15 18:33:32 +00001239 void writeValueImpl(raw_ostream &OS) const override {
1240 OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
1241 }
1242 };
1243
Richard Smithb87c4652013-10-31 21:23:20 +00001244 class TypeArgument : public SimpleArgument {
1245 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +00001246 TypeArgument(const Record &Arg, StringRef Attr)
Richard Smithb87c4652013-10-31 21:23:20 +00001247 : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1248 {}
1249
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001250 void writeAccessors(raw_ostream &OS) const override {
Richard Smithb87c4652013-10-31 21:23:20 +00001251 OS << " QualType get" << getUpperName() << "() const {\n";
1252 OS << " return " << getLowerName() << "->getType();\n";
1253 OS << " }";
1254 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1255 OS << " return " << getLowerName() << ";\n";
1256 OS << " }";
1257 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001258
Richard Smithf26d5512017-08-15 22:58:45 +00001259 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1260 OS << " if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
1261 OS << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
1262 OS << " return false;\n";
1263 }
1264
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001265 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
Richard Smithb87c4652013-10-31 21:23:20 +00001266 OS << "A->get" << getUpperName() << "Loc()";
1267 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001268
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001269 void writePCHWrite(raw_ostream &OS) const override {
Benjamin Krameradcd0262020-01-28 20:23:46 +01001270 OS << " "
1271 << WritePCHRecord(getType(),
1272 "SA->get" + std::string(getUpperName()) + "Loc()");
Richard Smithb87c4652013-10-31 21:23:20 +00001273 }
1274 };
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001275
Hans Wennborgdcfba332015-10-06 23:40:43 +00001276} // end anonymous namespace
Peter Collingbournebee583f2011-10-06 13:03:08 +00001277
Aaron Ballman2f22b942014-05-20 19:47:14 +00001278static std::unique_ptr<Argument>
1279createArgument(const Record &Arg, StringRef Attr,
1280 const Record *Search = nullptr) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001281 if (!Search)
1282 Search = &Arg;
1283
David Blaikie28f30ca2014-08-08 23:59:38 +00001284 std::unique_ptr<Argument> Ptr;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001285 llvm::StringRef ArgName = Search->getName();
1286
David Blaikie28f30ca2014-08-08 23:59:38 +00001287 if (ArgName == "AlignedArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001288 Ptr = std::make_unique<AlignedArgument>(Arg, Attr);
David Blaikie28f30ca2014-08-08 23:59:38 +00001289 else if (ArgName == "EnumArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001290 Ptr = std::make_unique<EnumArgument>(Arg, Attr);
David Blaikie28f30ca2014-08-08 23:59:38 +00001291 else if (ArgName == "ExprArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001292 Ptr = std::make_unique<ExprArgument>(Arg, Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001293 else if (ArgName == "FunctionArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001294 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *");
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00001295 else if (ArgName == "NamedArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001296 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "NamedDecl *");
Peter Collingbournebee583f2011-10-06 13:03:08 +00001297 else if (ArgName == "IdentifierArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001298 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
David Majnemer4bb09802014-02-10 19:50:15 +00001299 else if (ArgName == "DefaultBoolArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001300 Ptr = std::make_unique<DefaultSimpleArgument>(
David Blaikie28f30ca2014-08-08 23:59:38 +00001301 Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1302 else if (ArgName == "BoolArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001303 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "bool");
Aaron Ballman18a78382013-11-21 00:28:23 +00001304 else if (ArgName == "DefaultIntArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001305 Ptr = std::make_unique<DefaultSimpleArgument>(
David Blaikie28f30ca2014-08-08 23:59:38 +00001306 Arg, Attr, "int", Arg.getValueAsInt("Default"));
1307 else if (ArgName == "IntArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001308 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "int");
David Blaikie28f30ca2014-08-08 23:59:38 +00001309 else if (ArgName == "StringArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001310 Ptr = std::make_unique<StringArgument>(Arg, Attr);
David Blaikie28f30ca2014-08-08 23:59:38 +00001311 else if (ArgName == "TypeArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001312 Ptr = std::make_unique<TypeArgument>(Arg, Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001313 else if (ArgName == "UnsignedArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001314 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
Peter Collingbournebee583f2011-10-06 13:03:08 +00001315 else if (ArgName == "VariadicUnsignedArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001316 Ptr = std::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
Peter Collingbourne915df992015-05-15 18:33:32 +00001317 else if (ArgName == "VariadicStringArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001318 Ptr = std::make_unique<VariadicStringArgument>(Arg, Attr);
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001319 else if (ArgName == "VariadicEnumArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001320 Ptr = std::make_unique<VariadicEnumArgument>(Arg, Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001321 else if (ArgName == "VariadicExprArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001322 Ptr = std::make_unique<VariadicExprArgument>(Arg, Attr);
Joel E. Denny81508102018-03-13 14:51:22 +00001323 else if (ArgName == "VariadicParamIdxArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001324 Ptr = std::make_unique<VariadicParamIdxArgument>(Arg, Attr);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00001325 else if (ArgName == "VariadicParamOrParamIdxArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001326 Ptr = std::make_unique<VariadicParamOrParamIdxArgument>(Arg, Attr);
Joel E. Denny81508102018-03-13 14:51:22 +00001327 else if (ArgName == "ParamIdxArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001328 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "ParamIdx");
Erich Keane3efe0022018-07-20 14:13:28 +00001329 else if (ArgName == "VariadicIdentifierArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001330 Ptr = std::make_unique<VariadicIdentifierArgument>(Arg, Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001331 else if (ArgName == "VersionArgument")
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001332 Ptr = std::make_unique<VersionArgument>(Arg, Attr);
Johannes Doerfert1228d422019-12-19 20:42:12 -06001333 else if (ArgName == "OMPTraitInfoArgument")
Johannes Doerfert55eca282020-03-13 23:42:05 -05001334 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "OMPTraitInfo *");
Peter Collingbournebee583f2011-10-06 13:03:08 +00001335
1336 if (!Ptr) {
Aaron Ballman18a78382013-11-21 00:28:23 +00001337 // Search in reverse order so that the most-derived type is handled first.
Craig Topper25761242016-01-18 19:52:54 +00001338 ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
David Majnemerf7e36092016-06-23 00:15:04 +00001339 for (const auto &Base : llvm::reverse(Bases)) {
Craig Topper25761242016-01-18 19:52:54 +00001340 if ((Ptr = createArgument(Arg, Attr, Base.first)))
Peter Collingbournebee583f2011-10-06 13:03:08 +00001341 break;
1342 }
1343 }
Aaron Ballman8ee40b72013-09-09 23:33:17 +00001344
1345 if (Ptr && Arg.getValueAsBit("Optional"))
1346 Ptr->setOptional(true);
1347
John McCalla62c1a92015-10-28 00:17:34 +00001348 if (Ptr && Arg.getValueAsBit("Fake"))
1349 Ptr->setFake(true);
1350
David Blaikie28f30ca2014-08-08 23:59:38 +00001351 return Ptr;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001352}
1353
Douglas Gregor49ccfaa2011-11-19 19:22:57 +00001354static void writeAvailabilityValue(raw_ostream &OS) {
1355 OS << "\" << getPlatform()->getName();\n"
Manman Ren42e09eb2016-03-10 23:54:12 +00001356 << " if (getStrict()) OS << \", strict\";\n"
Douglas Gregor49ccfaa2011-11-19 19:22:57 +00001357 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1358 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1359 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1360 << " if (getUnavailable()) OS << \", unavailable\";\n"
1361 << " OS << \"";
1362}
1363
Manman Renc7890fe2016-03-16 18:50:49 +00001364static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
1365 OS << "\\\"\" << getMessage() << \"\\\"\";\n";
1366 // Only GNU deprecated has an optional fixit argument at the second position.
1367 if (Variety == "GNU")
1368 OS << " if (!getReplacement().empty()) OS << \", \\\"\""
1369 " << getReplacement() << \"\\\"\";\n";
1370 OS << " OS << \"";
1371}
1372
Reid Kleckner7420f962020-03-11 19:43:37 -07001373static void writeGetSpellingFunction(const Record &R, raw_ostream &OS) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001374 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Aaron Ballman3e424b52013-12-26 18:30:57 +00001375
1376 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1377 if (Spellings.empty()) {
1378 OS << " return \"(No spelling)\";\n}\n\n";
1379 return;
1380 }
1381
Erich Keane6a24e802019-09-13 17:39:31 +00001382 OS << " switch (getAttributeSpellingListIndex()) {\n"
Aaron Ballman3e424b52013-12-26 18:30:57 +00001383 " default:\n"
1384 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1385 " return \"(No spelling)\";\n";
1386
1387 for (unsigned I = 0; I < Spellings.size(); ++I)
1388 OS << " case " << I << ":\n"
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001389 " return \"" << Spellings[I].name() << "\";\n";
Aaron Ballman3e424b52013-12-26 18:30:57 +00001390 // End of the switch statement.
1391 OS << " }\n";
1392 // End of the getSpelling function.
1393 OS << "}\n\n";
1394}
1395
Aaron Ballman8f1439b2014-03-05 16:49:55 +00001396static void
Reid Kleckner7420f962020-03-11 19:43:37 -07001397writePrettyPrintFunction(const Record &R,
Aaron Ballman8f1439b2014-03-05 16:49:55 +00001398 const std::vector<std::unique_ptr<Argument>> &Args,
1399 raw_ostream &OS) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001400 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Michael Han99315932013-01-24 16:46:58 +00001401
1402 OS << "void " << R.getName() << "Attr::printPretty("
1403 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1404
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001405 if (Spellings.empty()) {
Michael Han99315932013-01-24 16:46:58 +00001406 OS << "}\n\n";
1407 return;
1408 }
1409
Erich Keane6a24e802019-09-13 17:39:31 +00001410 OS << " switch (getAttributeSpellingListIndex()) {\n"
1411 " default:\n"
1412 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1413 " break;\n";
Michael Han99315932013-01-24 16:46:58 +00001414
1415 for (unsigned I = 0; I < Spellings.size(); ++ I) {
1416 llvm::SmallString<16> Prefix;
1417 llvm::SmallString<8> Suffix;
1418 // The actual spelling of the name and namespace (if applicable)
1419 // of an attribute without considering prefix and suffix.
1420 llvm::SmallString<64> Spelling;
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001421 std::string Name = Spellings[I].name();
1422 std::string Variety = Spellings[I].variety();
Michael Han99315932013-01-24 16:46:58 +00001423
1424 if (Variety == "GNU") {
1425 Prefix = " __attribute__((";
1426 Suffix = "))";
Aaron Ballman606093a2017-10-15 15:01:42 +00001427 } else if (Variety == "CXX11" || Variety == "C2x") {
Michael Han99315932013-01-24 16:46:58 +00001428 Prefix = " [[";
1429 Suffix = "]]";
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001430 std::string Namespace = Spellings[I].nameSpace();
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001431 if (!Namespace.empty()) {
Michael Han99315932013-01-24 16:46:58 +00001432 Spelling += Namespace;
1433 Spelling += "::";
1434 }
1435 } else if (Variety == "Declspec") {
1436 Prefix = " __declspec(";
1437 Suffix = ")";
Nico Weber20e08042016-09-03 02:55:10 +00001438 } else if (Variety == "Microsoft") {
1439 Prefix = "[";
1440 Suffix = "]";
Richard Smith0cdcc982013-01-29 01:24:26 +00001441 } else if (Variety == "Keyword") {
1442 Prefix = " ";
1443 Suffix = "";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001444 } else if (Variety == "Pragma") {
1445 Prefix = "#pragma ";
1446 Suffix = "\n";
1447 std::string Namespace = Spellings[I].nameSpace();
1448 if (!Namespace.empty()) {
1449 Spelling += Namespace;
1450 Spelling += " ";
1451 }
Michael Han99315932013-01-24 16:46:58 +00001452 } else {
Richard Smith0cdcc982013-01-29 01:24:26 +00001453 llvm_unreachable("Unknown attribute syntax variety!");
Michael Han99315932013-01-24 16:46:58 +00001454 }
1455
1456 Spelling += Name;
1457
1458 OS <<
1459 " case " << I << " : {\n"
Yaron Keren09fb7c62015-03-10 07:33:23 +00001460 " OS << \"" << Prefix << Spelling;
Michael Han99315932013-01-24 16:46:58 +00001461
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001462 if (Variety == "Pragma") {
Alexey Bataevcbecfdf2018-02-14 17:38:47 +00001463 OS << "\";\n";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001464 OS << " printPrettyPragma(OS, Policy);\n";
Alexey Bataev6d455322015-10-12 06:59:48 +00001465 OS << " OS << \"\\n\";";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001466 OS << " break;\n";
1467 OS << " }\n";
1468 continue;
1469 }
1470
Michael Han99315932013-01-24 16:46:58 +00001471 if (Spelling == "availability") {
Aaron Ballman48a533d2018-02-27 23:49:28 +00001472 OS << "(";
Michael Han99315932013-01-24 16:46:58 +00001473 writeAvailabilityValue(OS);
Aaron Ballman48a533d2018-02-27 23:49:28 +00001474 OS << ")";
Manman Renc7890fe2016-03-16 18:50:49 +00001475 } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
Aaron Ballman48a533d2018-02-27 23:49:28 +00001476 OS << "(";
1477 writeDeprecatedAttrValue(OS, Variety);
1478 OS << ")";
Michael Han99315932013-01-24 16:46:58 +00001479 } else {
Aaron Ballman48a533d2018-02-27 23:49:28 +00001480 // To avoid printing parentheses around an empty argument list or
1481 // printing spurious commas at the end of an argument list, we need to
1482 // determine where the last provided non-fake argument is.
1483 unsigned NonFakeArgs = 0;
1484 unsigned TrailingOptArgs = 0;
1485 bool FoundNonOptArg = false;
1486 for (const auto &arg : llvm::reverse(Args)) {
1487 if (arg->isFake())
1488 continue;
1489 ++NonFakeArgs;
1490 if (FoundNonOptArg)
1491 continue;
1492 // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
1493 // any way to detect whether the argument was omitted.
1494 if (!arg->isOptional() || arg->getIsOmitted() == "false") {
1495 FoundNonOptArg = true;
1496 continue;
1497 }
1498 if (!TrailingOptArgs++)
1499 OS << "\";\n"
1500 << " unsigned TrailingOmittedArgs = 0;\n";
1501 OS << " if (" << arg->getIsOmitted() << ")\n"
1502 << " ++TrailingOmittedArgs;\n";
Michael Han99315932013-01-24 16:46:58 +00001503 }
Aaron Ballman48a533d2018-02-27 23:49:28 +00001504 if (TrailingOptArgs)
1505 OS << " OS << \"";
1506 if (TrailingOptArgs < NonFakeArgs)
1507 OS << "(";
1508 else if (TrailingOptArgs)
1509 OS << "\";\n"
1510 << " if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
1511 << " OS << \"(\";\n"
1512 << " OS << \"";
1513 unsigned ArgIndex = 0;
1514 for (const auto &arg : Args) {
1515 if (arg->isFake())
1516 continue;
1517 if (ArgIndex) {
1518 if (ArgIndex >= NonFakeArgs - TrailingOptArgs)
1519 OS << "\";\n"
1520 << " if (" << ArgIndex << " < " << NonFakeArgs
1521 << " - TrailingOmittedArgs)\n"
1522 << " OS << \", \";\n"
1523 << " OS << \"";
1524 else
1525 OS << ", ";
1526 }
1527 std::string IsOmitted = arg->getIsOmitted();
1528 if (arg->isOptional() && IsOmitted != "false")
1529 OS << "\";\n"
1530 << " if (!(" << IsOmitted << ")) {\n"
1531 << " OS << \"";
1532 arg->writeValue(OS);
1533 if (arg->isOptional() && IsOmitted != "false")
1534 OS << "\";\n"
1535 << " }\n"
1536 << " OS << \"";
1537 ++ArgIndex;
1538 }
1539 if (TrailingOptArgs < NonFakeArgs)
1540 OS << ")";
1541 else if (TrailingOptArgs)
1542 OS << "\";\n"
1543 << " if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
1544 << " OS << \")\";\n"
1545 << " OS << \"";
Michael Han99315932013-01-24 16:46:58 +00001546 }
1547
Yaron Keren09fb7c62015-03-10 07:33:23 +00001548 OS << Suffix + "\";\n";
Michael Han99315932013-01-24 16:46:58 +00001549
1550 OS <<
1551 " break;\n"
1552 " }\n";
1553 }
1554
1555 // End of the switch statement.
1556 OS << "}\n";
1557 // End of the print function.
1558 OS << "}\n\n";
1559}
1560
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001561/// Return the index of a spelling in a spelling list.
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001562static unsigned
1563getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1564 const FlattenedSpelling &Spelling) {
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00001565 assert(!SpellingList.empty() && "Spelling list is empty!");
Michael Hanaf02bbe2013-02-01 01:19:17 +00001566
1567 for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001568 const FlattenedSpelling &S = SpellingList[Index];
1569 if (S.variety() != Spelling.variety())
Michael Hanaf02bbe2013-02-01 01:19:17 +00001570 continue;
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001571 if (S.nameSpace() != Spelling.nameSpace())
Michael Hanaf02bbe2013-02-01 01:19:17 +00001572 continue;
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001573 if (S.name() != Spelling.name())
Michael Hanaf02bbe2013-02-01 01:19:17 +00001574 continue;
1575
1576 return Index;
1577 }
1578
1579 llvm_unreachable("Unknown spelling!");
1580}
1581
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001582static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
Michael Hanaf02bbe2013-02-01 01:19:17 +00001583 std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
George Burgess IV1881a572016-12-01 00:13:18 +00001584 if (Accessors.empty())
1585 return;
1586
1587 const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1588 assert(!SpellingList.empty() &&
1589 "Attribute with empty spelling list can't have accessors!");
Aaron Ballman2f22b942014-05-20 19:47:14 +00001590 for (const auto *Accessor : Accessors) {
Erich Keane3bff4142017-10-16 23:25:24 +00001591 const StringRef Name = Accessor->getValueAsString("Name");
George Burgess IV1881a572016-12-01 00:13:18 +00001592 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
Michael Hanaf02bbe2013-02-01 01:19:17 +00001593
Erich Keane6a24e802019-09-13 17:39:31 +00001594 OS << " bool " << Name
1595 << "() const { return getAttributeSpellingListIndex() == ";
Michael Hanaf02bbe2013-02-01 01:19:17 +00001596 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001597 OS << getSpellingListIndex(SpellingList, Spellings[Index]);
George Burgess IV1881a572016-12-01 00:13:18 +00001598 if (Index != Spellings.size() - 1)
Erich Keane6a24e802019-09-13 17:39:31 +00001599 OS << " ||\n getAttributeSpellingListIndex() == ";
Michael Hanaf02bbe2013-02-01 01:19:17 +00001600 else
1601 OS << "; }\n";
1602 }
1603 }
1604}
1605
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001606static bool
1607SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
Aaron Ballman36a53502014-01-16 13:03:14 +00001608 assert(!Spellings.empty() && "An empty list of spellings was provided");
Benjamin Krameradcd0262020-01-28 20:23:46 +01001609 std::string FirstName =
1610 std::string(NormalizeNameForSpellingComparison(Spellings.front().name()));
Aaron Ballman2f22b942014-05-20 19:47:14 +00001611 for (const auto &Spelling :
1612 llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01001613 std::string Name =
1614 std::string(NormalizeNameForSpellingComparison(Spelling.name()));
Aaron Ballman36a53502014-01-16 13:03:14 +00001615 if (Name != FirstName)
1616 return false;
1617 }
1618 return true;
1619}
1620
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001621typedef std::map<unsigned, std::string> SemanticSpellingMap;
1622static std::string
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001623CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001624 SemanticSpellingMap &Map) {
1625 // The enumerants are automatically generated based on the variety,
1626 // namespace (if present) and name for each attribute spelling. However,
1627 // care is taken to avoid trampling on the reserved namespace due to
1628 // underscores.
1629 std::string Ret(" enum Spelling {\n");
1630 std::set<std::string> Uniques;
1631 unsigned Idx = 0;
Erich Keane68b09772019-09-17 14:11:51 +00001632
1633 // If we have a need to have this many spellings we likely need to add an
1634 // extra bit to the SpellingIndex in AttributeCommonInfo, then increase the
1635 // value of SpellingNotCalculated there and here.
1636 assert(Spellings.size() < 15 &&
1637 "Too many spellings, would step on SpellingNotCalculated in "
1638 "AttributeCommonInfo");
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001639 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001640 const FlattenedSpelling &S = *I;
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00001641 const std::string &Variety = S.variety();
1642 const std::string &Spelling = S.name();
1643 const std::string &Namespace = S.nameSpace();
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001644 std::string EnumName;
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001645
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001646 EnumName += (Variety + "_");
1647 if (!Namespace.empty())
1648 EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1649 "_");
1650 EnumName += NormalizeNameForSpellingComparison(Spelling);
1651
1652 // Even if the name is not unique, this spelling index corresponds to a
1653 // particular enumerant name that we've calculated.
1654 Map[Idx] = EnumName;
1655
1656 // Since we have been stripping underscores to avoid trampling on the
1657 // reserved namespace, we may have inadvertently created duplicate
1658 // enumerant names. These duplicates are not considered part of the
1659 // semantic spelling, and can be elided.
1660 if (Uniques.find(EnumName) != Uniques.end())
1661 continue;
1662
1663 Uniques.insert(EnumName);
1664 if (I != Spellings.begin())
1665 Ret += ",\n";
Aaron Ballman9bf6b752015-03-10 17:19:18 +00001666 // Duplicate spellings are not considered part of the semantic spelling
1667 // enumeration, but the spelling index and semantic spelling values are
1668 // meant to be equivalent, so we must specify a concrete value for each
1669 // enumerator.
1670 Ret += " " + EnumName + " = " + llvm::utostr(Idx);
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001671 }
Erich Keane68b09772019-09-17 14:11:51 +00001672 Ret += ",\n SpellingNotCalculated = 15\n";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001673 Ret += "\n };\n\n";
1674 return Ret;
1675}
1676
1677void WriteSemanticSpellingSwitch(const std::string &VarName,
1678 const SemanticSpellingMap &Map,
1679 raw_ostream &OS) {
1680 OS << " switch (" << VarName << ") {\n default: "
1681 << "llvm_unreachable(\"Unknown spelling list index\");\n";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001682 for (const auto &I : Map)
1683 OS << " case " << I.first << ": return " << I.second << ";\n";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001684 OS << " }\n";
1685}
1686
Aaron Ballman35db2b32014-01-29 22:13:45 +00001687// Emits the LateParsed property for attributes.
1688static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1689 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1690 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1691
Aaron Ballman2f22b942014-05-20 19:47:14 +00001692 for (const auto *Attr : Attrs) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001693 bool LateParsed = Attr->getValueAsBit("LateParsed");
Aaron Ballman35db2b32014-01-29 22:13:45 +00001694
1695 if (LateParsed) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001696 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
Aaron Ballman35db2b32014-01-29 22:13:45 +00001697
1698 // FIXME: Handle non-GNU attributes
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001699 for (const auto &I : Spellings) {
1700 if (I.variety() != "GNU")
Aaron Ballman35db2b32014-01-29 22:13:45 +00001701 continue;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001702 OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
Aaron Ballman35db2b32014-01-29 22:13:45 +00001703 }
1704 }
1705 }
1706 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1707}
1708
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001709static bool hasGNUorCXX11Spelling(const Record &Attribute) {
1710 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
1711 for (const auto &I : Spellings) {
1712 if (I.variety() == "GNU" || I.variety() == "CXX11")
1713 return true;
1714 }
1715 return false;
1716}
1717
1718namespace {
1719
1720struct AttributeSubjectMatchRule {
1721 const Record *MetaSubject;
1722 const Record *Constraint;
1723
1724 AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
1725 : MetaSubject(MetaSubject), Constraint(Constraint) {
1726 assert(MetaSubject && "Missing subject");
1727 }
1728
1729 bool isSubRule() const { return Constraint != nullptr; }
1730
1731 std::vector<Record *> getSubjects() const {
1732 return (Constraint ? Constraint : MetaSubject)
1733 ->getValueAsListOfDefs("Subjects");
1734 }
1735
1736 std::vector<Record *> getLangOpts() const {
1737 if (Constraint) {
1738 // Lookup the options in the sub-rule first, in case the sub-rule
1739 // overrides the rules options.
1740 std::vector<Record *> Opts = Constraint->getValueAsListOfDefs("LangOpts");
1741 if (!Opts.empty())
1742 return Opts;
1743 }
1744 return MetaSubject->getValueAsListOfDefs("LangOpts");
1745 }
1746
1747 // Abstract rules are used only for sub-rules
1748 bool isAbstractRule() const { return getSubjects().empty(); }
1749
Erich Keane3bff4142017-10-16 23:25:24 +00001750 StringRef getName() const {
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001751 return (Constraint ? Constraint : MetaSubject)->getValueAsString("Name");
1752 }
1753
1754 bool isNegatedSubRule() const {
1755 assert(isSubRule() && "Not a sub-rule");
1756 return Constraint->getValueAsBit("Negated");
1757 }
1758
1759 std::string getSpelling() const {
Benjamin Krameradcd0262020-01-28 20:23:46 +01001760 std::string Result = std::string(MetaSubject->getValueAsString("Name"));
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001761 if (isSubRule()) {
1762 Result += '(';
1763 if (isNegatedSubRule())
1764 Result += "unless(";
1765 Result += getName();
1766 if (isNegatedSubRule())
1767 Result += ')';
1768 Result += ')';
1769 }
1770 return Result;
1771 }
1772
1773 std::string getEnumValueName() const {
Craig Topper00648582017-05-31 19:01:22 +00001774 SmallString<128> Result;
1775 Result += "SubjectMatchRule_";
1776 Result += MetaSubject->getValueAsString("Name");
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001777 if (isSubRule()) {
1778 Result += "_";
1779 if (isNegatedSubRule())
1780 Result += "not_";
1781 Result += Constraint->getValueAsString("Name");
1782 }
1783 if (isAbstractRule())
1784 Result += "_abstract";
Benjamin Krameradcd0262020-01-28 20:23:46 +01001785 return std::string(Result.str());
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001786 }
1787
1788 std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
1789
1790 static const char *EnumName;
1791};
1792
1793const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";
1794
1795struct PragmaClangAttributeSupport {
1796 std::vector<AttributeSubjectMatchRule> Rules;
Alex Lorenz24952fb2017-04-19 15:52:11 +00001797
1798 class RuleOrAggregateRuleSet {
1799 std::vector<AttributeSubjectMatchRule> Rules;
1800 bool IsRule;
1801 RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
1802 bool IsRule)
1803 : Rules(Rules), IsRule(IsRule) {}
1804
1805 public:
1806 bool isRule() const { return IsRule; }
1807
1808 const AttributeSubjectMatchRule &getRule() const {
1809 assert(IsRule && "not a rule!");
1810 return Rules[0];
1811 }
1812
1813 ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
1814 return Rules;
1815 }
1816
1817 static RuleOrAggregateRuleSet
1818 getRule(const AttributeSubjectMatchRule &Rule) {
1819 return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
1820 }
1821 static RuleOrAggregateRuleSet
1822 getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
1823 return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
1824 }
1825 };
1826 llvm::DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001827
1828 PragmaClangAttributeSupport(RecordKeeper &Records);
1829
1830 bool isAttributedSupported(const Record &Attribute);
1831
1832 void emitMatchRuleList(raw_ostream &OS);
1833
John Brawn590dc8d2020-02-26 16:31:24 +00001834 void generateStrictConformsTo(const Record &Attr, raw_ostream &OS);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001835
1836 void generateParsingHelpers(raw_ostream &OS);
1837};
1838
1839} // end anonymous namespace
1840
Alex Lorenz24952fb2017-04-19 15:52:11 +00001841static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
John McCallbaf91d02019-10-25 16:28:03 -07001842 const Record *CurrentBase = D->getValueAsOptionalDef(BaseFieldName);
Alex Lorenz24952fb2017-04-19 15:52:11 +00001843 if (!CurrentBase)
1844 return false;
1845 if (CurrentBase == Base)
1846 return true;
1847 return doesDeclDeriveFrom(CurrentBase, Base);
1848}
1849
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001850PragmaClangAttributeSupport::PragmaClangAttributeSupport(
1851 RecordKeeper &Records) {
1852 std::vector<Record *> MetaSubjects =
1853 Records.getAllDerivedDefinitions("AttrSubjectMatcherRule");
1854 auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
1855 const Record *MetaSubject,
Saleem Abdulrasoolbe4773c2017-05-01 00:26:59 +00001856 const Record *Constraint) {
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001857 Rules.emplace_back(MetaSubject, Constraint);
1858 std::vector<Record *> ApplicableSubjects =
1859 SubjectContainer->getValueAsListOfDefs("Subjects");
1860 for (const auto *Subject : ApplicableSubjects) {
1861 bool Inserted =
Alex Lorenz24952fb2017-04-19 15:52:11 +00001862 SubjectsToRules
1863 .try_emplace(Subject, RuleOrAggregateRuleSet::getRule(
1864 AttributeSubjectMatchRule(MetaSubject,
1865 Constraint)))
1866 .second;
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001867 if (!Inserted) {
1868 PrintFatalError("Attribute subject match rules should not represent"
1869 "same attribute subjects.");
1870 }
1871 }
1872 };
1873 for (const auto *MetaSubject : MetaSubjects) {
Saleem Abdulrasoolbe4773c2017-05-01 00:26:59 +00001874 MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001875 std::vector<Record *> Constraints =
1876 MetaSubject->getValueAsListOfDefs("Constraints");
1877 for (const auto *Constraint : Constraints)
1878 MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
1879 }
Alex Lorenz24952fb2017-04-19 15:52:11 +00001880
1881 std::vector<Record *> Aggregates =
1882 Records.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule");
John McCallbaf91d02019-10-25 16:28:03 -07001883 std::vector<Record *> DeclNodes =
1884 Records.getAllDerivedDefinitions(DeclNodeClassName);
Alex Lorenz24952fb2017-04-19 15:52:11 +00001885 for (const auto *Aggregate : Aggregates) {
1886 Record *SubjectDecl = Aggregate->getValueAsDef("Subject");
1887
1888 // Gather sub-classes of the aggregate subject that act as attribute
1889 // subject rules.
1890 std::vector<AttributeSubjectMatchRule> Rules;
1891 for (const auto *D : DeclNodes) {
1892 if (doesDeclDeriveFrom(D, SubjectDecl)) {
1893 auto It = SubjectsToRules.find(D);
1894 if (It == SubjectsToRules.end())
1895 continue;
1896 if (!It->second.isRule() || It->second.getRule().isSubRule())
1897 continue; // Assume that the rule will be included as well.
1898 Rules.push_back(It->second.getRule());
1899 }
1900 }
1901
1902 bool Inserted =
1903 SubjectsToRules
1904 .try_emplace(SubjectDecl,
1905 RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
1906 .second;
1907 if (!Inserted) {
1908 PrintFatalError("Attribute subject match rules should not represent"
1909 "same attribute subjects.");
1910 }
1911 }
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001912}
1913
1914static PragmaClangAttributeSupport &
1915getPragmaAttributeSupport(RecordKeeper &Records) {
1916 static PragmaClangAttributeSupport Instance(Records);
1917 return Instance;
1918}
1919
1920void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
1921 OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
1922 OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
1923 "IsNegated) "
1924 << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
1925 OS << "#endif\n";
1926 for (const auto &Rule : Rules) {
1927 OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
1928 OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
1929 << Rule.isAbstractRule();
1930 if (Rule.isSubRule())
1931 OS << ", "
1932 << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
1933 << ", " << Rule.isNegatedSubRule();
1934 OS << ")\n";
1935 }
1936 OS << "#undef ATTR_MATCH_SUB_RULE\n";
1937}
1938
1939bool PragmaClangAttributeSupport::isAttributedSupported(
1940 const Record &Attribute) {
Richard Smith1bb64532018-08-30 01:01:07 +00001941 // If the attribute explicitly specified whether to support #pragma clang
1942 // attribute, use that setting.
1943 bool Unset;
1944 bool SpecifiedResult =
1945 Attribute.getValueAsBitOrUnset("PragmaAttributeSupport", Unset);
1946 if (!Unset)
1947 return SpecifiedResult;
1948
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001949 // Opt-out rules:
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001950 // An attribute requires delayed parsing (LateParsed is on)
1951 if (Attribute.getValueAsBit("LateParsed"))
1952 return false;
1953 // An attribute has no GNU/CXX11 spelling
1954 if (!hasGNUorCXX11Spelling(Attribute))
1955 return false;
1956 // An attribute subject list has a subject that isn't covered by one of the
1957 // subject match rules or has no subjects at all.
1958 if (Attribute.isValueUnset("Subjects"))
1959 return false;
1960 const Record *SubjectObj = Attribute.getValueAsDef("Subjects");
1961 std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
1962 if (Subjects.empty())
1963 return false;
1964 for (const auto *Subject : Subjects) {
1965 if (SubjectsToRules.find(Subject) == SubjectsToRules.end())
1966 return false;
1967 }
1968 return true;
1969}
1970
John McCall2c91c3b2019-05-30 04:09:01 +00001971static std::string GenerateTestExpression(ArrayRef<Record *> LangOpts) {
1972 std::string Test;
1973
1974 for (auto *E : LangOpts) {
1975 if (!Test.empty())
1976 Test += " || ";
1977
1978 const StringRef Code = E->getValueAsString("CustomCode");
1979 if (!Code.empty()) {
1980 Test += "(";
1981 Test += Code;
1982 Test += ")";
Aaron Ballmaneda58ac2020-03-14 15:57:28 -04001983 if (!E->getValueAsString("Name").empty()) {
1984 PrintWarning(
1985 E->getLoc(),
1986 "non-empty 'Name' field ignored because 'CustomCode' was supplied");
1987 }
John McCall2c91c3b2019-05-30 04:09:01 +00001988 } else {
1989 Test += "LangOpts.";
1990 Test += E->getValueAsString("Name");
1991 }
1992 }
1993
1994 if (Test.empty())
1995 return "true";
1996
1997 return Test;
1998}
1999
John Brawn590dc8d2020-02-26 16:31:24 +00002000void
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002001PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
2002 raw_ostream &OS) {
John Brawn590dc8d2020-02-26 16:31:24 +00002003 if (!isAttributedSupported(Attr) || Attr.isValueUnset("Subjects"))
2004 return;
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002005 // Generate a function that constructs a set of matching rules that describe
2006 // to which declarations the attribute should apply to.
John Brawn590dc8d2020-02-26 16:31:24 +00002007 OS << "virtual void getPragmaAttributeMatchRules("
2008 << "llvm::SmallVectorImpl<std::pair<"
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002009 << AttributeSubjectMatchRule::EnumName
John Brawn590dc8d2020-02-26 16:31:24 +00002010 << ", bool>> &MatchRules, const LangOptions &LangOpts) const {\n";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002011 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
2012 std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
2013 for (const auto *Subject : Subjects) {
2014 auto It = SubjectsToRules.find(Subject);
2015 assert(It != SubjectsToRules.end() &&
2016 "This attribute is unsupported by #pragma clang attribute");
Alex Lorenz24952fb2017-04-19 15:52:11 +00002017 for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
2018 // The rule might be language specific, so only subtract it from the given
2019 // rules if the specific language options are specified.
2020 std::vector<Record *> LangOpts = Rule.getLangOpts();
Erich Keane3bff4142017-10-16 23:25:24 +00002021 OS << " MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
John McCall2c91c3b2019-05-30 04:09:01 +00002022 << ", /*IsSupported=*/" << GenerateTestExpression(LangOpts)
2023 << "));\n";
Alex Lorenz24952fb2017-04-19 15:52:11 +00002024 }
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002025 }
Erich Keane3bff4142017-10-16 23:25:24 +00002026 OS << "}\n\n";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002027}
2028
2029void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
2030 // Generate routines that check the names of sub-rules.
2031 OS << "Optional<attr::SubjectMatchRule> "
2032 "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
2033 OS << " return None;\n";
2034 OS << "}\n\n";
2035
2036 std::map<const Record *, std::vector<AttributeSubjectMatchRule>>
2037 SubMatchRules;
2038 for (const auto &Rule : Rules) {
2039 if (!Rule.isSubRule())
2040 continue;
2041 SubMatchRules[Rule.MetaSubject].push_back(Rule);
2042 }
2043
2044 for (const auto &SubMatchRule : SubMatchRules) {
2045 OS << "Optional<attr::SubjectMatchRule> isAttributeSubjectMatchSubRuleFor_"
2046 << SubMatchRule.first->getValueAsString("Name")
2047 << "(StringRef Name, bool IsUnless) {\n";
2048 OS << " if (IsUnless)\n";
2049 OS << " return "
2050 "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
2051 for (const auto &Rule : SubMatchRule.second) {
2052 if (Rule.isNegatedSubRule())
2053 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2054 << ").\n";
2055 }
2056 OS << " Default(None);\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 << "}\n\n";
2066 }
2067
2068 // Generate the function that checks for the top-level rules.
2069 OS << "std::pair<Optional<attr::SubjectMatchRule>, "
2070 "Optional<attr::SubjectMatchRule> (*)(StringRef, "
2071 "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
2072 OS << " return "
2073 "llvm::StringSwitch<std::pair<Optional<attr::SubjectMatchRule>, "
2074 "Optional<attr::SubjectMatchRule> (*) (StringRef, "
2075 "bool)>>(Name).\n";
2076 for (const auto &Rule : Rules) {
2077 if (Rule.isSubRule())
2078 continue;
2079 std::string SubRuleFunction;
2080 if (SubMatchRules.count(Rule.MetaSubject))
Erich Keane3bff4142017-10-16 23:25:24 +00002081 SubRuleFunction =
2082 ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002083 else
2084 SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
2085 OS << " Case(\"" << Rule.getName() << "\", std::make_pair("
2086 << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
2087 }
2088 OS << " Default(std::make_pair(None, "
2089 "defaultIsAttributeSubjectMatchSubRuleFor));\n";
2090 OS << "}\n\n";
2091
2092 // Generate the function that checks for the submatch rules.
2093 OS << "const char *validAttributeSubjectMatchSubRules("
2094 << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
2095 OS << " switch (Rule) {\n";
2096 for (const auto &SubMatchRule : SubMatchRules) {
2097 OS << " case "
2098 << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
2099 << ":\n";
2100 OS << " return \"'";
2101 bool IsFirst = true;
2102 for (const auto &Rule : SubMatchRule.second) {
2103 if (!IsFirst)
2104 OS << ", '";
2105 IsFirst = false;
2106 if (Rule.isNegatedSubRule())
2107 OS << "unless(";
2108 OS << Rule.getName();
2109 if (Rule.isNegatedSubRule())
2110 OS << ')';
2111 OS << "'";
2112 }
2113 OS << "\";\n";
2114 }
2115 OS << " default: return nullptr;\n";
2116 OS << " }\n";
2117 OS << "}\n\n";
2118}
2119
George Burgess IV1881a572016-12-01 00:13:18 +00002120template <typename Fn>
2121static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
2122 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2123 SmallDenseSet<StringRef, 8> Seen;
2124 for (const FlattenedSpelling &S : Spellings) {
2125 if (Seen.insert(S.name()).second)
2126 F(S);
2127 }
2128}
2129
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002130/// Emits the first-argument-is-type property for attributes.
Aaron Ballman35db2b32014-01-29 22:13:45 +00002131static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
2132 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
2133 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2134
Aaron Ballman2f22b942014-05-20 19:47:14 +00002135 for (const auto *Attr : Attrs) {
Aaron Ballman35db2b32014-01-29 22:13:45 +00002136 // Determine whether the first argument is a type.
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002137 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
Aaron Ballman35db2b32014-01-29 22:13:45 +00002138 if (Args.empty())
2139 continue;
2140
Craig Topper25761242016-01-18 19:52:54 +00002141 if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
Aaron Ballman35db2b32014-01-29 22:13:45 +00002142 continue;
2143
2144 // All these spellings take a single type argument.
George Burgess IV1881a572016-12-01 00:13:18 +00002145 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2146 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2147 });
Aaron Ballman35db2b32014-01-29 22:13:45 +00002148 }
2149 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
2150}
2151
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002152/// Emits the parse-arguments-in-unevaluated-context property for
Aaron Ballman35db2b32014-01-29 22:13:45 +00002153/// attributes.
2154static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
2155 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
2156 ParsedAttrMap Attrs = getParsedAttrList(Records);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002157 for (const auto &I : Attrs) {
2158 const Record &Attr = *I.second;
Aaron Ballman35db2b32014-01-29 22:13:45 +00002159
2160 if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
2161 continue;
2162
2163 // All these spellings take are parsed unevaluated.
George Burgess IV1881a572016-12-01 00:13:18 +00002164 forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
2165 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2166 });
Aaron Ballman35db2b32014-01-29 22:13:45 +00002167 }
2168 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
2169}
2170
2171static bool isIdentifierArgument(Record *Arg) {
2172 return !Arg->getSuperClasses().empty() &&
Craig Topper25761242016-01-18 19:52:54 +00002173 llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
Aaron Ballman35db2b32014-01-29 22:13:45 +00002174 .Case("IdentifierArgument", true)
2175 .Case("EnumArgument", true)
Aaron Ballman55ef1512014-12-19 16:42:04 +00002176 .Case("VariadicEnumArgument", true)
Aaron Ballman35db2b32014-01-29 22:13:45 +00002177 .Default(false);
2178}
2179
Erich Keane3efe0022018-07-20 14:13:28 +00002180static bool isVariadicIdentifierArgument(Record *Arg) {
2181 return !Arg->getSuperClasses().empty() &&
2182 llvm::StringSwitch<bool>(
2183 Arg->getSuperClasses().back().first->getName())
2184 .Case("VariadicIdentifierArgument", true)
Johannes Doerfertac991bb2019-01-19 05:36:54 +00002185 .Case("VariadicParamOrParamIdxArgument", true)
Erich Keane3efe0022018-07-20 14:13:28 +00002186 .Default(false);
2187}
2188
2189static void emitClangAttrVariadicIdentifierArgList(RecordKeeper &Records,
2190 raw_ostream &OS) {
2191 OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
2192 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2193 for (const auto *A : Attrs) {
2194 // Determine whether the first argument is a variadic identifier.
2195 std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
2196 if (Args.empty() || !isVariadicIdentifierArgument(Args[0]))
2197 continue;
2198
2199 // All these spellings take an identifier argument.
2200 forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
2201 OS << ".Case(\"" << S.name() << "\", "
2202 << "true"
2203 << ")\n";
2204 });
2205 }
2206 OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
2207}
2208
Aaron Ballman35db2b32014-01-29 22:13:45 +00002209// Emits the first-argument-is-identifier property for attributes.
2210static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
2211 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
2212 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2213
Aaron Ballman2f22b942014-05-20 19:47:14 +00002214 for (const auto *Attr : Attrs) {
Aaron Ballman35db2b32014-01-29 22:13:45 +00002215 // Determine whether the first argument is an identifier.
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002216 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
Aaron Ballman35db2b32014-01-29 22:13:45 +00002217 if (Args.empty() || !isIdentifierArgument(Args[0]))
2218 continue;
2219
2220 // All these spellings take an identifier argument.
George Burgess IV1881a572016-12-01 00:13:18 +00002221 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2222 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2223 });
Aaron Ballman35db2b32014-01-29 22:13:45 +00002224 }
2225 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
2226}
2227
Johannes Doerfertac991bb2019-01-19 05:36:54 +00002228static bool keywordThisIsaIdentifierInArgument(const Record *Arg) {
2229 return !Arg->getSuperClasses().empty() &&
2230 llvm::StringSwitch<bool>(
2231 Arg->getSuperClasses().back().first->getName())
2232 .Case("VariadicParamOrParamIdxArgument", true)
2233 .Default(false);
2234}
2235
2236static void emitClangAttrThisIsaIdentifierArgList(RecordKeeper &Records,
2237 raw_ostream &OS) {
2238 OS << "#if defined(CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST)\n";
2239 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2240 for (const auto *A : Attrs) {
2241 // Determine whether the first argument is a variadic identifier.
2242 std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
2243 if (Args.empty() || !keywordThisIsaIdentifierInArgument(Args[0]))
2244 continue;
2245
2246 // All these spellings take an identifier argument.
2247 forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
2248 OS << ".Case(\"" << S.name() << "\", "
2249 << "true"
2250 << ")\n";
2251 });
2252 }
2253 OS << "#endif // CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST\n\n";
2254}
2255
Reid Kleckner7420f962020-03-11 19:43:37 -07002256static void emitAttributes(RecordKeeper &Records, raw_ostream &OS,
2257 bool Header) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00002258 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
Erich Keane6a24e802019-09-13 17:39:31 +00002259 ParsedAttrMap AttrMap = getParsedAttrList(Records);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002260
Aaron Ballman2f22b942014-05-20 19:47:14 +00002261 for (const auto *Attr : Attrs) {
2262 const Record &R = *Attr;
Aaron Ballman06bd44b2014-02-17 18:23:02 +00002263
2264 // FIXME: Currently, documentation is generated as-needed due to the fact
2265 // that there is no way to allow a generated project "reach into" the docs
2266 // directory (for instance, it may be an out-of-tree build). However, we want
2267 // to ensure that every attribute has a Documentation field, and produce an
2268 // error if it has been neglected. Otherwise, the on-demand generation which
2269 // happens server-side will fail. This code is ensuring that functionality,
2270 // even though this Emitter doesn't technically need the documentation.
2271 // When attribute documentation can be generated as part of the build
2272 // itself, this code can be removed.
2273 (void)R.getValueAsListOfDefs("Documentation");
Johannes Doerfert1228d422019-12-19 20:42:12 -06002274
Douglas Gregorb2daf842012-05-02 15:56:52 +00002275 if (!R.getValueAsBit("ASTNode"))
2276 continue;
Johannes Doerfert1228d422019-12-19 20:42:12 -06002277
Craig Topper25761242016-01-18 19:52:54 +00002278 ArrayRef<std::pair<Record *, SMRange>> Supers = R.getSuperClasses();
Aaron Ballman0979e9e2013-07-30 01:44:15 +00002279 assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
Aaron Ballman0979e9e2013-07-30 01:44:15 +00002280 std::string SuperName;
Richard Smith33bddbd2018-01-04 23:42:29 +00002281 bool Inheritable = false;
David Majnemerf7e36092016-06-23 00:15:04 +00002282 for (const auto &Super : llvm::reverse(Supers)) {
Craig Topper25761242016-01-18 19:52:54 +00002283 const Record *R = Super.first;
Aaron Ballmanb9a457a2018-05-03 15:33:50 +00002284 if (R->getName() != "TargetSpecificAttr" &&
2285 R->getName() != "DeclOrTypeAttr" && SuperName.empty())
Benjamin Krameradcd0262020-01-28 20:23:46 +01002286 SuperName = std::string(R->getName());
Richard Smith33bddbd2018-01-04 23:42:29 +00002287 if (R->getName() == "InheritableAttr")
2288 Inheritable = true;
Aaron Ballman0979e9e2013-07-30 01:44:15 +00002289 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00002290
Reid Kleckner7420f962020-03-11 19:43:37 -07002291 if (Header)
2292 OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
2293 else
2294 OS << "\n// " << R.getName() << "Attr implementation\n\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002295
2296 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002297 std::vector<std::unique_ptr<Argument>> Args;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002298 Args.reserve(ArgRecords.size());
2299
John McCalla62c1a92015-10-28 00:17:34 +00002300 bool HasOptArg = false;
2301 bool HasFakeArg = false;
Aaron Ballman2f22b942014-05-20 19:47:14 +00002302 for (const auto *ArgRecord : ArgRecords) {
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002303 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
Reid Kleckner7420f962020-03-11 19:43:37 -07002304 if (Header) {
2305 Args.back()->writeDeclarations(OS);
2306 OS << "\n\n";
2307 }
John McCalla62c1a92015-10-28 00:17:34 +00002308
2309 // For these purposes, fake takes priority over optional.
2310 if (Args.back()->isFake()) {
2311 HasFakeArg = true;
2312 } else if (Args.back()->isOptional()) {
2313 HasOptArg = true;
2314 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00002315 }
2316
Reid Kleckner7420f962020-03-11 19:43:37 -07002317 if (Header)
2318 OS << "public:\n";
Aaron Ballman36a53502014-01-16 13:03:14 +00002319
Aaron Ballmanc669cc02014-01-27 22:10:04 +00002320 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Aaron Ballman36a53502014-01-16 13:03:14 +00002321
2322 // If there are zero or one spellings, all spelling-related functionality
2323 // can be elided. If all of the spellings share the same name, the spelling
2324 // functionality can also be elided.
2325 bool ElideSpelling = (Spellings.size() <= 1) ||
2326 SpellingNamesAreCommon(Spellings);
2327
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00002328 // This maps spelling index values to semantic Spelling enumerants.
2329 SemanticSpellingMap SemanticToSyntacticMap;
Aaron Ballman36a53502014-01-16 13:03:14 +00002330
Reid Kleckner7420f962020-03-11 19:43:37 -07002331 std::string SpellingEnum;
Erich Keane661c9502020-03-17 08:23:45 -07002332 if (Spellings.size() > 1)
Reid Kleckner7420f962020-03-11 19:43:37 -07002333 SpellingEnum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2334 if (Header)
2335 OS << SpellingEnum;
Aaron Ballman36a53502014-01-16 13:03:14 +00002336
Erich Keane6a24e802019-09-13 17:39:31 +00002337 const auto &ParsedAttrSpellingItr = llvm::find_if(
2338 AttrMap, [R](const std::pair<std::string, const Record *> &P) {
2339 return &R == P.second;
2340 });
2341
John McCalla62c1a92015-10-28 00:17:34 +00002342 // Emit CreateImplicit factory methods.
Erich Keane6a24e802019-09-13 17:39:31 +00002343 auto emitCreate = [&](bool Implicit, bool emitFake) {
Reid Kleckner7420f962020-03-11 19:43:37 -07002344 if (Header)
2345 OS << " static ";
2346 OS << R.getName() << "Attr *";
2347 if (!Header)
2348 OS << R.getName() << "Attr::";
2349 OS << "Create";
2350 if (Implicit)
2351 OS << "Implicit";
Erich Keane6a24e802019-09-13 17:39:31 +00002352 OS << "(";
John McCalla62c1a92015-10-28 00:17:34 +00002353 OS << "ASTContext &Ctx";
John McCalla62c1a92015-10-28 00:17:34 +00002354 for (auto const &ai : Args) {
2355 if (ai->isFake() && !emitFake) continue;
2356 OS << ", ";
2357 ai->writeCtorParameters(OS);
2358 }
Reid Kleckner7420f962020-03-11 19:43:37 -07002359 OS << ", const AttributeCommonInfo &CommonInfo";
2360 if (Header)
2361 OS << " = {SourceRange{}}";
2362 OS << ")";
2363 if (Header) {
2364 OS << ";\n";
2365 return;
2366 }
2367
2368 OS << " {\n";
2369 OS << " auto *A = new (Ctx) " << R.getName();
Erich Keane6a24e802019-09-13 17:39:31 +00002370 OS << "Attr(Ctx, CommonInfo";
John McCalla62c1a92015-10-28 00:17:34 +00002371 for (auto const &ai : Args) {
2372 if (ai->isFake() && !emitFake) continue;
John McCalla62c1a92015-10-28 00:17:34 +00002373 OS << ", ";
Erich Keane6a24e802019-09-13 17:39:31 +00002374 ai->writeImplicitCtorArgs(OS);
John McCalla62c1a92015-10-28 00:17:34 +00002375 }
Erich Keane6a24e802019-09-13 17:39:31 +00002376 OS << ");\n";
2377 if (Implicit) {
Reid Kleckner7420f962020-03-11 19:43:37 -07002378 OS << " A->setImplicit(true);\n";
Erich Keane6a24e802019-09-13 17:39:31 +00002379 }
2380 if (Implicit || ElideSpelling) {
Reid Kleckner7420f962020-03-11 19:43:37 -07002381 OS << " if (!A->isAttributeSpellingListCalculated() && "
Erich Keane6a24e802019-09-13 17:39:31 +00002382 "!A->getAttrName())\n";
Reid Kleckner7420f962020-03-11 19:43:37 -07002383 OS << " A->setAttributeSpellingListIndex(0);\n";
Erich Keane6a24e802019-09-13 17:39:31 +00002384 }
Reid Kleckner7420f962020-03-11 19:43:37 -07002385 OS << " return A;\n}\n\n";
John McCalla62c1a92015-10-28 00:17:34 +00002386 };
Aaron Ballman36a53502014-01-16 13:03:14 +00002387
Erich Keane6a24e802019-09-13 17:39:31 +00002388 auto emitCreateNoCI = [&](bool Implicit, bool emitFake) {
Reid Kleckner7420f962020-03-11 19:43:37 -07002389 if (Header)
2390 OS << " static ";
2391 OS << R.getName() << "Attr *";
2392 if (!Header)
2393 OS << R.getName() << "Attr::";
2394 OS << "Create";
Erich Keane6a24e802019-09-13 17:39:31 +00002395 if (Implicit)
2396 OS << "Implicit";
2397 OS << "(";
2398 OS << "ASTContext &Ctx";
2399 for (auto const &ai : Args) {
2400 if (ai->isFake() && !emitFake) continue;
2401 OS << ", ";
2402 ai->writeCtorParameters(OS);
2403 }
2404 OS << ", SourceRange Range, AttributeCommonInfo::Syntax Syntax";
Reid Kleckner7420f962020-03-11 19:43:37 -07002405 if (!ElideSpelling) {
2406 OS << ", " << R.getName() << "Attr::Spelling S";
2407 if (Header)
2408 OS << " = static_cast<Spelling>(SpellingNotCalculated)";
2409 }
2410 OS << ")";
2411 if (Header) {
2412 OS << ";\n";
2413 return;
2414 }
2415
2416 OS << " {\n";
2417 OS << " AttributeCommonInfo I(Range, ";
Erich Keane6a24e802019-09-13 17:39:31 +00002418
2419 if (ParsedAttrSpellingItr != std::end(AttrMap))
2420 OS << "AT_" << ParsedAttrSpellingItr->first;
2421 else
2422 OS << "NoSemaHandlerAttribute";
2423
2424 OS << ", Syntax";
2425 if (!ElideSpelling)
Erich Keanef9cd3812019-09-13 17:56:38 +00002426 OS << ", S";
Erich Keane6a24e802019-09-13 17:39:31 +00002427 OS << ");\n";
Reid Kleckner7420f962020-03-11 19:43:37 -07002428 OS << " return Create";
Erich Keane6a24e802019-09-13 17:39:31 +00002429 if (Implicit)
2430 OS << "Implicit";
2431 OS << "(Ctx";
2432 for (auto const &ai : Args) {
2433 if (ai->isFake() && !emitFake) continue;
2434 OS << ", ";
2435 ai->writeImplicitCtorArgs(OS);
2436 }
2437 OS << ", I);\n";
Reid Kleckner7420f962020-03-11 19:43:37 -07002438 OS << "}\n\n";
Erich Keane6a24e802019-09-13 17:39:31 +00002439 };
2440
2441 auto emitCreates = [&](bool emitFake) {
2442 emitCreate(true, emitFake);
2443 emitCreate(false, emitFake);
2444 emitCreateNoCI(true, emitFake);
2445 emitCreateNoCI(false, emitFake);
2446 };
2447
Reid Kleckner7420f962020-03-11 19:43:37 -07002448 if (Header)
2449 OS << " // Factory methods\n";
2450
John McCalla62c1a92015-10-28 00:17:34 +00002451 // Emit a CreateImplicit that takes all the arguments.
Erich Keane6a24e802019-09-13 17:39:31 +00002452 emitCreates(true);
John McCalla62c1a92015-10-28 00:17:34 +00002453
2454 // Emit a CreateImplicit that takes all the non-fake arguments.
Erich Keane6a24e802019-09-13 17:39:31 +00002455 if (HasFakeArg)
2456 emitCreates(false);
Michael Han99315932013-01-24 16:46:58 +00002457
John McCalla62c1a92015-10-28 00:17:34 +00002458 // Emit constructors.
2459 auto emitCtor = [&](bool emitOpt, bool emitFake) {
2460 auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
2461 if (arg->isFake()) return emitFake;
2462 if (arg->isOptional()) return emitOpt;
2463 return true;
2464 };
Reid Kleckner7420f962020-03-11 19:43:37 -07002465 if (Header)
2466 OS << " ";
2467 else
2468 OS << R.getName() << "Attr::";
2469 OS << R.getName()
Erich Keane6a24e802019-09-13 17:39:31 +00002470 << "Attr(ASTContext &Ctx, const AttributeCommonInfo &CommonInfo";
2471 OS << '\n';
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002472 for (auto const &ai : Args) {
John McCalla62c1a92015-10-28 00:17:34 +00002473 if (!shouldEmitArg(ai)) continue;
2474 OS << " , ";
2475 ai->writeCtorParameters(OS);
2476 OS << "\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002477 }
2478
Reid Kleckner7420f962020-03-11 19:43:37 -07002479 OS << " )";
2480 if (Header) {
2481 OS << ";\n";
2482 return;
2483 }
2484 OS << "\n : " << SuperName << "(Ctx, CommonInfo, ";
Erich Keane6a24e802019-09-13 17:39:31 +00002485 OS << "attr::" << R.getName() << ", "
2486 << (R.getValueAsBit("LateParsed") ? "true" : "false");
Richard Smith33bddbd2018-01-04 23:42:29 +00002487 if (Inheritable) {
2488 OS << ", "
2489 << (R.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
2490 : "false");
2491 }
2492 OS << ")\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002493
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002494 for (auto const &ai : Args) {
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002495 OS << " , ";
John McCalla62c1a92015-10-28 00:17:34 +00002496 if (!shouldEmitArg(ai)) {
2497 ai->writeCtorDefaultInitializers(OS);
2498 } else {
2499 ai->writeCtorInitializers(OS);
2500 }
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002501 OS << "\n";
2502 }
2503
2504 OS << " {\n";
Johannes Doerfert1228d422019-12-19 20:42:12 -06002505
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002506 for (auto const &ai : Args) {
John McCalla62c1a92015-10-28 00:17:34 +00002507 if (!shouldEmitArg(ai)) continue;
2508 ai->writeCtorBody(OS);
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002509 }
Reid Kleckner7420f962020-03-11 19:43:37 -07002510 OS << "}\n\n";
John McCalla62c1a92015-10-28 00:17:34 +00002511 };
2512
Reid Kleckner7420f962020-03-11 19:43:37 -07002513 if (Header)
2514 OS << "\n // Constructors\n";
2515
John McCalla62c1a92015-10-28 00:17:34 +00002516 // Emit a constructor that includes all the arguments.
2517 // This is necessary for cloning.
2518 emitCtor(true, true);
2519
2520 // Emit a constructor that takes all the non-fake arguments.
Erich Keane6a24e802019-09-13 17:39:31 +00002521 if (HasFakeArg)
John McCalla62c1a92015-10-28 00:17:34 +00002522 emitCtor(true, false);
Johannes Doerfert1228d422019-12-19 20:42:12 -06002523
John McCalla62c1a92015-10-28 00:17:34 +00002524 // Emit a constructor that takes all the non-fake, non-optional arguments.
Erich Keane6a24e802019-09-13 17:39:31 +00002525 if (HasOptArg)
John McCalla62c1a92015-10-28 00:17:34 +00002526 emitCtor(false, false);
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002527
Reid Kleckner7420f962020-03-11 19:43:37 -07002528 if (Header) {
2529 OS << '\n';
2530 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
2531 OS << " void printPretty(raw_ostream &OS,\n"
2532 << " const PrintingPolicy &Policy) const;\n";
2533 OS << " const char *getSpelling() const;\n";
2534 }
Johannes Doerfert1228d422019-12-19 20:42:12 -06002535
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00002536 if (!ElideSpelling) {
2537 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
Reid Kleckner7420f962020-03-11 19:43:37 -07002538 if (Header)
2539 OS << " Spelling getSemanticSpelling() const;\n";
2540 else {
2541 OS << R.getName() << "Attr::Spelling " << R.getName()
2542 << "Attr::getSemanticSpelling() const {\n";
2543 WriteSemanticSpellingSwitch("getAttributeSpellingListIndex()",
2544 SemanticToSyntacticMap, OS);
2545 OS << "}\n";
2546 }
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00002547 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00002548
Reid Kleckner7420f962020-03-11 19:43:37 -07002549 if (Header)
2550 writeAttrAccessorDefinition(R, OS);
Michael Hanaf02bbe2013-02-01 01:19:17 +00002551
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002552 for (auto const &ai : Args) {
Reid Kleckner7420f962020-03-11 19:43:37 -07002553 if (Header) {
2554 ai->writeAccessors(OS);
2555 } else {
2556 ai->writeAccessorDefinitions(OS);
2557 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00002558 OS << "\n\n";
Aaron Ballman682ee422013-09-11 19:47:58 +00002559
John McCalla62c1a92015-10-28 00:17:34 +00002560 // Don't write conversion routines for fake arguments.
2561 if (ai->isFake()) continue;
2562
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002563 if (ai->isEnumArg())
Reid Kleckner7420f962020-03-11 19:43:37 -07002564 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS,
2565 Header);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002566 else if (ai->isVariadicEnumArg())
Reid Kleckner7420f962020-03-11 19:43:37 -07002567 static_cast<const VariadicEnumArgument *>(ai.get())->writeConversion(
2568 OS, Header);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002569 }
2570
Reid Kleckner7420f962020-03-11 19:43:37 -07002571 if (Header) {
2572 OS << R.getValueAsString("AdditionalMembers");
2573 OS << "\n\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002574
Reid Kleckner7420f962020-03-11 19:43:37 -07002575 OS << " static bool classof(const Attr *A) { return A->getKind() == "
2576 << "attr::" << R.getName() << "; }\n";
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002577
Reid Kleckner7420f962020-03-11 19:43:37 -07002578 OS << "};\n\n";
2579 } else {
2580 OS << R.getName() << "Attr *" << R.getName()
2581 << "Attr::clone(ASTContext &C) const {\n";
2582 OS << " auto *A = new (C) " << R.getName() << "Attr(C, *this";
2583 for (auto const &ai : Args) {
2584 OS << ", ";
2585 ai->writeCloneArgs(OS);
2586 }
2587 OS << ");\n";
2588 OS << " A->Inherited = Inherited;\n";
2589 OS << " A->IsPackExpansion = IsPackExpansion;\n";
2590 OS << " A->setImplicit(Implicit);\n";
2591 OS << " return A;\n}\n\n";
2592
2593 writePrettyPrintFunction(R, Args, OS);
2594 writeGetSpellingFunction(R, OS);
2595 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00002596 }
Reid Kleckner7420f962020-03-11 19:43:37 -07002597}
2598// Emits the class definitions for attributes.
2599void clang::EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
2600 emitSourceFileHeader("Attribute classes' definitions", OS);
2601
2602 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
2603 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
2604
2605 emitAttributes(Records, OS, true);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002606
Eugene Zelenko5f02b772015-12-08 18:49:01 +00002607 OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002608}
2609
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002610// Emits the class method definitions for attributes.
John McCallc45f8d42019-10-01 23:12:57 +00002611void clang::EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002612 emitSourceFileHeader("Attribute classes' member function definitions", OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002613
Reid Kleckner7420f962020-03-11 19:43:37 -07002614 emitAttributes(Records, OS, false);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002615
Reid Kleckner7420f962020-03-11 19:43:37 -07002616 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Benjamin Kramer845e32c2015-03-19 16:06:49 +00002617
2618 // Instead of relying on virtual dispatch we just create a huge dispatch
2619 // switch. This is both smaller and faster than virtual functions.
2620 auto EmitFunc = [&](const char *Method) {
2621 OS << " switch (getKind()) {\n";
2622 for (const auto *Attr : Attrs) {
2623 const Record &R = *Attr;
2624 if (!R.getValueAsBit("ASTNode"))
2625 continue;
2626
2627 OS << " case attr::" << R.getName() << ":\n";
2628 OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
2629 << ";\n";
2630 }
Benjamin Kramer845e32c2015-03-19 16:06:49 +00002631 OS << " }\n";
2632 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
2633 OS << "}\n\n";
2634 };
2635
2636 OS << "const char *Attr::getSpelling() const {\n";
2637 EmitFunc("getSpelling()");
2638
2639 OS << "Attr *Attr::clone(ASTContext &C) const {\n";
2640 EmitFunc("clone(C)");
2641
2642 OS << "void Attr::printPretty(raw_ostream &OS, "
2643 "const PrintingPolicy &Policy) const {\n";
2644 EmitFunc("printPretty(OS, Policy)");
Peter Collingbournebee583f2011-10-06 13:03:08 +00002645}
2646
John McCall2225c8b2016-03-01 00:18:05 +00002647static void emitAttrList(raw_ostream &OS, StringRef Class,
Peter Collingbournebee583f2011-10-06 13:03:08 +00002648 const std::vector<Record*> &AttrList) {
John McCall2225c8b2016-03-01 00:18:05 +00002649 for (auto Cur : AttrList) {
2650 OS << Class << "(" << Cur->getName() << ")\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002651 }
2652}
2653
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002654// Determines if an attribute has a Pragma spelling.
2655static bool AttrHasPragmaSpelling(const Record *R) {
2656 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
George Burgess IV1881a572016-12-01 00:13:18 +00002657 return llvm::find_if(Spellings, [](const FlattenedSpelling &S) {
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002658 return S.variety() == "Pragma";
2659 }) != Spellings.end();
2660}
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002661
John McCall2225c8b2016-03-01 00:18:05 +00002662namespace {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002663
John McCall2225c8b2016-03-01 00:18:05 +00002664 struct AttrClassDescriptor {
2665 const char * const MacroName;
2666 const char * const TableGenName;
2667 };
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002668
2669} // end anonymous namespace
John McCall2225c8b2016-03-01 00:18:05 +00002670
2671static const AttrClassDescriptor AttrClassDescriptors[] = {
2672 { "ATTR", "Attr" },
Richard Smithe43e2b32018-08-20 21:47:29 +00002673 { "TYPE_ATTR", "TypeAttr" },
Richard Smith4f902c72016-03-08 00:32:55 +00002674 { "STMT_ATTR", "StmtAttr" },
John McCall2225c8b2016-03-01 00:18:05 +00002675 { "INHERITABLE_ATTR", "InheritableAttr" },
Richard Smithe43e2b32018-08-20 21:47:29 +00002676 { "DECL_OR_TYPE_ATTR", "DeclOrTypeAttr" },
John McCall477f2bb2016-03-03 06:39:32 +00002677 { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
2678 { "PARAMETER_ABI_ATTR", "ParameterABIAttr" }
John McCall2225c8b2016-03-01 00:18:05 +00002679};
2680
2681static void emitDefaultDefine(raw_ostream &OS, StringRef name,
2682 const char *superName) {
2683 OS << "#ifndef " << name << "\n";
2684 OS << "#define " << name << "(NAME) ";
2685 if (superName) OS << superName << "(NAME)";
2686 OS << "\n#endif\n\n";
2687}
2688
2689namespace {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002690
John McCall2225c8b2016-03-01 00:18:05 +00002691 /// A class of attributes.
2692 struct AttrClass {
2693 const AttrClassDescriptor &Descriptor;
2694 Record *TheRecord;
2695 AttrClass *SuperClass = nullptr;
2696 std::vector<AttrClass*> SubClasses;
2697 std::vector<Record*> Attrs;
2698
2699 AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
2700 : Descriptor(Descriptor), TheRecord(R) {}
2701
2702 void emitDefaultDefines(raw_ostream &OS) const {
2703 // Default the macro unless this is a root class (i.e. Attr).
2704 if (SuperClass) {
2705 emitDefaultDefine(OS, Descriptor.MacroName,
2706 SuperClass->Descriptor.MacroName);
2707 }
2708 }
2709
2710 void emitUndefs(raw_ostream &OS) const {
2711 OS << "#undef " << Descriptor.MacroName << "\n";
2712 }
2713
2714 void emitAttrList(raw_ostream &OS) const {
2715 for (auto SubClass : SubClasses) {
2716 SubClass->emitAttrList(OS);
2717 }
2718
2719 ::emitAttrList(OS, Descriptor.MacroName, Attrs);
2720 }
2721
2722 void classifyAttrOnRoot(Record *Attr) {
2723 bool result = classifyAttr(Attr);
2724 assert(result && "failed to classify on root"); (void) result;
2725 }
2726
2727 void emitAttrRange(raw_ostream &OS) const {
2728 OS << "ATTR_RANGE(" << Descriptor.TableGenName
2729 << ", " << getFirstAttr()->getName()
2730 << ", " << getLastAttr()->getName() << ")\n";
2731 }
2732
2733 private:
2734 bool classifyAttr(Record *Attr) {
2735 // Check all the subclasses.
2736 for (auto SubClass : SubClasses) {
2737 if (SubClass->classifyAttr(Attr))
2738 return true;
2739 }
2740
2741 // It's not more specific than this class, but it might still belong here.
2742 if (Attr->isSubClassOf(TheRecord)) {
2743 Attrs.push_back(Attr);
2744 return true;
2745 }
2746
2747 return false;
2748 }
2749
2750 Record *getFirstAttr() const {
2751 if (!SubClasses.empty())
2752 return SubClasses.front()->getFirstAttr();
2753 return Attrs.front();
2754 }
2755
2756 Record *getLastAttr() const {
2757 if (!Attrs.empty())
2758 return Attrs.back();
2759 return SubClasses.back()->getLastAttr();
2760 }
2761 };
2762
2763 /// The entire hierarchy of attribute classes.
2764 class AttrClassHierarchy {
2765 std::vector<std::unique_ptr<AttrClass>> Classes;
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002766
John McCall2225c8b2016-03-01 00:18:05 +00002767 public:
2768 AttrClassHierarchy(RecordKeeper &Records) {
2769 // Find records for all the classes.
2770 for (auto &Descriptor : AttrClassDescriptors) {
2771 Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
2772 AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
2773 Classes.emplace_back(Class);
2774 }
2775
2776 // Link up the hierarchy.
2777 for (auto &Class : Classes) {
2778 if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
2779 Class->SuperClass = SuperClass;
2780 SuperClass->SubClasses.push_back(Class.get());
2781 }
2782 }
2783
2784#ifndef NDEBUG
2785 for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
2786 assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
2787 "only the first class should be a root class!");
2788 }
2789#endif
2790 }
2791
2792 void emitDefaultDefines(raw_ostream &OS) const {
2793 for (auto &Class : Classes) {
2794 Class->emitDefaultDefines(OS);
2795 }
2796 }
2797
2798 void emitUndefs(raw_ostream &OS) const {
2799 for (auto &Class : Classes) {
2800 Class->emitUndefs(OS);
2801 }
2802 }
2803
2804 void emitAttrLists(raw_ostream &OS) const {
2805 // Just start from the root class.
2806 Classes[0]->emitAttrList(OS);
2807 }
2808
2809 void emitAttrRanges(raw_ostream &OS) const {
2810 for (auto &Class : Classes)
2811 Class->emitAttrRange(OS);
2812 }
2813
2814 void classifyAttr(Record *Attr) {
2815 // Add the attribute to the root class.
2816 Classes[0]->classifyAttrOnRoot(Attr);
2817 }
2818
2819 private:
2820 AttrClass *findClassByRecord(Record *R) const {
2821 for (auto &Class : Classes) {
2822 if (Class->TheRecord == R)
2823 return Class.get();
2824 }
2825 return nullptr;
2826 }
2827
2828 AttrClass *findSuperClass(Record *R) const {
2829 // TableGen flattens the superclass list, so we just need to walk it
2830 // in reverse.
2831 auto SuperClasses = R->getSuperClasses();
2832 for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
2833 auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
2834 if (SuperClass) return SuperClass;
2835 }
2836 return nullptr;
2837 }
2838 };
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002839
2840} // end anonymous namespace
John McCall2225c8b2016-03-01 00:18:05 +00002841
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002842namespace clang {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002843
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002844// Emits the enumeration list for attributes.
2845void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002846 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002847
John McCall2225c8b2016-03-01 00:18:05 +00002848 AttrClassHierarchy Hierarchy(Records);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002849
John McCall2225c8b2016-03-01 00:18:05 +00002850 // Add defaulting macro definitions.
2851 Hierarchy.emitDefaultDefines(OS);
2852 emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002853
John McCall2225c8b2016-03-01 00:18:05 +00002854 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2855 std::vector<Record *> PragmaAttrs;
Aaron Ballman2f22b942014-05-20 19:47:14 +00002856 for (auto *Attr : Attrs) {
2857 if (!Attr->getValueAsBit("ASTNode"))
Douglas Gregorb2daf842012-05-02 15:56:52 +00002858 continue;
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002859
John McCall2225c8b2016-03-01 00:18:05 +00002860 // Add the attribute to the ad-hoc groups.
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002861 if (AttrHasPragmaSpelling(Attr))
2862 PragmaAttrs.push_back(Attr);
2863
John McCall2225c8b2016-03-01 00:18:05 +00002864 // Place it in the hierarchy.
2865 Hierarchy.classifyAttr(Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002866 }
2867
John McCall2225c8b2016-03-01 00:18:05 +00002868 // Emit the main attribute list.
2869 Hierarchy.emitAttrLists(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002870
John McCall2225c8b2016-03-01 00:18:05 +00002871 // Emit the ad hoc groups.
2872 emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
2873
2874 // Emit the attribute ranges.
2875 OS << "#ifdef ATTR_RANGE\n";
2876 Hierarchy.emitAttrRanges(OS);
2877 OS << "#undef ATTR_RANGE\n";
2878 OS << "#endif\n";
2879
2880 Hierarchy.emitUndefs(OS);
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002881 OS << "#undef PRAGMA_SPELLING_ATTR\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002882}
2883
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002884// Emits the enumeration list for attributes.
2885void EmitClangAttrSubjectMatchRuleList(RecordKeeper &Records, raw_ostream &OS) {
2886 emitSourceFileHeader(
2887 "List of all attribute subject matching rules that Clang recognizes", OS);
2888 PragmaClangAttributeSupport &PragmaAttributeSupport =
2889 getPragmaAttributeSupport(Records);
2890 emitDefaultDefine(OS, "ATTR_MATCH_RULE", nullptr);
2891 PragmaAttributeSupport.emitMatchRuleList(OS);
2892 OS << "#undef ATTR_MATCH_RULE\n";
2893}
2894
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002895// Emits the code to read an attribute from a precompiled header.
2896void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002897 emitSourceFileHeader("Attribute deserialization code", OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002898
2899 Record *InhClass = Records.getClass("InheritableAttr");
2900 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
2901 ArgRecords;
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002902 std::vector<std::unique_ptr<Argument>> Args;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002903
2904 OS << " switch (Kind) {\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00002905 for (const auto *Attr : Attrs) {
2906 const Record &R = *Attr;
Douglas Gregorb2daf842012-05-02 15:56:52 +00002907 if (!R.getValueAsBit("ASTNode"))
2908 continue;
Erich Keane6a24e802019-09-13 17:39:31 +00002909
Peter Collingbournebee583f2011-10-06 13:03:08 +00002910 OS << " case attr::" << R.getName() << ": {\n";
2911 if (R.isSubClassOf(InhClass))
David L. Jones267b8842017-01-24 01:04:30 +00002912 OS << " bool isInherited = Record.readInt();\n";
2913 OS << " bool isImplicit = Record.readInt();\n";
Nathan Ridge8b3b7552020-04-01 01:29:58 -04002914 OS << " bool isPackExpansion = Record.readInt();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002915 ArgRecords = R.getValueAsListOfDefs("Args");
2916 Args.clear();
Aaron Ballman2f22b942014-05-20 19:47:14 +00002917 for (const auto *Arg : ArgRecords) {
2918 Args.emplace_back(createArgument(*Arg, R.getName()));
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002919 Args.back()->writePCHReadDecls(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002920 }
Erich Keane6a24e802019-09-13 17:39:31 +00002921 OS << " New = new (Context) " << R.getName() << "Attr(Context, Info";
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002922 for (auto const &ri : Args) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00002923 OS << ", ";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002924 ri->writePCHReadArgs(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002925 }
Erich Keane6a24e802019-09-13 17:39:31 +00002926 OS << ");\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002927 if (R.isSubClassOf(InhClass))
2928 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
Aaron Ballman36a53502014-01-16 13:03:14 +00002929 OS << " New->setImplicit(isImplicit);\n";
Nathan Ridge8b3b7552020-04-01 01:29:58 -04002930 OS << " New->setPackExpansion(isPackExpansion);\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002931 OS << " break;\n";
2932 OS << " }\n";
2933 }
2934 OS << " }\n";
2935}
2936
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002937// Emits the code to write an attribute to a precompiled header.
2938void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002939 emitSourceFileHeader("Attribute serialization code", OS);
2940
Peter Collingbournebee583f2011-10-06 13:03:08 +00002941 Record *InhClass = Records.getClass("InheritableAttr");
2942 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002943
2944 OS << " switch (A->getKind()) {\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00002945 for (const auto *Attr : Attrs) {
2946 const Record &R = *Attr;
Douglas Gregorb2daf842012-05-02 15:56:52 +00002947 if (!R.getValueAsBit("ASTNode"))
2948 continue;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002949 OS << " case attr::" << R.getName() << ": {\n";
2950 Args = R.getValueAsListOfDefs("Args");
2951 if (R.isSubClassOf(InhClass) || !Args.empty())
Eugene Zelenko5f02b772015-12-08 18:49:01 +00002952 OS << " const auto *SA = cast<" << R.getName()
Peter Collingbournebee583f2011-10-06 13:03:08 +00002953 << "Attr>(A);\n";
2954 if (R.isSubClassOf(InhClass))
2955 OS << " Record.push_back(SA->isInherited());\n";
Aaron Ballman36a53502014-01-16 13:03:14 +00002956 OS << " Record.push_back(A->isImplicit());\n";
Nathan Ridge8b3b7552020-04-01 01:29:58 -04002957 OS << " Record.push_back(A->isPackExpansion());\n";
Aaron Ballman36a53502014-01-16 13:03:14 +00002958
Aaron Ballman2f22b942014-05-20 19:47:14 +00002959 for (const auto *Arg : Args)
2960 createArgument(*Arg, R.getName())->writePCHWrite(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002961 OS << " break;\n";
2962 OS << " }\n";
2963 }
2964 OS << " }\n";
2965}
2966
Erich Keane75449672017-12-20 18:51:08 +00002967// Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
2968// parameter with only a single check type, if applicable.
Richard Smith78b239e2019-06-20 20:44:45 +00002969static bool GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
Erich Keane75449672017-12-20 18:51:08 +00002970 std::string *FnName,
2971 StringRef ListName,
2972 StringRef CheckAgainst,
2973 StringRef Scope) {
2974 if (!R->isValueUnset(ListName)) {
2975 Test += " && (";
2976 std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
2977 for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
2978 StringRef Part = *I;
2979 Test += CheckAgainst;
2980 Test += " == ";
2981 Test += Scope;
2982 Test += Part;
2983 if (I + 1 != E)
2984 Test += " || ";
2985 if (FnName)
2986 *FnName += Part;
2987 }
2988 Test += ")";
Richard Smith78b239e2019-06-20 20:44:45 +00002989 return true;
Erich Keane75449672017-12-20 18:51:08 +00002990 }
Richard Smith78b239e2019-06-20 20:44:45 +00002991 return false;
Erich Keane75449672017-12-20 18:51:08 +00002992}
2993
Bob Wilson0058b822015-07-20 22:57:36 +00002994// Generate a conditional expression to check if the current target satisfies
2995// the conditions for a TargetSpecificAttr record, and append the code for
2996// those checks to the Test string. If the FnName string pointer is non-null,
2997// append a unique suffix to distinguish this set of target checks from other
2998// TargetSpecificAttr records.
Richard Smith78b239e2019-06-20 20:44:45 +00002999static bool GenerateTargetSpecificAttrChecks(const Record *R,
Craig Topper00648582017-05-31 19:01:22 +00003000 std::vector<StringRef> &Arches,
Bob Wilson0058b822015-07-20 22:57:36 +00003001 std::string &Test,
3002 std::string *FnName) {
Richard Smith78b239e2019-06-20 20:44:45 +00003003 bool AnyTargetChecks = false;
3004
Bob Wilson0058b822015-07-20 22:57:36 +00003005 // It is assumed that there will be an llvm::Triple object
3006 // named "T" and a TargetInfo object named "Target" within
3007 // scope that can be used to determine whether the attribute exists in
3008 // a given target.
Erich Keane75449672017-12-20 18:51:08 +00003009 Test += "true";
3010 // If one or more architectures is specified, check those. Arches are handled
3011 // differently because GenerateTargetRequirements needs to combine the list
3012 // with ParseKind.
3013 if (!Arches.empty()) {
Richard Smith78b239e2019-06-20 20:44:45 +00003014 AnyTargetChecks = true;
Erich Keane75449672017-12-20 18:51:08 +00003015 Test += " && (";
3016 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
3017 StringRef Part = *I;
3018 Test += "T.getArch() == llvm::Triple::";
3019 Test += Part;
3020 if (I + 1 != E)
3021 Test += " || ";
3022 if (FnName)
3023 *FnName += Part;
3024 }
3025 Test += ")";
Bob Wilson0058b822015-07-20 22:57:36 +00003026 }
Bob Wilson0058b822015-07-20 22:57:36 +00003027
3028 // If the attribute is specific to particular OSes, check those.
Richard Smith78b239e2019-06-20 20:44:45 +00003029 AnyTargetChecks |= GenerateTargetSpecificAttrCheck(
3030 R, Test, FnName, "OSes", "T.getOS()", "llvm::Triple::");
Bob Wilson0058b822015-07-20 22:57:36 +00003031
Erich Keane75449672017-12-20 18:51:08 +00003032 // If one or more object formats is specified, check those.
Richard Smith78b239e2019-06-20 20:44:45 +00003033 AnyTargetChecks |=
3034 GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
3035 "T.getObjectFormat()", "llvm::Triple::");
3036
3037 // If custom code is specified, emit it.
3038 StringRef Code = R->getValueAsString("CustomCode");
3039 if (!Code.empty()) {
3040 AnyTargetChecks = true;
3041 Test += " && (";
3042 Test += Code;
3043 Test += ")";
3044 }
3045
3046 return AnyTargetChecks;
Bob Wilson0058b822015-07-20 22:57:36 +00003047}
3048
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003049static void GenerateHasAttrSpellingStringSwitch(
3050 const std::vector<Record *> &Attrs, raw_ostream &OS,
3051 const std::string &Variety = "", const std::string &Scope = "") {
3052 for (const auto *Attr : Attrs) {
Aaron Ballmana0344c52014-11-14 13:44:02 +00003053 // C++11-style attributes have specific version information associated with
3054 // them. If the attribute has no scope, the version information must not
3055 // have the default value (1), as that's incorrect. Instead, the unscoped
3056 // attribute version information should be taken from the SD-6 standing
Johannes Doerfert1228d422019-12-19 20:42:12 -06003057 // document, which can be found at:
Aaron Ballmana0344c52014-11-14 13:44:02 +00003058 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
3059 int Version = 1;
3060
3061 if (Variety == "CXX11") {
3062 std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
3063 for (const auto &Spelling : Spellings) {
3064 if (Spelling->getValueAsString("Variety") == "CXX11") {
3065 Version = static_cast<int>(Spelling->getValueAsInt("Version"));
3066 if (Scope.empty() && Version == 1)
3067 PrintError(Spelling->getLoc(), "C++ standard attributes must "
3068 "have valid version information.");
3069 break;
3070 }
3071 }
3072 }
3073
Aaron Ballman0fa06d82014-01-09 22:57:44 +00003074 std::string Test;
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003075 if (Attr->isSubClassOf("TargetSpecificAttr")) {
3076 const Record *R = Attr->getValueAsDef("Target");
Craig Topper00648582017-05-31 19:01:22 +00003077 std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
Hans Wennborgdcfba332015-10-06 23:40:43 +00003078 GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
Bob Wilson7c730832015-07-20 22:57:31 +00003079
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003080 // If this is the C++11 variety, also add in the LangOpts test.
3081 if (Variety == "CXX11")
3082 Test += " && LangOpts.CPlusPlus11";
Aaron Ballman606093a2017-10-15 15:01:42 +00003083 else if (Variety == "C2x")
3084 Test += " && LangOpts.DoubleSquareBracketAttributes";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003085 } else if (Variety == "CXX11")
3086 // C++11 mode should be checked against LangOpts, which is presumed to be
3087 // present in the caller.
3088 Test = "LangOpts.CPlusPlus11";
Aaron Ballman606093a2017-10-15 15:01:42 +00003089 else if (Variety == "C2x")
3090 Test = "LangOpts.DoubleSquareBracketAttributes";
Aaron Ballman0fa06d82014-01-09 22:57:44 +00003091
Aaron Ballmana0344c52014-11-14 13:44:02 +00003092 std::string TestStr =
Aaron Ballman28afa182014-11-17 18:17:19 +00003093 !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003094 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003095 for (const auto &S : Spellings)
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003096 if (Variety.empty() || (Variety == S.variety() &&
3097 (Scope.empty() || Scope == S.nameSpace())))
Aaron Ballmana0344c52014-11-14 13:44:02 +00003098 OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00003099 }
Aaron Ballmana0344c52014-11-14 13:44:02 +00003100 OS << " .Default(0);\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003101}
3102
3103// Emits the list of spellings for attributes.
3104void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3105 emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
3106
3107 // Separate all of the attributes out into four group: generic, C++11, GNU,
3108 // and declspecs. Then generate a big switch statement for each of them.
3109 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Nico Weber20e08042016-09-03 02:55:10 +00003110 std::vector<Record *> Declspec, Microsoft, GNU, Pragma;
Aaron Ballman606093a2017-10-15 15:01:42 +00003111 std::map<std::string, std::vector<Record *>> CXX, C2x;
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003112
3113 // Walk over the list of all attributes, and split them out based on the
3114 // spelling variety.
3115 for (auto *R : Attrs) {
3116 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
3117 for (const auto &SI : Spellings) {
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00003118 const std::string &Variety = SI.variety();
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003119 if (Variety == "GNU")
3120 GNU.push_back(R);
3121 else if (Variety == "Declspec")
3122 Declspec.push_back(R);
Nico Weber20e08042016-09-03 02:55:10 +00003123 else if (Variety == "Microsoft")
3124 Microsoft.push_back(R);
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003125 else if (Variety == "CXX11")
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003126 CXX[SI.nameSpace()].push_back(R);
Aaron Ballman606093a2017-10-15 15:01:42 +00003127 else if (Variety == "C2x")
3128 C2x[SI.nameSpace()].push_back(R);
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003129 else if (Variety == "Pragma")
3130 Pragma.push_back(R);
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003131 }
3132 }
3133
Bob Wilson7c730832015-07-20 22:57:31 +00003134 OS << "const llvm::Triple &T = Target.getTriple();\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003135 OS << "switch (Syntax) {\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003136 OS << "case AttrSyntax::GNU:\n";
Aaron Ballmana0344c52014-11-14 13:44:02 +00003137 OS << " return llvm::StringSwitch<int>(Name)\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003138 GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
3139 OS << "case AttrSyntax::Declspec:\n";
Aaron Ballmana0344c52014-11-14 13:44:02 +00003140 OS << " return llvm::StringSwitch<int>(Name)\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003141 GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
Nico Weber20e08042016-09-03 02:55:10 +00003142 OS << "case AttrSyntax::Microsoft:\n";
3143 OS << " return llvm::StringSwitch<int>(Name)\n";
3144 GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003145 OS << "case AttrSyntax::Pragma:\n";
Aaron Ballmana0344c52014-11-14 13:44:02 +00003146 OS << " return llvm::StringSwitch<int>(Name)\n";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003147 GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
Aaron Ballman606093a2017-10-15 15:01:42 +00003148 auto fn = [&OS](const char *Spelling, const char *Variety,
3149 const std::map<std::string, std::vector<Record *>> &List) {
3150 OS << "case AttrSyntax::" << Variety << ": {\n";
3151 // C++11-style attributes are further split out based on the Scope.
3152 for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
Stephen Kellydb8fac12019-01-11 19:16:01 +00003153 if (I != List.cbegin())
3154 OS << " else ";
3155 if (I->first.empty())
3156 OS << "if (ScopeName == \"\") {\n";
3157 else
3158 OS << "if (ScopeName == \"" << I->first << "\") {\n";
3159 OS << " return llvm::StringSwitch<int>(Name)\n";
3160 GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
3161 OS << "}";
Aaron Ballman606093a2017-10-15 15:01:42 +00003162 }
Aaron Ballman4ff3b5ab2017-10-18 12:11:58 +00003163 OS << "\n} break;\n";
Aaron Ballman606093a2017-10-15 15:01:42 +00003164 };
3165 fn("CXX11", "CXX", CXX);
3166 fn("C2x", "C", C2x);
Aaron Ballman2fbf9942014-03-31 13:14:44 +00003167 OS << "}\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00003168}
3169
Michael Han99315932013-01-24 16:46:58 +00003170void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00003171 emitSourceFileHeader("Code to translate different attribute spellings "
3172 "into internal identifiers", OS);
Michael Han99315932013-01-24 16:46:58 +00003173
Erich Keane6a24e802019-09-13 17:39:31 +00003174 OS << " switch (getParsedKind()) {\n";
3175 OS << " case IgnoredAttribute:\n";
3176 OS << " case UnknownAttribute:\n";
3177 OS << " case NoSemaHandlerAttribute:\n";
3178 OS << " llvm_unreachable(\"Ignored/unknown shouldn't get here\");\n";
Michael Han99315932013-01-24 16:46:58 +00003179
Aaron Ballman64e69862013-12-15 13:05:48 +00003180 ParsedAttrMap Attrs = getParsedAttrList(Records);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003181 for (const auto &I : Attrs) {
Aaron Ballman2f22b942014-05-20 19:47:14 +00003182 const Record &R = *I.second;
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003183 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003184 OS << " case AT_" << I.first << ": {\n";
Richard Smith852e9ce2013-11-27 01:46:48 +00003185 for (unsigned I = 0; I < Spellings.size(); ++ I) {
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003186 OS << " if (Name == \"" << Spellings[I].name() << "\" && "
Erich Keane6a24e802019-09-13 17:39:31 +00003187 << "getSyntax() == AttributeCommonInfo::AS_" << Spellings[I].variety()
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003188 << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
3189 << " return " << I << ";\n";
Michael Han99315932013-01-24 16:46:58 +00003190 }
Richard Smith852e9ce2013-11-27 01:46:48 +00003191
3192 OS << " break;\n";
3193 OS << " }\n";
Michael Han99315932013-01-24 16:46:58 +00003194 }
3195
3196 OS << " }\n";
Aaron Ballman64e69862013-12-15 13:05:48 +00003197 OS << " return 0;\n";
Michael Han99315932013-01-24 16:46:58 +00003198}
3199
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003200// Emits code used by RecursiveASTVisitor to visit attributes
3201void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
3202 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
3203
3204 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3205
3206 // Write method declarations for Traverse* methods.
3207 // We emit this here because we only generate methods for attributes that
3208 // are declared as ASTNodes.
3209 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00003210 for (const auto *Attr : Attrs) {
3211 const Record &R = *Attr;
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003212 if (!R.getValueAsBit("ASTNode"))
3213 continue;
3214 OS << " bool Traverse"
3215 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
3216 OS << " bool Visit"
3217 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3218 << " return true; \n"
Hans Wennborg4afe5042015-07-22 20:46:26 +00003219 << " }\n";
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003220 }
3221 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
3222
3223 // Write individual Traverse* methods for each attribute class.
Aaron Ballman2f22b942014-05-20 19:47:14 +00003224 for (const auto *Attr : Attrs) {
3225 const Record &R = *Attr;
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003226 if (!R.getValueAsBit("ASTNode"))
3227 continue;
3228
3229 OS << "template <typename Derived>\n"
DeLesley Hutchinsbb79c332013-12-30 21:03:02 +00003230 << "bool VISITORCLASS<Derived>::Traverse"
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003231 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3232 << " if (!getDerived().VisitAttr(A))\n"
3233 << " return false;\n"
3234 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
3235 << " return false;\n";
3236
3237 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
Aaron Ballman2f22b942014-05-20 19:47:14 +00003238 for (const auto *Arg : ArgRecords)
3239 createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003240
3241 OS << " return true;\n";
3242 OS << "}\n\n";
3243 }
3244
3245 // Write generic Traverse routine
3246 OS << "template <typename Derived>\n"
DeLesley Hutchinsbb79c332013-12-30 21:03:02 +00003247 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003248 << " if (!A)\n"
3249 << " return true;\n"
3250 << "\n"
John McCall2225c8b2016-03-01 00:18:05 +00003251 << " switch (A->getKind()) {\n";
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003252
Aaron Ballman2f22b942014-05-20 19:47:14 +00003253 for (const auto *Attr : Attrs) {
3254 const Record &R = *Attr;
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003255 if (!R.getValueAsBit("ASTNode"))
3256 continue;
3257
3258 OS << " case attr::" << R.getName() << ":\n"
3259 << " return getDerived().Traverse" << R.getName() << "Attr("
3260 << "cast<" << R.getName() << "Attr>(A));\n";
3261 }
John McCall5d7cf772016-03-01 02:09:20 +00003262 OS << " }\n"; // end switch
3263 OS << " llvm_unreachable(\"bad attribute kind\");\n";
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003264 OS << "}\n"; // end function
3265 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
3266}
3267
Erich Keanea32910d2017-03-23 18:51:54 +00003268void EmitClangAttrTemplateInstantiateHelper(const std::vector<Record *> &Attrs,
3269 raw_ostream &OS,
3270 bool AppliesToDecl) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003271
Erich Keanea32910d2017-03-23 18:51:54 +00003272 OS << " switch (At->getKind()) {\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00003273 for (const auto *Attr : Attrs) {
3274 const Record &R = *Attr;
Douglas Gregorb2daf842012-05-02 15:56:52 +00003275 if (!R.getValueAsBit("ASTNode"))
3276 continue;
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003277 OS << " case attr::" << R.getName() << ": {\n";
Erich Keanea32910d2017-03-23 18:51:54 +00003278 bool ShouldClone = R.getValueAsBit("Clone") &&
3279 (!AppliesToDecl ||
3280 R.getValueAsBit("MeaningfulToClassTemplateDefinition"));
Rafael Espindola7f90b7d2012-05-15 14:09:55 +00003281
3282 if (!ShouldClone) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00003283 OS << " return nullptr;\n";
Rafael Espindola7f90b7d2012-05-15 14:09:55 +00003284 OS << " }\n";
3285 continue;
3286 }
3287
Eugene Zelenko5f02b772015-12-08 18:49:01 +00003288 OS << " const auto *A = cast<"
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003289 << R.getName() << "Attr>(At);\n";
3290 bool TDependent = R.getValueAsBit("TemplateDependent");
3291
3292 if (!TDependent) {
3293 OS << " return A->clone(C);\n";
3294 OS << " }\n";
3295 continue;
3296 }
3297
3298 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003299 std::vector<std::unique_ptr<Argument>> Args;
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003300 Args.reserve(ArgRecords.size());
3301
Aaron Ballman2f22b942014-05-20 19:47:14 +00003302 for (const auto *ArgRecord : ArgRecords)
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003303 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003304
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003305 for (auto const &ai : Args)
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003306 ai->writeTemplateInstantiation(OS);
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003307
Erich Keane6a24e802019-09-13 17:39:31 +00003308 OS << " return new (C) " << R.getName() << "Attr(C, *A";
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003309 for (auto const &ai : Args) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003310 OS << ", ";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003311 ai->writeTemplateInstantiationArgs(OS);
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003312 }
Erich Keane6a24e802019-09-13 17:39:31 +00003313 OS << ");\n }\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003314 }
3315 OS << " } // end switch\n"
3316 << " llvm_unreachable(\"Unknown attribute!\");\n"
Erich Keanea32910d2017-03-23 18:51:54 +00003317 << " return nullptr;\n";
3318}
3319
3320// Emits code to instantiate dependent attributes on templates.
3321void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
3322 emitSourceFileHeader("Template instantiation code for attributes", OS);
3323
3324 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3325
3326 OS << "namespace clang {\n"
3327 << "namespace sema {\n\n"
3328 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
3329 << "Sema &S,\n"
3330 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3331 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
3332 OS << "}\n\n"
3333 << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
3334 << " ASTContext &C, Sema &S,\n"
3335 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3336 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
3337 OS << "}\n\n"
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00003338 << "} // end namespace sema\n"
3339 << "} // end namespace clang\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003340}
3341
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003342// Emits the list of parsed attributes.
3343void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
3344 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
3345
3346 OS << "#ifndef PARSED_ATTR\n";
3347 OS << "#define PARSED_ATTR(NAME) NAME\n";
3348 OS << "#endif\n\n";
Johannes Doerfert1228d422019-12-19 20:42:12 -06003349
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003350 ParsedAttrMap Names = getParsedAttrList(Records);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003351 for (const auto &I : Names) {
3352 OS << "PARSED_ATTR(" << I.first << ")\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003353 }
3354}
3355
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00003356static bool isArgVariadic(const Record &R, StringRef AttrName) {
3357 return createArgument(R, AttrName)->isVariadic();
3358}
3359
Erich Keanedf9e8ae2017-10-16 22:47:26 +00003360static void emitArgInfo(const Record &R, raw_ostream &OS) {
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003361 // This function will count the number of arguments specified for the
3362 // attribute and emit the number of required arguments followed by the
3363 // number of optional arguments.
3364 std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
3365 unsigned ArgCount = 0, OptCount = 0;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00003366 bool HasVariadic = false;
Aaron Ballman2f22b942014-05-20 19:47:14 +00003367 for (const auto *Arg : Args) {
George Burgess IV8a36ace2016-12-01 17:52:39 +00003368 // If the arg is fake, it's the user's job to supply it: general parsing
3369 // logic shouldn't need to know anything about it.
3370 if (Arg->getValueAsBit("Fake"))
3371 continue;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003372 Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00003373 if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
3374 HasVariadic = true;
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003375 }
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00003376
3377 // If there is a variadic argument, we will set the optional argument count
3378 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
John Brawn590dc8d2020-02-26 16:31:24 +00003379 OS << " NumArgs = " << ArgCount << ";\n";
3380 OS << " OptArgs = " << (HasVariadic ? 15 : OptCount) << ";\n";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003381}
3382
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003383static std::string GetDiagnosticSpelling(const Record &R) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01003384 std::string Ret = std::string(R.getValueAsString("DiagSpelling"));
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003385 if (!Ret.empty())
3386 return Ret;
3387
3388 // If we couldn't find the DiagSpelling in this object, we can check to see
3389 // if the object is one that has a base, and if it is, loop up to the Base
3390 // member recursively.
John McCallbaf91d02019-10-25 16:28:03 -07003391 if (auto Base = R.getValueAsOptionalDef(BaseFieldName))
3392 return GetDiagnosticSpelling(*Base);
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003393
3394 return "";
3395}
3396
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003397static std::string CalculateDiagnostic(const Record &S) {
3398 // If the SubjectList object has a custom diagnostic associated with it,
3399 // return that directly.
Erich Keane3bff4142017-10-16 23:25:24 +00003400 const StringRef CustomDiag = S.getValueAsString("CustomDiag");
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003401 if (!CustomDiag.empty())
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003402 return ("\"" + Twine(CustomDiag) + "\"").str();
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003403
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003404 std::vector<std::string> DiagList;
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003405 std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
Aaron Ballman2f22b942014-05-20 19:47:14 +00003406 for (const auto *Subject : Subjects) {
3407 const Record &R = *Subject;
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003408 // Get the diagnostic text from the Decl or Stmt node given.
3409 std::string V = GetDiagnosticSpelling(R);
3410 if (V.empty()) {
3411 PrintError(R.getLoc(),
3412 "Could not determine diagnostic spelling for the node: " +
3413 R.getName() + "; please add one to DeclNodes.td");
3414 } else {
3415 // The node may contain a list of elements itself, so split the elements
3416 // by a comma, and trim any whitespace.
3417 SmallVector<StringRef, 2> Frags;
3418 llvm::SplitString(V, Frags, ",");
3419 for (auto Str : Frags) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01003420 DiagList.push_back(std::string(Str.trim()));
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003421 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003422 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003423 }
3424
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003425 if (DiagList.empty()) {
3426 PrintFatalError(S.getLoc(),
3427 "Could not deduce diagnostic argument for Attr subjects");
3428 return "";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003429 }
3430
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003431 // FIXME: this is not particularly good for localization purposes and ideally
3432 // should be part of the diagnostics engine itself with some sort of list
3433 // specifier.
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003434
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003435 // A single member of the list can be returned directly.
3436 if (DiagList.size() == 1)
3437 return '"' + DiagList.front() + '"';
3438
3439 if (DiagList.size() == 2)
3440 return '"' + DiagList[0] + " and " + DiagList[1] + '"';
3441
3442 // If there are more than two in the list, we serialize the first N - 1
3443 // elements with a comma. This leaves the string in the state: foo, bar,
3444 // baz (but misses quux). We can then add ", and " for the last element
3445 // manually.
3446 std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
3447 return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003448}
3449
Aaron Ballman12b9f652014-01-16 13:55:42 +00003450static std::string GetSubjectWithSuffix(const Record *R) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01003451 const std::string &B = std::string(R->getName());
Aaron Ballman12b9f652014-01-16 13:55:42 +00003452 if (B == "DeclBase")
3453 return "Decl";
3454 return B + "Decl";
3455}
Hans Wennborgdcfba332015-10-06 23:40:43 +00003456
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003457static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
3458 return "is" + Subject.getName().str();
3459}
3460
John Brawn590dc8d2020-02-26 16:31:24 +00003461static void GenerateCustomAppertainsTo(const Record &Subject, raw_ostream &OS) {
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003462 std::string FnName = functionNameForCustomAppertainsTo(Subject);
Aaron Ballmana358c902013-12-02 14:58:17 +00003463
John Brawn590dc8d2020-02-26 16:31:24 +00003464 // If this code has already been generated, we don't need to do anything.
Aaron Ballman80469032013-11-29 14:57:58 +00003465 static std::set<std::string> CustomSubjectSet;
Eugene Zelenko5f02b772015-12-08 18:49:01 +00003466 auto I = CustomSubjectSet.find(FnName);
Aaron Ballman80469032013-11-29 14:57:58 +00003467 if (I != CustomSubjectSet.end())
John Brawn590dc8d2020-02-26 16:31:24 +00003468 return;
Aaron Ballman80469032013-11-29 14:57:58 +00003469
John McCallbaf91d02019-10-25 16:28:03 -07003470 // This only works with non-root Decls.
3471 Record *Base = Subject.getValueAsDef(BaseFieldName);
Aaron Ballman80469032013-11-29 14:57:58 +00003472
3473 // Not currently support custom subjects within custom subjects.
3474 if (Base->isSubClassOf("SubsetSubject")) {
3475 PrintFatalError(Subject.getLoc(),
3476 "SubsetSubjects within SubsetSubjects is not supported");
John Brawn590dc8d2020-02-26 16:31:24 +00003477 return;
Aaron Ballman80469032013-11-29 14:57:58 +00003478 }
3479
Aaron Ballman80469032013-11-29 14:57:58 +00003480 OS << "static bool " << FnName << "(const Decl *D) {\n";
Erich Keane873de982018-08-03 14:24:34 +00003481 OS << " if (const auto *S = dyn_cast<";
3482 OS << GetSubjectWithSuffix(Base);
3483 OS << ">(D))\n";
3484 OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
Aaron Ballman47553042014-01-16 14:32:03 +00003485 OS << " return false;\n";
Aaron Ballman80469032013-11-29 14:57:58 +00003486 OS << "}\n\n";
3487
3488 CustomSubjectSet.insert(FnName);
Aaron Ballman80469032013-11-29 14:57:58 +00003489}
3490
John Brawn590dc8d2020-02-26 16:31:24 +00003491static void GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003492 // If the attribute does not contain a Subjects definition, then use the
3493 // default appertainsTo logic.
3494 if (Attr.isValueUnset("Subjects"))
John Brawn590dc8d2020-02-26 16:31:24 +00003495 return;
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003496
3497 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
3498 std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
3499
3500 // If the list of subjects is empty, it is assumed that the attribute
3501 // appertains to everything.
3502 if (Subjects.empty())
John Brawn590dc8d2020-02-26 16:31:24 +00003503 return;
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003504
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003505 bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
3506
3507 // Otherwise, generate an appertainsTo check specific to this attribute which
John Brawn590dc8d2020-02-26 16:31:24 +00003508 // checks all of the given subjects against the Decl passed in.
Richard Smithf4e248c2018-08-01 00:33:25 +00003509 //
3510 // If D is null, that means the attribute was not applied to a declaration
3511 // at all (for instance because it was applied to a type), or that the caller
3512 // has determined that the check should fail (perhaps prior to the creation
3513 // of the declaration).
John Brawn590dc8d2020-02-26 16:31:24 +00003514 OS << "virtual bool diagAppertainsToDecl(Sema &S, ";
3515 OS << "const ParsedAttr &Attr, const Decl *D) const {\n";
Aaron Ballman920d90f2020-03-21 15:46:40 -04003516 OS << " if (";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003517 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
John Brawn590dc8d2020-02-26 16:31:24 +00003518 // If the subject has custom code associated with it, use the generated
3519 // function for it. The function cannot be inlined into this check (yet)
3520 // because it requires the subject to be of a specific type, and were that
3521 // information inlined here, it would not support an attribute with multiple
3522 // custom subjects.
Aaron Ballman80469032013-11-29 14:57:58 +00003523 if ((*I)->isSubClassOf("SubsetSubject")) {
John Brawn590dc8d2020-02-26 16:31:24 +00003524 OS << "!" << functionNameForCustomAppertainsTo(**I) << "(D)";
Aaron Ballman80469032013-11-29 14:57:58 +00003525 } else {
John Brawn590dc8d2020-02-26 16:31:24 +00003526 OS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
Aaron Ballman80469032013-11-29 14:57:58 +00003527 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003528
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003529 if (I + 1 != E)
John Brawn590dc8d2020-02-26 16:31:24 +00003530 OS << " && ";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003531 }
Aaron Ballman920d90f2020-03-21 15:46:40 -04003532 OS << ") {\n";
John Brawn590dc8d2020-02-26 16:31:24 +00003533 OS << " S.Diag(Attr.getLoc(), diag::";
3534 OS << (Warn ? "warn_attribute_wrong_decl_type_str" :
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003535 "err_attribute_wrong_decl_type_str");
John Brawn590dc8d2020-02-26 16:31:24 +00003536 OS << ")\n";
3537 OS << " << Attr << ";
3538 OS << CalculateDiagnostic(*SubjectObj) << ";\n";
3539 OS << " return false;\n";
3540 OS << " }\n";
3541 OS << " return true;\n";
3542 OS << "}\n\n";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003543}
3544
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003545static void
3546emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
3547 raw_ostream &OS) {
3548 OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
3549 << AttributeSubjectMatchRule::EnumName << " rule) {\n";
3550 OS << " switch (rule) {\n";
3551 for (const auto &Rule : PragmaAttributeSupport.Rules) {
3552 if (Rule.isAbstractRule()) {
3553 OS << " case " << Rule.getEnumValue() << ":\n";
3554 OS << " assert(false && \"Abstract matcher rule isn't allowed\");\n";
3555 OS << " return false;\n";
3556 continue;
3557 }
3558 std::vector<Record *> Subjects = Rule.getSubjects();
3559 assert(!Subjects.empty() && "Missing subjects");
3560 OS << " case " << Rule.getEnumValue() << ":\n";
3561 OS << " return ";
3562 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
3563 // If the subject has custom code associated with it, use the function
3564 // that was generated for GenerateAppertainsTo to check if the declaration
3565 // is valid.
3566 if ((*I)->isSubClassOf("SubsetSubject"))
3567 OS << functionNameForCustomAppertainsTo(**I) << "(D)";
3568 else
3569 OS << "isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3570
3571 if (I + 1 != E)
3572 OS << " || ";
3573 }
3574 OS << ";\n";
3575 }
3576 OS << " }\n";
3577 OS << " llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
3578 OS << "}\n\n";
3579}
3580
John Brawn590dc8d2020-02-26 16:31:24 +00003581static void GenerateLangOptRequirements(const Record &R,
3582 raw_ostream &OS) {
Aaron Ballman3aff6332013-12-02 19:30:36 +00003583 // If the attribute has an empty or unset list of language requirements,
John Brawn590dc8d2020-02-26 16:31:24 +00003584 // use the default handler.
Aaron Ballman3aff6332013-12-02 19:30:36 +00003585 std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
3586 if (LangOpts.empty())
John Brawn590dc8d2020-02-26 16:31:24 +00003587 return;
Aaron Ballman3aff6332013-12-02 19:30:36 +00003588
John Brawn590dc8d2020-02-26 16:31:24 +00003589 OS << "virtual bool diagLangOpts(Sema &S, const ParsedAttr &Attr) ";
3590 OS << "const {\n";
John McCall2c91c3b2019-05-30 04:09:01 +00003591 OS << " auto &LangOpts = S.LangOpts;\n";
3592 OS << " if (" << GenerateTestExpression(LangOpts) << ")\n";
Aaron Ballman3aff6332013-12-02 19:30:36 +00003593 OS << " return true;\n\n";
3594 OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
Erich Keane6a24e802019-09-13 17:39:31 +00003595 OS << "<< Attr;\n";
Aaron Ballman3aff6332013-12-02 19:30:36 +00003596 OS << " return false;\n";
3597 OS << "}\n\n";
Aaron Ballman3aff6332013-12-02 19:30:36 +00003598}
3599
John Brawn590dc8d2020-02-26 16:31:24 +00003600static void GenerateTargetRequirements(const Record &Attr,
3601 const ParsedAttrMap &Dupes,
3602 raw_ostream &OS) {
3603 // If the attribute is not a target specific attribute, use the default
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003604 // target handler.
3605 if (!Attr.isSubClassOf("TargetSpecificAttr"))
John Brawn590dc8d2020-02-26 16:31:24 +00003606 return;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003607
3608 // Get the list of architectures to be tested for.
3609 const Record *R = Attr.getValueAsDef("Target");
Craig Topper00648582017-05-31 19:01:22 +00003610 std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003611
3612 // If there are other attributes which share the same parsed attribute kind,
3613 // such as target-specific attributes with a shared spelling, collapse the
3614 // duplicate architectures. This is required because a shared target-specific
Erich Keanee891aa92018-07-13 15:07:47 +00003615 // attribute has only one ParsedAttr::Kind enumeration value, but it
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003616 // applies to multiple target architectures. In order for the attribute to be
3617 // considered valid, all of its architectures need to be included.
3618 if (!Attr.isValueUnset("ParseKind")) {
Erich Keane3bff4142017-10-16 23:25:24 +00003619 const StringRef APK = Attr.getValueAsString("ParseKind");
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003620 for (const auto &I : Dupes) {
3621 if (I.first == APK) {
Craig Topper00648582017-05-31 19:01:22 +00003622 std::vector<StringRef> DA =
3623 I.second->getValueAsDef("Target")->getValueAsListOfStrings(
3624 "Arches");
3625 Arches.insert(Arches.end(), DA.begin(), DA.end());
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003626 }
3627 }
3628 }
3629
Bob Wilson0058b822015-07-20 22:57:36 +00003630 std::string FnName = "isTarget";
3631 std::string Test;
Richard Smith78b239e2019-06-20 20:44:45 +00003632 bool UsesT = GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
Bob Wilson7c730832015-07-20 22:57:31 +00003633
John Brawn590dc8d2020-02-26 16:31:24 +00003634 OS << "virtual bool existsInTarget(const TargetInfo &Target) const {\n";
Richard Smith78b239e2019-06-20 20:44:45 +00003635 if (UsesT)
3636 OS << " const llvm::Triple &T = Target.getTriple(); (void)T;\n";
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003637 OS << " return " << Test << ";\n";
3638 OS << "}\n\n";
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003639}
3640
John Brawn590dc8d2020-02-26 16:31:24 +00003641static void GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
3642 raw_ostream &OS) {
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003643 // If the attribute does not have a semantic form, we can bail out early.
3644 if (!Attr.getValueAsBit("ASTNode"))
John Brawn590dc8d2020-02-26 16:31:24 +00003645 return;
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003646
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003647 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003648
3649 // If there are zero or one spellings, or all of the spellings share the same
3650 // name, we can also bail out early.
3651 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
John Brawn590dc8d2020-02-26 16:31:24 +00003652 return;
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003653
3654 // Generate the enumeration we will use for the mapping.
3655 SemanticSpellingMap SemanticToSyntacticMap;
3656 std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
Matthias Braunbbbf5d42016-12-04 05:55:09 +00003657 std::string Name = Attr.getName().str() + "AttrSpellingMap";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003658
John Brawn590dc8d2020-02-26 16:31:24 +00003659 OS << "virtual unsigned spellingIndexToSemanticSpelling(";
3660 OS << "const ParsedAttr &Attr) const {\n";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003661 OS << Enum;
3662 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
3663 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
3664 OS << "}\n\n";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003665}
3666
John Brawnfa0320d2020-02-28 14:51:30 +00003667static void GenerateHandleDeclAttribute(const Record &Attr, raw_ostream &OS) {
3668 // Only generate if Attr can be handled simply.
3669 if (!Attr.getValueAsBit("SimpleHandler"))
3670 return;
3671
3672 // Generate a function which just converts from ParsedAttr to the Attr type.
3673 OS << "virtual AttrHandling handleDeclAttribute(Sema &S, Decl *D,";
3674 OS << "const ParsedAttr &Attr) const {\n";
3675 OS << " D->addAttr(::new (S.Context) " << Attr.getName();
3676 OS << "Attr(S.Context, Attr));\n";
3677 OS << " return AttributeApplied;\n";
3678 OS << "}\n\n";
3679}
3680
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003681static bool IsKnownToGCC(const Record &Attr) {
3682 // Look at the spellings for this subject; if there are any spellings which
3683 // claim to be known to GCC, the attribute is known to GCC.
George Burgess IV1881a572016-12-01 00:13:18 +00003684 return llvm::any_of(
3685 GetFlattenedSpellings(Attr),
3686 [](const FlattenedSpelling &S) { return S.knownToGCC(); });
Aaron Ballman9a99e0d2014-01-20 17:18:35 +00003687}
3688
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003689/// Emits the parsed attribute helpers
3690void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3691 emitSourceFileHeader("Parsed attribute helpers", OS);
3692
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003693 PragmaClangAttributeSupport &PragmaAttributeSupport =
3694 getPragmaAttributeSupport(Records);
3695
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003696 // Get the list of parsed attributes, and accept the optional list of
3697 // duplicates due to the ParseKind.
3698 ParsedAttrMap Dupes;
3699 ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003700
John Brawn590dc8d2020-02-26 16:31:24 +00003701 // Generate all of the custom appertainsTo functions that the attributes
3702 // will be using.
3703 for (auto I : Attrs) {
3704 const Record &Attr = *I.second;
3705 if (Attr.isValueUnset("Subjects"))
3706 continue;
3707 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
3708 for (auto Subject : SubjectObj->getValueAsListOfDefs("Subjects"))
3709 if (Subject->isSubClassOf("SubsetSubject"))
3710 GenerateCustomAppertainsTo(*Subject, OS);
3711 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003712
John Brawn590dc8d2020-02-26 16:31:24 +00003713 // Generate a ParsedAttrInfo struct for each of the attributes.
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003714 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003715 // TODO: If the attribute's kind appears in the list of duplicates, that is
3716 // because it is a target-specific attribute that appears multiple times.
3717 // It would be beneficial to test whether the duplicates are "similar
3718 // enough" to each other to not cause problems. For instance, check that
Alp Toker96cf7582014-01-18 21:49:37 +00003719 // the spellings are identical, and custom parsing rules match, etc.
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003720
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003721 // We need to generate struct instances based off ParsedAttrInfo from
Erich Keanee891aa92018-07-13 15:07:47 +00003722 // ParsedAttr.cpp.
John Brawn75d4d4b2020-02-07 14:21:13 +00003723 const std::string &AttrName = I->first;
John Brawn590dc8d2020-02-26 16:31:24 +00003724 const Record &Attr = *I->second;
Benjamin Kramere8743c02020-03-28 18:12:28 +01003725 auto Spellings = GetFlattenedSpellings(Attr);
3726 if (!Spellings.empty()) {
3727 OS << "static constexpr ParsedAttrInfo::Spelling " << I->first
3728 << "Spellings[] = {\n";
3729 for (const auto &S : Spellings) {
3730 const std::string &RawSpelling = S.name();
3731 std::string Spelling;
3732 if (!S.nameSpace().empty())
3733 Spelling += S.nameSpace() + "::";
3734 if (S.variety() == "GNU")
3735 Spelling += NormalizeGNUAttrSpelling(RawSpelling);
3736 else
3737 Spelling += RawSpelling;
3738 OS << " {AttributeCommonInfo::AS_" << S.variety();
3739 OS << ", \"" << Spelling << "\"},\n";
3740 }
3741 OS << "};\n";
3742 }
3743 OS << "struct ParsedAttrInfo" << I->first
3744 << " final : public ParsedAttrInfo {\n";
Benjamin Kramer347e31c2020-03-28 19:21:56 +01003745 OS << " ParsedAttrInfo" << I->first << "() {\n";
John Brawn75d4d4b2020-02-07 14:21:13 +00003746 OS << " AttrKind = ParsedAttr::AT_" << AttrName << ";\n";
John Brawn590dc8d2020-02-26 16:31:24 +00003747 emitArgInfo(Attr, OS);
3748 OS << " HasCustomParsing = ";
3749 OS << Attr.getValueAsBit("HasCustomParsing") << ";\n";
3750 OS << " IsTargetSpecific = ";
3751 OS << Attr.isSubClassOf("TargetSpecificAttr") << ";\n";
3752 OS << " IsType = ";
3753 OS << (Attr.isSubClassOf("TypeAttr") ||
3754 Attr.isSubClassOf("DeclOrTypeAttr")) << ";\n";
3755 OS << " IsStmt = ";
3756 OS << Attr.isSubClassOf("StmtAttr") << ";\n";
3757 OS << " IsKnownToGCC = ";
3758 OS << IsKnownToGCC(Attr) << ";\n";
3759 OS << " IsSupportedByPragmaAttribute = ";
3760 OS << PragmaAttributeSupport.isAttributedSupported(*I->second) << ";\n";
Benjamin Kramere8743c02020-03-28 18:12:28 +01003761 if (!Spellings.empty())
3762 OS << " Spellings = " << I->first << "Spellings;\n";
John Brawn590dc8d2020-02-26 16:31:24 +00003763 OS << " }\n";
3764 GenerateAppertainsTo(Attr, OS);
3765 GenerateLangOptRequirements(Attr, OS);
3766 GenerateTargetRequirements(Attr, Dupes, OS);
3767 GenerateSpellingIndexToSemanticSpelling(Attr, OS);
3768 PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
John Brawnfa0320d2020-02-28 14:51:30 +00003769 GenerateHandleDeclAttribute(Attr, OS);
John Brawn590dc8d2020-02-26 16:31:24 +00003770 OS << "static const ParsedAttrInfo" << I->first << " Instance;\n";
3771 OS << "};\n";
3772 OS << "const ParsedAttrInfo" << I->first << " ParsedAttrInfo" << I->first
3773 << "::Instance;\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003774 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003775
John Brawn590dc8d2020-02-26 16:31:24 +00003776 OS << "static const ParsedAttrInfo *AttrInfoMap[] = {\n";
3777 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
3778 OS << "&ParsedAttrInfo" << I->first << "::Instance,\n";
3779 }
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003780 OS << "};\n\n";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003781
3782 // Generate the attribute match rules.
3783 emitAttributeMatchRules(PragmaAttributeSupport, OS);
Michael Han4a045172012-03-07 00:12:16 +00003784}
3785
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00003786// Emits the kind list of parsed attributes
3787void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00003788 emitSourceFileHeader("Attribute name matcher", OS);
3789
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003790 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Nico Weber20e08042016-09-03 02:55:10 +00003791 std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
Aaron Ballman606093a2017-10-15 15:01:42 +00003792 Keywords, Pragma, C2x;
Aaron Ballman64e69862013-12-15 13:05:48 +00003793 std::set<std::string> Seen;
Aaron Ballman2f22b942014-05-20 19:47:14 +00003794 for (const auto *A : Attrs) {
3795 const Record &Attr = *A;
Richard Smith852e9ce2013-11-27 01:46:48 +00003796
Michael Han4a045172012-03-07 00:12:16 +00003797 bool SemaHandler = Attr.getValueAsBit("SemaHandler");
Douglas Gregor19fbb8f2012-05-02 16:18:45 +00003798 bool Ignored = Attr.getValueAsBit("Ignored");
Douglas Gregor19fbb8f2012-05-02 16:18:45 +00003799 if (SemaHandler || Ignored) {
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003800 // Attribute spellings can be shared between target-specific attributes,
3801 // and can be shared between syntaxes for the same attribute. For
3802 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
3803 // specific attribute, or MSP430-specific attribute. Additionally, an
3804 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
3805 // for the same semantic attribute. Ultimately, we need to map each of
Erich Keaneb79f3312019-09-16 13:58:59 +00003806 // these to a single AttributeCommonInfo::Kind value, but the
3807 // StringMatcher class cannot handle duplicate match strings. So we
3808 // generate a list of string to match based on the syntax, and emit
3809 // multiple string matchers depending on the syntax used.
Aaron Ballman64e69862013-12-15 13:05:48 +00003810 std::string AttrName;
3811 if (Attr.isSubClassOf("TargetSpecificAttr") &&
3812 !Attr.isValueUnset("ParseKind")) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01003813 AttrName = std::string(Attr.getValueAsString("ParseKind"));
Aaron Ballman64e69862013-12-15 13:05:48 +00003814 if (Seen.find(AttrName) != Seen.end())
3815 continue;
3816 Seen.insert(AttrName);
3817 } else
3818 AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
3819
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003820 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003821 for (const auto &S : Spellings) {
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00003822 const std::string &RawSpelling = S.name();
Craig Topper8ae12032014-05-07 06:21:57 +00003823 std::vector<StringMatcher::StringPair> *Matches = nullptr;
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00003824 std::string Spelling;
3825 const std::string &Variety = S.variety();
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003826 if (Variety == "CXX11") {
3827 Matches = &CXX11;
John Brawnbc3f1712020-03-25 10:53:30 +00003828 if (!S.nameSpace().empty())
3829 Spelling += S.nameSpace() + "::";
Aaron Ballman606093a2017-10-15 15:01:42 +00003830 } else if (Variety == "C2x") {
3831 Matches = &C2x;
John Brawnbc3f1712020-03-25 10:53:30 +00003832 if (!S.nameSpace().empty())
3833 Spelling += S.nameSpace() + "::";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003834 } else if (Variety == "GNU")
3835 Matches = &GNU;
3836 else if (Variety == "Declspec")
3837 Matches = &Declspec;
Nico Weber20e08042016-09-03 02:55:10 +00003838 else if (Variety == "Microsoft")
3839 Matches = &Microsoft;
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003840 else if (Variety == "Keyword")
3841 Matches = &Keywords;
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003842 else if (Variety == "Pragma")
3843 Matches = &Pragma;
Alexis Hunta0e54d42012-06-18 16:13:52 +00003844
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003845 assert(Matches && "Unsupported spelling variety found");
3846
Justin Lebar4086fe52017-01-05 16:51:54 +00003847 if (Variety == "GNU")
3848 Spelling += NormalizeGNUAttrSpelling(RawSpelling);
3849 else
3850 Spelling += RawSpelling;
3851
Douglas Gregor19fbb8f2012-05-02 16:18:45 +00003852 if (SemaHandler)
Erich Keanee891aa92018-07-13 15:07:47 +00003853 Matches->push_back(StringMatcher::StringPair(
Erich Keaneb79f3312019-09-16 13:58:59 +00003854 Spelling, "return AttributeCommonInfo::AT_" + AttrName + ";"));
Douglas Gregor19fbb8f2012-05-02 16:18:45 +00003855 else
Erich Keanee891aa92018-07-13 15:07:47 +00003856 Matches->push_back(StringMatcher::StringPair(
Erich Keaneb79f3312019-09-16 13:58:59 +00003857 Spelling, "return AttributeCommonInfo::IgnoredAttribute;"));
Michael Han4a045172012-03-07 00:12:16 +00003858 }
3859 }
3860 }
Erich Keanee891aa92018-07-13 15:07:47 +00003861
Erich Keaneb79f3312019-09-16 13:58:59 +00003862 OS << "static AttributeCommonInfo::Kind getAttrKind(StringRef Name, ";
3863 OS << "AttributeCommonInfo::Syntax Syntax) {\n";
3864 OS << " if (AttributeCommonInfo::AS_GNU == Syntax) {\n";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003865 StringMatcher("Name", GNU, OS).Emit();
Erich Keaneb79f3312019-09-16 13:58:59 +00003866 OS << " } else if (AttributeCommonInfo::AS_Declspec == Syntax) {\n";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003867 StringMatcher("Name", Declspec, OS).Emit();
Erich Keaneb79f3312019-09-16 13:58:59 +00003868 OS << " } else if (AttributeCommonInfo::AS_Microsoft == Syntax) {\n";
Nico Weber20e08042016-09-03 02:55:10 +00003869 StringMatcher("Name", Microsoft, OS).Emit();
Erich Keaneb79f3312019-09-16 13:58:59 +00003870 OS << " } else if (AttributeCommonInfo::AS_CXX11 == Syntax) {\n";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003871 StringMatcher("Name", CXX11, OS).Emit();
Erich Keaneb79f3312019-09-16 13:58:59 +00003872 OS << " } else if (AttributeCommonInfo::AS_C2x == Syntax) {\n";
Aaron Ballman606093a2017-10-15 15:01:42 +00003873 StringMatcher("Name", C2x, OS).Emit();
Erich Keaneb79f3312019-09-16 13:58:59 +00003874 OS << " } else if (AttributeCommonInfo::AS_Keyword == Syntax || ";
3875 OS << "AttributeCommonInfo::AS_ContextSensitiveKeyword == Syntax) {\n";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003876 StringMatcher("Name", Keywords, OS).Emit();
Erich Keaneb79f3312019-09-16 13:58:59 +00003877 OS << " } else if (AttributeCommonInfo::AS_Pragma == Syntax) {\n";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003878 StringMatcher("Name", Pragma, OS).Emit();
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003879 OS << " }\n";
Erich Keaneb79f3312019-09-16 13:58:59 +00003880 OS << " return AttributeCommonInfo::UnknownAttribute;\n"
Douglas Gregor377f99b2012-05-02 17:33:51 +00003881 << "}\n";
Michael Han4a045172012-03-07 00:12:16 +00003882}
3883
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003884// Emits the code to dump an attribute.
Stephen Kellydb8fac12019-01-11 19:16:01 +00003885void EmitClangAttrTextNodeDump(RecordKeeper &Records, raw_ostream &OS) {
3886 emitSourceFileHeader("Attribute text node dumper", OS);
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00003887
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003888 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
Aaron Ballman2f22b942014-05-20 19:47:14 +00003889 for (const auto *Attr : Attrs) {
3890 const Record &R = *Attr;
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003891 if (!R.getValueAsBit("ASTNode"))
3892 continue;
Aaron Ballmanbc909612014-01-22 21:51:20 +00003893
3894 // If the attribute has a semantically-meaningful name (which is determined
3895 // by whether there is a Spelling enumeration for it), then write out the
3896 // spelling used for the attribute.
Stephen Kellydb8fac12019-01-11 19:16:01 +00003897
3898 std::string FunctionContent;
3899 llvm::raw_string_ostream SS(FunctionContent);
3900
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003901 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Aaron Ballmanbc909612014-01-22 21:51:20 +00003902 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
Stephen Kellydb8fac12019-01-11 19:16:01 +00003903 SS << " OS << \" \" << A->getSpelling();\n";
Aaron Ballmanbc909612014-01-22 21:51:20 +00003904
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003905 Args = R.getValueAsListOfDefs("Args");
Stephen Kellydb8fac12019-01-11 19:16:01 +00003906 for (const auto *Arg : Args)
3907 createArgument(*Arg, R.getName())->writeDump(SS);
Richard Trieude5cc7d2013-01-31 01:44:26 +00003908
Stephen Kellydb8fac12019-01-11 19:16:01 +00003909 if (SS.tell()) {
3910 OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
3911 << "Attr *A) {\n";
3912 if (!Args.empty())
3913 OS << " const auto *SA = cast<" << R.getName()
3914 << "Attr>(A); (void)SA;\n";
3915 OS << SS.str();
3916 OS << " }\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003917 }
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003918 }
Stephen Kellydb8fac12019-01-11 19:16:01 +00003919}
3920
3921void EmitClangAttrNodeTraverse(RecordKeeper &Records, raw_ostream &OS) {
3922 emitSourceFileHeader("Attribute text node traverser", OS);
3923
3924 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
3925 for (const auto *Attr : Attrs) {
3926 const Record &R = *Attr;
3927 if (!R.getValueAsBit("ASTNode"))
3928 continue;
3929
3930 std::string FunctionContent;
3931 llvm::raw_string_ostream SS(FunctionContent);
3932
3933 Args = R.getValueAsListOfDefs("Args");
3934 for (const auto *Arg : Args)
3935 createArgument(*Arg, R.getName())->writeDumpChildren(SS);
3936 if (SS.tell()) {
3937 OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
3938 << "Attr *A) {\n";
3939 if (!Args.empty())
3940 OS << " const auto *SA = cast<" << R.getName()
3941 << "Attr>(A); (void)SA;\n";
3942 OS << SS.str();
3943 OS << " }\n";
3944 }
3945 }
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003946}
3947
Aaron Ballman35db2b32014-01-29 22:13:45 +00003948void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
3949 raw_ostream &OS) {
3950 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
3951 emitClangAttrArgContextList(Records, OS);
3952 emitClangAttrIdentifierArgList(Records, OS);
Erich Keane3efe0022018-07-20 14:13:28 +00003953 emitClangAttrVariadicIdentifierArgList(Records, OS);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00003954 emitClangAttrThisIsaIdentifierArgList(Records, OS);
Aaron Ballman35db2b32014-01-29 22:13:45 +00003955 emitClangAttrTypeArgList(Records, OS);
3956 emitClangAttrLateParsedList(Records, OS);
3957}
3958
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003959void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper &Records,
3960 raw_ostream &OS) {
3961 getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
3962}
3963
Richard Smith09ac4a12018-08-30 19:16:33 +00003964enum class SpellingKind {
3965 GNU,
3966 CXX11,
3967 C2x,
3968 Declspec,
3969 Microsoft,
3970 Keyword,
3971 Pragma,
3972};
3973static const size_t NumSpellingKinds = (size_t)SpellingKind::Pragma + 1;
3974
3975class SpellingList {
3976 std::vector<std::string> Spellings[NumSpellingKinds];
3977
3978public:
3979 ArrayRef<std::string> operator[](SpellingKind K) const {
3980 return Spellings[(size_t)K];
3981 }
3982
3983 void add(const Record &Attr, FlattenedSpelling Spelling) {
3984 SpellingKind Kind = StringSwitch<SpellingKind>(Spelling.variety())
3985 .Case("GNU", SpellingKind::GNU)
3986 .Case("CXX11", SpellingKind::CXX11)
3987 .Case("C2x", SpellingKind::C2x)
3988 .Case("Declspec", SpellingKind::Declspec)
3989 .Case("Microsoft", SpellingKind::Microsoft)
3990 .Case("Keyword", SpellingKind::Keyword)
3991 .Case("Pragma", SpellingKind::Pragma);
3992 std::string Name;
3993 if (!Spelling.nameSpace().empty()) {
3994 switch (Kind) {
3995 case SpellingKind::CXX11:
3996 case SpellingKind::C2x:
3997 Name = Spelling.nameSpace() + "::";
3998 break;
3999 case SpellingKind::Pragma:
4000 Name = Spelling.nameSpace() + " ";
4001 break;
4002 default:
4003 PrintFatalError(Attr.getLoc(), "Unexpected namespace in spelling");
4004 }
4005 }
4006 Name += Spelling.name();
4007
4008 Spellings[(size_t)Kind].push_back(Name);
4009 }
4010};
4011
Aaron Ballman97dba042014-02-17 15:27:10 +00004012class DocumentationData {
4013public:
Aaron Ballman1a3e5852014-02-17 16:18:32 +00004014 const Record *Documentation;
4015 const Record *Attribute;
Erich Keanea98a2be2017-10-16 20:31:05 +00004016 std::string Heading;
Richard Smith09ac4a12018-08-30 19:16:33 +00004017 SpellingList SupportedSpellings;
Aaron Ballman97dba042014-02-17 15:27:10 +00004018
Erich Keanea98a2be2017-10-16 20:31:05 +00004019 DocumentationData(const Record &Documentation, const Record &Attribute,
Richard Smith09ac4a12018-08-30 19:16:33 +00004020 std::pair<std::string, SpellingList> HeadingAndSpellings)
Erich Keanea98a2be2017-10-16 20:31:05 +00004021 : Documentation(&Documentation), Attribute(&Attribute),
Richard Smith09ac4a12018-08-30 19:16:33 +00004022 Heading(std::move(HeadingAndSpellings.first)),
4023 SupportedSpellings(std::move(HeadingAndSpellings.second)) {}
Aaron Ballman97dba042014-02-17 15:27:10 +00004024};
4025
Aaron Ballman4de1b582014-02-19 22:59:32 +00004026static void WriteCategoryHeader(const Record *DocCategory,
Aaron Ballman97dba042014-02-17 15:27:10 +00004027 raw_ostream &OS) {
Erich Keane3bff4142017-10-16 23:25:24 +00004028 const StringRef Name = DocCategory->getValueAsString("Name");
4029 OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
Aaron Ballman4de1b582014-02-19 22:59:32 +00004030
4031 // If there is content, print that as well.
Erich Keane3bff4142017-10-16 23:25:24 +00004032 const StringRef ContentStr = DocCategory->getValueAsString("Content");
Benjamin Kramer5c404072015-04-10 21:37:21 +00004033 // Trim leading and trailing newlines and spaces.
Erich Keane3bff4142017-10-16 23:25:24 +00004034 OS << ContentStr.trim();
Benjamin Kramer5c404072015-04-10 21:37:21 +00004035
Aaron Ballman4de1b582014-02-19 22:59:32 +00004036 OS << "\n\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00004037}
4038
Richard Smith09ac4a12018-08-30 19:16:33 +00004039static std::pair<std::string, SpellingList>
4040GetAttributeHeadingAndSpellings(const Record &Documentation,
4041 const Record &Attribute) {
Aaron Ballman97dba042014-02-17 15:27:10 +00004042 // FIXME: there is no way to have a per-spelling category for the attribute
4043 // documentation. This may not be a limiting factor since the spellings
4044 // should generally be consistently applied across the category.
4045
Erich Keanea98a2be2017-10-16 20:31:05 +00004046 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
Richard Smith09ac4a12018-08-30 19:16:33 +00004047 if (Spellings.empty())
4048 PrintFatalError(Attribute.getLoc(),
4049 "Attribute has no supported spellings; cannot be "
4050 "documented");
Aaron Ballman97dba042014-02-17 15:27:10 +00004051
4052 // Determine the heading to be used for this attribute.
Benjamin Krameradcd0262020-01-28 20:23:46 +01004053 std::string Heading = std::string(Documentation.getValueAsString("Heading"));
Aaron Ballman97dba042014-02-17 15:27:10 +00004054 if (Heading.empty()) {
4055 // If there's only one spelling, we can simply use that.
4056 if (Spellings.size() == 1)
4057 Heading = Spellings.begin()->name();
4058 else {
4059 std::set<std::string> Uniques;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00004060 for (auto I = Spellings.begin(), E = Spellings.end();
4061 I != E && Uniques.size() <= 1; ++I) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01004062 std::string Spelling =
4063 std::string(NormalizeNameForSpellingComparison(I->name()));
Aaron Ballman97dba042014-02-17 15:27:10 +00004064 Uniques.insert(Spelling);
4065 }
4066 // If the semantic map has only one spelling, that is sufficient for our
4067 // needs.
4068 if (Uniques.size() == 1)
4069 Heading = *Uniques.begin();
4070 }
4071 }
4072
4073 // If the heading is still empty, it is an error.
4074 if (Heading.empty())
Erich Keanea98a2be2017-10-16 20:31:05 +00004075 PrintFatalError(Attribute.getLoc(),
Aaron Ballman97dba042014-02-17 15:27:10 +00004076 "This attribute requires a heading to be specified");
4077
Richard Smith09ac4a12018-08-30 19:16:33 +00004078 SpellingList SupportedSpellings;
4079 for (const auto &I : Spellings)
4080 SupportedSpellings.add(Attribute, I);
Aaron Ballman97dba042014-02-17 15:27:10 +00004081
Richard Smith09ac4a12018-08-30 19:16:33 +00004082 return std::make_pair(std::move(Heading), std::move(SupportedSpellings));
Erich Keanea98a2be2017-10-16 20:31:05 +00004083}
4084
4085static void WriteDocumentation(RecordKeeper &Records,
4086 const DocumentationData &Doc, raw_ostream &OS) {
4087 OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00004088
4089 // List what spelling syntaxes the attribute supports.
4090 OS << ".. csv-table:: Supported Syntaxes\n";
Richard Smith09ac4a12018-08-30 19:16:33 +00004091 OS << " :header: \"GNU\", \"C++11\", \"C2x\", \"``__declspec``\",";
4092 OS << " \"Keyword\", \"``#pragma``\", \"``#pragma clang attribute``\"\n\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00004093 OS << " \"";
Richard Smith09ac4a12018-08-30 19:16:33 +00004094 for (size_t Kind = 0; Kind != NumSpellingKinds; ++Kind) {
4095 SpellingKind K = (SpellingKind)Kind;
Richard Smith23ff7e82018-08-30 19:19:15 +00004096 // TODO: List Microsoft (IDL-style attribute) spellings once we fully
4097 // support them.
Richard Smith09ac4a12018-08-30 19:16:33 +00004098 if (K == SpellingKind::Microsoft)
4099 continue;
4100
4101 bool PrintedAny = false;
4102 for (StringRef Spelling : Doc.SupportedSpellings[K]) {
4103 if (PrintedAny)
4104 OS << " |br| ";
4105 OS << "``" << Spelling << "``";
4106 PrintedAny = true;
4107 }
4108
4109 OS << "\",\"";
4110 }
4111
4112 if (getPragmaAttributeSupport(Records).isAttributedSupported(
4113 *Doc.Attribute))
4114 OS << "Yes";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00004115 OS << "\"\n\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00004116
4117 // If the attribute is deprecated, print a message about it, and possibly
4118 // provide a replacement attribute.
Aaron Ballman1a3e5852014-02-17 16:18:32 +00004119 if (!Doc.Documentation->isValueUnset("Deprecated")) {
Aaron Ballman97dba042014-02-17 15:27:10 +00004120 OS << "This attribute has been deprecated, and may be removed in a future "
4121 << "version of Clang.";
Aaron Ballman1a3e5852014-02-17 16:18:32 +00004122 const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
Erich Keane3bff4142017-10-16 23:25:24 +00004123 const StringRef Replacement = Deprecated.getValueAsString("Replacement");
Aaron Ballman97dba042014-02-17 15:27:10 +00004124 if (!Replacement.empty())
Joel E. Denny6053ec22018-02-28 16:57:33 +00004125 OS << " This attribute has been superseded by ``" << Replacement
4126 << "``.";
Aaron Ballman97dba042014-02-17 15:27:10 +00004127 OS << "\n\n";
4128 }
4129
Erich Keane3bff4142017-10-16 23:25:24 +00004130 const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
Aaron Ballman97dba042014-02-17 15:27:10 +00004131 // Trim leading and trailing newlines and spaces.
Erich Keane3bff4142017-10-16 23:25:24 +00004132 OS << ContentStr.trim();
Aaron Ballman97dba042014-02-17 15:27:10 +00004133
4134 OS << "\n\n\n";
4135}
4136
4137void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
4138 // Get the documentation introduction paragraph.
4139 const Record *Documentation = Records.getDef("GlobalDocumentation");
4140 if (!Documentation) {
4141 PrintFatalError("The Documentation top-level definition is missing, "
4142 "no documentation will be generated.");
4143 return;
4144 }
4145
Aaron Ballman4de1b582014-02-19 22:59:32 +00004146 OS << Documentation->getValueAsString("Intro") << "\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00004147
Aaron Ballman97dba042014-02-17 15:27:10 +00004148 // Gather the Documentation lists from each of the attributes, based on the
4149 // category provided.
4150 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00004151 std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
Aaron Ballman2f22b942014-05-20 19:47:14 +00004152 for (const auto *A : Attrs) {
4153 const Record &Attr = *A;
Aaron Ballman97dba042014-02-17 15:27:10 +00004154 std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
Aaron Ballman2f22b942014-05-20 19:47:14 +00004155 for (const auto *D : Docs) {
4156 const Record &Doc = *D;
Aaron Ballman4de1b582014-02-19 22:59:32 +00004157 const Record *Category = Doc.getValueAsDef("Category");
Aaron Ballman97dba042014-02-17 15:27:10 +00004158 // If the category is "undocumented", then there cannot be any other
4159 // documentation categories (otherwise, the attribute would become
4160 // documented).
Erich Keane3bff4142017-10-16 23:25:24 +00004161 const StringRef Cat = Category->getValueAsString("Name");
Aaron Ballman4de1b582014-02-19 22:59:32 +00004162 bool Undocumented = Cat == "Undocumented";
Aaron Ballman97dba042014-02-17 15:27:10 +00004163 if (Undocumented && Docs.size() > 1)
4164 PrintFatalError(Doc.getLoc(),
4165 "Attribute is \"Undocumented\", but has multiple "
Erich Keanea98a2be2017-10-16 20:31:05 +00004166 "documentation categories");
Aaron Ballman97dba042014-02-17 15:27:10 +00004167
4168 if (!Undocumented)
Erich Keanea98a2be2017-10-16 20:31:05 +00004169 SplitDocs[Category].push_back(DocumentationData(
Richard Smith09ac4a12018-08-30 19:16:33 +00004170 Doc, Attr, GetAttributeHeadingAndSpellings(Doc, Attr)));
Aaron Ballman97dba042014-02-17 15:27:10 +00004171 }
4172 }
4173
4174 // Having split the attributes out based on what documentation goes where,
4175 // we can begin to generate sections of documentation.
Erich Keanea98a2be2017-10-16 20:31:05 +00004176 for (auto &I : SplitDocs) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00004177 WriteCategoryHeader(I.first, OS);
Aaron Ballman97dba042014-02-17 15:27:10 +00004178
Fangrui Song1d38c132018-09-30 21:41:11 +00004179 llvm::sort(I.second,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00004180 [](const DocumentationData &D1, const DocumentationData &D2) {
4181 return D1.Heading < D2.Heading;
Fangrui Song1d38c132018-09-30 21:41:11 +00004182 });
Erich Keanea98a2be2017-10-16 20:31:05 +00004183
Aaron Ballman97dba042014-02-17 15:27:10 +00004184 // Walk over each of the attributes in the category and write out their
4185 // documentation.
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00004186 for (const auto &Doc : I.second)
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004187 WriteDocumentation(Records, Doc, OS);
4188 }
4189}
4190
4191void EmitTestPragmaAttributeSupportedAttributes(RecordKeeper &Records,
4192 raw_ostream &OS) {
4193 PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
4194 ParsedAttrMap Attrs = getParsedAttrList(Records);
Erik Pilkington23c48c22018-12-04 00:31:31 +00004195 OS << "#pragma clang attribute supports the following attributes:\n";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004196 for (const auto &I : Attrs) {
4197 if (!Support.isAttributedSupported(*I.second))
4198 continue;
4199 OS << I.first;
4200 if (I.second->isValueUnset("Subjects")) {
4201 OS << " ()\n";
4202 continue;
4203 }
4204 const Record *SubjectObj = I.second->getValueAsDef("Subjects");
4205 std::vector<Record *> Subjects =
4206 SubjectObj->getValueAsListOfDefs("Subjects");
4207 OS << " (";
4208 for (const auto &Subject : llvm::enumerate(Subjects)) {
4209 if (Subject.index())
4210 OS << ", ";
Alex Lorenz24952fb2017-04-19 15:52:11 +00004211 PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
4212 Support.SubjectsToRules.find(Subject.value())->getSecond();
4213 if (RuleSet.isRule()) {
4214 OS << RuleSet.getRule().getEnumValueName();
4215 continue;
4216 }
4217 OS << "(";
4218 for (const auto &Rule : llvm::enumerate(RuleSet.getAggregateRuleSet())) {
4219 if (Rule.index())
4220 OS << ", ";
4221 OS << Rule.value().getEnumValueName();
4222 }
4223 OS << ")";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004224 }
4225 OS << ")\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00004226 }
Erik Pilkington23c48c22018-12-04 00:31:31 +00004227 OS << "End of supported attributes.\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00004228}
4229
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00004230} // end namespace clang