blob: 077bfe48ab3851cb9e1f08390a7bed9e420e40a7 [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
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000013#include "llvm/ADT/ArrayRef.h"
Alex Lorenz9e7bf162017-04-18 14:33:39 +000014#include "llvm/ADT/DenseMap.h"
George Burgess IV1881a572016-12-01 00:13:18 +000015#include "llvm/ADT/DenseSet.h"
Alex Lorenz3bfe9622017-04-18 10:46:41 +000016#include "llvm/ADT/STLExtras.h"
Alex Lorenz9e7bf162017-04-18 14:33:39 +000017#include "llvm/ADT/SmallString.h"
Aaron Ballman28afa182014-11-17 18:17:19 +000018#include "llvm/ADT/StringExtras.h"
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000019#include "llvm/ADT/StringRef.h"
Alex Lorenz9e7bf162017-04-18 14:33:39 +000020#include "llvm/ADT/StringSet.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000021#include "llvm/ADT/StringSwitch.h"
Alex Lorenz9e7bf162017-04-18 14:33:39 +000022#include "llvm/ADT/iterator_range.h"
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000023#include "llvm/Support/ErrorHandling.h"
24#include "llvm/Support/raw_ostream.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000025#include "llvm/TableGen/Error.h"
Peter Collingbournebee583f2011-10-06 13:03:08 +000026#include "llvm/TableGen/Record.h"
Douglas Gregor377f99b2012-05-02 17:33:51 +000027#include "llvm/TableGen/StringMatcher.h"
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +000028#include "llvm/TableGen/TableGenBackend.h"
Peter Collingbournebee583f2011-10-06 13:03:08 +000029#include <algorithm>
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000030#include <cassert>
Peter Collingbournebee583f2011-10-06 13:03:08 +000031#include <cctype>
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000032#include <cstddef>
33#include <cstdint>
34#include <map>
Aaron Ballman8f1439b2014-03-05 16:49:55 +000035#include <memory>
Aaron Ballman80469032013-11-29 14:57:58 +000036#include <set>
Chandler Carruth5553d0d2014-01-07 11:51:46 +000037#include <sstream>
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000038#include <string>
39#include <utility>
40#include <vector>
Peter Collingbournebee583f2011-10-06 13:03:08 +000041
42using namespace llvm;
43
Benjamin Kramerd910d162015-03-10 18:24:01 +000044namespace {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000045
Aaron Ballmanc669cc02014-01-27 22:10:04 +000046class FlattenedSpelling {
47 std::string V, N, NS;
48 bool K;
49
50public:
51 FlattenedSpelling(const std::string &Variety, const std::string &Name,
52 const std::string &Namespace, bool KnownToGCC) :
53 V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
54 explicit FlattenedSpelling(const Record &Spelling) :
55 V(Spelling.getValueAsString("Variety")),
56 N(Spelling.getValueAsString("Name")) {
57
Aaron Ballmanffc43362017-10-26 12:19:02 +000058 assert(V != "GCC" && V != "Clang" &&
59 "Given a GCC spelling, which means this hasn't been flattened!");
Aaron Ballman606093a2017-10-15 15:01:42 +000060 if (V == "CXX11" || V == "C2x" || V == "Pragma")
Aaron Ballmanc669cc02014-01-27 22:10:04 +000061 NS = Spelling.getValueAsString("Namespace");
62 bool Unset;
63 K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
64 }
65
66 const std::string &variety() const { return V; }
67 const std::string &name() const { return N; }
68 const std::string &nameSpace() const { return NS; }
69 bool knownToGCC() const { return K; }
70};
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000071
Hans Wennborgdcfba332015-10-06 23:40:43 +000072} // end anonymous namespace
Aaron Ballmanc669cc02014-01-27 22:10:04 +000073
Benjamin Kramerd910d162015-03-10 18:24:01 +000074static std::vector<FlattenedSpelling>
75GetFlattenedSpellings(const Record &Attr) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +000076 std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
77 std::vector<FlattenedSpelling> Ret;
78
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +000079 for (const auto &Spelling : Spellings) {
Aaron Ballmanffc43362017-10-26 12:19:02 +000080 StringRef Variety = Spelling->getValueAsString("Variety");
81 StringRef Name = Spelling->getValueAsString("Name");
82 if (Variety == "GCC") {
Aaron Ballmanc669cc02014-01-27 22:10:04 +000083 // Gin up two new spelling objects to add into the list.
Aaron Ballmanffc43362017-10-26 12:19:02 +000084 Ret.emplace_back("GNU", Name, "", true);
85 Ret.emplace_back("CXX11", Name, "gnu", true);
86 } else if (Variety == "Clang") {
87 Ret.emplace_back("GNU", Name, "", false);
88 Ret.emplace_back("CXX11", Name, "clang", false);
Aaron Ballman10007812018-01-03 22:22:48 +000089 if (Spelling->getValueAsBit("AllowInC"))
90 Ret.emplace_back("C2x", Name, "clang", false);
Aaron Ballmanc669cc02014-01-27 22:10:04 +000091 } else
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +000092 Ret.push_back(FlattenedSpelling(*Spelling));
Aaron Ballmanc669cc02014-01-27 22:10:04 +000093 }
94
95 return Ret;
96}
97
Peter Collingbournebee583f2011-10-06 13:03:08 +000098static std::string ReadPCHRecord(StringRef type) {
99 return StringSwitch<std::string>(type)
David L. Jones267b8842017-01-24 01:04:30 +0000100 .EndsWith("Decl *", "Record.GetLocalDeclAs<"
101 + std::string(type, 0, type.size()-1) + ">(Record.readInt())")
102 .Case("TypeSourceInfo *", "Record.getTypeSourceInfo()")
103 .Case("Expr *", "Record.readExpr()")
104 .Case("IdentifierInfo *", "Record.getIdentifierInfo()")
105 .Case("StringRef", "Record.readString()")
Joel E. Denny81508102018-03-13 14:51:22 +0000106 .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
David L. Jones267b8842017-01-24 01:04:30 +0000107 .Default("Record.readInt()");
Peter Collingbournebee583f2011-10-06 13:03:08 +0000108}
109
Richard Smith19978562016-05-18 00:16:51 +0000110// Get a type that is suitable for storing an object of the specified type.
111static StringRef getStorageType(StringRef type) {
112 return StringSwitch<StringRef>(type)
113 .Case("StringRef", "std::string")
114 .Default(type);
115}
116
Peter Collingbournebee583f2011-10-06 13:03:08 +0000117// Assumes that the way to get the value is SA->getname()
118static std::string WritePCHRecord(StringRef type, StringRef name) {
Richard Smith290d8012016-04-06 17:06:00 +0000119 return "Record." + StringSwitch<std::string>(type)
120 .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
121 .Case("TypeSourceInfo *", "AddTypeSourceInfo(" + std::string(name) + ");\n")
Peter Collingbournebee583f2011-10-06 13:03:08 +0000122 .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
Richard Smith290d8012016-04-06 17:06:00 +0000123 .Case("IdentifierInfo *", "AddIdentifierRef(" + std::string(name) + ");\n")
124 .Case("StringRef", "AddString(" + std::string(name) + ");\n")
Joel E. Denny81508102018-03-13 14:51:22 +0000125 .Case("ParamIdx", "push_back(" + std::string(name) + ".serialize());\n")
Richard Smith290d8012016-04-06 17:06:00 +0000126 .Default("push_back(" + std::string(name) + ");\n");
Peter Collingbournebee583f2011-10-06 13:03:08 +0000127}
128
Michael Han4a045172012-03-07 00:12:16 +0000129// Normalize attribute name by removing leading and trailing
130// underscores. For example, __foo, foo__, __foo__ would
131// become foo.
132static StringRef NormalizeAttrName(StringRef AttrName) {
George Burgess IV1881a572016-12-01 00:13:18 +0000133 AttrName.consume_front("__");
134 AttrName.consume_back("__");
Michael Han4a045172012-03-07 00:12:16 +0000135 return AttrName;
136}
137
Aaron Ballman36a53502014-01-16 13:03:14 +0000138// Normalize the name by removing any and all leading and trailing underscores.
139// This is different from NormalizeAttrName in that it also handles names like
140// _pascal and __pascal.
141static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
Benjamin Kramer5c404072015-04-10 21:37:21 +0000142 return Name.trim("_");
Aaron Ballman36a53502014-01-16 13:03:14 +0000143}
144
Justin Lebar4086fe52017-01-05 16:51:54 +0000145// Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
146// removing "__" if it appears at the beginning and end of the attribute's name.
147static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
Michael Han4a045172012-03-07 00:12:16 +0000148 if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
149 AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
150 }
151
152 return AttrSpelling;
153}
154
Aaron Ballman2f22b942014-05-20 19:47:14 +0000155typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
Aaron Ballman64e69862013-12-15 13:05:48 +0000156
Aaron Ballmanab7691c2014-01-09 22:48:32 +0000157static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
Craig Topper8ae12032014-05-07 06:21:57 +0000158 ParsedAttrMap *Dupes = nullptr) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000159 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Aaron Ballman64e69862013-12-15 13:05:48 +0000160 std::set<std::string> Seen;
161 ParsedAttrMap R;
Aaron Ballman2f22b942014-05-20 19:47:14 +0000162 for (const auto *Attr : Attrs) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000163 if (Attr->getValueAsBit("SemaHandler")) {
Aaron Ballman64e69862013-12-15 13:05:48 +0000164 std::string AN;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000165 if (Attr->isSubClassOf("TargetSpecificAttr") &&
166 !Attr->isValueUnset("ParseKind")) {
167 AN = Attr->getValueAsString("ParseKind");
Aaron Ballman64e69862013-12-15 13:05:48 +0000168
169 // If this attribute has already been handled, it does not need to be
170 // handled again.
Aaron Ballmanab7691c2014-01-09 22:48:32 +0000171 if (Seen.find(AN) != Seen.end()) {
172 if (Dupes)
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000173 Dupes->push_back(std::make_pair(AN, Attr));
Aaron Ballman64e69862013-12-15 13:05:48 +0000174 continue;
Aaron Ballmanab7691c2014-01-09 22:48:32 +0000175 }
Aaron Ballman64e69862013-12-15 13:05:48 +0000176 Seen.insert(AN);
177 } else
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000178 AN = NormalizeAttrName(Attr->getName()).str();
Aaron Ballman64e69862013-12-15 13:05:48 +0000179
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000180 R.push_back(std::make_pair(AN, Attr));
Aaron Ballman64e69862013-12-15 13:05:48 +0000181 }
182 }
183 return R;
184}
185
Peter Collingbournebee583f2011-10-06 13:03:08 +0000186namespace {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000187
Peter Collingbournebee583f2011-10-06 13:03:08 +0000188 class Argument {
189 std::string lowerName, upperName;
190 StringRef attrName;
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000191 bool isOpt;
John McCalla62c1a92015-10-28 00:17:34 +0000192 bool Fake;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000193
194 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000195 Argument(const Record &Arg, StringRef Attr)
Peter Collingbournebee583f2011-10-06 13:03:08 +0000196 : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
John McCalla62c1a92015-10-28 00:17:34 +0000197 attrName(Attr), isOpt(false), Fake(false) {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000198 if (!lowerName.empty()) {
199 lowerName[0] = std::tolower(lowerName[0]);
200 upperName[0] = std::toupper(upperName[0]);
201 }
Reid Klecknerebeb0ca2016-05-31 17:42:56 +0000202 // Work around MinGW's macro definition of 'interface' to 'struct'. We
203 // have an attribute argument called 'Interface', so only the lower case
204 // name conflicts with the macro definition.
205 if (lowerName == "interface")
206 lowerName = "interface_";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000207 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000208 virtual ~Argument() = default;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000209
210 StringRef getLowerName() const { return lowerName; }
211 StringRef getUpperName() const { return upperName; }
212 StringRef getAttrName() const { return attrName; }
213
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000214 bool isOptional() const { return isOpt; }
215 void setOptional(bool set) { isOpt = set; }
216
John McCalla62c1a92015-10-28 00:17:34 +0000217 bool isFake() const { return Fake; }
218 void setFake(bool fake) { Fake = fake; }
219
Peter Collingbournebee583f2011-10-06 13:03:08 +0000220 // These functions print the argument contents formatted in different ways.
221 virtual void writeAccessors(raw_ostream &OS) const = 0;
222 virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +0000223 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000224 virtual void writeCloneArgs(raw_ostream &OS) const = 0;
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000225 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
Daniel Dunbardc51baa2012-02-10 06:00:29 +0000226 virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000227 virtual void writeCtorBody(raw_ostream &OS) const {}
228 virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000229 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000230 virtual void writeCtorParameters(raw_ostream &OS) const = 0;
231 virtual void writeDeclarations(raw_ostream &OS) const = 0;
232 virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
233 virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
234 virtual void writePCHWrite(raw_ostream &OS) const = 0;
Aaron Ballman48a533d2018-02-27 23:49:28 +0000235 virtual std::string getIsOmitted() const { return "false"; }
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000236 virtual void writeValue(raw_ostream &OS) const = 0;
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000237 virtual void writeDump(raw_ostream &OS) const = 0;
238 virtual void writeDumpChildren(raw_ostream &OS) const {}
Richard Trieude5cc7d2013-01-31 01:44:26 +0000239 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
Aaron Ballman682ee422013-09-11 19:47:58 +0000240
241 virtual bool isEnumArg() const { return false; }
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000242 virtual bool isVariadicEnumArg() const { return false; }
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000243 virtual bool isVariadic() const { return false; }
Aaron Ballman36a53502014-01-16 13:03:14 +0000244
245 virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
246 OS << getUpperName();
247 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000248 };
249
250 class SimpleArgument : public Argument {
251 std::string type;
252
253 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000254 SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000255 : Argument(Arg, Attr), type(std::move(T)) {}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000256
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000257 std::string getType() const { return type; }
258
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000259 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000260 OS << " " << type << " get" << getUpperName() << "() const {\n";
261 OS << " return " << getLowerName() << ";\n";
262 OS << " }";
263 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000264
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000265 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000266 OS << getLowerName();
267 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000268
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000269 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000270 OS << "A->get" << getUpperName() << "()";
271 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000272
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000273 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000274 OS << getLowerName() << "(" << getUpperName() << ")";
275 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000276
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000277 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000278 OS << getLowerName() << "()";
279 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000280
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000281 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000282 OS << type << " " << getUpperName();
283 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000284
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000285 void writeDeclarations(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000286 OS << type << " " << getLowerName() << ";";
287 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000288
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000289 void writePCHReadDecls(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000290 std::string read = ReadPCHRecord(type);
291 OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
292 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000293
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000294 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000295 OS << getLowerName();
296 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000297
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000298 void writePCHWrite(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000299 OS << " " << WritePCHRecord(type, "SA->get" +
300 std::string(getUpperName()) + "()");
301 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000302
Aaron Ballman48a533d2018-02-27 23:49:28 +0000303 std::string getIsOmitted() const override {
304 if (type == "IdentifierInfo *")
305 return "!get" + getUpperName().str() + "()";
Joel E. Denny81508102018-03-13 14:51:22 +0000306 if (type == "ParamIdx")
307 return "!get" + getUpperName().str() + "().isValid()";
Aaron Ballman48a533d2018-02-27 23:49:28 +0000308 return "false";
309 }
310
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000311 void writeValue(raw_ostream &OS) const override {
Aaron Ballman48a533d2018-02-27 23:49:28 +0000312 if (type == "FunctionDecl *")
Richard Smithb87c4652013-10-31 21:23:20 +0000313 OS << "\" << get" << getUpperName()
314 << "()->getNameInfo().getAsString() << \"";
Aaron Ballman48a533d2018-02-27 23:49:28 +0000315 else if (type == "IdentifierInfo *")
316 // Some non-optional (comma required) identifier arguments can be the
317 // empty string but are then recorded as a nullptr.
318 OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
319 << "()->getName() : \"\") << \"";
320 else if (type == "TypeSourceInfo *")
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000321 OS << "\" << get" << getUpperName() << "().getAsString() << \"";
Joel E. Denny81508102018-03-13 14:51:22 +0000322 else if (type == "ParamIdx")
323 OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
Aaron Ballman48a533d2018-02-27 23:49:28 +0000324 else
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000325 OS << "\" << get" << getUpperName() << "() << \"";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000326 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000327
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000328 void writeDump(raw_ostream &OS) const override {
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +0000329 if (type == "FunctionDecl *" || type == "NamedDecl *") {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000330 OS << " OS << \" \";\n";
331 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
332 } else if (type == "IdentifierInfo *") {
Aaron Ballman48a533d2018-02-27 23:49:28 +0000333 // Some non-optional (comma required) identifier arguments can be the
334 // empty string but are then recorded as a nullptr.
335 OS << " if (SA->get" << getUpperName() << "())\n"
336 << " OS << \" \" << SA->get" << getUpperName()
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000337 << "()->getName();\n";
Richard Smithb87c4652013-10-31 21:23:20 +0000338 } else if (type == "TypeSourceInfo *") {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000339 OS << " OS << \" \" << SA->get" << getUpperName()
340 << "().getAsString();\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000341 } else if (type == "bool") {
342 OS << " if (SA->get" << getUpperName() << "()) OS << \" "
343 << getUpperName() << "\";\n";
344 } else if (type == "int" || type == "unsigned") {
345 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
Joel E. Denny81508102018-03-13 14:51:22 +0000346 } else if (type == "ParamIdx") {
347 if (isOptional())
348 OS << " if (SA->get" << getUpperName() << "().isValid())\n ";
349 OS << " OS << \" \" << SA->get" << getUpperName()
350 << "().getSourceIndex();\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000351 } else {
352 llvm_unreachable("Unknown SimpleArgument type!");
353 }
354 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000355 };
356
Aaron Ballman18a78382013-11-21 00:28:23 +0000357 class DefaultSimpleArgument : public SimpleArgument {
358 int64_t Default;
359
360 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000361 DefaultSimpleArgument(const Record &Arg, StringRef Attr,
Aaron Ballman18a78382013-11-21 00:28:23 +0000362 std::string T, int64_t Default)
363 : SimpleArgument(Arg, Attr, T), Default(Default) {}
364
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000365 void writeAccessors(raw_ostream &OS) const override {
Aaron Ballman18a78382013-11-21 00:28:23 +0000366 SimpleArgument::writeAccessors(OS);
367
368 OS << "\n\n static const " << getType() << " Default" << getUpperName()
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000369 << " = ";
370 if (getType() == "bool")
371 OS << (Default != 0 ? "true" : "false");
372 else
373 OS << Default;
374 OS << ";";
Aaron Ballman18a78382013-11-21 00:28:23 +0000375 }
376 };
377
Peter Collingbournebee583f2011-10-06 13:03:08 +0000378 class StringArgument : public Argument {
379 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000380 StringArgument(const Record &Arg, StringRef Attr)
Peter Collingbournebee583f2011-10-06 13:03:08 +0000381 : Argument(Arg, Attr)
382 {}
383
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000384 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000385 OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
386 OS << " return llvm::StringRef(" << getLowerName() << ", "
387 << getLowerName() << "Length);\n";
388 OS << " }\n";
389 OS << " unsigned get" << getUpperName() << "Length() const {\n";
390 OS << " return " << getLowerName() << "Length;\n";
391 OS << " }\n";
392 OS << " void set" << getUpperName()
393 << "(ASTContext &C, llvm::StringRef S) {\n";
394 OS << " " << getLowerName() << "Length = S.size();\n";
395 OS << " this->" << getLowerName() << " = new (C, 1) char ["
396 << getLowerName() << "Length];\n";
Chandler Carruth38a45cc2015-08-04 03:53:01 +0000397 OS << " if (!S.empty())\n";
398 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
Peter Collingbournebee583f2011-10-06 13:03:08 +0000399 << getLowerName() << "Length);\n";
400 OS << " }";
401 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000402
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000403 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000404 OS << "get" << getUpperName() << "()";
405 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000406
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000407 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000408 OS << "A->get" << getUpperName() << "()";
409 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000410
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000411 void writeCtorBody(raw_ostream &OS) const override {
Chandler Carruth38a45cc2015-08-04 03:53:01 +0000412 OS << " if (!" << getUpperName() << ".empty())\n";
413 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000414 << ".data(), " << getLowerName() << "Length);\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000415 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000416
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000417 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000418 OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
419 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
420 << "Length])";
421 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000422
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000423 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Hans Wennborg59dbe862015-09-29 20:56:43 +0000424 OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000425 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000426
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000427 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000428 OS << "llvm::StringRef " << getUpperName();
429 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000430
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000431 void writeDeclarations(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000432 OS << "unsigned " << getLowerName() << "Length;\n";
433 OS << "char *" << getLowerName() << ";";
434 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000435
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000436 void writePCHReadDecls(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000437 OS << " std::string " << getLowerName()
David L. Jones267b8842017-01-24 01:04:30 +0000438 << "= Record.readString();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000439 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000440
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000441 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000442 OS << getLowerName();
443 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000444
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000445 void writePCHWrite(raw_ostream &OS) const override {
Richard Smith290d8012016-04-06 17:06:00 +0000446 OS << " Record.AddString(SA->get" << getUpperName() << "());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000447 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000448
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000449 void writeValue(raw_ostream &OS) const override {
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000450 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
451 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000452
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000453 void writeDump(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000454 OS << " OS << \" \\\"\" << SA->get" << getUpperName()
455 << "() << \"\\\"\";\n";
456 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000457 };
458
459 class AlignedArgument : public Argument {
460 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000461 AlignedArgument(const Record &Arg, StringRef Attr)
Peter Collingbournebee583f2011-10-06 13:03:08 +0000462 : Argument(Arg, Attr)
463 {}
464
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000465 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000466 OS << " bool is" << getUpperName() << "Dependent() const;\n";
467
468 OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
469
470 OS << " bool is" << getUpperName() << "Expr() const {\n";
471 OS << " return is" << getLowerName() << "Expr;\n";
472 OS << " }\n";
473
474 OS << " Expr *get" << getUpperName() << "Expr() const {\n";
475 OS << " assert(is" << getLowerName() << "Expr);\n";
476 OS << " return " << getLowerName() << "Expr;\n";
477 OS << " }\n";
478
479 OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
480 OS << " assert(!is" << getLowerName() << "Expr);\n";
481 OS << " return " << getLowerName() << "Type;\n";
482 OS << " }";
483 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000484
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000485 void writeAccessorDefinitions(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000486 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
487 << "Dependent() const {\n";
488 OS << " if (is" << getLowerName() << "Expr)\n";
489 OS << " return " << getLowerName() << "Expr && (" << getLowerName()
490 << "Expr->isValueDependent() || " << getLowerName()
491 << "Expr->isTypeDependent());\n";
492 OS << " else\n";
493 OS << " return " << getLowerName()
494 << "Type->getType()->isDependentType();\n";
495 OS << "}\n";
496
497 // FIXME: Do not do the calculation here
498 // FIXME: Handle types correctly
499 // A null pointer means maximum alignment
Peter Collingbournebee583f2011-10-06 13:03:08 +0000500 OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
501 << "(ASTContext &Ctx) const {\n";
502 OS << " assert(!is" << getUpperName() << "Dependent());\n";
503 OS << " if (is" << getLowerName() << "Expr)\n";
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +0000504 OS << " return " << getLowerName() << "Expr ? " << getLowerName()
505 << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
506 << " * Ctx.getCharWidth() : "
507 << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000508 OS << " else\n";
509 OS << " return 0; // FIXME\n";
510 OS << "}\n";
511 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000512
Richard Smithf26d5512017-08-15 22:58:45 +0000513 void writeASTVisitorTraversal(raw_ostream &OS) const override {
514 StringRef Name = getUpperName();
515 OS << " if (A->is" << Name << "Expr()) {\n"
516 << " if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n"
517 << " return false;\n"
518 << " } else if (auto *TSI = A->get" << Name << "Type()) {\n"
519 << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
520 << " return false;\n"
521 << " }\n";
522 }
523
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000524 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000525 OS << "is" << getLowerName() << "Expr, is" << getLowerName()
526 << "Expr ? static_cast<void*>(" << getLowerName()
527 << "Expr) : " << getLowerName()
528 << "Type";
529 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000530
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000531 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000532 // FIXME: move the definition in Sema::InstantiateAttrs to here.
533 // In the meantime, aligned attributes are cloned.
534 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000535
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000536 void writeCtorBody(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000537 OS << " if (is" << getLowerName() << "Expr)\n";
538 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
539 << getUpperName() << ");\n";
540 OS << " else\n";
541 OS << " " << getLowerName()
542 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000543 << ");\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000544 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000545
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000546 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000547 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
548 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000549
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000550 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000551 OS << "is" << getLowerName() << "Expr(false)";
552 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000553
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000554 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000555 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
556 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000557
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000558 void writeImplicitCtorArgs(raw_ostream &OS) const override {
Aaron Ballman36a53502014-01-16 13:03:14 +0000559 OS << "Is" << getUpperName() << "Expr, " << getUpperName();
560 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000561
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000562 void writeDeclarations(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000563 OS << "bool is" << getLowerName() << "Expr;\n";
564 OS << "union {\n";
565 OS << "Expr *" << getLowerName() << "Expr;\n";
566 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
567 OS << "};";
568 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000569
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000570 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000571 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
572 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000573
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000574 void writePCHReadDecls(raw_ostream &OS) const override {
David L. Jones267b8842017-01-24 01:04:30 +0000575 OS << " bool is" << getLowerName() << "Expr = Record.readInt();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000576 OS << " void *" << getLowerName() << "Ptr;\n";
577 OS << " if (is" << getLowerName() << "Expr)\n";
David L. Jones267b8842017-01-24 01:04:30 +0000578 OS << " " << getLowerName() << "Ptr = Record.readExpr();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000579 OS << " else\n";
580 OS << " " << getLowerName()
David L. Jones267b8842017-01-24 01:04:30 +0000581 << "Ptr = Record.getTypeSourceInfo();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000582 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000583
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000584 void writePCHWrite(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000585 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
586 OS << " if (SA->is" << getUpperName() << "Expr())\n";
Richard Smith290d8012016-04-06 17:06:00 +0000587 OS << " Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000588 OS << " else\n";
Richard Smith290d8012016-04-06 17:06:00 +0000589 OS << " Record.AddTypeSourceInfo(SA->get" << getUpperName()
590 << "Type());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000591 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000592
Aaron Ballman48a533d2018-02-27 23:49:28 +0000593 std::string getIsOmitted() const override {
594 return "!is" + getLowerName().str() + "Expr || !" + getLowerName().str()
595 + "Expr";
596 }
597
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000598 void writeValue(raw_ostream &OS) const override {
Richard Trieuddd01ce2014-06-09 22:53:25 +0000599 OS << "\";\n";
Aaron Ballman48a533d2018-02-27 23:49:28 +0000600 OS << " " << getLowerName()
601 << "Expr->printPretty(OS, nullptr, Policy);\n";
Richard Trieuddd01ce2014-06-09 22:53:25 +0000602 OS << " OS << \"";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000603 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000604
Stephen Kellydb8fac12019-01-11 19:16:01 +0000605 void writeDump(raw_ostream &OS) const override {
606 OS << " if (!SA->is" << getUpperName() << "Expr())\n";
607 OS << " dumpType(SA->get" << getUpperName()
608 << "Type()->getType());\n";
609 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000610
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000611 void writeDumpChildren(raw_ostream &OS) const override {
Richard Smithf7514452014-10-30 21:02:37 +0000612 OS << " if (SA->is" << getUpperName() << "Expr())\n";
Stephen Kelly6d110d62019-01-30 19:49:49 +0000613 OS << " Visit(SA->get" << getUpperName() << "Expr());\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000614 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000615
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000616 void writeHasChildren(raw_ostream &OS) const override {
Richard Trieude5cc7d2013-01-31 01:44:26 +0000617 OS << "SA->is" << getUpperName() << "Expr()";
618 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000619 };
620
621 class VariadicArgument : public Argument {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000622 std::string Type, ArgName, ArgSizeName, RangeName;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000623
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000624 protected:
625 // Assumed to receive a parameter: raw_ostream OS.
626 virtual void writeValueImpl(raw_ostream &OS) const {
627 OS << " OS << Val;\n";
628 }
Joel E. Denny81508102018-03-13 14:51:22 +0000629 // Assumed to receive a parameter: raw_ostream OS.
630 virtual void writeDumpImpl(raw_ostream &OS) const {
631 OS << " OS << \" \" << Val;\n";
632 }
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000633
Peter Collingbournebee583f2011-10-06 13:03:08 +0000634 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000635 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000636 : Argument(Arg, Attr), Type(std::move(T)),
637 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
638 RangeName(getLowerName()) {}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000639
Benjamin Kramer1b582012016-02-13 18:11:49 +0000640 const std::string &getType() const { return Type; }
641 const std::string &getArgName() const { return ArgName; }
642 const std::string &getArgSizeName() const { return ArgSizeName; }
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000643 bool isVariadic() const override { return true; }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000644
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000645 void writeAccessors(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000646 std::string IteratorType = getLowerName().str() + "_iterator";
647 std::string BeginFn = getLowerName().str() + "_begin()";
648 std::string EndFn = getLowerName().str() + "_end()";
649
650 OS << " typedef " << Type << "* " << IteratorType << ";\n";
651 OS << " " << IteratorType << " " << BeginFn << " const {"
652 << " return " << ArgName << "; }\n";
653 OS << " " << IteratorType << " " << EndFn << " const {"
654 << " return " << ArgName << " + " << ArgSizeName << "; }\n";
655 OS << " unsigned " << getLowerName() << "_size() const {"
656 << " return " << ArgSizeName << "; }\n";
657 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
658 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
659 << "); }\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000660 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000661
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000662 void writeCloneArgs(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000663 OS << ArgName << ", " << ArgSizeName;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000664 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000665
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000666 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000667 // This isn't elegant, but we have to go through public methods...
668 OS << "A->" << getLowerName() << "_begin(), "
669 << "A->" << getLowerName() << "_size()";
670 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000671
Richard Smithf26d5512017-08-15 22:58:45 +0000672 void writeASTVisitorTraversal(raw_ostream &OS) const override {
673 // FIXME: Traverse the elements.
674 }
675
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000676 void writeCtorBody(raw_ostream &OS) const override {
Aaron Ballmand6459e52014-05-01 15:21:03 +0000677 OS << " std::copy(" << getUpperName() << ", " << getUpperName()
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000678 << " + " << ArgSizeName << ", " << ArgName << ");\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000679 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000680
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000681 void writeCtorInitializers(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000682 OS << ArgSizeName << "(" << getUpperName() << "Size), "
683 << ArgName << "(new (Ctx, 16) " << getType() << "["
684 << ArgSizeName << "])";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000685 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000686
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000687 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000688 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000689 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000690
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000691 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000692 OS << getType() << " *" << getUpperName() << ", unsigned "
693 << getUpperName() << "Size";
694 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000695
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000696 void writeImplicitCtorArgs(raw_ostream &OS) const override {
Aaron Ballman36a53502014-01-16 13:03:14 +0000697 OS << getUpperName() << ", " << getUpperName() << "Size";
698 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000699
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000700 void writeDeclarations(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000701 OS << " unsigned " << ArgSizeName << ";\n";
702 OS << " " << getType() << " *" << ArgName << ";";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000703 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000704
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000705 void writePCHReadDecls(raw_ostream &OS) const override {
David L. Jones267b8842017-01-24 01:04:30 +0000706 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
Richard Smith19978562016-05-18 00:16:51 +0000707 OS << " SmallVector<" << getType() << ", 4> "
708 << getLowerName() << ";\n";
709 OS << " " << getLowerName() << ".reserve(" << getLowerName()
Peter Collingbournebee583f2011-10-06 13:03:08 +0000710 << "Size);\n";
Richard Smith19978562016-05-18 00:16:51 +0000711
712 // If we can't store the values in the current type (if it's something
713 // like StringRef), store them in a different type and convert the
714 // container afterwards.
715 std::string StorageType = getStorageType(getType());
716 std::string StorageName = getLowerName();
717 if (StorageType != getType()) {
718 StorageName += "Storage";
719 OS << " SmallVector<" << StorageType << ", 4> "
720 << StorageName << ";\n";
721 OS << " " << StorageName << ".reserve(" << getLowerName()
722 << "Size);\n";
723 }
724
725 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000726 std::string read = ReadPCHRecord(Type);
Richard Smith19978562016-05-18 00:16:51 +0000727 OS << " " << StorageName << ".push_back(" << read << ");\n";
728
729 if (StorageType != getType()) {
730 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
731 OS << " " << getLowerName() << ".push_back("
732 << StorageName << "[i]);\n";
733 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000734 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000735
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000736 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000737 OS << getLowerName() << ".data(), " << getLowerName() << "Size";
738 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000739
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000740 void writePCHWrite(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000741 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000742 OS << " for (auto &Val : SA->" << RangeName << "())\n";
743 OS << " " << WritePCHRecord(Type, "Val");
Peter Collingbournebee583f2011-10-06 13:03:08 +0000744 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000745
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000746 void writeValue(raw_ostream &OS) const override {
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000747 OS << "\";\n";
748 OS << " bool isFirst = true;\n"
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000749 << " for (const auto &Val : " << RangeName << "()) {\n"
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000750 << " if (isFirst) isFirst = false;\n"
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000751 << " else OS << \", \";\n";
752 writeValueImpl(OS);
753 OS << " }\n";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000754 OS << " OS << \"";
755 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000756
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000757 void writeDump(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000758 OS << " for (const auto &Val : SA->" << RangeName << "())\n";
Joel E. Denny81508102018-03-13 14:51:22 +0000759 writeDumpImpl(OS);
760 }
761 };
762
763 class VariadicParamIdxArgument : public VariadicArgument {
764 public:
765 VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
766 : VariadicArgument(Arg, Attr, "ParamIdx") {}
767
768 public:
769 void writeValueImpl(raw_ostream &OS) const override {
770 OS << " OS << Val.getSourceIndex();\n";
771 }
772
773 void writeDumpImpl(raw_ostream &OS) const override {
774 OS << " OS << \" \" << Val.getSourceIndex();\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000775 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000776 };
777
Johannes Doerfertac991bb2019-01-19 05:36:54 +0000778 struct VariadicParamOrParamIdxArgument : public VariadicArgument {
779 VariadicParamOrParamIdxArgument(const Record &Arg, StringRef Attr)
780 : VariadicArgument(Arg, Attr, "int") {}
781 };
782
Reid Klecknerf526b9482014-02-12 18:22:18 +0000783 // Unique the enums, but maintain the original declaration ordering.
Craig Topper00648582017-05-31 19:01:22 +0000784 std::vector<StringRef>
785 uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
786 std::vector<StringRef> uniques;
George Burgess IV1881a572016-12-01 00:13:18 +0000787 SmallDenseSet<StringRef, 8> unique_set;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000788 for (const auto &i : enums) {
George Burgess IV1881a572016-12-01 00:13:18 +0000789 if (unique_set.insert(i).second)
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000790 uniques.push_back(i);
Reid Klecknerf526b9482014-02-12 18:22:18 +0000791 }
792 return uniques;
793 }
794
Peter Collingbournebee583f2011-10-06 13:03:08 +0000795 class EnumArgument : public Argument {
796 std::string type;
Craig Topper00648582017-05-31 19:01:22 +0000797 std::vector<StringRef> values, enums, uniques;
798
Peter Collingbournebee583f2011-10-06 13:03:08 +0000799 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000800 EnumArgument(const Record &Arg, StringRef Attr)
Peter Collingbournebee583f2011-10-06 13:03:08 +0000801 : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
Aaron Ballman0e468c02014-01-05 21:08:29 +0000802 values(Arg.getValueAsListOfStrings("Values")),
803 enums(Arg.getValueAsListOfStrings("Enums")),
Reid Klecknerf526b9482014-02-12 18:22:18 +0000804 uniques(uniqueEnumsInOrder(enums))
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000805 {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000806 // FIXME: Emit a proper error
807 assert(!uniques.empty());
808 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000809
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000810 bool isEnumArg() const override { return true; }
Aaron Ballman682ee422013-09-11 19:47:58 +0000811
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000812 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000813 OS << " " << type << " get" << getUpperName() << "() const {\n";
814 OS << " return " << getLowerName() << ";\n";
815 OS << " }";
816 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000817
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000818 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000819 OS << getLowerName();
820 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000821
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000822 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000823 OS << "A->get" << getUpperName() << "()";
824 }
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000825 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000826 OS << getLowerName() << "(" << getUpperName() << ")";
827 }
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000828 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000829 OS << getLowerName() << "(" << type << "(0))";
830 }
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000831 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000832 OS << type << " " << getUpperName();
833 }
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000834 void writeDeclarations(raw_ostream &OS) const override {
Eugene Zelenko5f02b772015-12-08 18:49:01 +0000835 auto i = uniques.cbegin(), e = uniques.cend();
Peter Collingbournebee583f2011-10-06 13:03:08 +0000836 // The last one needs to not have a comma.
837 --e;
838
839 OS << "public:\n";
840 OS << " enum " << type << " {\n";
841 for (; i != e; ++i)
842 OS << " " << *i << ",\n";
843 OS << " " << *e << "\n";
844 OS << " };\n";
845 OS << "private:\n";
846 OS << " " << type << " " << getLowerName() << ";";
847 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000848
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000849 void writePCHReadDecls(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000850 OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
851 << "(static_cast<" << getAttrName() << "Attr::" << type
David L. Jones267b8842017-01-24 01:04:30 +0000852 << ">(Record.readInt()));\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000853 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000854
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000855 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000856 OS << getLowerName();
857 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000858
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000859 void writePCHWrite(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000860 OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
861 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000862
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000863 void writeValue(raw_ostream &OS) const override {
Aaron Ballman36d79102014-09-15 16:16:14 +0000864 // FIXME: this isn't 100% correct -- some enum arguments require printing
865 // as a string literal, while others require printing as an identifier.
866 // Tablegen currently does not distinguish between the two forms.
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000867 OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
868 << getUpperName() << "()) << \"\\\"";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000869 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000870
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000871 void writeDump(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000872 OS << " switch(SA->get" << getUpperName() << "()) {\n";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000873 for (const auto &I : uniques) {
874 OS << " case " << getAttrName() << "Attr::" << I << ":\n";
875 OS << " OS << \" " << I << "\";\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000876 OS << " break;\n";
877 }
878 OS << " }\n";
879 }
Aaron Ballman682ee422013-09-11 19:47:58 +0000880
881 void writeConversion(raw_ostream &OS) const {
882 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
883 OS << type << " &Out) {\n";
884 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000885 OS << type << ">>(Val)\n";
Aaron Ballman682ee422013-09-11 19:47:58 +0000886 for (size_t I = 0; I < enums.size(); ++I) {
887 OS << " .Case(\"" << values[I] << "\", ";
888 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
889 }
890 OS << " .Default(Optional<" << type << ">());\n";
891 OS << " if (R) {\n";
892 OS << " Out = *R;\n return true;\n }\n";
893 OS << " return false;\n";
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000894 OS << " }\n\n";
895
896 // Mapping from enumeration values back to enumeration strings isn't
897 // trivial because some enumeration values have multiple named
898 // enumerators, such as type_visibility(internal) and
899 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
900 OS << " static const char *Convert" << type << "ToStr("
901 << type << " Val) {\n"
902 << " switch(Val) {\n";
George Burgess IV1881a572016-12-01 00:13:18 +0000903 SmallDenseSet<StringRef, 8> Uniques;
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000904 for (size_t I = 0; I < enums.size(); ++I) {
905 if (Uniques.insert(enums[I]).second)
906 OS << " case " << getAttrName() << "Attr::" << enums[I]
907 << ": return \"" << values[I] << "\";\n";
908 }
909 OS << " }\n"
910 << " llvm_unreachable(\"No enumerator with that value\");\n"
911 << " }\n";
Aaron Ballman682ee422013-09-11 19:47:58 +0000912 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000913 };
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000914
915 class VariadicEnumArgument: public VariadicArgument {
916 std::string type, QualifiedTypeName;
Craig Topper00648582017-05-31 19:01:22 +0000917 std::vector<StringRef> values, enums, uniques;
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000918
919 protected:
920 void writeValueImpl(raw_ostream &OS) const override {
Aaron Ballman36d79102014-09-15 16:16:14 +0000921 // FIXME: this isn't 100% correct -- some enum arguments require printing
922 // as a string literal, while others require printing as an identifier.
923 // Tablegen currently does not distinguish between the two forms.
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000924 OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
925 << "ToStr(Val)" << "<< \"\\\"\";\n";
926 }
927
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000928 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000929 VariadicEnumArgument(const Record &Arg, StringRef Attr)
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000930 : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
931 type(Arg.getValueAsString("Type")),
Aaron Ballman0e468c02014-01-05 21:08:29 +0000932 values(Arg.getValueAsListOfStrings("Values")),
933 enums(Arg.getValueAsListOfStrings("Enums")),
Reid Klecknerf526b9482014-02-12 18:22:18 +0000934 uniques(uniqueEnumsInOrder(enums))
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000935 {
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000936 QualifiedTypeName = getAttrName().str() + "Attr::" + type;
937
938 // FIXME: Emit a proper error
939 assert(!uniques.empty());
940 }
941
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000942 bool isVariadicEnumArg() const override { return true; }
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000943
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000944 void writeDeclarations(raw_ostream &OS) const override {
Eugene Zelenko5f02b772015-12-08 18:49:01 +0000945 auto i = uniques.cbegin(), e = uniques.cend();
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000946 // The last one needs to not have a comma.
947 --e;
948
949 OS << "public:\n";
950 OS << " enum " << type << " {\n";
951 for (; i != e; ++i)
952 OS << " " << *i << ",\n";
953 OS << " " << *e << "\n";
954 OS << " };\n";
955 OS << "private:\n";
956
957 VariadicArgument::writeDeclarations(OS);
958 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000959
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000960 void writeDump(raw_ostream &OS) const override {
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000961 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
962 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
963 << getLowerName() << "_end(); I != E; ++I) {\n";
964 OS << " switch(*I) {\n";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000965 for (const auto &UI : uniques) {
966 OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
967 OS << " OS << \" " << UI << "\";\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000968 OS << " break;\n";
969 }
970 OS << " }\n";
971 OS << " }\n";
972 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000973
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000974 void writePCHReadDecls(raw_ostream &OS) const override {
David L. Jones267b8842017-01-24 01:04:30 +0000975 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000976 OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
977 << ";\n";
978 OS << " " << getLowerName() << ".reserve(" << getLowerName()
979 << "Size);\n";
980 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
981 OS << " " << getLowerName() << ".push_back(" << "static_cast<"
David L. Jones267b8842017-01-24 01:04:30 +0000982 << QualifiedTypeName << ">(Record.readInt()));\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000983 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000984
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000985 void writePCHWrite(raw_ostream &OS) const override {
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000986 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
987 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
988 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
989 << getLowerName() << "_end(); i != e; ++i)\n";
990 OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
991 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000992
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000993 void writeConversion(raw_ostream &OS) const {
994 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
995 OS << type << " &Out) {\n";
996 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000997 OS << type << ">>(Val)\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000998 for (size_t I = 0; I < enums.size(); ++I) {
999 OS << " .Case(\"" << values[I] << "\", ";
1000 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
1001 }
1002 OS << " .Default(Optional<" << type << ">());\n";
1003 OS << " if (R) {\n";
1004 OS << " Out = *R;\n return true;\n }\n";
1005 OS << " return false;\n";
Aaron Ballman25a2cb92014-09-15 15:14:13 +00001006 OS << " }\n\n";
1007
1008 OS << " static const char *Convert" << type << "ToStr("
1009 << type << " Val) {\n"
1010 << " switch(Val) {\n";
George Burgess IV1881a572016-12-01 00:13:18 +00001011 SmallDenseSet<StringRef, 8> Uniques;
Aaron Ballman25a2cb92014-09-15 15:14:13 +00001012 for (size_t I = 0; I < enums.size(); ++I) {
1013 if (Uniques.insert(enums[I]).second)
1014 OS << " case " << getAttrName() << "Attr::" << enums[I]
1015 << ": return \"" << values[I] << "\";\n";
1016 }
1017 OS << " }\n"
1018 << " llvm_unreachable(\"No enumerator with that value\");\n"
1019 << " }\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001020 }
1021 };
Peter Collingbournebee583f2011-10-06 13:03:08 +00001022
1023 class VersionArgument : public Argument {
1024 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +00001025 VersionArgument(const Record &Arg, StringRef Attr)
Peter Collingbournebee583f2011-10-06 13:03:08 +00001026 : Argument(Arg, Attr)
1027 {}
1028
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001029 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001030 OS << " VersionTuple get" << getUpperName() << "() const {\n";
1031 OS << " return " << getLowerName() << ";\n";
1032 OS << " }\n";
1033 OS << " void set" << getUpperName()
1034 << "(ASTContext &C, VersionTuple V) {\n";
1035 OS << " " << getLowerName() << " = V;\n";
1036 OS << " }";
1037 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001038
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001039 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001040 OS << "get" << getUpperName() << "()";
1041 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001042
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001043 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001044 OS << "A->get" << getUpperName() << "()";
1045 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001046
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001047 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001048 OS << getLowerName() << "(" << getUpperName() << ")";
1049 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001050
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001051 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballman8ee40b72013-09-09 23:33:17 +00001052 OS << getLowerName() << "()";
1053 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001054
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001055 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001056 OS << "VersionTuple " << getUpperName();
1057 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001058
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001059 void writeDeclarations(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001060 OS << "VersionTuple " << getLowerName() << ";\n";
1061 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001062
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001063 void writePCHReadDecls(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001064 OS << " VersionTuple " << getLowerName()
David L. Jones267b8842017-01-24 01:04:30 +00001065 << "= Record.readVersionTuple();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001066 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001067
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001068 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001069 OS << getLowerName();
1070 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001071
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001072 void writePCHWrite(raw_ostream &OS) const override {
Richard Smith290d8012016-04-06 17:06:00 +00001073 OS << " Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001074 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001075
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001076 void writeValue(raw_ostream &OS) const override {
Douglas Gregor49ccfaa2011-11-19 19:22:57 +00001077 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1078 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001079
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001080 void writeDump(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001081 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
1082 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001083 };
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001084
1085 class ExprArgument : public SimpleArgument {
1086 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +00001087 ExprArgument(const Record &Arg, StringRef Attr)
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001088 : SimpleArgument(Arg, Attr, "Expr *")
1089 {}
1090
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001091 void writeASTVisitorTraversal(raw_ostream &OS) const override {
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00001092 OS << " if (!"
1093 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1094 OS << " return false;\n";
1095 }
1096
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001097 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001098 OS << "tempInst" << getUpperName();
1099 }
1100
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001101 void writeTemplateInstantiation(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001102 OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
1103 OS << " {\n";
1104 OS << " EnterExpressionEvaluationContext "
Faisal Valid143a0c2017-04-01 21:30:49 +00001105 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001106 OS << " ExprResult " << "Result = S.SubstExpr("
1107 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1108 OS << " tempInst" << getUpperName() << " = "
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001109 << "Result.getAs<Expr>();\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001110 OS << " }\n";
1111 }
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001112
Craig Topper3164f332014-03-11 03:39:26 +00001113 void writeDump(raw_ostream &OS) const override {}
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001114
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001115 void writeDumpChildren(raw_ostream &OS) const override {
Stephen Kelly6d110d62019-01-30 19:49:49 +00001116 OS << " Visit(SA->get" << getUpperName() << "());\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001117 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001118
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001119 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001120 };
1121
1122 class VariadicExprArgument : public VariadicArgument {
1123 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +00001124 VariadicExprArgument(const Record &Arg, StringRef Attr)
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001125 : VariadicArgument(Arg, Attr, "Expr *")
1126 {}
1127
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001128 void writeASTVisitorTraversal(raw_ostream &OS) const override {
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00001129 OS << " {\n";
1130 OS << " " << getType() << " *I = A->" << getLowerName()
1131 << "_begin();\n";
1132 OS << " " << getType() << " *E = A->" << getLowerName()
1133 << "_end();\n";
1134 OS << " for (; I != E; ++I) {\n";
1135 OS << " if (!getDerived().TraverseStmt(*I))\n";
1136 OS << " return false;\n";
1137 OS << " }\n";
1138 OS << " }\n";
1139 }
1140
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001141 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001142 OS << "tempInst" << getUpperName() << ", "
1143 << "A->" << getLowerName() << "_size()";
1144 }
1145
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001146 void writeTemplateInstantiation(raw_ostream &OS) const override {
Eugene Zelenko5f02b772015-12-08 18:49:01 +00001147 OS << " auto *tempInst" << getUpperName()
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001148 << " = new (C, 16) " << getType()
1149 << "[A->" << getLowerName() << "_size()];\n";
1150 OS << " {\n";
1151 OS << " EnterExpressionEvaluationContext "
Faisal Valid143a0c2017-04-01 21:30:49 +00001152 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001153 OS << " " << getType() << " *TI = tempInst" << getUpperName()
1154 << ";\n";
1155 OS << " " << getType() << " *I = A->" << getLowerName()
1156 << "_begin();\n";
1157 OS << " " << getType() << " *E = A->" << getLowerName()
1158 << "_end();\n";
1159 OS << " for (; I != E; ++I, ++TI) {\n";
1160 OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001161 OS << " *TI = Result.getAs<Expr>();\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001162 OS << " }\n";
1163 OS << " }\n";
1164 }
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001165
Craig Topper3164f332014-03-11 03:39:26 +00001166 void writeDump(raw_ostream &OS) const override {}
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001167
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001168 void writeDumpChildren(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001169 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1170 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
Richard Smithf7514452014-10-30 21:02:37 +00001171 << getLowerName() << "_end(); I != E; ++I)\n";
Stephen Kelly6d110d62019-01-30 19:49:49 +00001172 OS << " Visit(*I);\n";
Richard Trieude5cc7d2013-01-31 01:44:26 +00001173 }
1174
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001175 void writeHasChildren(raw_ostream &OS) const override {
Richard Trieude5cc7d2013-01-31 01:44:26 +00001176 OS << "SA->" << getLowerName() << "_begin() != "
1177 << "SA->" << getLowerName() << "_end()";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001178 }
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001179 };
Richard Smithb87c4652013-10-31 21:23:20 +00001180
Erich Keane3efe0022018-07-20 14:13:28 +00001181 class VariadicIdentifierArgument : public VariadicArgument {
1182 public:
1183 VariadicIdentifierArgument(const Record &Arg, StringRef Attr)
1184 : VariadicArgument(Arg, Attr, "IdentifierInfo *")
1185 {}
1186 };
1187
Peter Collingbourne915df992015-05-15 18:33:32 +00001188 class VariadicStringArgument : public VariadicArgument {
1189 public:
1190 VariadicStringArgument(const Record &Arg, StringRef Attr)
Benjamin Kramer1b582012016-02-13 18:11:49 +00001191 : VariadicArgument(Arg, Attr, "StringRef")
Peter Collingbourne915df992015-05-15 18:33:32 +00001192 {}
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001193
Benjamin Kramer1b582012016-02-13 18:11:49 +00001194 void writeCtorBody(raw_ostream &OS) const override {
1195 OS << " for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1196 " ++I) {\n"
1197 " StringRef Ref = " << getUpperName() << "[I];\n"
1198 " if (!Ref.empty()) {\n"
1199 " char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1200 " std::memcpy(Mem, Ref.data(), Ref.size());\n"
1201 " " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1202 " }\n"
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001203 " }\n";
Benjamin Kramer1b582012016-02-13 18:11:49 +00001204 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001205
Peter Collingbourne915df992015-05-15 18:33:32 +00001206 void writeValueImpl(raw_ostream &OS) const override {
1207 OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
1208 }
1209 };
1210
Richard Smithb87c4652013-10-31 21:23:20 +00001211 class TypeArgument : public SimpleArgument {
1212 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +00001213 TypeArgument(const Record &Arg, StringRef Attr)
Richard Smithb87c4652013-10-31 21:23:20 +00001214 : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1215 {}
1216
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001217 void writeAccessors(raw_ostream &OS) const override {
Richard Smithb87c4652013-10-31 21:23:20 +00001218 OS << " QualType get" << getUpperName() << "() const {\n";
1219 OS << " return " << getLowerName() << "->getType();\n";
1220 OS << " }";
1221 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1222 OS << " return " << getLowerName() << ";\n";
1223 OS << " }";
1224 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001225
Richard Smithf26d5512017-08-15 22:58:45 +00001226 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1227 OS << " if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
1228 OS << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
1229 OS << " return false;\n";
1230 }
1231
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001232 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
Richard Smithb87c4652013-10-31 21:23:20 +00001233 OS << "A->get" << getUpperName() << "Loc()";
1234 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001235
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001236 void writePCHWrite(raw_ostream &OS) const override {
Richard Smithb87c4652013-10-31 21:23:20 +00001237 OS << " " << WritePCHRecord(
1238 getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
1239 }
1240 };
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001241
Hans Wennborgdcfba332015-10-06 23:40:43 +00001242} // end anonymous namespace
Peter Collingbournebee583f2011-10-06 13:03:08 +00001243
Aaron Ballman2f22b942014-05-20 19:47:14 +00001244static std::unique_ptr<Argument>
1245createArgument(const Record &Arg, StringRef Attr,
1246 const Record *Search = nullptr) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001247 if (!Search)
1248 Search = &Arg;
1249
David Blaikie28f30ca2014-08-08 23:59:38 +00001250 std::unique_ptr<Argument> Ptr;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001251 llvm::StringRef ArgName = Search->getName();
1252
David Blaikie28f30ca2014-08-08 23:59:38 +00001253 if (ArgName == "AlignedArgument")
1254 Ptr = llvm::make_unique<AlignedArgument>(Arg, Attr);
1255 else if (ArgName == "EnumArgument")
1256 Ptr = llvm::make_unique<EnumArgument>(Arg, Attr);
1257 else if (ArgName == "ExprArgument")
1258 Ptr = llvm::make_unique<ExprArgument>(Arg, Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001259 else if (ArgName == "FunctionArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001260 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *");
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00001261 else if (ArgName == "NamedArgument")
1262 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "NamedDecl *");
Peter Collingbournebee583f2011-10-06 13:03:08 +00001263 else if (ArgName == "IdentifierArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001264 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
David Majnemer4bb09802014-02-10 19:50:15 +00001265 else if (ArgName == "DefaultBoolArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001266 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1267 Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1268 else if (ArgName == "BoolArgument")
1269 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "bool");
Aaron Ballman18a78382013-11-21 00:28:23 +00001270 else if (ArgName == "DefaultIntArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001271 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1272 Arg, Attr, "int", Arg.getValueAsInt("Default"));
1273 else if (ArgName == "IntArgument")
1274 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "int");
1275 else if (ArgName == "StringArgument")
1276 Ptr = llvm::make_unique<StringArgument>(Arg, Attr);
1277 else if (ArgName == "TypeArgument")
1278 Ptr = llvm::make_unique<TypeArgument>(Arg, Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001279 else if (ArgName == "UnsignedArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001280 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
Peter Collingbournebee583f2011-10-06 13:03:08 +00001281 else if (ArgName == "VariadicUnsignedArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001282 Ptr = llvm::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
Peter Collingbourne915df992015-05-15 18:33:32 +00001283 else if (ArgName == "VariadicStringArgument")
1284 Ptr = llvm::make_unique<VariadicStringArgument>(Arg, Attr);
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001285 else if (ArgName == "VariadicEnumArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001286 Ptr = llvm::make_unique<VariadicEnumArgument>(Arg, Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001287 else if (ArgName == "VariadicExprArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001288 Ptr = llvm::make_unique<VariadicExprArgument>(Arg, Attr);
Joel E. Denny81508102018-03-13 14:51:22 +00001289 else if (ArgName == "VariadicParamIdxArgument")
1290 Ptr = llvm::make_unique<VariadicParamIdxArgument>(Arg, Attr);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00001291 else if (ArgName == "VariadicParamOrParamIdxArgument")
1292 Ptr = llvm::make_unique<VariadicParamOrParamIdxArgument>(Arg, Attr);
Joel E. Denny81508102018-03-13 14:51:22 +00001293 else if (ArgName == "ParamIdxArgument")
1294 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "ParamIdx");
Erich Keane3efe0022018-07-20 14:13:28 +00001295 else if (ArgName == "VariadicIdentifierArgument")
1296 Ptr = llvm::make_unique<VariadicIdentifierArgument>(Arg, Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001297 else if (ArgName == "VersionArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001298 Ptr = llvm::make_unique<VersionArgument>(Arg, Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001299
1300 if (!Ptr) {
Aaron Ballman18a78382013-11-21 00:28:23 +00001301 // Search in reverse order so that the most-derived type is handled first.
Craig Topper25761242016-01-18 19:52:54 +00001302 ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
David Majnemerf7e36092016-06-23 00:15:04 +00001303 for (const auto &Base : llvm::reverse(Bases)) {
Craig Topper25761242016-01-18 19:52:54 +00001304 if ((Ptr = createArgument(Arg, Attr, Base.first)))
Peter Collingbournebee583f2011-10-06 13:03:08 +00001305 break;
1306 }
1307 }
Aaron Ballman8ee40b72013-09-09 23:33:17 +00001308
1309 if (Ptr && Arg.getValueAsBit("Optional"))
1310 Ptr->setOptional(true);
1311
John McCalla62c1a92015-10-28 00:17:34 +00001312 if (Ptr && Arg.getValueAsBit("Fake"))
1313 Ptr->setFake(true);
1314
David Blaikie28f30ca2014-08-08 23:59:38 +00001315 return Ptr;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001316}
1317
Douglas Gregor49ccfaa2011-11-19 19:22:57 +00001318static void writeAvailabilityValue(raw_ostream &OS) {
1319 OS << "\" << getPlatform()->getName();\n"
Manman Ren42e09eb2016-03-10 23:54:12 +00001320 << " if (getStrict()) OS << \", strict\";\n"
Douglas Gregor49ccfaa2011-11-19 19:22:57 +00001321 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1322 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1323 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1324 << " if (getUnavailable()) OS << \", unavailable\";\n"
1325 << " OS << \"";
1326}
1327
Manman Renc7890fe2016-03-16 18:50:49 +00001328static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
1329 OS << "\\\"\" << getMessage() << \"\\\"\";\n";
1330 // Only GNU deprecated has an optional fixit argument at the second position.
1331 if (Variety == "GNU")
1332 OS << " if (!getReplacement().empty()) OS << \", \\\"\""
1333 " << getReplacement() << \"\\\"\";\n";
1334 OS << " OS << \"";
1335}
1336
Aaron Ballman3e424b52013-12-26 18:30:57 +00001337static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001338 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Aaron Ballman3e424b52013-12-26 18:30:57 +00001339
1340 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1341 if (Spellings.empty()) {
1342 OS << " return \"(No spelling)\";\n}\n\n";
1343 return;
1344 }
1345
1346 OS << " switch (SpellingListIndex) {\n"
1347 " default:\n"
1348 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1349 " return \"(No spelling)\";\n";
1350
1351 for (unsigned I = 0; I < Spellings.size(); ++I)
1352 OS << " case " << I << ":\n"
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001353 " return \"" << Spellings[I].name() << "\";\n";
Aaron Ballman3e424b52013-12-26 18:30:57 +00001354 // End of the switch statement.
1355 OS << " }\n";
1356 // End of the getSpelling function.
1357 OS << "}\n\n";
1358}
1359
Aaron Ballman8f1439b2014-03-05 16:49:55 +00001360static void
1361writePrettyPrintFunction(Record &R,
1362 const std::vector<std::unique_ptr<Argument>> &Args,
1363 raw_ostream &OS) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001364 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Michael Han99315932013-01-24 16:46:58 +00001365
1366 OS << "void " << R.getName() << "Attr::printPretty("
1367 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1368
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001369 if (Spellings.empty()) {
Michael Han99315932013-01-24 16:46:58 +00001370 OS << "}\n\n";
1371 return;
1372 }
1373
1374 OS <<
1375 " switch (SpellingListIndex) {\n"
1376 " default:\n"
1377 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1378 " break;\n";
1379
1380 for (unsigned I = 0; I < Spellings.size(); ++ I) {
1381 llvm::SmallString<16> Prefix;
1382 llvm::SmallString<8> Suffix;
1383 // The actual spelling of the name and namespace (if applicable)
1384 // of an attribute without considering prefix and suffix.
1385 llvm::SmallString<64> Spelling;
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001386 std::string Name = Spellings[I].name();
1387 std::string Variety = Spellings[I].variety();
Michael Han99315932013-01-24 16:46:58 +00001388
1389 if (Variety == "GNU") {
1390 Prefix = " __attribute__((";
1391 Suffix = "))";
Aaron Ballman606093a2017-10-15 15:01:42 +00001392 } else if (Variety == "CXX11" || Variety == "C2x") {
Michael Han99315932013-01-24 16:46:58 +00001393 Prefix = " [[";
1394 Suffix = "]]";
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001395 std::string Namespace = Spellings[I].nameSpace();
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001396 if (!Namespace.empty()) {
Michael Han99315932013-01-24 16:46:58 +00001397 Spelling += Namespace;
1398 Spelling += "::";
1399 }
1400 } else if (Variety == "Declspec") {
1401 Prefix = " __declspec(";
1402 Suffix = ")";
Nico Weber20e08042016-09-03 02:55:10 +00001403 } else if (Variety == "Microsoft") {
1404 Prefix = "[";
1405 Suffix = "]";
Richard Smith0cdcc982013-01-29 01:24:26 +00001406 } else if (Variety == "Keyword") {
1407 Prefix = " ";
1408 Suffix = "";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001409 } else if (Variety == "Pragma") {
1410 Prefix = "#pragma ";
1411 Suffix = "\n";
1412 std::string Namespace = Spellings[I].nameSpace();
1413 if (!Namespace.empty()) {
1414 Spelling += Namespace;
1415 Spelling += " ";
1416 }
Michael Han99315932013-01-24 16:46:58 +00001417 } else {
Richard Smith0cdcc982013-01-29 01:24:26 +00001418 llvm_unreachable("Unknown attribute syntax variety!");
Michael Han99315932013-01-24 16:46:58 +00001419 }
1420
1421 Spelling += Name;
1422
1423 OS <<
1424 " case " << I << " : {\n"
Yaron Keren09fb7c62015-03-10 07:33:23 +00001425 " OS << \"" << Prefix << Spelling;
Michael Han99315932013-01-24 16:46:58 +00001426
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001427 if (Variety == "Pragma") {
Alexey Bataevcbecfdf2018-02-14 17:38:47 +00001428 OS << "\";\n";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001429 OS << " printPrettyPragma(OS, Policy);\n";
Alexey Bataev6d455322015-10-12 06:59:48 +00001430 OS << " OS << \"\\n\";";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001431 OS << " break;\n";
1432 OS << " }\n";
1433 continue;
1434 }
1435
Michael Han99315932013-01-24 16:46:58 +00001436 if (Spelling == "availability") {
Aaron Ballman48a533d2018-02-27 23:49:28 +00001437 OS << "(";
Michael Han99315932013-01-24 16:46:58 +00001438 writeAvailabilityValue(OS);
Aaron Ballman48a533d2018-02-27 23:49:28 +00001439 OS << ")";
Manman Renc7890fe2016-03-16 18:50:49 +00001440 } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
Aaron Ballman48a533d2018-02-27 23:49:28 +00001441 OS << "(";
1442 writeDeprecatedAttrValue(OS, Variety);
1443 OS << ")";
Michael Han99315932013-01-24 16:46:58 +00001444 } else {
Aaron Ballman48a533d2018-02-27 23:49:28 +00001445 // To avoid printing parentheses around an empty argument list or
1446 // printing spurious commas at the end of an argument list, we need to
1447 // determine where the last provided non-fake argument is.
1448 unsigned NonFakeArgs = 0;
1449 unsigned TrailingOptArgs = 0;
1450 bool FoundNonOptArg = false;
1451 for (const auto &arg : llvm::reverse(Args)) {
1452 if (arg->isFake())
1453 continue;
1454 ++NonFakeArgs;
1455 if (FoundNonOptArg)
1456 continue;
1457 // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
1458 // any way to detect whether the argument was omitted.
1459 if (!arg->isOptional() || arg->getIsOmitted() == "false") {
1460 FoundNonOptArg = true;
1461 continue;
1462 }
1463 if (!TrailingOptArgs++)
1464 OS << "\";\n"
1465 << " unsigned TrailingOmittedArgs = 0;\n";
1466 OS << " if (" << arg->getIsOmitted() << ")\n"
1467 << " ++TrailingOmittedArgs;\n";
Michael Han99315932013-01-24 16:46:58 +00001468 }
Aaron Ballman48a533d2018-02-27 23:49:28 +00001469 if (TrailingOptArgs)
1470 OS << " OS << \"";
1471 if (TrailingOptArgs < NonFakeArgs)
1472 OS << "(";
1473 else if (TrailingOptArgs)
1474 OS << "\";\n"
1475 << " if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
1476 << " OS << \"(\";\n"
1477 << " OS << \"";
1478 unsigned ArgIndex = 0;
1479 for (const auto &arg : Args) {
1480 if (arg->isFake())
1481 continue;
1482 if (ArgIndex) {
1483 if (ArgIndex >= NonFakeArgs - TrailingOptArgs)
1484 OS << "\";\n"
1485 << " if (" << ArgIndex << " < " << NonFakeArgs
1486 << " - TrailingOmittedArgs)\n"
1487 << " OS << \", \";\n"
1488 << " OS << \"";
1489 else
1490 OS << ", ";
1491 }
1492 std::string IsOmitted = arg->getIsOmitted();
1493 if (arg->isOptional() && IsOmitted != "false")
1494 OS << "\";\n"
1495 << " if (!(" << IsOmitted << ")) {\n"
1496 << " OS << \"";
1497 arg->writeValue(OS);
1498 if (arg->isOptional() && IsOmitted != "false")
1499 OS << "\";\n"
1500 << " }\n"
1501 << " OS << \"";
1502 ++ArgIndex;
1503 }
1504 if (TrailingOptArgs < NonFakeArgs)
1505 OS << ")";
1506 else if (TrailingOptArgs)
1507 OS << "\";\n"
1508 << " if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
1509 << " OS << \")\";\n"
1510 << " OS << \"";
Michael Han99315932013-01-24 16:46:58 +00001511 }
1512
Yaron Keren09fb7c62015-03-10 07:33:23 +00001513 OS << Suffix + "\";\n";
Michael Han99315932013-01-24 16:46:58 +00001514
1515 OS <<
1516 " break;\n"
1517 " }\n";
1518 }
1519
1520 // End of the switch statement.
1521 OS << "}\n";
1522 // End of the print function.
1523 OS << "}\n\n";
1524}
1525
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001526/// Return the index of a spelling in a spelling list.
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001527static unsigned
1528getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1529 const FlattenedSpelling &Spelling) {
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00001530 assert(!SpellingList.empty() && "Spelling list is empty!");
Michael Hanaf02bbe2013-02-01 01:19:17 +00001531
1532 for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001533 const FlattenedSpelling &S = SpellingList[Index];
1534 if (S.variety() != Spelling.variety())
Michael Hanaf02bbe2013-02-01 01:19:17 +00001535 continue;
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001536 if (S.nameSpace() != Spelling.nameSpace())
Michael Hanaf02bbe2013-02-01 01:19:17 +00001537 continue;
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001538 if (S.name() != Spelling.name())
Michael Hanaf02bbe2013-02-01 01:19:17 +00001539 continue;
1540
1541 return Index;
1542 }
1543
1544 llvm_unreachable("Unknown spelling!");
1545}
1546
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001547static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
Michael Hanaf02bbe2013-02-01 01:19:17 +00001548 std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
George Burgess IV1881a572016-12-01 00:13:18 +00001549 if (Accessors.empty())
1550 return;
1551
1552 const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1553 assert(!SpellingList.empty() &&
1554 "Attribute with empty spelling list can't have accessors!");
Aaron Ballman2f22b942014-05-20 19:47:14 +00001555 for (const auto *Accessor : Accessors) {
Erich Keane3bff4142017-10-16 23:25:24 +00001556 const StringRef Name = Accessor->getValueAsString("Name");
George Burgess IV1881a572016-12-01 00:13:18 +00001557 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
Michael Hanaf02bbe2013-02-01 01:19:17 +00001558
1559 OS << " bool " << Name << "() const { return SpellingListIndex == ";
1560 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001561 OS << getSpellingListIndex(SpellingList, Spellings[Index]);
George Burgess IV1881a572016-12-01 00:13:18 +00001562 if (Index != Spellings.size() - 1)
Michael Hanaf02bbe2013-02-01 01:19:17 +00001563 OS << " ||\n SpellingListIndex == ";
1564 else
1565 OS << "; }\n";
1566 }
1567 }
1568}
1569
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001570static bool
1571SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
Aaron Ballman36a53502014-01-16 13:03:14 +00001572 assert(!Spellings.empty() && "An empty list of spellings was provided");
1573 std::string FirstName = NormalizeNameForSpellingComparison(
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001574 Spellings.front().name());
Aaron Ballman2f22b942014-05-20 19:47:14 +00001575 for (const auto &Spelling :
1576 llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
1577 std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
Aaron Ballman36a53502014-01-16 13:03:14 +00001578 if (Name != FirstName)
1579 return false;
1580 }
1581 return true;
1582}
1583
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001584typedef std::map<unsigned, std::string> SemanticSpellingMap;
1585static std::string
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001586CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001587 SemanticSpellingMap &Map) {
1588 // The enumerants are automatically generated based on the variety,
1589 // namespace (if present) and name for each attribute spelling. However,
1590 // care is taken to avoid trampling on the reserved namespace due to
1591 // underscores.
1592 std::string Ret(" enum Spelling {\n");
1593 std::set<std::string> Uniques;
1594 unsigned Idx = 0;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001595 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001596 const FlattenedSpelling &S = *I;
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00001597 const std::string &Variety = S.variety();
1598 const std::string &Spelling = S.name();
1599 const std::string &Namespace = S.nameSpace();
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001600 std::string EnumName;
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001601
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001602 EnumName += (Variety + "_");
1603 if (!Namespace.empty())
1604 EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1605 "_");
1606 EnumName += NormalizeNameForSpellingComparison(Spelling);
1607
1608 // Even if the name is not unique, this spelling index corresponds to a
1609 // particular enumerant name that we've calculated.
1610 Map[Idx] = EnumName;
1611
1612 // Since we have been stripping underscores to avoid trampling on the
1613 // reserved namespace, we may have inadvertently created duplicate
1614 // enumerant names. These duplicates are not considered part of the
1615 // semantic spelling, and can be elided.
1616 if (Uniques.find(EnumName) != Uniques.end())
1617 continue;
1618
1619 Uniques.insert(EnumName);
1620 if (I != Spellings.begin())
1621 Ret += ",\n";
Aaron Ballman9bf6b752015-03-10 17:19:18 +00001622 // Duplicate spellings are not considered part of the semantic spelling
1623 // enumeration, but the spelling index and semantic spelling values are
1624 // meant to be equivalent, so we must specify a concrete value for each
1625 // enumerator.
1626 Ret += " " + EnumName + " = " + llvm::utostr(Idx);
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001627 }
1628 Ret += "\n };\n\n";
1629 return Ret;
1630}
1631
1632void WriteSemanticSpellingSwitch(const std::string &VarName,
1633 const SemanticSpellingMap &Map,
1634 raw_ostream &OS) {
1635 OS << " switch (" << VarName << ") {\n default: "
1636 << "llvm_unreachable(\"Unknown spelling list index\");\n";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001637 for (const auto &I : Map)
1638 OS << " case " << I.first << ": return " << I.second << ";\n";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001639 OS << " }\n";
1640}
1641
Aaron Ballman35db2b32014-01-29 22:13:45 +00001642// Emits the LateParsed property for attributes.
1643static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1644 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1645 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1646
Aaron Ballman2f22b942014-05-20 19:47:14 +00001647 for (const auto *Attr : Attrs) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001648 bool LateParsed = Attr->getValueAsBit("LateParsed");
Aaron Ballman35db2b32014-01-29 22:13:45 +00001649
1650 if (LateParsed) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001651 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
Aaron Ballman35db2b32014-01-29 22:13:45 +00001652
1653 // FIXME: Handle non-GNU attributes
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001654 for (const auto &I : Spellings) {
1655 if (I.variety() != "GNU")
Aaron Ballman35db2b32014-01-29 22:13:45 +00001656 continue;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001657 OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
Aaron Ballman35db2b32014-01-29 22:13:45 +00001658 }
1659 }
1660 }
1661 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1662}
1663
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001664static bool hasGNUorCXX11Spelling(const Record &Attribute) {
1665 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
1666 for (const auto &I : Spellings) {
1667 if (I.variety() == "GNU" || I.variety() == "CXX11")
1668 return true;
1669 }
1670 return false;
1671}
1672
1673namespace {
1674
1675struct AttributeSubjectMatchRule {
1676 const Record *MetaSubject;
1677 const Record *Constraint;
1678
1679 AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
1680 : MetaSubject(MetaSubject), Constraint(Constraint) {
1681 assert(MetaSubject && "Missing subject");
1682 }
1683
1684 bool isSubRule() const { return Constraint != nullptr; }
1685
1686 std::vector<Record *> getSubjects() const {
1687 return (Constraint ? Constraint : MetaSubject)
1688 ->getValueAsListOfDefs("Subjects");
1689 }
1690
1691 std::vector<Record *> getLangOpts() const {
1692 if (Constraint) {
1693 // Lookup the options in the sub-rule first, in case the sub-rule
1694 // overrides the rules options.
1695 std::vector<Record *> Opts = Constraint->getValueAsListOfDefs("LangOpts");
1696 if (!Opts.empty())
1697 return Opts;
1698 }
1699 return MetaSubject->getValueAsListOfDefs("LangOpts");
1700 }
1701
1702 // Abstract rules are used only for sub-rules
1703 bool isAbstractRule() const { return getSubjects().empty(); }
1704
Erich Keane3bff4142017-10-16 23:25:24 +00001705 StringRef getName() const {
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001706 return (Constraint ? Constraint : MetaSubject)->getValueAsString("Name");
1707 }
1708
1709 bool isNegatedSubRule() const {
1710 assert(isSubRule() && "Not a sub-rule");
1711 return Constraint->getValueAsBit("Negated");
1712 }
1713
1714 std::string getSpelling() const {
1715 std::string Result = MetaSubject->getValueAsString("Name");
1716 if (isSubRule()) {
1717 Result += '(';
1718 if (isNegatedSubRule())
1719 Result += "unless(";
1720 Result += getName();
1721 if (isNegatedSubRule())
1722 Result += ')';
1723 Result += ')';
1724 }
1725 return Result;
1726 }
1727
1728 std::string getEnumValueName() const {
Craig Topper00648582017-05-31 19:01:22 +00001729 SmallString<128> Result;
1730 Result += "SubjectMatchRule_";
1731 Result += MetaSubject->getValueAsString("Name");
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001732 if (isSubRule()) {
1733 Result += "_";
1734 if (isNegatedSubRule())
1735 Result += "not_";
1736 Result += Constraint->getValueAsString("Name");
1737 }
1738 if (isAbstractRule())
1739 Result += "_abstract";
Craig Topper00648582017-05-31 19:01:22 +00001740 return Result.str();
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001741 }
1742
1743 std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
1744
1745 static const char *EnumName;
1746};
1747
1748const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";
1749
1750struct PragmaClangAttributeSupport {
1751 std::vector<AttributeSubjectMatchRule> Rules;
Alex Lorenz24952fb2017-04-19 15:52:11 +00001752
1753 class RuleOrAggregateRuleSet {
1754 std::vector<AttributeSubjectMatchRule> Rules;
1755 bool IsRule;
1756 RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
1757 bool IsRule)
1758 : Rules(Rules), IsRule(IsRule) {}
1759
1760 public:
1761 bool isRule() const { return IsRule; }
1762
1763 const AttributeSubjectMatchRule &getRule() const {
1764 assert(IsRule && "not a rule!");
1765 return Rules[0];
1766 }
1767
1768 ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
1769 return Rules;
1770 }
1771
1772 static RuleOrAggregateRuleSet
1773 getRule(const AttributeSubjectMatchRule &Rule) {
1774 return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
1775 }
1776 static RuleOrAggregateRuleSet
1777 getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
1778 return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
1779 }
1780 };
1781 llvm::DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001782
1783 PragmaClangAttributeSupport(RecordKeeper &Records);
1784
1785 bool isAttributedSupported(const Record &Attribute);
1786
1787 void emitMatchRuleList(raw_ostream &OS);
1788
1789 std::string generateStrictConformsTo(const Record &Attr, raw_ostream &OS);
1790
1791 void generateParsingHelpers(raw_ostream &OS);
1792};
1793
1794} // end anonymous namespace
1795
Alex Lorenz24952fb2017-04-19 15:52:11 +00001796static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
1797 const Record *CurrentBase = D->getValueAsDef("Base");
1798 if (!CurrentBase)
1799 return false;
1800 if (CurrentBase == Base)
1801 return true;
1802 return doesDeclDeriveFrom(CurrentBase, Base);
1803}
1804
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001805PragmaClangAttributeSupport::PragmaClangAttributeSupport(
1806 RecordKeeper &Records) {
1807 std::vector<Record *> MetaSubjects =
1808 Records.getAllDerivedDefinitions("AttrSubjectMatcherRule");
1809 auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
1810 const Record *MetaSubject,
Saleem Abdulrasoolbe4773c2017-05-01 00:26:59 +00001811 const Record *Constraint) {
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001812 Rules.emplace_back(MetaSubject, Constraint);
1813 std::vector<Record *> ApplicableSubjects =
1814 SubjectContainer->getValueAsListOfDefs("Subjects");
1815 for (const auto *Subject : ApplicableSubjects) {
1816 bool Inserted =
Alex Lorenz24952fb2017-04-19 15:52:11 +00001817 SubjectsToRules
1818 .try_emplace(Subject, RuleOrAggregateRuleSet::getRule(
1819 AttributeSubjectMatchRule(MetaSubject,
1820 Constraint)))
1821 .second;
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001822 if (!Inserted) {
1823 PrintFatalError("Attribute subject match rules should not represent"
1824 "same attribute subjects.");
1825 }
1826 }
1827 };
1828 for (const auto *MetaSubject : MetaSubjects) {
Saleem Abdulrasoolbe4773c2017-05-01 00:26:59 +00001829 MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001830 std::vector<Record *> Constraints =
1831 MetaSubject->getValueAsListOfDefs("Constraints");
1832 for (const auto *Constraint : Constraints)
1833 MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
1834 }
Alex Lorenz24952fb2017-04-19 15:52:11 +00001835
1836 std::vector<Record *> Aggregates =
1837 Records.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule");
1838 std::vector<Record *> DeclNodes = Records.getAllDerivedDefinitions("DDecl");
1839 for (const auto *Aggregate : Aggregates) {
1840 Record *SubjectDecl = Aggregate->getValueAsDef("Subject");
1841
1842 // Gather sub-classes of the aggregate subject that act as attribute
1843 // subject rules.
1844 std::vector<AttributeSubjectMatchRule> Rules;
1845 for (const auto *D : DeclNodes) {
1846 if (doesDeclDeriveFrom(D, SubjectDecl)) {
1847 auto It = SubjectsToRules.find(D);
1848 if (It == SubjectsToRules.end())
1849 continue;
1850 if (!It->second.isRule() || It->second.getRule().isSubRule())
1851 continue; // Assume that the rule will be included as well.
1852 Rules.push_back(It->second.getRule());
1853 }
1854 }
1855
1856 bool Inserted =
1857 SubjectsToRules
1858 .try_emplace(SubjectDecl,
1859 RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
1860 .second;
1861 if (!Inserted) {
1862 PrintFatalError("Attribute subject match rules should not represent"
1863 "same attribute subjects.");
1864 }
1865 }
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001866}
1867
1868static PragmaClangAttributeSupport &
1869getPragmaAttributeSupport(RecordKeeper &Records) {
1870 static PragmaClangAttributeSupport Instance(Records);
1871 return Instance;
1872}
1873
1874void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
1875 OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
1876 OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
1877 "IsNegated) "
1878 << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
1879 OS << "#endif\n";
1880 for (const auto &Rule : Rules) {
1881 OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
1882 OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
1883 << Rule.isAbstractRule();
1884 if (Rule.isSubRule())
1885 OS << ", "
1886 << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
1887 << ", " << Rule.isNegatedSubRule();
1888 OS << ")\n";
1889 }
1890 OS << "#undef ATTR_MATCH_SUB_RULE\n";
1891}
1892
1893bool PragmaClangAttributeSupport::isAttributedSupported(
1894 const Record &Attribute) {
Richard Smith1bb64532018-08-30 01:01:07 +00001895 // If the attribute explicitly specified whether to support #pragma clang
1896 // attribute, use that setting.
1897 bool Unset;
1898 bool SpecifiedResult =
1899 Attribute.getValueAsBitOrUnset("PragmaAttributeSupport", Unset);
1900 if (!Unset)
1901 return SpecifiedResult;
1902
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001903 // Opt-out rules:
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001904 // An attribute requires delayed parsing (LateParsed is on)
1905 if (Attribute.getValueAsBit("LateParsed"))
1906 return false;
1907 // An attribute has no GNU/CXX11 spelling
1908 if (!hasGNUorCXX11Spelling(Attribute))
1909 return false;
1910 // An attribute subject list has a subject that isn't covered by one of the
1911 // subject match rules or has no subjects at all.
1912 if (Attribute.isValueUnset("Subjects"))
1913 return false;
1914 const Record *SubjectObj = Attribute.getValueAsDef("Subjects");
1915 std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
1916 if (Subjects.empty())
1917 return false;
1918 for (const auto *Subject : Subjects) {
1919 if (SubjectsToRules.find(Subject) == SubjectsToRules.end())
1920 return false;
1921 }
1922 return true;
1923}
1924
1925std::string
1926PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
1927 raw_ostream &OS) {
1928 if (!isAttributedSupported(Attr))
1929 return "nullptr";
1930 // Generate a function that constructs a set of matching rules that describe
1931 // to which declarations the attribute should apply to.
1932 std::string FnName = "matchRulesFor" + Attr.getName().str();
Erich Keane3bff4142017-10-16 23:25:24 +00001933 OS << "static void " << FnName << "(llvm::SmallVectorImpl<std::pair<"
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001934 << AttributeSubjectMatchRule::EnumName
1935 << ", bool>> &MatchRules, const LangOptions &LangOpts) {\n";
1936 if (Attr.isValueUnset("Subjects")) {
Erich Keane3bff4142017-10-16 23:25:24 +00001937 OS << "}\n\n";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001938 return FnName;
1939 }
1940 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
1941 std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
1942 for (const auto *Subject : Subjects) {
1943 auto It = SubjectsToRules.find(Subject);
1944 assert(It != SubjectsToRules.end() &&
1945 "This attribute is unsupported by #pragma clang attribute");
Alex Lorenz24952fb2017-04-19 15:52:11 +00001946 for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
1947 // The rule might be language specific, so only subtract it from the given
1948 // rules if the specific language options are specified.
1949 std::vector<Record *> LangOpts = Rule.getLangOpts();
Erich Keane3bff4142017-10-16 23:25:24 +00001950 OS << " MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
Alex Lorenz24952fb2017-04-19 15:52:11 +00001951 << ", /*IsSupported=*/";
1952 if (!LangOpts.empty()) {
1953 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
Erich Keane3bff4142017-10-16 23:25:24 +00001954 const StringRef Part = (*I)->getValueAsString("Name");
Alex Lorenz24952fb2017-04-19 15:52:11 +00001955 if ((*I)->getValueAsBit("Negated"))
Erich Keane3bff4142017-10-16 23:25:24 +00001956 OS << "!";
1957 OS << "LangOpts." << Part;
Alex Lorenz24952fb2017-04-19 15:52:11 +00001958 if (I + 1 != E)
Erich Keane3bff4142017-10-16 23:25:24 +00001959 OS << " || ";
Alex Lorenz24952fb2017-04-19 15:52:11 +00001960 }
1961 } else
Erich Keane3bff4142017-10-16 23:25:24 +00001962 OS << "true";
1963 OS << "));\n";
Alex Lorenz24952fb2017-04-19 15:52:11 +00001964 }
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001965 }
Erich Keane3bff4142017-10-16 23:25:24 +00001966 OS << "}\n\n";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001967 return FnName;
1968}
1969
1970void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
1971 // Generate routines that check the names of sub-rules.
1972 OS << "Optional<attr::SubjectMatchRule> "
1973 "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
1974 OS << " return None;\n";
1975 OS << "}\n\n";
1976
1977 std::map<const Record *, std::vector<AttributeSubjectMatchRule>>
1978 SubMatchRules;
1979 for (const auto &Rule : Rules) {
1980 if (!Rule.isSubRule())
1981 continue;
1982 SubMatchRules[Rule.MetaSubject].push_back(Rule);
1983 }
1984
1985 for (const auto &SubMatchRule : SubMatchRules) {
1986 OS << "Optional<attr::SubjectMatchRule> isAttributeSubjectMatchSubRuleFor_"
1987 << SubMatchRule.first->getValueAsString("Name")
1988 << "(StringRef Name, bool IsUnless) {\n";
1989 OS << " if (IsUnless)\n";
1990 OS << " return "
1991 "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
1992 for (const auto &Rule : SubMatchRule.second) {
1993 if (Rule.isNegatedSubRule())
1994 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
1995 << ").\n";
1996 }
1997 OS << " Default(None);\n";
1998 OS << " return "
1999 "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
2000 for (const auto &Rule : SubMatchRule.second) {
2001 if (!Rule.isNegatedSubRule())
2002 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2003 << ").\n";
2004 }
2005 OS << " Default(None);\n";
2006 OS << "}\n\n";
2007 }
2008
2009 // Generate the function that checks for the top-level rules.
2010 OS << "std::pair<Optional<attr::SubjectMatchRule>, "
2011 "Optional<attr::SubjectMatchRule> (*)(StringRef, "
2012 "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
2013 OS << " return "
2014 "llvm::StringSwitch<std::pair<Optional<attr::SubjectMatchRule>, "
2015 "Optional<attr::SubjectMatchRule> (*) (StringRef, "
2016 "bool)>>(Name).\n";
2017 for (const auto &Rule : Rules) {
2018 if (Rule.isSubRule())
2019 continue;
2020 std::string SubRuleFunction;
2021 if (SubMatchRules.count(Rule.MetaSubject))
Erich Keane3bff4142017-10-16 23:25:24 +00002022 SubRuleFunction =
2023 ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002024 else
2025 SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
2026 OS << " Case(\"" << Rule.getName() << "\", std::make_pair("
2027 << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
2028 }
2029 OS << " Default(std::make_pair(None, "
2030 "defaultIsAttributeSubjectMatchSubRuleFor));\n";
2031 OS << "}\n\n";
2032
2033 // Generate the function that checks for the submatch rules.
2034 OS << "const char *validAttributeSubjectMatchSubRules("
2035 << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
2036 OS << " switch (Rule) {\n";
2037 for (const auto &SubMatchRule : SubMatchRules) {
2038 OS << " case "
2039 << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
2040 << ":\n";
2041 OS << " return \"'";
2042 bool IsFirst = true;
2043 for (const auto &Rule : SubMatchRule.second) {
2044 if (!IsFirst)
2045 OS << ", '";
2046 IsFirst = false;
2047 if (Rule.isNegatedSubRule())
2048 OS << "unless(";
2049 OS << Rule.getName();
2050 if (Rule.isNegatedSubRule())
2051 OS << ')';
2052 OS << "'";
2053 }
2054 OS << "\";\n";
2055 }
2056 OS << " default: return nullptr;\n";
2057 OS << " }\n";
2058 OS << "}\n\n";
2059}
2060
George Burgess IV1881a572016-12-01 00:13:18 +00002061template <typename Fn>
2062static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
2063 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2064 SmallDenseSet<StringRef, 8> Seen;
2065 for (const FlattenedSpelling &S : Spellings) {
2066 if (Seen.insert(S.name()).second)
2067 F(S);
2068 }
2069}
2070
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002071/// Emits the first-argument-is-type property for attributes.
Aaron Ballman35db2b32014-01-29 22:13:45 +00002072static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
2073 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
2074 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2075
Aaron Ballman2f22b942014-05-20 19:47:14 +00002076 for (const auto *Attr : Attrs) {
Aaron Ballman35db2b32014-01-29 22:13:45 +00002077 // Determine whether the first argument is a type.
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002078 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
Aaron Ballman35db2b32014-01-29 22:13:45 +00002079 if (Args.empty())
2080 continue;
2081
Craig Topper25761242016-01-18 19:52:54 +00002082 if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
Aaron Ballman35db2b32014-01-29 22:13:45 +00002083 continue;
2084
2085 // All these spellings take a single type argument.
George Burgess IV1881a572016-12-01 00:13:18 +00002086 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2087 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2088 });
Aaron Ballman35db2b32014-01-29 22:13:45 +00002089 }
2090 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
2091}
2092
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002093/// Emits the parse-arguments-in-unevaluated-context property for
Aaron Ballman35db2b32014-01-29 22:13:45 +00002094/// attributes.
2095static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
2096 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
2097 ParsedAttrMap Attrs = getParsedAttrList(Records);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002098 for (const auto &I : Attrs) {
2099 const Record &Attr = *I.second;
Aaron Ballman35db2b32014-01-29 22:13:45 +00002100
2101 if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
2102 continue;
2103
2104 // All these spellings take are parsed unevaluated.
George Burgess IV1881a572016-12-01 00:13:18 +00002105 forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
2106 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2107 });
Aaron Ballman35db2b32014-01-29 22:13:45 +00002108 }
2109 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
2110}
2111
2112static bool isIdentifierArgument(Record *Arg) {
2113 return !Arg->getSuperClasses().empty() &&
Craig Topper25761242016-01-18 19:52:54 +00002114 llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
Aaron Ballman35db2b32014-01-29 22:13:45 +00002115 .Case("IdentifierArgument", true)
2116 .Case("EnumArgument", true)
Aaron Ballman55ef1512014-12-19 16:42:04 +00002117 .Case("VariadicEnumArgument", true)
Aaron Ballman35db2b32014-01-29 22:13:45 +00002118 .Default(false);
2119}
2120
Erich Keane3efe0022018-07-20 14:13:28 +00002121static bool isVariadicIdentifierArgument(Record *Arg) {
2122 return !Arg->getSuperClasses().empty() &&
2123 llvm::StringSwitch<bool>(
2124 Arg->getSuperClasses().back().first->getName())
2125 .Case("VariadicIdentifierArgument", true)
Johannes Doerfertac991bb2019-01-19 05:36:54 +00002126 .Case("VariadicParamOrParamIdxArgument", true)
Erich Keane3efe0022018-07-20 14:13:28 +00002127 .Default(false);
2128}
2129
2130static void emitClangAttrVariadicIdentifierArgList(RecordKeeper &Records,
2131 raw_ostream &OS) {
2132 OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
2133 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2134 for (const auto *A : Attrs) {
2135 // Determine whether the first argument is a variadic identifier.
2136 std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
2137 if (Args.empty() || !isVariadicIdentifierArgument(Args[0]))
2138 continue;
2139
2140 // All these spellings take an identifier argument.
2141 forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
2142 OS << ".Case(\"" << S.name() << "\", "
2143 << "true"
2144 << ")\n";
2145 });
2146 }
2147 OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
2148}
2149
Aaron Ballman35db2b32014-01-29 22:13:45 +00002150// Emits the first-argument-is-identifier property for attributes.
2151static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
2152 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
2153 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2154
Aaron Ballman2f22b942014-05-20 19:47:14 +00002155 for (const auto *Attr : Attrs) {
Aaron Ballman35db2b32014-01-29 22:13:45 +00002156 // Determine whether the first argument is an identifier.
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002157 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
Aaron Ballman35db2b32014-01-29 22:13:45 +00002158 if (Args.empty() || !isIdentifierArgument(Args[0]))
2159 continue;
2160
2161 // All these spellings take an identifier argument.
George Burgess IV1881a572016-12-01 00:13:18 +00002162 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2163 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2164 });
Aaron Ballman35db2b32014-01-29 22:13:45 +00002165 }
2166 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
2167}
2168
Johannes Doerfertac991bb2019-01-19 05:36:54 +00002169static bool keywordThisIsaIdentifierInArgument(const Record *Arg) {
2170 return !Arg->getSuperClasses().empty() &&
2171 llvm::StringSwitch<bool>(
2172 Arg->getSuperClasses().back().first->getName())
2173 .Case("VariadicParamOrParamIdxArgument", true)
2174 .Default(false);
2175}
2176
2177static void emitClangAttrThisIsaIdentifierArgList(RecordKeeper &Records,
2178 raw_ostream &OS) {
2179 OS << "#if defined(CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST)\n";
2180 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2181 for (const auto *A : Attrs) {
2182 // Determine whether the first argument is a variadic identifier.
2183 std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
2184 if (Args.empty() || !keywordThisIsaIdentifierInArgument(Args[0]))
2185 continue;
2186
2187 // All these spellings take an identifier argument.
2188 forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
2189 OS << ".Case(\"" << S.name() << "\", "
2190 << "true"
2191 << ")\n";
2192 });
2193 }
2194 OS << "#endif // CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST\n\n";
2195}
2196
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002197namespace clang {
2198
2199// Emits the class definitions for attributes.
2200void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002201 emitSourceFileHeader("Attribute classes' definitions", OS);
2202
Peter Collingbournebee583f2011-10-06 13:03:08 +00002203 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
2204 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
2205
2206 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2207
Aaron Ballman2f22b942014-05-20 19:47:14 +00002208 for (const auto *Attr : Attrs) {
2209 const Record &R = *Attr;
Aaron Ballman06bd44b2014-02-17 18:23:02 +00002210
2211 // FIXME: Currently, documentation is generated as-needed due to the fact
2212 // that there is no way to allow a generated project "reach into" the docs
2213 // directory (for instance, it may be an out-of-tree build). However, we want
2214 // to ensure that every attribute has a Documentation field, and produce an
2215 // error if it has been neglected. Otherwise, the on-demand generation which
2216 // happens server-side will fail. This code is ensuring that functionality,
2217 // even though this Emitter doesn't technically need the documentation.
2218 // When attribute documentation can be generated as part of the build
2219 // itself, this code can be removed.
2220 (void)R.getValueAsListOfDefs("Documentation");
Douglas Gregorb2daf842012-05-02 15:56:52 +00002221
2222 if (!R.getValueAsBit("ASTNode"))
2223 continue;
2224
Craig Topper25761242016-01-18 19:52:54 +00002225 ArrayRef<std::pair<Record *, SMRange>> Supers = R.getSuperClasses();
Aaron Ballman0979e9e2013-07-30 01:44:15 +00002226 assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
Aaron Ballman0979e9e2013-07-30 01:44:15 +00002227 std::string SuperName;
Richard Smith33bddbd2018-01-04 23:42:29 +00002228 bool Inheritable = false;
David Majnemerf7e36092016-06-23 00:15:04 +00002229 for (const auto &Super : llvm::reverse(Supers)) {
Craig Topper25761242016-01-18 19:52:54 +00002230 const Record *R = Super.first;
Aaron Ballmanb9a457a2018-05-03 15:33:50 +00002231 if (R->getName() != "TargetSpecificAttr" &&
2232 R->getName() != "DeclOrTypeAttr" && SuperName.empty())
Craig Topper25761242016-01-18 19:52:54 +00002233 SuperName = R->getName();
Richard Smith33bddbd2018-01-04 23:42:29 +00002234 if (R->getName() == "InheritableAttr")
2235 Inheritable = true;
Aaron Ballman0979e9e2013-07-30 01:44:15 +00002236 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00002237
2238 OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
2239
2240 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002241 std::vector<std::unique_ptr<Argument>> Args;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002242 Args.reserve(ArgRecords.size());
2243
John McCalla62c1a92015-10-28 00:17:34 +00002244 bool HasOptArg = false;
2245 bool HasFakeArg = false;
Aaron Ballman2f22b942014-05-20 19:47:14 +00002246 for (const auto *ArgRecord : ArgRecords) {
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002247 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2248 Args.back()->writeDeclarations(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002249 OS << "\n\n";
John McCalla62c1a92015-10-28 00:17:34 +00002250
2251 // For these purposes, fake takes priority over optional.
2252 if (Args.back()->isFake()) {
2253 HasFakeArg = true;
2254 } else if (Args.back()->isOptional()) {
2255 HasOptArg = true;
2256 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00002257 }
2258
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002259 OS << "public:\n";
Aaron Ballman36a53502014-01-16 13:03:14 +00002260
Aaron Ballmanc669cc02014-01-27 22:10:04 +00002261 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Aaron Ballman36a53502014-01-16 13:03:14 +00002262
2263 // If there are zero or one spellings, all spelling-related functionality
2264 // can be elided. If all of the spellings share the same name, the spelling
2265 // functionality can also be elided.
2266 bool ElideSpelling = (Spellings.size() <= 1) ||
2267 SpellingNamesAreCommon(Spellings);
2268
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00002269 // This maps spelling index values to semantic Spelling enumerants.
2270 SemanticSpellingMap SemanticToSyntacticMap;
Aaron Ballman36a53502014-01-16 13:03:14 +00002271
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00002272 if (!ElideSpelling)
2273 OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
Aaron Ballman36a53502014-01-16 13:03:14 +00002274
John McCalla62c1a92015-10-28 00:17:34 +00002275 // Emit CreateImplicit factory methods.
2276 auto emitCreateImplicit = [&](bool emitFake) {
2277 OS << " static " << R.getName() << "Attr *CreateImplicit(";
2278 OS << "ASTContext &Ctx";
2279 if (!ElideSpelling)
2280 OS << ", Spelling S";
2281 for (auto const &ai : Args) {
2282 if (ai->isFake() && !emitFake) continue;
2283 OS << ", ";
2284 ai->writeCtorParameters(OS);
2285 }
2286 OS << ", SourceRange Loc = SourceRange()";
2287 OS << ") {\n";
Eugene Zelenko5f02b772015-12-08 18:49:01 +00002288 OS << " auto *A = new (Ctx) " << R.getName();
John McCalla62c1a92015-10-28 00:17:34 +00002289 OS << "Attr(Loc, Ctx, ";
2290 for (auto const &ai : Args) {
2291 if (ai->isFake() && !emitFake) continue;
2292 ai->writeImplicitCtorArgs(OS);
2293 OS << ", ";
2294 }
2295 OS << (ElideSpelling ? "0" : "S") << ");\n";
2296 OS << " A->setImplicit(true);\n";
2297 OS << " return A;\n }\n\n";
2298 };
Aaron Ballman36a53502014-01-16 13:03:14 +00002299
John McCalla62c1a92015-10-28 00:17:34 +00002300 // Emit a CreateImplicit that takes all the arguments.
2301 emitCreateImplicit(true);
2302
2303 // Emit a CreateImplicit that takes all the non-fake arguments.
2304 if (HasFakeArg) {
2305 emitCreateImplicit(false);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002306 }
Michael Han99315932013-01-24 16:46:58 +00002307
John McCalla62c1a92015-10-28 00:17:34 +00002308 // Emit constructors.
2309 auto emitCtor = [&](bool emitOpt, bool emitFake) {
2310 auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
2311 if (arg->isFake()) return emitFake;
2312 if (arg->isOptional()) return emitOpt;
2313 return true;
2314 };
Michael Han99315932013-01-24 16:46:58 +00002315
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002316 OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002317 for (auto const &ai : Args) {
John McCalla62c1a92015-10-28 00:17:34 +00002318 if (!shouldEmitArg(ai)) continue;
2319 OS << " , ";
2320 ai->writeCtorParameters(OS);
2321 OS << "\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002322 }
2323
2324 OS << " , ";
Aaron Ballman36a53502014-01-16 13:03:14 +00002325 OS << "unsigned SI\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002326
2327 OS << " )\n";
Benjamin Kramer845e32c2015-03-19 16:06:49 +00002328 OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI, "
Richard Smith33bddbd2018-01-04 23:42:29 +00002329 << ( R.getValueAsBit("LateParsed") ? "true" : "false" );
2330 if (Inheritable) {
2331 OS << ", "
2332 << (R.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
2333 : "false");
2334 }
2335 OS << ")\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002336
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002337 for (auto const &ai : Args) {
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002338 OS << " , ";
John McCalla62c1a92015-10-28 00:17:34 +00002339 if (!shouldEmitArg(ai)) {
2340 ai->writeCtorDefaultInitializers(OS);
2341 } else {
2342 ai->writeCtorInitializers(OS);
2343 }
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002344 OS << "\n";
2345 }
2346
2347 OS << " {\n";
2348
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002349 for (auto const &ai : Args) {
John McCalla62c1a92015-10-28 00:17:34 +00002350 if (!shouldEmitArg(ai)) continue;
2351 ai->writeCtorBody(OS);
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002352 }
2353 OS << " }\n\n";
John McCalla62c1a92015-10-28 00:17:34 +00002354 };
2355
2356 // Emit a constructor that includes all the arguments.
2357 // This is necessary for cloning.
2358 emitCtor(true, true);
2359
2360 // Emit a constructor that takes all the non-fake arguments.
2361 if (HasFakeArg) {
2362 emitCtor(true, false);
2363 }
2364
2365 // Emit a constructor that takes all the non-fake, non-optional arguments.
2366 if (HasOptArg) {
2367 emitCtor(false, false);
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002368 }
2369
Benjamin Kramer845e32c2015-03-19 16:06:49 +00002370 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
Craig Toppercbce6e92014-03-11 06:22:39 +00002371 OS << " void printPretty(raw_ostream &OS,\n"
Benjamin Kramer845e32c2015-03-19 16:06:49 +00002372 << " const PrintingPolicy &Policy) const;\n";
2373 OS << " const char *getSpelling() const;\n";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00002374
2375 if (!ElideSpelling) {
2376 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
2377 OS << " Spelling getSemanticSpelling() const {\n";
2378 WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
2379 OS);
2380 OS << " }\n";
2381 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00002382
Michael Hanaf02bbe2013-02-01 01:19:17 +00002383 writeAttrAccessorDefinition(R, OS);
2384
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002385 for (auto const &ai : Args) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002386 ai->writeAccessors(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002387 OS << "\n\n";
Aaron Ballman682ee422013-09-11 19:47:58 +00002388
John McCalla62c1a92015-10-28 00:17:34 +00002389 // Don't write conversion routines for fake arguments.
2390 if (ai->isFake()) continue;
2391
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002392 if (ai->isEnumArg())
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002393 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002394 else if (ai->isVariadicEnumArg())
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002395 static_cast<const VariadicEnumArgument *>(ai.get())
2396 ->writeConversion(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002397 }
2398
Jakob Stoklund Olesen6f2288b62012-01-13 04:57:47 +00002399 OS << R.getValueAsString("AdditionalMembers");
Peter Collingbournebee583f2011-10-06 13:03:08 +00002400 OS << "\n\n";
2401
2402 OS << " static bool classof(const Attr *A) { return A->getKind() == "
2403 << "attr::" << R.getName() << "; }\n";
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002404
Peter Collingbournebee583f2011-10-06 13:03:08 +00002405 OS << "};\n\n";
2406 }
2407
Eugene Zelenko5f02b772015-12-08 18:49:01 +00002408 OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002409}
2410
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002411// Emits the class method definitions for attributes.
2412void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002413 emitSourceFileHeader("Attribute classes' member function definitions", OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002414
2415 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
Peter Collingbournebee583f2011-10-06 13:03:08 +00002416
Aaron Ballman2f22b942014-05-20 19:47:14 +00002417 for (auto *Attr : Attrs) {
2418 Record &R = *Attr;
Douglas Gregorb2daf842012-05-02 15:56:52 +00002419
2420 if (!R.getValueAsBit("ASTNode"))
2421 continue;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002422
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002423 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2424 std::vector<std::unique_ptr<Argument>> Args;
Aaron Ballman2f22b942014-05-20 19:47:14 +00002425 for (const auto *Arg : ArgRecords)
2426 Args.emplace_back(createArgument(*Arg, R.getName()));
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002427
2428 for (auto const &ai : Args)
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002429 ai->writeAccessorDefinitions(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002430
2431 OS << R.getName() << "Attr *" << R.getName()
2432 << "Attr::clone(ASTContext &C) const {\n";
Hans Wennborg613807b2014-05-31 01:30:30 +00002433 OS << " auto *A = new (C) " << R.getName() << "Attr(getLocation(), C";
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002434 for (auto const &ai : Args) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00002435 OS << ", ";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002436 ai->writeCloneArgs(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002437 }
Hans Wennborg613807b2014-05-31 01:30:30 +00002438 OS << ", getSpellingListIndex());\n";
2439 OS << " A->Inherited = Inherited;\n";
2440 OS << " A->IsPackExpansion = IsPackExpansion;\n";
2441 OS << " A->Implicit = Implicit;\n";
2442 OS << " return A;\n}\n\n";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +00002443
Michael Han99315932013-01-24 16:46:58 +00002444 writePrettyPrintFunction(R, Args, OS);
Aaron Ballman3e424b52013-12-26 18:30:57 +00002445 writeGetSpellingFunction(R, OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002446 }
Benjamin Kramer845e32c2015-03-19 16:06:49 +00002447
2448 // Instead of relying on virtual dispatch we just create a huge dispatch
2449 // switch. This is both smaller and faster than virtual functions.
2450 auto EmitFunc = [&](const char *Method) {
2451 OS << " switch (getKind()) {\n";
2452 for (const auto *Attr : Attrs) {
2453 const Record &R = *Attr;
2454 if (!R.getValueAsBit("ASTNode"))
2455 continue;
2456
2457 OS << " case attr::" << R.getName() << ":\n";
2458 OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
2459 << ";\n";
2460 }
Benjamin Kramer845e32c2015-03-19 16:06:49 +00002461 OS << " }\n";
2462 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
2463 OS << "}\n\n";
2464 };
2465
2466 OS << "const char *Attr::getSpelling() const {\n";
2467 EmitFunc("getSpelling()");
2468
2469 OS << "Attr *Attr::clone(ASTContext &C) const {\n";
2470 EmitFunc("clone(C)");
2471
2472 OS << "void Attr::printPretty(raw_ostream &OS, "
2473 "const PrintingPolicy &Policy) const {\n";
2474 EmitFunc("printPretty(OS, Policy)");
Peter Collingbournebee583f2011-10-06 13:03:08 +00002475}
2476
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002477} // end namespace clang
2478
John McCall2225c8b2016-03-01 00:18:05 +00002479static void emitAttrList(raw_ostream &OS, StringRef Class,
Peter Collingbournebee583f2011-10-06 13:03:08 +00002480 const std::vector<Record*> &AttrList) {
John McCall2225c8b2016-03-01 00:18:05 +00002481 for (auto Cur : AttrList) {
2482 OS << Class << "(" << Cur->getName() << ")\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002483 }
2484}
2485
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002486// Determines if an attribute has a Pragma spelling.
2487static bool AttrHasPragmaSpelling(const Record *R) {
2488 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
George Burgess IV1881a572016-12-01 00:13:18 +00002489 return llvm::find_if(Spellings, [](const FlattenedSpelling &S) {
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002490 return S.variety() == "Pragma";
2491 }) != Spellings.end();
2492}
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002493
John McCall2225c8b2016-03-01 00:18:05 +00002494namespace {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002495
John McCall2225c8b2016-03-01 00:18:05 +00002496 struct AttrClassDescriptor {
2497 const char * const MacroName;
2498 const char * const TableGenName;
2499 };
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002500
2501} // end anonymous namespace
John McCall2225c8b2016-03-01 00:18:05 +00002502
2503static const AttrClassDescriptor AttrClassDescriptors[] = {
2504 { "ATTR", "Attr" },
Richard Smithe43e2b32018-08-20 21:47:29 +00002505 { "TYPE_ATTR", "TypeAttr" },
Richard Smith4f902c72016-03-08 00:32:55 +00002506 { "STMT_ATTR", "StmtAttr" },
John McCall2225c8b2016-03-01 00:18:05 +00002507 { "INHERITABLE_ATTR", "InheritableAttr" },
Richard Smithe43e2b32018-08-20 21:47:29 +00002508 { "DECL_OR_TYPE_ATTR", "DeclOrTypeAttr" },
John McCall477f2bb2016-03-03 06:39:32 +00002509 { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
2510 { "PARAMETER_ABI_ATTR", "ParameterABIAttr" }
John McCall2225c8b2016-03-01 00:18:05 +00002511};
2512
2513static void emitDefaultDefine(raw_ostream &OS, StringRef name,
2514 const char *superName) {
2515 OS << "#ifndef " << name << "\n";
2516 OS << "#define " << name << "(NAME) ";
2517 if (superName) OS << superName << "(NAME)";
2518 OS << "\n#endif\n\n";
2519}
2520
2521namespace {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002522
John McCall2225c8b2016-03-01 00:18:05 +00002523 /// A class of attributes.
2524 struct AttrClass {
2525 const AttrClassDescriptor &Descriptor;
2526 Record *TheRecord;
2527 AttrClass *SuperClass = nullptr;
2528 std::vector<AttrClass*> SubClasses;
2529 std::vector<Record*> Attrs;
2530
2531 AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
2532 : Descriptor(Descriptor), TheRecord(R) {}
2533
2534 void emitDefaultDefines(raw_ostream &OS) const {
2535 // Default the macro unless this is a root class (i.e. Attr).
2536 if (SuperClass) {
2537 emitDefaultDefine(OS, Descriptor.MacroName,
2538 SuperClass->Descriptor.MacroName);
2539 }
2540 }
2541
2542 void emitUndefs(raw_ostream &OS) const {
2543 OS << "#undef " << Descriptor.MacroName << "\n";
2544 }
2545
2546 void emitAttrList(raw_ostream &OS) const {
2547 for (auto SubClass : SubClasses) {
2548 SubClass->emitAttrList(OS);
2549 }
2550
2551 ::emitAttrList(OS, Descriptor.MacroName, Attrs);
2552 }
2553
2554 void classifyAttrOnRoot(Record *Attr) {
2555 bool result = classifyAttr(Attr);
2556 assert(result && "failed to classify on root"); (void) result;
2557 }
2558
2559 void emitAttrRange(raw_ostream &OS) const {
2560 OS << "ATTR_RANGE(" << Descriptor.TableGenName
2561 << ", " << getFirstAttr()->getName()
2562 << ", " << getLastAttr()->getName() << ")\n";
2563 }
2564
2565 private:
2566 bool classifyAttr(Record *Attr) {
2567 // Check all the subclasses.
2568 for (auto SubClass : SubClasses) {
2569 if (SubClass->classifyAttr(Attr))
2570 return true;
2571 }
2572
2573 // It's not more specific than this class, but it might still belong here.
2574 if (Attr->isSubClassOf(TheRecord)) {
2575 Attrs.push_back(Attr);
2576 return true;
2577 }
2578
2579 return false;
2580 }
2581
2582 Record *getFirstAttr() const {
2583 if (!SubClasses.empty())
2584 return SubClasses.front()->getFirstAttr();
2585 return Attrs.front();
2586 }
2587
2588 Record *getLastAttr() const {
2589 if (!Attrs.empty())
2590 return Attrs.back();
2591 return SubClasses.back()->getLastAttr();
2592 }
2593 };
2594
2595 /// The entire hierarchy of attribute classes.
2596 class AttrClassHierarchy {
2597 std::vector<std::unique_ptr<AttrClass>> Classes;
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002598
John McCall2225c8b2016-03-01 00:18:05 +00002599 public:
2600 AttrClassHierarchy(RecordKeeper &Records) {
2601 // Find records for all the classes.
2602 for (auto &Descriptor : AttrClassDescriptors) {
2603 Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
2604 AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
2605 Classes.emplace_back(Class);
2606 }
2607
2608 // Link up the hierarchy.
2609 for (auto &Class : Classes) {
2610 if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
2611 Class->SuperClass = SuperClass;
2612 SuperClass->SubClasses.push_back(Class.get());
2613 }
2614 }
2615
2616#ifndef NDEBUG
2617 for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
2618 assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
2619 "only the first class should be a root class!");
2620 }
2621#endif
2622 }
2623
2624 void emitDefaultDefines(raw_ostream &OS) const {
2625 for (auto &Class : Classes) {
2626 Class->emitDefaultDefines(OS);
2627 }
2628 }
2629
2630 void emitUndefs(raw_ostream &OS) const {
2631 for (auto &Class : Classes) {
2632 Class->emitUndefs(OS);
2633 }
2634 }
2635
2636 void emitAttrLists(raw_ostream &OS) const {
2637 // Just start from the root class.
2638 Classes[0]->emitAttrList(OS);
2639 }
2640
2641 void emitAttrRanges(raw_ostream &OS) const {
2642 for (auto &Class : Classes)
2643 Class->emitAttrRange(OS);
2644 }
2645
2646 void classifyAttr(Record *Attr) {
2647 // Add the attribute to the root class.
2648 Classes[0]->classifyAttrOnRoot(Attr);
2649 }
2650
2651 private:
2652 AttrClass *findClassByRecord(Record *R) const {
2653 for (auto &Class : Classes) {
2654 if (Class->TheRecord == R)
2655 return Class.get();
2656 }
2657 return nullptr;
2658 }
2659
2660 AttrClass *findSuperClass(Record *R) const {
2661 // TableGen flattens the superclass list, so we just need to walk it
2662 // in reverse.
2663 auto SuperClasses = R->getSuperClasses();
2664 for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
2665 auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
2666 if (SuperClass) return SuperClass;
2667 }
2668 return nullptr;
2669 }
2670 };
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002671
2672} // end anonymous namespace
John McCall2225c8b2016-03-01 00:18:05 +00002673
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002674namespace clang {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002675
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002676// Emits the enumeration list for attributes.
2677void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002678 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002679
John McCall2225c8b2016-03-01 00:18:05 +00002680 AttrClassHierarchy Hierarchy(Records);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002681
John McCall2225c8b2016-03-01 00:18:05 +00002682 // Add defaulting macro definitions.
2683 Hierarchy.emitDefaultDefines(OS);
2684 emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002685
John McCall2225c8b2016-03-01 00:18:05 +00002686 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2687 std::vector<Record *> PragmaAttrs;
Aaron Ballman2f22b942014-05-20 19:47:14 +00002688 for (auto *Attr : Attrs) {
2689 if (!Attr->getValueAsBit("ASTNode"))
Douglas Gregorb2daf842012-05-02 15:56:52 +00002690 continue;
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002691
John McCall2225c8b2016-03-01 00:18:05 +00002692 // Add the attribute to the ad-hoc groups.
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002693 if (AttrHasPragmaSpelling(Attr))
2694 PragmaAttrs.push_back(Attr);
2695
John McCall2225c8b2016-03-01 00:18:05 +00002696 // Place it in the hierarchy.
2697 Hierarchy.classifyAttr(Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002698 }
2699
John McCall2225c8b2016-03-01 00:18:05 +00002700 // Emit the main attribute list.
2701 Hierarchy.emitAttrLists(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002702
John McCall2225c8b2016-03-01 00:18:05 +00002703 // Emit the ad hoc groups.
2704 emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
2705
2706 // Emit the attribute ranges.
2707 OS << "#ifdef ATTR_RANGE\n";
2708 Hierarchy.emitAttrRanges(OS);
2709 OS << "#undef ATTR_RANGE\n";
2710 OS << "#endif\n";
2711
2712 Hierarchy.emitUndefs(OS);
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002713 OS << "#undef PRAGMA_SPELLING_ATTR\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002714}
2715
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002716// Emits the enumeration list for attributes.
2717void EmitClangAttrSubjectMatchRuleList(RecordKeeper &Records, raw_ostream &OS) {
2718 emitSourceFileHeader(
2719 "List of all attribute subject matching rules that Clang recognizes", OS);
2720 PragmaClangAttributeSupport &PragmaAttributeSupport =
2721 getPragmaAttributeSupport(Records);
2722 emitDefaultDefine(OS, "ATTR_MATCH_RULE", nullptr);
2723 PragmaAttributeSupport.emitMatchRuleList(OS);
2724 OS << "#undef ATTR_MATCH_RULE\n";
2725}
2726
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002727// Emits the code to read an attribute from a precompiled header.
2728void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002729 emitSourceFileHeader("Attribute deserialization code", OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002730
2731 Record *InhClass = Records.getClass("InheritableAttr");
2732 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
2733 ArgRecords;
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002734 std::vector<std::unique_ptr<Argument>> Args;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002735
2736 OS << " switch (Kind) {\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00002737 for (const auto *Attr : Attrs) {
2738 const Record &R = *Attr;
Douglas Gregorb2daf842012-05-02 15:56:52 +00002739 if (!R.getValueAsBit("ASTNode"))
2740 continue;
2741
Peter Collingbournebee583f2011-10-06 13:03:08 +00002742 OS << " case attr::" << R.getName() << ": {\n";
2743 if (R.isSubClassOf(InhClass))
David L. Jones267b8842017-01-24 01:04:30 +00002744 OS << " bool isInherited = Record.readInt();\n";
2745 OS << " bool isImplicit = Record.readInt();\n";
2746 OS << " unsigned Spelling = Record.readInt();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002747 ArgRecords = R.getValueAsListOfDefs("Args");
2748 Args.clear();
Aaron Ballman2f22b942014-05-20 19:47:14 +00002749 for (const auto *Arg : ArgRecords) {
2750 Args.emplace_back(createArgument(*Arg, R.getName()));
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002751 Args.back()->writePCHReadDecls(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002752 }
2753 OS << " New = new (Context) " << R.getName() << "Attr(Range, Context";
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002754 for (auto const &ri : Args) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00002755 OS << ", ";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002756 ri->writePCHReadArgs(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002757 }
Aaron Ballman36a53502014-01-16 13:03:14 +00002758 OS << ", Spelling);\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002759 if (R.isSubClassOf(InhClass))
2760 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
Aaron Ballman36a53502014-01-16 13:03:14 +00002761 OS << " New->setImplicit(isImplicit);\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002762 OS << " break;\n";
2763 OS << " }\n";
2764 }
2765 OS << " }\n";
2766}
2767
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002768// Emits the code to write an attribute to a precompiled header.
2769void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002770 emitSourceFileHeader("Attribute serialization code", OS);
2771
Peter Collingbournebee583f2011-10-06 13:03:08 +00002772 Record *InhClass = Records.getClass("InheritableAttr");
2773 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002774
2775 OS << " switch (A->getKind()) {\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00002776 for (const auto *Attr : Attrs) {
2777 const Record &R = *Attr;
Douglas Gregorb2daf842012-05-02 15:56:52 +00002778 if (!R.getValueAsBit("ASTNode"))
2779 continue;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002780 OS << " case attr::" << R.getName() << ": {\n";
2781 Args = R.getValueAsListOfDefs("Args");
2782 if (R.isSubClassOf(InhClass) || !Args.empty())
Eugene Zelenko5f02b772015-12-08 18:49:01 +00002783 OS << " const auto *SA = cast<" << R.getName()
Peter Collingbournebee583f2011-10-06 13:03:08 +00002784 << "Attr>(A);\n";
2785 if (R.isSubClassOf(InhClass))
2786 OS << " Record.push_back(SA->isInherited());\n";
Aaron Ballman36a53502014-01-16 13:03:14 +00002787 OS << " Record.push_back(A->isImplicit());\n";
2788 OS << " Record.push_back(A->getSpellingListIndex());\n";
2789
Aaron Ballman2f22b942014-05-20 19:47:14 +00002790 for (const auto *Arg : Args)
2791 createArgument(*Arg, R.getName())->writePCHWrite(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002792 OS << " break;\n";
2793 OS << " }\n";
2794 }
2795 OS << " }\n";
2796}
2797
Erich Keane75449672017-12-20 18:51:08 +00002798// Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
2799// parameter with only a single check type, if applicable.
2800static void GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
2801 std::string *FnName,
2802 StringRef ListName,
2803 StringRef CheckAgainst,
2804 StringRef Scope) {
2805 if (!R->isValueUnset(ListName)) {
2806 Test += " && (";
2807 std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
2808 for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
2809 StringRef Part = *I;
2810 Test += CheckAgainst;
2811 Test += " == ";
2812 Test += Scope;
2813 Test += Part;
2814 if (I + 1 != E)
2815 Test += " || ";
2816 if (FnName)
2817 *FnName += Part;
2818 }
2819 Test += ")";
2820 }
2821}
2822
Bob Wilson0058b822015-07-20 22:57:36 +00002823// Generate a conditional expression to check if the current target satisfies
2824// the conditions for a TargetSpecificAttr record, and append the code for
2825// those checks to the Test string. If the FnName string pointer is non-null,
2826// append a unique suffix to distinguish this set of target checks from other
2827// TargetSpecificAttr records.
2828static void GenerateTargetSpecificAttrChecks(const Record *R,
Craig Topper00648582017-05-31 19:01:22 +00002829 std::vector<StringRef> &Arches,
Bob Wilson0058b822015-07-20 22:57:36 +00002830 std::string &Test,
2831 std::string *FnName) {
2832 // It is assumed that there will be an llvm::Triple object
2833 // named "T" and a TargetInfo object named "Target" within
2834 // scope that can be used to determine whether the attribute exists in
2835 // a given target.
Erich Keane75449672017-12-20 18:51:08 +00002836 Test += "true";
2837 // If one or more architectures is specified, check those. Arches are handled
2838 // differently because GenerateTargetRequirements needs to combine the list
2839 // with ParseKind.
2840 if (!Arches.empty()) {
2841 Test += " && (";
2842 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
2843 StringRef Part = *I;
2844 Test += "T.getArch() == llvm::Triple::";
2845 Test += Part;
2846 if (I + 1 != E)
2847 Test += " || ";
2848 if (FnName)
2849 *FnName += Part;
2850 }
2851 Test += ")";
Bob Wilson0058b822015-07-20 22:57:36 +00002852 }
Bob Wilson0058b822015-07-20 22:57:36 +00002853
2854 // If the attribute is specific to particular OSes, check those.
Erich Keane75449672017-12-20 18:51:08 +00002855 GenerateTargetSpecificAttrCheck(R, Test, FnName, "OSes", "T.getOS()",
2856 "llvm::Triple::");
Bob Wilson0058b822015-07-20 22:57:36 +00002857
2858 // If one or more CXX ABIs are specified, check those as well.
Erich Keane75449672017-12-20 18:51:08 +00002859 GenerateTargetSpecificAttrCheck(R, Test, FnName, "CXXABIs",
2860 "Target.getCXXABI().getKind()",
2861 "TargetCXXABI::");
2862 // If one or more object formats is specified, check those.
2863 GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
2864 "T.getObjectFormat()", "llvm::Triple::");
Bob Wilson0058b822015-07-20 22:57:36 +00002865}
2866
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002867static void GenerateHasAttrSpellingStringSwitch(
2868 const std::vector<Record *> &Attrs, raw_ostream &OS,
2869 const std::string &Variety = "", const std::string &Scope = "") {
2870 for (const auto *Attr : Attrs) {
Aaron Ballmana0344c52014-11-14 13:44:02 +00002871 // C++11-style attributes have specific version information associated with
2872 // them. If the attribute has no scope, the version information must not
2873 // have the default value (1), as that's incorrect. Instead, the unscoped
2874 // attribute version information should be taken from the SD-6 standing
2875 // document, which can be found at:
2876 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
2877 int Version = 1;
2878
2879 if (Variety == "CXX11") {
2880 std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
2881 for (const auto &Spelling : Spellings) {
2882 if (Spelling->getValueAsString("Variety") == "CXX11") {
2883 Version = static_cast<int>(Spelling->getValueAsInt("Version"));
2884 if (Scope.empty() && Version == 1)
2885 PrintError(Spelling->getLoc(), "C++ standard attributes must "
2886 "have valid version information.");
2887 break;
2888 }
2889 }
2890 }
2891
Aaron Ballman0fa06d82014-01-09 22:57:44 +00002892 std::string Test;
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002893 if (Attr->isSubClassOf("TargetSpecificAttr")) {
2894 const Record *R = Attr->getValueAsDef("Target");
Craig Topper00648582017-05-31 19:01:22 +00002895 std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
Hans Wennborgdcfba332015-10-06 23:40:43 +00002896 GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
Bob Wilson7c730832015-07-20 22:57:31 +00002897
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002898 // If this is the C++11 variety, also add in the LangOpts test.
2899 if (Variety == "CXX11")
2900 Test += " && LangOpts.CPlusPlus11";
Aaron Ballman606093a2017-10-15 15:01:42 +00002901 else if (Variety == "C2x")
2902 Test += " && LangOpts.DoubleSquareBracketAttributes";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002903 } else if (Variety == "CXX11")
2904 // C++11 mode should be checked against LangOpts, which is presumed to be
2905 // present in the caller.
2906 Test = "LangOpts.CPlusPlus11";
Aaron Ballman606093a2017-10-15 15:01:42 +00002907 else if (Variety == "C2x")
2908 Test = "LangOpts.DoubleSquareBracketAttributes";
Aaron Ballman0fa06d82014-01-09 22:57:44 +00002909
Aaron Ballmana0344c52014-11-14 13:44:02 +00002910 std::string TestStr =
Aaron Ballman28afa182014-11-17 18:17:19 +00002911 !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002912 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002913 for (const auto &S : Spellings)
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002914 if (Variety.empty() || (Variety == S.variety() &&
2915 (Scope.empty() || Scope == S.nameSpace())))
Aaron Ballmana0344c52014-11-14 13:44:02 +00002916 OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002917 }
Aaron Ballmana0344c52014-11-14 13:44:02 +00002918 OS << " .Default(0);\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002919}
2920
2921// Emits the list of spellings for attributes.
2922void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2923 emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
2924
2925 // Separate all of the attributes out into four group: generic, C++11, GNU,
2926 // and declspecs. Then generate a big switch statement for each of them.
2927 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Nico Weber20e08042016-09-03 02:55:10 +00002928 std::vector<Record *> Declspec, Microsoft, GNU, Pragma;
Aaron Ballman606093a2017-10-15 15:01:42 +00002929 std::map<std::string, std::vector<Record *>> CXX, C2x;
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002930
2931 // Walk over the list of all attributes, and split them out based on the
2932 // spelling variety.
2933 for (auto *R : Attrs) {
2934 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
2935 for (const auto &SI : Spellings) {
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00002936 const std::string &Variety = SI.variety();
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002937 if (Variety == "GNU")
2938 GNU.push_back(R);
2939 else if (Variety == "Declspec")
2940 Declspec.push_back(R);
Nico Weber20e08042016-09-03 02:55:10 +00002941 else if (Variety == "Microsoft")
2942 Microsoft.push_back(R);
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00002943 else if (Variety == "CXX11")
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002944 CXX[SI.nameSpace()].push_back(R);
Aaron Ballman606093a2017-10-15 15:01:42 +00002945 else if (Variety == "C2x")
2946 C2x[SI.nameSpace()].push_back(R);
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00002947 else if (Variety == "Pragma")
2948 Pragma.push_back(R);
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002949 }
2950 }
2951
Bob Wilson7c730832015-07-20 22:57:31 +00002952 OS << "const llvm::Triple &T = Target.getTriple();\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002953 OS << "switch (Syntax) {\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002954 OS << "case AttrSyntax::GNU:\n";
Aaron Ballmana0344c52014-11-14 13:44:02 +00002955 OS << " return llvm::StringSwitch<int>(Name)\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002956 GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
2957 OS << "case AttrSyntax::Declspec:\n";
Aaron Ballmana0344c52014-11-14 13:44:02 +00002958 OS << " return llvm::StringSwitch<int>(Name)\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002959 GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
Nico Weber20e08042016-09-03 02:55:10 +00002960 OS << "case AttrSyntax::Microsoft:\n";
2961 OS << " return llvm::StringSwitch<int>(Name)\n";
2962 GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00002963 OS << "case AttrSyntax::Pragma:\n";
Aaron Ballmana0344c52014-11-14 13:44:02 +00002964 OS << " return llvm::StringSwitch<int>(Name)\n";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00002965 GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
Aaron Ballman606093a2017-10-15 15:01:42 +00002966 auto fn = [&OS](const char *Spelling, const char *Variety,
2967 const std::map<std::string, std::vector<Record *>> &List) {
2968 OS << "case AttrSyntax::" << Variety << ": {\n";
2969 // C++11-style attributes are further split out based on the Scope.
2970 for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
Stephen Kellydb8fac12019-01-11 19:16:01 +00002971 if (I != List.cbegin())
2972 OS << " else ";
2973 if (I->first.empty())
2974 OS << "if (ScopeName == \"\") {\n";
2975 else
2976 OS << "if (ScopeName == \"" << I->first << "\") {\n";
2977 OS << " return llvm::StringSwitch<int>(Name)\n";
2978 GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
2979 OS << "}";
Aaron Ballman606093a2017-10-15 15:01:42 +00002980 }
Aaron Ballman4ff3b5ab2017-10-18 12:11:58 +00002981 OS << "\n} break;\n";
Aaron Ballman606093a2017-10-15 15:01:42 +00002982 };
2983 fn("CXX11", "CXX", CXX);
2984 fn("C2x", "C", C2x);
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002985 OS << "}\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002986}
2987
Michael Han99315932013-01-24 16:46:58 +00002988void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002989 emitSourceFileHeader("Code to translate different attribute spellings "
2990 "into internal identifiers", OS);
Michael Han99315932013-01-24 16:46:58 +00002991
John McCall2225c8b2016-03-01 00:18:05 +00002992 OS << " switch (AttrKind) {\n";
Michael Han99315932013-01-24 16:46:58 +00002993
Aaron Ballman64e69862013-12-15 13:05:48 +00002994 ParsedAttrMap Attrs = getParsedAttrList(Records);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002995 for (const auto &I : Attrs) {
Aaron Ballman2f22b942014-05-20 19:47:14 +00002996 const Record &R = *I.second;
Aaron Ballmanc669cc02014-01-27 22:10:04 +00002997 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002998 OS << " case AT_" << I.first << ": {\n";
Richard Smith852e9ce2013-11-27 01:46:48 +00002999 for (unsigned I = 0; I < Spellings.size(); ++ I) {
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003000 OS << " if (Name == \"" << Spellings[I].name() << "\" && "
3001 << "SyntaxUsed == "
3002 << StringSwitch<unsigned>(Spellings[I].variety())
3003 .Case("GNU", 0)
3004 .Case("CXX11", 1)
Aaron Ballman606093a2017-10-15 15:01:42 +00003005 .Case("C2x", 2)
3006 .Case("Declspec", 3)
3007 .Case("Microsoft", 4)
3008 .Case("Keyword", 5)
3009 .Case("Pragma", 6)
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003010 .Default(0)
3011 << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
3012 << " return " << I << ";\n";
Michael Han99315932013-01-24 16:46:58 +00003013 }
Richard Smith852e9ce2013-11-27 01:46:48 +00003014
3015 OS << " break;\n";
3016 OS << " }\n";
Michael Han99315932013-01-24 16:46:58 +00003017 }
3018
3019 OS << " }\n";
Aaron Ballman64e69862013-12-15 13:05:48 +00003020 OS << " return 0;\n";
Michael Han99315932013-01-24 16:46:58 +00003021}
3022
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003023// Emits code used by RecursiveASTVisitor to visit attributes
3024void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
3025 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
3026
3027 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3028
3029 // Write method declarations for Traverse* methods.
3030 // We emit this here because we only generate methods for attributes that
3031 // are declared as ASTNodes.
3032 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00003033 for (const auto *Attr : Attrs) {
3034 const Record &R = *Attr;
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003035 if (!R.getValueAsBit("ASTNode"))
3036 continue;
3037 OS << " bool Traverse"
3038 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
3039 OS << " bool Visit"
3040 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3041 << " return true; \n"
Hans Wennborg4afe5042015-07-22 20:46:26 +00003042 << " }\n";
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003043 }
3044 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
3045
3046 // Write individual Traverse* methods for each attribute class.
Aaron Ballman2f22b942014-05-20 19:47:14 +00003047 for (const auto *Attr : Attrs) {
3048 const Record &R = *Attr;
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003049 if (!R.getValueAsBit("ASTNode"))
3050 continue;
3051
3052 OS << "template <typename Derived>\n"
DeLesley Hutchinsbb79c332013-12-30 21:03:02 +00003053 << "bool VISITORCLASS<Derived>::Traverse"
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003054 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3055 << " if (!getDerived().VisitAttr(A))\n"
3056 << " return false;\n"
3057 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
3058 << " return false;\n";
3059
3060 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
Aaron Ballman2f22b942014-05-20 19:47:14 +00003061 for (const auto *Arg : ArgRecords)
3062 createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003063
3064 OS << " return true;\n";
3065 OS << "}\n\n";
3066 }
3067
3068 // Write generic Traverse routine
3069 OS << "template <typename Derived>\n"
DeLesley Hutchinsbb79c332013-12-30 21:03:02 +00003070 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003071 << " if (!A)\n"
3072 << " return true;\n"
3073 << "\n"
John McCall2225c8b2016-03-01 00:18:05 +00003074 << " switch (A->getKind()) {\n";
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003075
Aaron Ballman2f22b942014-05-20 19:47:14 +00003076 for (const auto *Attr : Attrs) {
3077 const Record &R = *Attr;
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003078 if (!R.getValueAsBit("ASTNode"))
3079 continue;
3080
3081 OS << " case attr::" << R.getName() << ":\n"
3082 << " return getDerived().Traverse" << R.getName() << "Attr("
3083 << "cast<" << R.getName() << "Attr>(A));\n";
3084 }
John McCall5d7cf772016-03-01 02:09:20 +00003085 OS << " }\n"; // end switch
3086 OS << " llvm_unreachable(\"bad attribute kind\");\n";
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003087 OS << "}\n"; // end function
3088 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
3089}
3090
Erich Keanea32910d2017-03-23 18:51:54 +00003091void EmitClangAttrTemplateInstantiateHelper(const std::vector<Record *> &Attrs,
3092 raw_ostream &OS,
3093 bool AppliesToDecl) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003094
Erich Keanea32910d2017-03-23 18:51:54 +00003095 OS << " switch (At->getKind()) {\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00003096 for (const auto *Attr : Attrs) {
3097 const Record &R = *Attr;
Douglas Gregorb2daf842012-05-02 15:56:52 +00003098 if (!R.getValueAsBit("ASTNode"))
3099 continue;
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003100 OS << " case attr::" << R.getName() << ": {\n";
Erich Keanea32910d2017-03-23 18:51:54 +00003101 bool ShouldClone = R.getValueAsBit("Clone") &&
3102 (!AppliesToDecl ||
3103 R.getValueAsBit("MeaningfulToClassTemplateDefinition"));
Rafael Espindola7f90b7d2012-05-15 14:09:55 +00003104
3105 if (!ShouldClone) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00003106 OS << " return nullptr;\n";
Rafael Espindola7f90b7d2012-05-15 14:09:55 +00003107 OS << " }\n";
3108 continue;
3109 }
3110
Eugene Zelenko5f02b772015-12-08 18:49:01 +00003111 OS << " const auto *A = cast<"
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003112 << R.getName() << "Attr>(At);\n";
3113 bool TDependent = R.getValueAsBit("TemplateDependent");
3114
3115 if (!TDependent) {
3116 OS << " return A->clone(C);\n";
3117 OS << " }\n";
3118 continue;
3119 }
3120
3121 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003122 std::vector<std::unique_ptr<Argument>> Args;
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003123 Args.reserve(ArgRecords.size());
3124
Aaron Ballman2f22b942014-05-20 19:47:14 +00003125 for (const auto *ArgRecord : ArgRecords)
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003126 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003127
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003128 for (auto const &ai : Args)
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003129 ai->writeTemplateInstantiation(OS);
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003130
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003131 OS << " return new (C) " << R.getName() << "Attr(A->getLocation(), C";
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003132 for (auto const &ai : Args) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003133 OS << ", ";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003134 ai->writeTemplateInstantiationArgs(OS);
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003135 }
Aaron Ballman36a53502014-01-16 13:03:14 +00003136 OS << ", A->getSpellingListIndex());\n }\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003137 }
3138 OS << " } // end switch\n"
3139 << " llvm_unreachable(\"Unknown attribute!\");\n"
Erich Keanea32910d2017-03-23 18:51:54 +00003140 << " return nullptr;\n";
3141}
3142
3143// Emits code to instantiate dependent attributes on templates.
3144void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
3145 emitSourceFileHeader("Template instantiation code for attributes", OS);
3146
3147 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3148
3149 OS << "namespace clang {\n"
3150 << "namespace sema {\n\n"
3151 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
3152 << "Sema &S,\n"
3153 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3154 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
3155 OS << "}\n\n"
3156 << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
3157 << " ASTContext &C, Sema &S,\n"
3158 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3159 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
3160 OS << "}\n\n"
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00003161 << "} // end namespace sema\n"
3162 << "} // end namespace clang\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003163}
3164
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003165// Emits the list of parsed attributes.
3166void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
3167 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
3168
3169 OS << "#ifndef PARSED_ATTR\n";
3170 OS << "#define PARSED_ATTR(NAME) NAME\n";
3171 OS << "#endif\n\n";
3172
3173 ParsedAttrMap Names = getParsedAttrList(Records);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003174 for (const auto &I : Names) {
3175 OS << "PARSED_ATTR(" << I.first << ")\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003176 }
3177}
3178
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00003179static bool isArgVariadic(const Record &R, StringRef AttrName) {
3180 return createArgument(R, AttrName)->isVariadic();
3181}
3182
Erich Keanedf9e8ae2017-10-16 22:47:26 +00003183static void emitArgInfo(const Record &R, raw_ostream &OS) {
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003184 // This function will count the number of arguments specified for the
3185 // attribute and emit the number of required arguments followed by the
3186 // number of optional arguments.
3187 std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
3188 unsigned ArgCount = 0, OptCount = 0;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00003189 bool HasVariadic = false;
Aaron Ballman2f22b942014-05-20 19:47:14 +00003190 for (const auto *Arg : Args) {
George Burgess IV8a36ace2016-12-01 17:52:39 +00003191 // If the arg is fake, it's the user's job to supply it: general parsing
3192 // logic shouldn't need to know anything about it.
3193 if (Arg->getValueAsBit("Fake"))
3194 continue;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003195 Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00003196 if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
3197 HasVariadic = true;
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003198 }
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00003199
3200 // If there is a variadic argument, we will set the optional argument count
3201 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
3202 OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount);
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003203}
3204
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003205static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
Erich Keanee891aa92018-07-13 15:07:47 +00003206 OS << "static bool defaultAppertainsTo(Sema &, const ParsedAttr &,";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003207 OS << "const Decl *) {\n";
3208 OS << " return true;\n";
3209 OS << "}\n\n";
3210}
3211
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003212static std::string GetDiagnosticSpelling(const Record &R) {
3213 std::string Ret = R.getValueAsString("DiagSpelling");
3214 if (!Ret.empty())
3215 return Ret;
3216
3217 // If we couldn't find the DiagSpelling in this object, we can check to see
3218 // if the object is one that has a base, and if it is, loop up to the Base
3219 // member recursively.
3220 std::string Super = R.getSuperClasses().back().first->getName();
3221 if (Super == "DDecl" || Super == "DStmt")
3222 return GetDiagnosticSpelling(*R.getValueAsDef("Base"));
3223
3224 return "";
3225}
3226
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003227static std::string CalculateDiagnostic(const Record &S) {
3228 // If the SubjectList object has a custom diagnostic associated with it,
3229 // return that directly.
Erich Keane3bff4142017-10-16 23:25:24 +00003230 const StringRef CustomDiag = S.getValueAsString("CustomDiag");
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003231 if (!CustomDiag.empty())
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003232 return ("\"" + Twine(CustomDiag) + "\"").str();
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003233
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003234 std::vector<std::string> DiagList;
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003235 std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
Aaron Ballman2f22b942014-05-20 19:47:14 +00003236 for (const auto *Subject : Subjects) {
3237 const Record &R = *Subject;
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003238 // Get the diagnostic text from the Decl or Stmt node given.
3239 std::string V = GetDiagnosticSpelling(R);
3240 if (V.empty()) {
3241 PrintError(R.getLoc(),
3242 "Could not determine diagnostic spelling for the node: " +
3243 R.getName() + "; please add one to DeclNodes.td");
3244 } else {
3245 // The node may contain a list of elements itself, so split the elements
3246 // by a comma, and trim any whitespace.
3247 SmallVector<StringRef, 2> Frags;
3248 llvm::SplitString(V, Frags, ",");
3249 for (auto Str : Frags) {
3250 DiagList.push_back(Str.trim());
3251 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003252 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003253 }
3254
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003255 if (DiagList.empty()) {
3256 PrintFatalError(S.getLoc(),
3257 "Could not deduce diagnostic argument for Attr subjects");
3258 return "";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003259 }
3260
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003261 // FIXME: this is not particularly good for localization purposes and ideally
3262 // should be part of the diagnostics engine itself with some sort of list
3263 // specifier.
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003264
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003265 // A single member of the list can be returned directly.
3266 if (DiagList.size() == 1)
3267 return '"' + DiagList.front() + '"';
3268
3269 if (DiagList.size() == 2)
3270 return '"' + DiagList[0] + " and " + DiagList[1] + '"';
3271
3272 // If there are more than two in the list, we serialize the first N - 1
3273 // elements with a comma. This leaves the string in the state: foo, bar,
3274 // baz (but misses quux). We can then add ", and " for the last element
3275 // manually.
3276 std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
3277 return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003278}
3279
Aaron Ballman12b9f652014-01-16 13:55:42 +00003280static std::string GetSubjectWithSuffix(const Record *R) {
George Burgess IV1881a572016-12-01 00:13:18 +00003281 const std::string &B = R->getName();
Aaron Ballman12b9f652014-01-16 13:55:42 +00003282 if (B == "DeclBase")
3283 return "Decl";
3284 return B + "Decl";
3285}
Hans Wennborgdcfba332015-10-06 23:40:43 +00003286
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003287static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
3288 return "is" + Subject.getName().str();
3289}
3290
Aaron Ballman80469032013-11-29 14:57:58 +00003291static std::string GenerateCustomAppertainsTo(const Record &Subject,
3292 raw_ostream &OS) {
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003293 std::string FnName = functionNameForCustomAppertainsTo(Subject);
Aaron Ballmana358c902013-12-02 14:58:17 +00003294
Aaron Ballman80469032013-11-29 14:57:58 +00003295 // If this code has already been generated, simply return the previous
3296 // instance of it.
3297 static std::set<std::string> CustomSubjectSet;
Eugene Zelenko5f02b772015-12-08 18:49:01 +00003298 auto I = CustomSubjectSet.find(FnName);
Aaron Ballman80469032013-11-29 14:57:58 +00003299 if (I != CustomSubjectSet.end())
3300 return *I;
3301
3302 Record *Base = Subject.getValueAsDef("Base");
3303
3304 // Not currently support custom subjects within custom subjects.
3305 if (Base->isSubClassOf("SubsetSubject")) {
3306 PrintFatalError(Subject.getLoc(),
3307 "SubsetSubjects within SubsetSubjects is not supported");
3308 return "";
3309 }
3310
Aaron Ballman80469032013-11-29 14:57:58 +00003311 OS << "static bool " << FnName << "(const Decl *D) {\n";
Erich Keane873de982018-08-03 14:24:34 +00003312 OS << " if (const auto *S = dyn_cast<";
3313 OS << GetSubjectWithSuffix(Base);
3314 OS << ">(D))\n";
3315 OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
Aaron Ballman47553042014-01-16 14:32:03 +00003316 OS << " return false;\n";
Aaron Ballman80469032013-11-29 14:57:58 +00003317 OS << "}\n\n";
3318
3319 CustomSubjectSet.insert(FnName);
3320 return FnName;
3321}
3322
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003323static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
3324 // If the attribute does not contain a Subjects definition, then use the
3325 // default appertainsTo logic.
3326 if (Attr.isValueUnset("Subjects"))
Aaron Ballman93b5cc62013-12-02 19:36:42 +00003327 return "defaultAppertainsTo";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003328
3329 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
3330 std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
3331
3332 // If the list of subjects is empty, it is assumed that the attribute
3333 // appertains to everything.
3334 if (Subjects.empty())
Aaron Ballman93b5cc62013-12-02 19:36:42 +00003335 return "defaultAppertainsTo";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003336
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003337 bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
3338
3339 // Otherwise, generate an appertainsTo check specific to this attribute which
3340 // checks all of the given subjects against the Decl passed in. Return the
3341 // name of that check to the caller.
Richard Smithf4e248c2018-08-01 00:33:25 +00003342 //
3343 // If D is null, that means the attribute was not applied to a declaration
3344 // at all (for instance because it was applied to a type), or that the caller
3345 // has determined that the check should fail (perhaps prior to the creation
3346 // of the declaration).
Matthias Braunbbbf5d42016-12-04 05:55:09 +00003347 std::string FnName = "check" + Attr.getName().str() + "AppertainsTo";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003348 std::stringstream SS;
Erich Keanee891aa92018-07-13 15:07:47 +00003349 SS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr, ";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003350 SS << "const Decl *D) {\n";
Richard Smithf4e248c2018-08-01 00:33:25 +00003351 SS << " if (!D || (";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003352 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
Aaron Ballman80469032013-11-29 14:57:58 +00003353 // If the subject has custom code associated with it, generate a function
3354 // for it. The function cannot be inlined into this check (yet) because it
3355 // requires the subject to be of a specific type, and were that information
3356 // inlined here, it would not support an attribute with multiple custom
3357 // subjects.
3358 if ((*I)->isSubClassOf("SubsetSubject")) {
3359 SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
3360 } else {
Aaron Ballman12b9f652014-01-16 13:55:42 +00003361 SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
Aaron Ballman80469032013-11-29 14:57:58 +00003362 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003363
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003364 if (I + 1 != E)
3365 SS << " && ";
3366 }
Richard Smithf4e248c2018-08-01 00:33:25 +00003367 SS << ")) {\n";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003368 SS << " S.Diag(Attr.getLoc(), diag::";
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003369 SS << (Warn ? "warn_attribute_wrong_decl_type_str" :
3370 "err_attribute_wrong_decl_type_str");
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003371 SS << ")\n";
Erich Keane44bacdf2018-08-09 13:21:32 +00003372 SS << " << Attr << ";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003373 SS << CalculateDiagnostic(*SubjectObj) << ";\n";
3374 SS << " return false;\n";
3375 SS << " }\n";
3376 SS << " return true;\n";
3377 SS << "}\n\n";
3378
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003379 OS << SS.str();
3380 return FnName;
3381}
3382
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003383static void
3384emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
3385 raw_ostream &OS) {
3386 OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
3387 << AttributeSubjectMatchRule::EnumName << " rule) {\n";
3388 OS << " switch (rule) {\n";
3389 for (const auto &Rule : PragmaAttributeSupport.Rules) {
3390 if (Rule.isAbstractRule()) {
3391 OS << " case " << Rule.getEnumValue() << ":\n";
3392 OS << " assert(false && \"Abstract matcher rule isn't allowed\");\n";
3393 OS << " return false;\n";
3394 continue;
3395 }
3396 std::vector<Record *> Subjects = Rule.getSubjects();
3397 assert(!Subjects.empty() && "Missing subjects");
3398 OS << " case " << Rule.getEnumValue() << ":\n";
3399 OS << " return ";
3400 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
3401 // If the subject has custom code associated with it, use the function
3402 // that was generated for GenerateAppertainsTo to check if the declaration
3403 // is valid.
3404 if ((*I)->isSubClassOf("SubsetSubject"))
3405 OS << functionNameForCustomAppertainsTo(**I) << "(D)";
3406 else
3407 OS << "isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3408
3409 if (I + 1 != E)
3410 OS << " || ";
3411 }
3412 OS << ";\n";
3413 }
3414 OS << " }\n";
3415 OS << " llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
3416 OS << "}\n\n";
3417}
3418
Aaron Ballman3aff6332013-12-02 19:30:36 +00003419static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
3420 OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
Erich Keanee891aa92018-07-13 15:07:47 +00003421 OS << "const ParsedAttr &) {\n";
Aaron Ballman3aff6332013-12-02 19:30:36 +00003422 OS << " return true;\n";
3423 OS << "}\n\n";
3424}
3425
3426static std::string GenerateLangOptRequirements(const Record &R,
3427 raw_ostream &OS) {
3428 // If the attribute has an empty or unset list of language requirements,
3429 // return the default handler.
3430 std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
3431 if (LangOpts.empty())
3432 return "defaultDiagnoseLangOpts";
3433
3434 // Generate the test condition, as well as a unique function name for the
3435 // diagnostic test. The list of options should usually be short (one or two
3436 // options), and the uniqueness isn't strictly necessary (it is just for
3437 // codegen efficiency).
3438 std::string FnName = "check", Test;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003439 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
Erich Keane3bff4142017-10-16 23:25:24 +00003440 const StringRef Part = (*I)->getValueAsString("Name");
Eric Fiselier341e8252016-09-02 18:53:31 +00003441 if ((*I)->getValueAsBit("Negated")) {
3442 FnName += "Not";
Alexis Hunt724f14e2014-11-28 00:53:20 +00003443 Test += "!";
Eric Fiselier341e8252016-09-02 18:53:31 +00003444 }
Erich Keane3bff4142017-10-16 23:25:24 +00003445 Test += "S.LangOpts.";
3446 Test += Part;
Aaron Ballman3aff6332013-12-02 19:30:36 +00003447 if (I + 1 != E)
3448 Test += " || ";
3449 FnName += Part;
3450 }
3451 FnName += "LangOpts";
3452
3453 // If this code has already been generated, simply return the previous
3454 // instance of it.
3455 static std::set<std::string> CustomLangOptsSet;
Eugene Zelenko5f02b772015-12-08 18:49:01 +00003456 auto I = CustomLangOptsSet.find(FnName);
Aaron Ballman3aff6332013-12-02 19:30:36 +00003457 if (I != CustomLangOptsSet.end())
3458 return *I;
3459
Erich Keanee891aa92018-07-13 15:07:47 +00003460 OS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr) {\n";
Aaron Ballman3aff6332013-12-02 19:30:36 +00003461 OS << " if (" << Test << ")\n";
3462 OS << " return true;\n\n";
3463 OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
3464 OS << "<< Attr.getName();\n";
3465 OS << " return false;\n";
3466 OS << "}\n\n";
3467
3468 CustomLangOptsSet.insert(FnName);
3469 return FnName;
3470}
3471
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003472static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
Bob Wilson7c730832015-07-20 22:57:31 +00003473 OS << "static bool defaultTargetRequirements(const TargetInfo &) {\n";
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003474 OS << " return true;\n";
3475 OS << "}\n\n";
3476}
3477
3478static std::string GenerateTargetRequirements(const Record &Attr,
3479 const ParsedAttrMap &Dupes,
3480 raw_ostream &OS) {
3481 // If the attribute is not a target specific attribute, return the default
3482 // target handler.
3483 if (!Attr.isSubClassOf("TargetSpecificAttr"))
3484 return "defaultTargetRequirements";
3485
3486 // Get the list of architectures to be tested for.
3487 const Record *R = Attr.getValueAsDef("Target");
Craig Topper00648582017-05-31 19:01:22 +00003488 std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003489
3490 // If there are other attributes which share the same parsed attribute kind,
3491 // such as target-specific attributes with a shared spelling, collapse the
3492 // duplicate architectures. This is required because a shared target-specific
Erich Keanee891aa92018-07-13 15:07:47 +00003493 // attribute has only one ParsedAttr::Kind enumeration value, but it
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003494 // applies to multiple target architectures. In order for the attribute to be
3495 // considered valid, all of its architectures need to be included.
3496 if (!Attr.isValueUnset("ParseKind")) {
Erich Keane3bff4142017-10-16 23:25:24 +00003497 const StringRef APK = Attr.getValueAsString("ParseKind");
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003498 for (const auto &I : Dupes) {
3499 if (I.first == APK) {
Craig Topper00648582017-05-31 19:01:22 +00003500 std::vector<StringRef> DA =
3501 I.second->getValueAsDef("Target")->getValueAsListOfStrings(
3502 "Arches");
3503 Arches.insert(Arches.end(), DA.begin(), DA.end());
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003504 }
3505 }
3506 }
3507
Bob Wilson0058b822015-07-20 22:57:36 +00003508 std::string FnName = "isTarget";
3509 std::string Test;
3510 GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
Bob Wilson7c730832015-07-20 22:57:31 +00003511
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003512 // If this code has already been generated, simply return the previous
3513 // instance of it.
3514 static std::set<std::string> CustomTargetSet;
Eugene Zelenko5f02b772015-12-08 18:49:01 +00003515 auto I = CustomTargetSet.find(FnName);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003516 if (I != CustomTargetSet.end())
3517 return *I;
3518
Bob Wilson7c730832015-07-20 22:57:31 +00003519 OS << "static bool " << FnName << "(const TargetInfo &Target) {\n";
3520 OS << " const llvm::Triple &T = Target.getTriple();\n";
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003521 OS << " return " << Test << ";\n";
3522 OS << "}\n\n";
3523
3524 CustomTargetSet.insert(FnName);
3525 return FnName;
3526}
3527
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003528static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
3529 OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
Erich Keanee891aa92018-07-13 15:07:47 +00003530 << "const ParsedAttr &Attr) {\n";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003531 OS << " return UINT_MAX;\n";
3532 OS << "}\n\n";
3533}
3534
3535static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
3536 raw_ostream &OS) {
3537 // If the attribute does not have a semantic form, we can bail out early.
3538 if (!Attr.getValueAsBit("ASTNode"))
3539 return "defaultSpellingIndexToSemanticSpelling";
3540
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003541 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003542
3543 // If there are zero or one spellings, or all of the spellings share the same
3544 // name, we can also bail out early.
3545 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
3546 return "defaultSpellingIndexToSemanticSpelling";
3547
3548 // Generate the enumeration we will use for the mapping.
3549 SemanticSpellingMap SemanticToSyntacticMap;
3550 std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
Matthias Braunbbbf5d42016-12-04 05:55:09 +00003551 std::string Name = Attr.getName().str() + "AttrSpellingMap";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003552
Erich Keanee891aa92018-07-13 15:07:47 +00003553 OS << "static unsigned " << Name << "(const ParsedAttr &Attr) {\n";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003554 OS << Enum;
3555 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
3556 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
3557 OS << "}\n\n";
3558
3559 return Name;
3560}
3561
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003562static bool IsKnownToGCC(const Record &Attr) {
3563 // Look at the spellings for this subject; if there are any spellings which
3564 // claim to be known to GCC, the attribute is known to GCC.
George Burgess IV1881a572016-12-01 00:13:18 +00003565 return llvm::any_of(
3566 GetFlattenedSpellings(Attr),
3567 [](const FlattenedSpelling &S) { return S.knownToGCC(); });
Aaron Ballman9a99e0d2014-01-20 17:18:35 +00003568}
3569
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003570/// Emits the parsed attribute helpers
3571void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3572 emitSourceFileHeader("Parsed attribute helpers", OS);
3573
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003574 PragmaClangAttributeSupport &PragmaAttributeSupport =
3575 getPragmaAttributeSupport(Records);
3576
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003577 // Get the list of parsed attributes, and accept the optional list of
3578 // duplicates due to the ParseKind.
3579 ParsedAttrMap Dupes;
3580 ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003581
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003582 // Generate the default appertainsTo, target and language option diagnostic,
3583 // and spelling list index mapping methods.
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003584 GenerateDefaultAppertainsTo(OS);
Aaron Ballman3aff6332013-12-02 19:30:36 +00003585 GenerateDefaultLangOptRequirements(OS);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003586 GenerateDefaultTargetRequirements(OS);
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003587 GenerateDefaultSpellingIndexToSemanticSpelling(OS);
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003588
3589 // Generate the appertainsTo diagnostic methods and write their names into
3590 // another mapping. At the same time, generate the AttrInfoMap object
3591 // contents. Due to the reliance on generated code, use separate streams so
3592 // that code will not be interleaved.
Erich Keanedf9e8ae2017-10-16 22:47:26 +00003593 std::string Buffer;
3594 raw_string_ostream SS {Buffer};
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003595 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003596 // TODO: If the attribute's kind appears in the list of duplicates, that is
3597 // because it is a target-specific attribute that appears multiple times.
3598 // It would be beneficial to test whether the duplicates are "similar
3599 // enough" to each other to not cause problems. For instance, check that
Alp Toker96cf7582014-01-18 21:49:37 +00003600 // the spellings are identical, and custom parsing rules match, etc.
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003601
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003602 // We need to generate struct instances based off ParsedAttrInfo from
Erich Keanee891aa92018-07-13 15:07:47 +00003603 // ParsedAttr.cpp.
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003604 SS << " { ";
3605 emitArgInfo(*I->second, SS);
3606 SS << ", " << I->second->getValueAsBit("HasCustomParsing");
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003607 SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
Aaron Ballmanb9a457a2018-05-03 15:33:50 +00003608 SS << ", "
3609 << (I->second->isSubClassOf("TypeAttr") ||
3610 I->second->isSubClassOf("DeclOrTypeAttr"));
Richard Smith4f902c72016-03-08 00:32:55 +00003611 SS << ", " << I->second->isSubClassOf("StmtAttr");
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003612 SS << ", " << IsKnownToGCC(*I->second);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003613 SS << ", " << PragmaAttributeSupport.isAttributedSupported(*I->second);
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003614 SS << ", " << GenerateAppertainsTo(*I->second, OS);
Aaron Ballman3aff6332013-12-02 19:30:36 +00003615 SS << ", " << GenerateLangOptRequirements(*I->second, OS);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003616 SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003617 SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003618 SS << ", "
3619 << PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003620 SS << " }";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003621
3622 if (I + 1 != E)
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003623 SS << ",";
3624
3625 SS << " // AT_" << I->first << "\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003626 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003627
Erich Keanee891aa92018-07-13 15:07:47 +00003628 OS << "static const ParsedAttrInfo AttrInfoMap[ParsedAttr::UnknownAttribute "
3629 "+ 1] = {\n";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003630 OS << SS.str();
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003631 OS << "};\n\n";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003632
3633 // Generate the attribute match rules.
3634 emitAttributeMatchRules(PragmaAttributeSupport, OS);
Michael Han4a045172012-03-07 00:12:16 +00003635}
3636
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00003637// Emits the kind list of parsed attributes
3638void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00003639 emitSourceFileHeader("Attribute name matcher", OS);
3640
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003641 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Nico Weber20e08042016-09-03 02:55:10 +00003642 std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
Aaron Ballman606093a2017-10-15 15:01:42 +00003643 Keywords, Pragma, C2x;
Aaron Ballman64e69862013-12-15 13:05:48 +00003644 std::set<std::string> Seen;
Aaron Ballman2f22b942014-05-20 19:47:14 +00003645 for (const auto *A : Attrs) {
3646 const Record &Attr = *A;
Richard Smith852e9ce2013-11-27 01:46:48 +00003647
Michael Han4a045172012-03-07 00:12:16 +00003648 bool SemaHandler = Attr.getValueAsBit("SemaHandler");
Douglas Gregor19fbb8f2012-05-02 16:18:45 +00003649 bool Ignored = Attr.getValueAsBit("Ignored");
Douglas Gregor19fbb8f2012-05-02 16:18:45 +00003650 if (SemaHandler || Ignored) {
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003651 // Attribute spellings can be shared between target-specific attributes,
3652 // and can be shared between syntaxes for the same attribute. For
3653 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
3654 // specific attribute, or MSP430-specific attribute. Additionally, an
3655 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
3656 // for the same semantic attribute. Ultimately, we need to map each of
Erich Keanee891aa92018-07-13 15:07:47 +00003657 // these to a single ParsedAttr::Kind value, but the StringMatcher
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003658 // class cannot handle duplicate match strings. So we generate a list of
3659 // string to match based on the syntax, and emit multiple string matchers
3660 // depending on the syntax used.
Aaron Ballman64e69862013-12-15 13:05:48 +00003661 std::string AttrName;
3662 if (Attr.isSubClassOf("TargetSpecificAttr") &&
3663 !Attr.isValueUnset("ParseKind")) {
3664 AttrName = Attr.getValueAsString("ParseKind");
3665 if (Seen.find(AttrName) != Seen.end())
3666 continue;
3667 Seen.insert(AttrName);
3668 } else
3669 AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
3670
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003671 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003672 for (const auto &S : Spellings) {
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00003673 const std::string &RawSpelling = S.name();
Craig Topper8ae12032014-05-07 06:21:57 +00003674 std::vector<StringMatcher::StringPair> *Matches = nullptr;
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00003675 std::string Spelling;
3676 const std::string &Variety = S.variety();
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003677 if (Variety == "CXX11") {
3678 Matches = &CXX11;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003679 Spelling += S.nameSpace();
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003680 Spelling += "::";
Aaron Ballman606093a2017-10-15 15:01:42 +00003681 } else if (Variety == "C2x") {
3682 Matches = &C2x;
3683 Spelling += S.nameSpace();
3684 Spelling += "::";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003685 } else if (Variety == "GNU")
3686 Matches = &GNU;
3687 else if (Variety == "Declspec")
3688 Matches = &Declspec;
Nico Weber20e08042016-09-03 02:55:10 +00003689 else if (Variety == "Microsoft")
3690 Matches = &Microsoft;
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003691 else if (Variety == "Keyword")
3692 Matches = &Keywords;
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003693 else if (Variety == "Pragma")
3694 Matches = &Pragma;
Alexis Hunta0e54d42012-06-18 16:13:52 +00003695
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003696 assert(Matches && "Unsupported spelling variety found");
3697
Justin Lebar4086fe52017-01-05 16:51:54 +00003698 if (Variety == "GNU")
3699 Spelling += NormalizeGNUAttrSpelling(RawSpelling);
3700 else
3701 Spelling += RawSpelling;
3702
Douglas Gregor19fbb8f2012-05-02 16:18:45 +00003703 if (SemaHandler)
Erich Keanee891aa92018-07-13 15:07:47 +00003704 Matches->push_back(StringMatcher::StringPair(
3705 Spelling, "return ParsedAttr::AT_" + AttrName + ";"));
Douglas Gregor19fbb8f2012-05-02 16:18:45 +00003706 else
Erich Keanee891aa92018-07-13 15:07:47 +00003707 Matches->push_back(StringMatcher::StringPair(
3708 Spelling, "return ParsedAttr::IgnoredAttribute;"));
Michael Han4a045172012-03-07 00:12:16 +00003709 }
3710 }
3711 }
Erich Keanee891aa92018-07-13 15:07:47 +00003712
3713 OS << "static ParsedAttr::Kind getAttrKind(StringRef Name, ";
3714 OS << "ParsedAttr::Syntax Syntax) {\n";
3715 OS << " if (ParsedAttr::AS_GNU == Syntax) {\n";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003716 StringMatcher("Name", GNU, OS).Emit();
Erich Keanee891aa92018-07-13 15:07:47 +00003717 OS << " } else if (ParsedAttr::AS_Declspec == Syntax) {\n";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003718 StringMatcher("Name", Declspec, OS).Emit();
Erich Keanee891aa92018-07-13 15:07:47 +00003719 OS << " } else if (ParsedAttr::AS_Microsoft == Syntax) {\n";
Nico Weber20e08042016-09-03 02:55:10 +00003720 StringMatcher("Name", Microsoft, OS).Emit();
Erich Keanee891aa92018-07-13 15:07:47 +00003721 OS << " } else if (ParsedAttr::AS_CXX11 == Syntax) {\n";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003722 StringMatcher("Name", CXX11, OS).Emit();
Erich Keanee891aa92018-07-13 15:07:47 +00003723 OS << " } else if (ParsedAttr::AS_C2x == Syntax) {\n";
Aaron Ballman606093a2017-10-15 15:01:42 +00003724 StringMatcher("Name", C2x, OS).Emit();
Erich Keanee891aa92018-07-13 15:07:47 +00003725 OS << " } else if (ParsedAttr::AS_Keyword == Syntax || ";
3726 OS << "ParsedAttr::AS_ContextSensitiveKeyword == Syntax) {\n";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003727 StringMatcher("Name", Keywords, OS).Emit();
Erich Keanee891aa92018-07-13 15:07:47 +00003728 OS << " } else if (ParsedAttr::AS_Pragma == Syntax) {\n";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003729 StringMatcher("Name", Pragma, OS).Emit();
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003730 OS << " }\n";
Erich Keanee891aa92018-07-13 15:07:47 +00003731 OS << " return ParsedAttr::UnknownAttribute;\n"
Douglas Gregor377f99b2012-05-02 17:33:51 +00003732 << "}\n";
Michael Han4a045172012-03-07 00:12:16 +00003733}
3734
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003735// Emits the code to dump an attribute.
Stephen Kellydb8fac12019-01-11 19:16:01 +00003736void EmitClangAttrTextNodeDump(RecordKeeper &Records, raw_ostream &OS) {
3737 emitSourceFileHeader("Attribute text node dumper", OS);
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00003738
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003739 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
Aaron Ballman2f22b942014-05-20 19:47:14 +00003740 for (const auto *Attr : Attrs) {
3741 const Record &R = *Attr;
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003742 if (!R.getValueAsBit("ASTNode"))
3743 continue;
Aaron Ballmanbc909612014-01-22 21:51:20 +00003744
3745 // If the attribute has a semantically-meaningful name (which is determined
3746 // by whether there is a Spelling enumeration for it), then write out the
3747 // spelling used for the attribute.
Stephen Kellydb8fac12019-01-11 19:16:01 +00003748
3749 std::string FunctionContent;
3750 llvm::raw_string_ostream SS(FunctionContent);
3751
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003752 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Aaron Ballmanbc909612014-01-22 21:51:20 +00003753 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
Stephen Kellydb8fac12019-01-11 19:16:01 +00003754 SS << " OS << \" \" << A->getSpelling();\n";
Aaron Ballmanbc909612014-01-22 21:51:20 +00003755
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003756 Args = R.getValueAsListOfDefs("Args");
Stephen Kellydb8fac12019-01-11 19:16:01 +00003757 for (const auto *Arg : Args)
3758 createArgument(*Arg, R.getName())->writeDump(SS);
Richard Trieude5cc7d2013-01-31 01:44:26 +00003759
Stephen Kellydb8fac12019-01-11 19:16:01 +00003760 if (SS.tell()) {
3761 OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
3762 << "Attr *A) {\n";
3763 if (!Args.empty())
3764 OS << " const auto *SA = cast<" << R.getName()
3765 << "Attr>(A); (void)SA;\n";
3766 OS << SS.str();
3767 OS << " }\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003768 }
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003769 }
Stephen Kellydb8fac12019-01-11 19:16:01 +00003770}
3771
3772void EmitClangAttrNodeTraverse(RecordKeeper &Records, raw_ostream &OS) {
3773 emitSourceFileHeader("Attribute text node traverser", OS);
3774
3775 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
3776 for (const auto *Attr : Attrs) {
3777 const Record &R = *Attr;
3778 if (!R.getValueAsBit("ASTNode"))
3779 continue;
3780
3781 std::string FunctionContent;
3782 llvm::raw_string_ostream SS(FunctionContent);
3783
3784 Args = R.getValueAsListOfDefs("Args");
3785 for (const auto *Arg : Args)
3786 createArgument(*Arg, R.getName())->writeDumpChildren(SS);
3787 if (SS.tell()) {
3788 OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
3789 << "Attr *A) {\n";
3790 if (!Args.empty())
3791 OS << " const auto *SA = cast<" << R.getName()
3792 << "Attr>(A); (void)SA;\n";
3793 OS << SS.str();
3794 OS << " }\n";
3795 }
3796 }
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003797}
3798
Aaron Ballman35db2b32014-01-29 22:13:45 +00003799void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
3800 raw_ostream &OS) {
3801 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
3802 emitClangAttrArgContextList(Records, OS);
3803 emitClangAttrIdentifierArgList(Records, OS);
Erich Keane3efe0022018-07-20 14:13:28 +00003804 emitClangAttrVariadicIdentifierArgList(Records, OS);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00003805 emitClangAttrThisIsaIdentifierArgList(Records, OS);
Aaron Ballman35db2b32014-01-29 22:13:45 +00003806 emitClangAttrTypeArgList(Records, OS);
3807 emitClangAttrLateParsedList(Records, OS);
3808}
3809
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003810void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper &Records,
3811 raw_ostream &OS) {
3812 getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
3813}
3814
Richard Smith09ac4a12018-08-30 19:16:33 +00003815enum class SpellingKind {
3816 GNU,
3817 CXX11,
3818 C2x,
3819 Declspec,
3820 Microsoft,
3821 Keyword,
3822 Pragma,
3823};
3824static const size_t NumSpellingKinds = (size_t)SpellingKind::Pragma + 1;
3825
3826class SpellingList {
3827 std::vector<std::string> Spellings[NumSpellingKinds];
3828
3829public:
3830 ArrayRef<std::string> operator[](SpellingKind K) const {
3831 return Spellings[(size_t)K];
3832 }
3833
3834 void add(const Record &Attr, FlattenedSpelling Spelling) {
3835 SpellingKind Kind = StringSwitch<SpellingKind>(Spelling.variety())
3836 .Case("GNU", SpellingKind::GNU)
3837 .Case("CXX11", SpellingKind::CXX11)
3838 .Case("C2x", SpellingKind::C2x)
3839 .Case("Declspec", SpellingKind::Declspec)
3840 .Case("Microsoft", SpellingKind::Microsoft)
3841 .Case("Keyword", SpellingKind::Keyword)
3842 .Case("Pragma", SpellingKind::Pragma);
3843 std::string Name;
3844 if (!Spelling.nameSpace().empty()) {
3845 switch (Kind) {
3846 case SpellingKind::CXX11:
3847 case SpellingKind::C2x:
3848 Name = Spelling.nameSpace() + "::";
3849 break;
3850 case SpellingKind::Pragma:
3851 Name = Spelling.nameSpace() + " ";
3852 break;
3853 default:
3854 PrintFatalError(Attr.getLoc(), "Unexpected namespace in spelling");
3855 }
3856 }
3857 Name += Spelling.name();
3858
3859 Spellings[(size_t)Kind].push_back(Name);
3860 }
3861};
3862
Aaron Ballman97dba042014-02-17 15:27:10 +00003863class DocumentationData {
3864public:
Aaron Ballman1a3e5852014-02-17 16:18:32 +00003865 const Record *Documentation;
3866 const Record *Attribute;
Erich Keanea98a2be2017-10-16 20:31:05 +00003867 std::string Heading;
Richard Smith09ac4a12018-08-30 19:16:33 +00003868 SpellingList SupportedSpellings;
Aaron Ballman97dba042014-02-17 15:27:10 +00003869
Erich Keanea98a2be2017-10-16 20:31:05 +00003870 DocumentationData(const Record &Documentation, const Record &Attribute,
Richard Smith09ac4a12018-08-30 19:16:33 +00003871 std::pair<std::string, SpellingList> HeadingAndSpellings)
Erich Keanea98a2be2017-10-16 20:31:05 +00003872 : Documentation(&Documentation), Attribute(&Attribute),
Richard Smith09ac4a12018-08-30 19:16:33 +00003873 Heading(std::move(HeadingAndSpellings.first)),
3874 SupportedSpellings(std::move(HeadingAndSpellings.second)) {}
Aaron Ballman97dba042014-02-17 15:27:10 +00003875};
3876
Aaron Ballman4de1b582014-02-19 22:59:32 +00003877static void WriteCategoryHeader(const Record *DocCategory,
Aaron Ballman97dba042014-02-17 15:27:10 +00003878 raw_ostream &OS) {
Erich Keane3bff4142017-10-16 23:25:24 +00003879 const StringRef Name = DocCategory->getValueAsString("Name");
3880 OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
Aaron Ballman4de1b582014-02-19 22:59:32 +00003881
3882 // If there is content, print that as well.
Erich Keane3bff4142017-10-16 23:25:24 +00003883 const StringRef ContentStr = DocCategory->getValueAsString("Content");
Benjamin Kramer5c404072015-04-10 21:37:21 +00003884 // Trim leading and trailing newlines and spaces.
Erich Keane3bff4142017-10-16 23:25:24 +00003885 OS << ContentStr.trim();
Benjamin Kramer5c404072015-04-10 21:37:21 +00003886
Aaron Ballman4de1b582014-02-19 22:59:32 +00003887 OS << "\n\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00003888}
3889
Richard Smith09ac4a12018-08-30 19:16:33 +00003890static std::pair<std::string, SpellingList>
3891GetAttributeHeadingAndSpellings(const Record &Documentation,
3892 const Record &Attribute) {
Aaron Ballman97dba042014-02-17 15:27:10 +00003893 // FIXME: there is no way to have a per-spelling category for the attribute
3894 // documentation. This may not be a limiting factor since the spellings
3895 // should generally be consistently applied across the category.
3896
Erich Keanea98a2be2017-10-16 20:31:05 +00003897 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
Richard Smith09ac4a12018-08-30 19:16:33 +00003898 if (Spellings.empty())
3899 PrintFatalError(Attribute.getLoc(),
3900 "Attribute has no supported spellings; cannot be "
3901 "documented");
Aaron Ballman97dba042014-02-17 15:27:10 +00003902
3903 // Determine the heading to be used for this attribute.
Erich Keanea98a2be2017-10-16 20:31:05 +00003904 std::string Heading = Documentation.getValueAsString("Heading");
Aaron Ballman97dba042014-02-17 15:27:10 +00003905 if (Heading.empty()) {
3906 // If there's only one spelling, we can simply use that.
3907 if (Spellings.size() == 1)
3908 Heading = Spellings.begin()->name();
3909 else {
3910 std::set<std::string> Uniques;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003911 for (auto I = Spellings.begin(), E = Spellings.end();
3912 I != E && Uniques.size() <= 1; ++I) {
Aaron Ballman97dba042014-02-17 15:27:10 +00003913 std::string Spelling = NormalizeNameForSpellingComparison(I->name());
3914 Uniques.insert(Spelling);
3915 }
3916 // If the semantic map has only one spelling, that is sufficient for our
3917 // needs.
3918 if (Uniques.size() == 1)
3919 Heading = *Uniques.begin();
3920 }
3921 }
3922
3923 // If the heading is still empty, it is an error.
3924 if (Heading.empty())
Erich Keanea98a2be2017-10-16 20:31:05 +00003925 PrintFatalError(Attribute.getLoc(),
Aaron Ballman97dba042014-02-17 15:27:10 +00003926 "This attribute requires a heading to be specified");
3927
Richard Smith09ac4a12018-08-30 19:16:33 +00003928 SpellingList SupportedSpellings;
3929 for (const auto &I : Spellings)
3930 SupportedSpellings.add(Attribute, I);
Aaron Ballman97dba042014-02-17 15:27:10 +00003931
Richard Smith09ac4a12018-08-30 19:16:33 +00003932 return std::make_pair(std::move(Heading), std::move(SupportedSpellings));
Erich Keanea98a2be2017-10-16 20:31:05 +00003933}
3934
3935static void WriteDocumentation(RecordKeeper &Records,
3936 const DocumentationData &Doc, raw_ostream &OS) {
3937 OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00003938
3939 // List what spelling syntaxes the attribute supports.
3940 OS << ".. csv-table:: Supported Syntaxes\n";
Richard Smith09ac4a12018-08-30 19:16:33 +00003941 OS << " :header: \"GNU\", \"C++11\", \"C2x\", \"``__declspec``\",";
3942 OS << " \"Keyword\", \"``#pragma``\", \"``#pragma clang attribute``\"\n\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00003943 OS << " \"";
Richard Smith09ac4a12018-08-30 19:16:33 +00003944 for (size_t Kind = 0; Kind != NumSpellingKinds; ++Kind) {
3945 SpellingKind K = (SpellingKind)Kind;
Richard Smith23ff7e82018-08-30 19:19:15 +00003946 // TODO: List Microsoft (IDL-style attribute) spellings once we fully
3947 // support them.
Richard Smith09ac4a12018-08-30 19:16:33 +00003948 if (K == SpellingKind::Microsoft)
3949 continue;
3950
3951 bool PrintedAny = false;
3952 for (StringRef Spelling : Doc.SupportedSpellings[K]) {
3953 if (PrintedAny)
3954 OS << " |br| ";
3955 OS << "``" << Spelling << "``";
3956 PrintedAny = true;
3957 }
3958
3959 OS << "\",\"";
3960 }
3961
3962 if (getPragmaAttributeSupport(Records).isAttributedSupported(
3963 *Doc.Attribute))
3964 OS << "Yes";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003965 OS << "\"\n\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00003966
3967 // If the attribute is deprecated, print a message about it, and possibly
3968 // provide a replacement attribute.
Aaron Ballman1a3e5852014-02-17 16:18:32 +00003969 if (!Doc.Documentation->isValueUnset("Deprecated")) {
Aaron Ballman97dba042014-02-17 15:27:10 +00003970 OS << "This attribute has been deprecated, and may be removed in a future "
3971 << "version of Clang.";
Aaron Ballman1a3e5852014-02-17 16:18:32 +00003972 const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
Erich Keane3bff4142017-10-16 23:25:24 +00003973 const StringRef Replacement = Deprecated.getValueAsString("Replacement");
Aaron Ballman97dba042014-02-17 15:27:10 +00003974 if (!Replacement.empty())
Joel E. Denny6053ec22018-02-28 16:57:33 +00003975 OS << " This attribute has been superseded by ``" << Replacement
3976 << "``.";
Aaron Ballman97dba042014-02-17 15:27:10 +00003977 OS << "\n\n";
3978 }
3979
Erich Keane3bff4142017-10-16 23:25:24 +00003980 const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
Aaron Ballman97dba042014-02-17 15:27:10 +00003981 // Trim leading and trailing newlines and spaces.
Erich Keane3bff4142017-10-16 23:25:24 +00003982 OS << ContentStr.trim();
Aaron Ballman97dba042014-02-17 15:27:10 +00003983
3984 OS << "\n\n\n";
3985}
3986
3987void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
3988 // Get the documentation introduction paragraph.
3989 const Record *Documentation = Records.getDef("GlobalDocumentation");
3990 if (!Documentation) {
3991 PrintFatalError("The Documentation top-level definition is missing, "
3992 "no documentation will be generated.");
3993 return;
3994 }
3995
Aaron Ballman4de1b582014-02-19 22:59:32 +00003996 OS << Documentation->getValueAsString("Intro") << "\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00003997
Aaron Ballman97dba042014-02-17 15:27:10 +00003998 // Gather the Documentation lists from each of the attributes, based on the
3999 // category provided.
4000 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00004001 std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
Aaron Ballman2f22b942014-05-20 19:47:14 +00004002 for (const auto *A : Attrs) {
4003 const Record &Attr = *A;
Aaron Ballman97dba042014-02-17 15:27:10 +00004004 std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
Aaron Ballman2f22b942014-05-20 19:47:14 +00004005 for (const auto *D : Docs) {
4006 const Record &Doc = *D;
Aaron Ballman4de1b582014-02-19 22:59:32 +00004007 const Record *Category = Doc.getValueAsDef("Category");
Aaron Ballman97dba042014-02-17 15:27:10 +00004008 // If the category is "undocumented", then there cannot be any other
4009 // documentation categories (otherwise, the attribute would become
4010 // documented).
Erich Keane3bff4142017-10-16 23:25:24 +00004011 const StringRef Cat = Category->getValueAsString("Name");
Aaron Ballman4de1b582014-02-19 22:59:32 +00004012 bool Undocumented = Cat == "Undocumented";
Aaron Ballman97dba042014-02-17 15:27:10 +00004013 if (Undocumented && Docs.size() > 1)
4014 PrintFatalError(Doc.getLoc(),
4015 "Attribute is \"Undocumented\", but has multiple "
Erich Keanea98a2be2017-10-16 20:31:05 +00004016 "documentation categories");
Aaron Ballman97dba042014-02-17 15:27:10 +00004017
4018 if (!Undocumented)
Erich Keanea98a2be2017-10-16 20:31:05 +00004019 SplitDocs[Category].push_back(DocumentationData(
Richard Smith09ac4a12018-08-30 19:16:33 +00004020 Doc, Attr, GetAttributeHeadingAndSpellings(Doc, Attr)));
Aaron Ballman97dba042014-02-17 15:27:10 +00004021 }
4022 }
4023
4024 // Having split the attributes out based on what documentation goes where,
4025 // we can begin to generate sections of documentation.
Erich Keanea98a2be2017-10-16 20:31:05 +00004026 for (auto &I : SplitDocs) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00004027 WriteCategoryHeader(I.first, OS);
Aaron Ballman97dba042014-02-17 15:27:10 +00004028
Fangrui Song1d38c132018-09-30 21:41:11 +00004029 llvm::sort(I.second,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00004030 [](const DocumentationData &D1, const DocumentationData &D2) {
4031 return D1.Heading < D2.Heading;
Fangrui Song1d38c132018-09-30 21:41:11 +00004032 });
Erich Keanea98a2be2017-10-16 20:31:05 +00004033
Aaron Ballman97dba042014-02-17 15:27:10 +00004034 // Walk over each of the attributes in the category and write out their
4035 // documentation.
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00004036 for (const auto &Doc : I.second)
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004037 WriteDocumentation(Records, Doc, OS);
4038 }
4039}
4040
4041void EmitTestPragmaAttributeSupportedAttributes(RecordKeeper &Records,
4042 raw_ostream &OS) {
4043 PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
4044 ParsedAttrMap Attrs = getParsedAttrList(Records);
Erik Pilkington23c48c22018-12-04 00:31:31 +00004045 OS << "#pragma clang attribute supports the following attributes:\n";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004046 for (const auto &I : Attrs) {
4047 if (!Support.isAttributedSupported(*I.second))
4048 continue;
4049 OS << I.first;
4050 if (I.second->isValueUnset("Subjects")) {
4051 OS << " ()\n";
4052 continue;
4053 }
4054 const Record *SubjectObj = I.second->getValueAsDef("Subjects");
4055 std::vector<Record *> Subjects =
4056 SubjectObj->getValueAsListOfDefs("Subjects");
4057 OS << " (";
4058 for (const auto &Subject : llvm::enumerate(Subjects)) {
4059 if (Subject.index())
4060 OS << ", ";
Alex Lorenz24952fb2017-04-19 15:52:11 +00004061 PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
4062 Support.SubjectsToRules.find(Subject.value())->getSecond();
4063 if (RuleSet.isRule()) {
4064 OS << RuleSet.getRule().getEnumValueName();
4065 continue;
4066 }
4067 OS << "(";
4068 for (const auto &Rule : llvm::enumerate(RuleSet.getAggregateRuleSet())) {
4069 if (Rule.index())
4070 OS << ", ";
4071 OS << Rule.value().getEnumValueName();
4072 }
4073 OS << ")";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004074 }
4075 OS << ")\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00004076 }
Erik Pilkington23c48c22018-12-04 00:31:31 +00004077 OS << "End of supported attributes.\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00004078}
4079
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00004080} // end namespace clang