DAGISelMatcherEmitter.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  1. //===- DAGISelMatcherEmitter.cpp - Matcher Emitter ------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains code to generate C++ code for a matcher.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeGenDAGPatterns.h"
  13. #include "DAGISelMatcher.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/MapVector.h"
  16. #include "llvm/ADT/StringMap.h"
  17. #include "llvm/ADT/TinyPtrVector.h"
  18. #include "llvm/Support/CommandLine.h"
  19. #include "llvm/Support/Format.h"
  20. #include "llvm/Support/SourceMgr.h"
  21. #include "llvm/TableGen/Error.h"
  22. #include "llvm/TableGen/Record.h"
  23. using namespace llvm;
  24. enum {
  25. IndexWidth = 6,
  26. FullIndexWidth = IndexWidth + 4,
  27. HistOpcWidth = 40,
  28. };
  29. cl::OptionCategory DAGISelCat("Options for -gen-dag-isel");
  30. // To reduce generated source code size.
  31. static cl::opt<bool> OmitComments("omit-comments",
  32. cl::desc("Do not generate comments"),
  33. cl::init(false), cl::cat(DAGISelCat));
  34. static cl::opt<bool> InstrumentCoverage(
  35. "instrument-coverage",
  36. cl::desc("Generates tables to help identify patterns matched"),
  37. cl::init(false), cl::cat(DAGISelCat));
  38. namespace {
  39. class MatcherTableEmitter {
  40. const CodeGenDAGPatterns &CGP;
  41. SmallVector<unsigned, Matcher::HighestKind+1> OpcodeCounts;
  42. DenseMap<TreePattern *, unsigned> NodePredicateMap;
  43. std::vector<TreePredicateFn> NodePredicates;
  44. std::vector<TreePredicateFn> NodePredicatesWithOperands;
  45. // We de-duplicate the predicates by code string, and use this map to track
  46. // all the patterns with "identical" predicates.
  47. StringMap<TinyPtrVector<TreePattern *>> NodePredicatesByCodeToRun;
  48. StringMap<unsigned> PatternPredicateMap;
  49. std::vector<std::string> PatternPredicates;
  50. DenseMap<const ComplexPattern*, unsigned> ComplexPatternMap;
  51. std::vector<const ComplexPattern*> ComplexPatterns;
  52. DenseMap<Record*, unsigned> NodeXFormMap;
  53. std::vector<Record*> NodeXForms;
  54. std::vector<std::string> VecIncludeStrings;
  55. MapVector<std::string, unsigned, StringMap<unsigned> > VecPatterns;
  56. unsigned getPatternIdxFromTable(std::string &&P, std::string &&include_loc) {
  57. const auto It = VecPatterns.find(P);
  58. if (It == VecPatterns.end()) {
  59. VecPatterns.insert(make_pair(std::move(P), VecPatterns.size()));
  60. VecIncludeStrings.push_back(std::move(include_loc));
  61. return VecIncludeStrings.size() - 1;
  62. }
  63. return It->second;
  64. }
  65. public:
  66. MatcherTableEmitter(const CodeGenDAGPatterns &cgp) : CGP(cgp) {
  67. OpcodeCounts.assign(Matcher::HighestKind+1, 0);
  68. }
  69. unsigned EmitMatcherList(const Matcher *N, const unsigned Indent,
  70. unsigned StartIdx, raw_ostream &OS);
  71. unsigned SizeMatcherList(Matcher *N, raw_ostream &OS);
  72. void EmitPredicateFunctions(raw_ostream &OS);
  73. void EmitHistogram(const Matcher *N, raw_ostream &OS);
  74. void EmitPatternMatchTable(raw_ostream &OS);
  75. private:
  76. void EmitNodePredicatesFunction(const std::vector<TreePredicateFn> &Preds,
  77. StringRef Decl, raw_ostream &OS);
  78. unsigned SizeMatcher(Matcher *N, raw_ostream &OS);
  79. unsigned EmitMatcher(const Matcher *N, const unsigned Indent, unsigned CurrentIdx,
  80. raw_ostream &OS);
  81. unsigned getNodePredicate(TreePredicateFn Pred) {
  82. TreePattern *TP = Pred.getOrigPatFragRecord();
  83. unsigned &Entry = NodePredicateMap[TP];
  84. if (Entry == 0) {
  85. TinyPtrVector<TreePattern *> &SameCodePreds =
  86. NodePredicatesByCodeToRun[Pred.getCodeToRunOnSDNode()];
  87. if (SameCodePreds.empty()) {
  88. // We've never seen a predicate with the same code: allocate an entry.
  89. if (Pred.usesOperands()) {
  90. NodePredicatesWithOperands.push_back(Pred);
  91. Entry = NodePredicatesWithOperands.size();
  92. } else {
  93. NodePredicates.push_back(Pred);
  94. Entry = NodePredicates.size();
  95. }
  96. } else {
  97. // We did see an identical predicate: re-use it.
  98. Entry = NodePredicateMap[SameCodePreds.front()];
  99. assert(Entry != 0);
  100. assert(TreePredicateFn(SameCodePreds.front()).usesOperands() ==
  101. Pred.usesOperands() &&
  102. "PatFrags with some code must have same usesOperands setting");
  103. }
  104. // In both cases, we've never seen this particular predicate before, so
  105. // mark it in the list of predicates sharing the same code.
  106. SameCodePreds.push_back(TP);
  107. }
  108. return Entry-1;
  109. }
  110. unsigned getPatternPredicate(StringRef PredName) {
  111. unsigned &Entry = PatternPredicateMap[PredName];
  112. if (Entry == 0) {
  113. PatternPredicates.push_back(PredName.str());
  114. Entry = PatternPredicates.size();
  115. }
  116. return Entry-1;
  117. }
  118. unsigned getComplexPat(const ComplexPattern &P) {
  119. unsigned &Entry = ComplexPatternMap[&P];
  120. if (Entry == 0) {
  121. ComplexPatterns.push_back(&P);
  122. Entry = ComplexPatterns.size();
  123. }
  124. return Entry-1;
  125. }
  126. unsigned getNodeXFormID(Record *Rec) {
  127. unsigned &Entry = NodeXFormMap[Rec];
  128. if (Entry == 0) {
  129. NodeXForms.push_back(Rec);
  130. Entry = NodeXForms.size();
  131. }
  132. return Entry-1;
  133. }
  134. };
  135. } // end anonymous namespace.
  136. static std::string GetPatFromTreePatternNode(const TreePatternNode *N) {
  137. std::string str;
  138. raw_string_ostream Stream(str);
  139. Stream << *N;
  140. return str;
  141. }
  142. static unsigned GetVBRSize(unsigned Val) {
  143. if (Val <= 127) return 1;
  144. unsigned NumBytes = 0;
  145. while (Val >= 128) {
  146. Val >>= 7;
  147. ++NumBytes;
  148. }
  149. return NumBytes+1;
  150. }
  151. /// EmitVBRValue - Emit the specified value as a VBR, returning the number of
  152. /// bytes emitted.
  153. static unsigned EmitVBRValue(uint64_t Val, raw_ostream &OS) {
  154. if (Val <= 127) {
  155. OS << Val << ", ";
  156. return 1;
  157. }
  158. uint64_t InVal = Val;
  159. unsigned NumBytes = 0;
  160. while (Val >= 128) {
  161. OS << (Val&127) << "|128,";
  162. Val >>= 7;
  163. ++NumBytes;
  164. }
  165. OS << Val;
  166. if (!OmitComments)
  167. OS << "/*" << InVal << "*/";
  168. OS << ", ";
  169. return NumBytes+1;
  170. }
  171. /// Emit the specified signed value as a VBR. To improve compression we encode
  172. /// positive numbers shifted left by 1 and negative numbers negated and shifted
  173. /// left by 1 with bit 0 set.
  174. static unsigned EmitSignedVBRValue(uint64_t Val, raw_ostream &OS) {
  175. if ((int64_t)Val >= 0)
  176. Val = Val << 1;
  177. else
  178. Val = (-Val << 1) | 1;
  179. return EmitVBRValue(Val, OS);
  180. }
  181. // This is expensive and slow.
  182. static std::string getIncludePath(const Record *R) {
  183. std::string str;
  184. raw_string_ostream Stream(str);
  185. auto Locs = R->getLoc();
  186. SMLoc L;
  187. if (Locs.size() > 1) {
  188. // Get where the pattern prototype was instantiated
  189. L = Locs[1];
  190. } else if (Locs.size() == 1) {
  191. L = Locs[0];
  192. }
  193. unsigned CurBuf = SrcMgr.FindBufferContainingLoc(L);
  194. assert(CurBuf && "Invalid or unspecified location!");
  195. Stream << SrcMgr.getBufferInfo(CurBuf).Buffer->getBufferIdentifier() << ":"
  196. << SrcMgr.FindLineNumber(L, CurBuf);
  197. return str;
  198. }
  199. /// This function traverses the matcher tree and sizes all the nodes
  200. /// that are children of the three kinds of nodes that have them.
  201. unsigned MatcherTableEmitter::
  202. SizeMatcherList(Matcher *N, raw_ostream &OS) {
  203. unsigned Size = 0;
  204. while (N) {
  205. Size += SizeMatcher(N, OS);
  206. N = N->getNext();
  207. }
  208. return Size;
  209. }
  210. /// This function sizes the children of the three kinds of nodes that
  211. /// have them. It does so by using special cases for those three
  212. /// nodes, but sharing the code in EmitMatcher() for the other kinds.
  213. unsigned MatcherTableEmitter::
  214. SizeMatcher(Matcher *N, raw_ostream &OS) {
  215. unsigned Idx = 0;
  216. ++OpcodeCounts[N->getKind()];
  217. switch (N->getKind()) {
  218. // The Scope matcher has its kind, a series of child size + child,
  219. // and a trailing zero.
  220. case Matcher::Scope: {
  221. ScopeMatcher *SM = cast<ScopeMatcher>(N);
  222. assert(SM->getNext() == nullptr && "Scope matcher should not have next");
  223. unsigned Size = 1; // Count the kind.
  224. for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i) {
  225. const unsigned ChildSize = SizeMatcherList(SM->getChild(i), OS);
  226. assert(ChildSize != 0 && "Matcher cannot have child of size 0");
  227. SM->getChild(i)->setSize(ChildSize);
  228. Size += GetVBRSize(ChildSize) + ChildSize; // Count VBR and child size.
  229. }
  230. ++Size; // Count the zero sentinel.
  231. return Size;
  232. }
  233. // SwitchOpcode and SwitchType have their kind, a series of child size +
  234. // opcode/type + child, and a trailing zero.
  235. case Matcher::SwitchOpcode:
  236. case Matcher::SwitchType: {
  237. unsigned Size = 1; // Count the kind.
  238. unsigned NumCases;
  239. if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
  240. NumCases = SOM->getNumCases();
  241. else
  242. NumCases = cast<SwitchTypeMatcher>(N)->getNumCases();
  243. for (unsigned i = 0, e = NumCases; i != e; ++i) {
  244. Matcher *Child;
  245. if (SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
  246. Child = SOM->getCaseMatcher(i);
  247. Size += 2; // Count the child's opcode.
  248. } else {
  249. Child = cast<SwitchTypeMatcher>(N)->getCaseMatcher(i);
  250. ++Size; // Count the child's type.
  251. }
  252. const unsigned ChildSize = SizeMatcherList(Child, OS);
  253. assert(ChildSize != 0 && "Matcher cannot have child of size 0");
  254. Child->setSize(ChildSize);
  255. Size += GetVBRSize(ChildSize) + ChildSize; // Count VBR and child size.
  256. }
  257. ++Size; // Count the zero sentinel.
  258. return Size;
  259. }
  260. default:
  261. // Employ the matcher emitter to size other matchers.
  262. return EmitMatcher(N, 0, Idx, OS);
  263. }
  264. llvm_unreachable("Unreachable");
  265. }
  266. static void BeginEmitFunction(raw_ostream &OS, StringRef RetType,
  267. StringRef Decl, bool AddOverride) {
  268. OS << "#ifdef GET_DAGISEL_DECL\n";
  269. OS << RetType << ' ' << Decl;
  270. if (AddOverride)
  271. OS << " override";
  272. OS << ";\n"
  273. "#endif\n"
  274. "#if defined(GET_DAGISEL_BODY) || DAGISEL_INLINE\n";
  275. OS << RetType << " DAGISEL_CLASS_COLONCOLON " << Decl << "\n";
  276. if (AddOverride) {
  277. OS << "#if DAGISEL_INLINE\n"
  278. " override\n"
  279. "#endif\n";
  280. }
  281. }
  282. static void EndEmitFunction(raw_ostream &OS) {
  283. OS << "#endif // GET_DAGISEL_BODY\n\n";
  284. }
  285. void MatcherTableEmitter::EmitPatternMatchTable(raw_ostream &OS) {
  286. assert(isUInt<16>(VecPatterns.size()) &&
  287. "Using only 16 bits to encode offset into Pattern Table");
  288. assert(VecPatterns.size() == VecIncludeStrings.size() &&
  289. "The sizes of Pattern and include vectors should be the same");
  290. BeginEmitFunction(OS, "StringRef", "getPatternForIndex(unsigned Index)",
  291. true/*AddOverride*/);
  292. OS << "{\n";
  293. OS << "static const char *PATTERN_MATCH_TABLE[] = {\n";
  294. for (const auto &It : VecPatterns) {
  295. OS << "\"" << It.first << "\",\n";
  296. }
  297. OS << "\n};";
  298. OS << "\nreturn StringRef(PATTERN_MATCH_TABLE[Index]);";
  299. OS << "\n}\n";
  300. EndEmitFunction(OS);
  301. BeginEmitFunction(OS, "StringRef", "getIncludePathForIndex(unsigned Index)",
  302. true/*AddOverride*/);
  303. OS << "{\n";
  304. OS << "static const char *INCLUDE_PATH_TABLE[] = {\n";
  305. for (const auto &It : VecIncludeStrings) {
  306. OS << "\"" << It << "\",\n";
  307. }
  308. OS << "\n};";
  309. OS << "\nreturn StringRef(INCLUDE_PATH_TABLE[Index]);";
  310. OS << "\n}\n";
  311. EndEmitFunction(OS);
  312. }
  313. /// EmitMatcher - Emit bytes for the specified matcher and return
  314. /// the number of bytes emitted.
  315. unsigned MatcherTableEmitter::
  316. EmitMatcher(const Matcher *N, const unsigned Indent, unsigned CurrentIdx,
  317. raw_ostream &OS) {
  318. OS.indent(Indent);
  319. switch (N->getKind()) {
  320. case Matcher::Scope: {
  321. const ScopeMatcher *SM = cast<ScopeMatcher>(N);
  322. unsigned StartIdx = CurrentIdx;
  323. // Emit all of the children.
  324. for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i) {
  325. if (i == 0) {
  326. OS << "OPC_Scope, ";
  327. ++CurrentIdx;
  328. } else {
  329. if (!OmitComments) {
  330. OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
  331. OS.indent(Indent) << "/*Scope*/ ";
  332. } else
  333. OS.indent(Indent);
  334. }
  335. unsigned ChildSize = SM->getChild(i)->getSize();
  336. unsigned VBRSize = EmitVBRValue(ChildSize, OS);
  337. if (!OmitComments) {
  338. OS << "/*->" << CurrentIdx + VBRSize + ChildSize << "*/";
  339. if (i == 0)
  340. OS << " // " << SM->getNumChildren() << " children in Scope";
  341. }
  342. OS << '\n';
  343. ChildSize = EmitMatcherList(SM->getChild(i), Indent+1,
  344. CurrentIdx + VBRSize, OS);
  345. assert(ChildSize == SM->getChild(i)->getSize() &&
  346. "Emitted child size does not match calculated size");
  347. CurrentIdx += VBRSize + ChildSize;
  348. }
  349. // Emit a zero as a sentinel indicating end of 'Scope'.
  350. if (!OmitComments)
  351. OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
  352. OS.indent(Indent) << "0, ";
  353. if (!OmitComments)
  354. OS << "/*End of Scope*/";
  355. OS << '\n';
  356. return CurrentIdx - StartIdx + 1;
  357. }
  358. case Matcher::RecordNode:
  359. OS << "OPC_RecordNode,";
  360. if (!OmitComments)
  361. OS << " // #"
  362. << cast<RecordMatcher>(N)->getResultNo() << " = "
  363. << cast<RecordMatcher>(N)->getWhatFor();
  364. OS << '\n';
  365. return 1;
  366. case Matcher::RecordChild:
  367. OS << "OPC_RecordChild" << cast<RecordChildMatcher>(N)->getChildNo()
  368. << ',';
  369. if (!OmitComments)
  370. OS << " // #"
  371. << cast<RecordChildMatcher>(N)->getResultNo() << " = "
  372. << cast<RecordChildMatcher>(N)->getWhatFor();
  373. OS << '\n';
  374. return 1;
  375. case Matcher::RecordMemRef:
  376. OS << "OPC_RecordMemRef,\n";
  377. return 1;
  378. case Matcher::CaptureGlueInput:
  379. OS << "OPC_CaptureGlueInput,\n";
  380. return 1;
  381. case Matcher::MoveChild: {
  382. const auto *MCM = cast<MoveChildMatcher>(N);
  383. OS << "OPC_MoveChild";
  384. // Handle the specialized forms.
  385. if (MCM->getChildNo() >= 8)
  386. OS << ", ";
  387. OS << MCM->getChildNo() << ",\n";
  388. return (MCM->getChildNo() >= 8) ? 2 : 1;
  389. }
  390. case Matcher::MoveParent:
  391. OS << "OPC_MoveParent,\n";
  392. return 1;
  393. case Matcher::CheckSame:
  394. OS << "OPC_CheckSame, "
  395. << cast<CheckSameMatcher>(N)->getMatchNumber() << ",\n";
  396. return 2;
  397. case Matcher::CheckChildSame:
  398. OS << "OPC_CheckChild"
  399. << cast<CheckChildSameMatcher>(N)->getChildNo() << "Same, "
  400. << cast<CheckChildSameMatcher>(N)->getMatchNumber() << ",\n";
  401. return 2;
  402. case Matcher::CheckPatternPredicate: {
  403. StringRef Pred =cast<CheckPatternPredicateMatcher>(N)->getPredicate();
  404. OS << "OPC_CheckPatternPredicate, " << getPatternPredicate(Pred) << ',';
  405. if (!OmitComments)
  406. OS << " // " << Pred;
  407. OS << '\n';
  408. return 2;
  409. }
  410. case Matcher::CheckPredicate: {
  411. TreePredicateFn Pred = cast<CheckPredicateMatcher>(N)->getPredicate();
  412. unsigned OperandBytes = 0;
  413. if (Pred.usesOperands()) {
  414. unsigned NumOps = cast<CheckPredicateMatcher>(N)->getNumOperands();
  415. OS << "OPC_CheckPredicateWithOperands, " << NumOps << "/*#Ops*/, ";
  416. for (unsigned i = 0; i < NumOps; ++i)
  417. OS << cast<CheckPredicateMatcher>(N)->getOperandNo(i) << ", ";
  418. OperandBytes = 1 + NumOps;
  419. } else {
  420. OS << "OPC_CheckPredicate, ";
  421. }
  422. OS << getNodePredicate(Pred) << ',';
  423. if (!OmitComments)
  424. OS << " // " << Pred.getFnName();
  425. OS << '\n';
  426. return 2 + OperandBytes;
  427. }
  428. case Matcher::CheckOpcode:
  429. OS << "OPC_CheckOpcode, TARGET_VAL("
  430. << cast<CheckOpcodeMatcher>(N)->getOpcode().getEnumName() << "),\n";
  431. return 3;
  432. case Matcher::SwitchOpcode:
  433. case Matcher::SwitchType: {
  434. unsigned StartIdx = CurrentIdx;
  435. unsigned NumCases;
  436. if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
  437. OS << "OPC_SwitchOpcode ";
  438. NumCases = SOM->getNumCases();
  439. } else {
  440. OS << "OPC_SwitchType ";
  441. NumCases = cast<SwitchTypeMatcher>(N)->getNumCases();
  442. }
  443. if (!OmitComments)
  444. OS << "/*" << NumCases << " cases */";
  445. OS << ", ";
  446. ++CurrentIdx;
  447. // For each case we emit the size, then the opcode, then the matcher.
  448. for (unsigned i = 0, e = NumCases; i != e; ++i) {
  449. const Matcher *Child;
  450. unsigned IdxSize;
  451. if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
  452. Child = SOM->getCaseMatcher(i);
  453. IdxSize = 2; // size of opcode in table is 2 bytes.
  454. } else {
  455. Child = cast<SwitchTypeMatcher>(N)->getCaseMatcher(i);
  456. IdxSize = 1; // size of type in table is 1 byte.
  457. }
  458. if (i != 0) {
  459. if (!OmitComments)
  460. OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
  461. OS.indent(Indent);
  462. if (!OmitComments)
  463. OS << (isa<SwitchOpcodeMatcher>(N) ?
  464. "/*SwitchOpcode*/ " : "/*SwitchType*/ ");
  465. }
  466. unsigned ChildSize = Child->getSize();
  467. CurrentIdx += EmitVBRValue(ChildSize, OS) + IdxSize;
  468. if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
  469. OS << "TARGET_VAL(" << SOM->getCaseOpcode(i).getEnumName() << "),";
  470. else
  471. OS << getEnumName(cast<SwitchTypeMatcher>(N)->getCaseType(i)) << ',';
  472. if (!OmitComments)
  473. OS << "// ->" << CurrentIdx + ChildSize;
  474. OS << '\n';
  475. ChildSize = EmitMatcherList(Child, Indent+1, CurrentIdx, OS);
  476. assert(ChildSize == Child->getSize() &&
  477. "Emitted child size does not match calculated size");
  478. CurrentIdx += ChildSize;
  479. }
  480. // Emit the final zero to terminate the switch.
  481. if (!OmitComments)
  482. OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
  483. OS.indent(Indent) << "0,";
  484. if (!OmitComments)
  485. OS << (isa<SwitchOpcodeMatcher>(N) ?
  486. " // EndSwitchOpcode" : " // EndSwitchType");
  487. OS << '\n';
  488. return CurrentIdx - StartIdx + 1;
  489. }
  490. case Matcher::CheckType:
  491. if (cast<CheckTypeMatcher>(N)->getResNo() == 0) {
  492. OS << "OPC_CheckType, "
  493. << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << ",\n";
  494. return 2;
  495. }
  496. OS << "OPC_CheckTypeRes, " << cast<CheckTypeMatcher>(N)->getResNo()
  497. << ", " << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << ",\n";
  498. return 3;
  499. case Matcher::CheckChildType:
  500. OS << "OPC_CheckChild"
  501. << cast<CheckChildTypeMatcher>(N)->getChildNo() << "Type, "
  502. << getEnumName(cast<CheckChildTypeMatcher>(N)->getType()) << ",\n";
  503. return 2;
  504. case Matcher::CheckInteger: {
  505. OS << "OPC_CheckInteger, ";
  506. unsigned Bytes =
  507. 1 + EmitSignedVBRValue(cast<CheckIntegerMatcher>(N)->getValue(), OS);
  508. OS << '\n';
  509. return Bytes;
  510. }
  511. case Matcher::CheckChildInteger: {
  512. OS << "OPC_CheckChild" << cast<CheckChildIntegerMatcher>(N)->getChildNo()
  513. << "Integer, ";
  514. unsigned Bytes = 1 + EmitSignedVBRValue(
  515. cast<CheckChildIntegerMatcher>(N)->getValue(), OS);
  516. OS << '\n';
  517. return Bytes;
  518. }
  519. case Matcher::CheckCondCode:
  520. OS << "OPC_CheckCondCode, ISD::"
  521. << cast<CheckCondCodeMatcher>(N)->getCondCodeName() << ",\n";
  522. return 2;
  523. case Matcher::CheckChild2CondCode:
  524. OS << "OPC_CheckChild2CondCode, ISD::"
  525. << cast<CheckChild2CondCodeMatcher>(N)->getCondCodeName() << ",\n";
  526. return 2;
  527. case Matcher::CheckValueType:
  528. OS << "OPC_CheckValueType, MVT::"
  529. << cast<CheckValueTypeMatcher>(N)->getTypeName() << ",\n";
  530. return 2;
  531. case Matcher::CheckComplexPat: {
  532. const CheckComplexPatMatcher *CCPM = cast<CheckComplexPatMatcher>(N);
  533. const ComplexPattern &Pattern = CCPM->getPattern();
  534. OS << "OPC_CheckComplexPat, /*CP*/" << getComplexPat(Pattern) << ", /*#*/"
  535. << CCPM->getMatchNumber() << ',';
  536. if (!OmitComments) {
  537. OS << " // " << Pattern.getSelectFunc();
  538. OS << ":$" << CCPM->getName();
  539. for (unsigned i = 0, e = Pattern.getNumOperands(); i != e; ++i)
  540. OS << " #" << CCPM->getFirstResult()+i;
  541. if (Pattern.hasProperty(SDNPHasChain))
  542. OS << " + chain result";
  543. }
  544. OS << '\n';
  545. return 3;
  546. }
  547. case Matcher::CheckAndImm: {
  548. OS << "OPC_CheckAndImm, ";
  549. unsigned Bytes=1+EmitVBRValue(cast<CheckAndImmMatcher>(N)->getValue(), OS);
  550. OS << '\n';
  551. return Bytes;
  552. }
  553. case Matcher::CheckOrImm: {
  554. OS << "OPC_CheckOrImm, ";
  555. unsigned Bytes = 1+EmitVBRValue(cast<CheckOrImmMatcher>(N)->getValue(), OS);
  556. OS << '\n';
  557. return Bytes;
  558. }
  559. case Matcher::CheckFoldableChainNode:
  560. OS << "OPC_CheckFoldableChainNode,\n";
  561. return 1;
  562. case Matcher::CheckImmAllOnesV:
  563. OS << "OPC_CheckImmAllOnesV,\n";
  564. return 1;
  565. case Matcher::CheckImmAllZerosV:
  566. OS << "OPC_CheckImmAllZerosV,\n";
  567. return 1;
  568. case Matcher::EmitInteger: {
  569. int64_t Val = cast<EmitIntegerMatcher>(N)->getValue();
  570. OS << "OPC_EmitInteger, "
  571. << getEnumName(cast<EmitIntegerMatcher>(N)->getVT()) << ", ";
  572. unsigned Bytes = 2 + EmitSignedVBRValue(Val, OS);
  573. OS << '\n';
  574. return Bytes;
  575. }
  576. case Matcher::EmitStringInteger: {
  577. const std::string &Val = cast<EmitStringIntegerMatcher>(N)->getValue();
  578. // These should always fit into 7 bits.
  579. OS << "OPC_EmitStringInteger, "
  580. << getEnumName(cast<EmitStringIntegerMatcher>(N)->getVT()) << ", " << Val
  581. << ",\n";
  582. return 3;
  583. }
  584. case Matcher::EmitRegister: {
  585. const EmitRegisterMatcher *Matcher = cast<EmitRegisterMatcher>(N);
  586. const CodeGenRegister *Reg = Matcher->getReg();
  587. // If the enum value of the register is larger than one byte can handle,
  588. // use EmitRegister2.
  589. if (Reg && Reg->EnumValue > 255) {
  590. OS << "OPC_EmitRegister2, " << getEnumName(Matcher->getVT()) << ", ";
  591. OS << "TARGET_VAL(" << getQualifiedName(Reg->TheDef) << "),\n";
  592. return 4;
  593. } else {
  594. OS << "OPC_EmitRegister, " << getEnumName(Matcher->getVT()) << ", ";
  595. if (Reg) {
  596. OS << getQualifiedName(Reg->TheDef) << ",\n";
  597. } else {
  598. OS << "0 ";
  599. if (!OmitComments)
  600. OS << "/*zero_reg*/";
  601. OS << ",\n";
  602. }
  603. return 3;
  604. }
  605. }
  606. case Matcher::EmitConvertToTarget:
  607. OS << "OPC_EmitConvertToTarget, "
  608. << cast<EmitConvertToTargetMatcher>(N)->getSlot() << ",\n";
  609. return 2;
  610. case Matcher::EmitMergeInputChains: {
  611. const EmitMergeInputChainsMatcher *MN =
  612. cast<EmitMergeInputChainsMatcher>(N);
  613. // Handle the specialized forms OPC_EmitMergeInputChains1_0, 1_1, and 1_2.
  614. if (MN->getNumNodes() == 1 && MN->getNode(0) < 3) {
  615. OS << "OPC_EmitMergeInputChains1_" << MN->getNode(0) << ",\n";
  616. return 1;
  617. }
  618. OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
  619. for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
  620. OS << MN->getNode(i) << ", ";
  621. OS << '\n';
  622. return 2+MN->getNumNodes();
  623. }
  624. case Matcher::EmitCopyToReg: {
  625. const auto *C2RMatcher = cast<EmitCopyToRegMatcher>(N);
  626. int Bytes = 3;
  627. const CodeGenRegister *Reg = C2RMatcher->getDestPhysReg();
  628. if (Reg->EnumValue > 255) {
  629. assert(isUInt<16>(Reg->EnumValue) && "not handled");
  630. OS << "OPC_EmitCopyToReg2, " << C2RMatcher->getSrcSlot() << ", "
  631. << "TARGET_VAL(" << getQualifiedName(Reg->TheDef) << "),\n";
  632. ++Bytes;
  633. } else {
  634. OS << "OPC_EmitCopyToReg, " << C2RMatcher->getSrcSlot() << ", "
  635. << getQualifiedName(Reg->TheDef) << ",\n";
  636. }
  637. return Bytes;
  638. }
  639. case Matcher::EmitNodeXForm: {
  640. const EmitNodeXFormMatcher *XF = cast<EmitNodeXFormMatcher>(N);
  641. OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
  642. << XF->getSlot() << ',';
  643. if (!OmitComments)
  644. OS << " // "<<XF->getNodeXForm()->getName();
  645. OS <<'\n';
  646. return 3;
  647. }
  648. case Matcher::EmitNode:
  649. case Matcher::MorphNodeTo: {
  650. auto NumCoveredBytes = 0;
  651. if (InstrumentCoverage) {
  652. if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
  653. NumCoveredBytes = 3;
  654. OS << "OPC_Coverage, ";
  655. std::string src =
  656. GetPatFromTreePatternNode(SNT->getPattern().getSrcPattern());
  657. std::string dst =
  658. GetPatFromTreePatternNode(SNT->getPattern().getDstPattern());
  659. Record *PatRecord = SNT->getPattern().getSrcRecord();
  660. std::string include_src = getIncludePath(PatRecord);
  661. unsigned Offset =
  662. getPatternIdxFromTable(src + " -> " + dst, std::move(include_src));
  663. OS << "TARGET_VAL(" << Offset << "),\n";
  664. OS.indent(FullIndexWidth + Indent);
  665. }
  666. }
  667. const EmitNodeMatcherCommon *EN = cast<EmitNodeMatcherCommon>(N);
  668. OS << (isa<EmitNodeMatcher>(EN) ? "OPC_EmitNode" : "OPC_MorphNodeTo");
  669. bool CompressVTs = EN->getNumVTs() < 3;
  670. if (CompressVTs)
  671. OS << EN->getNumVTs();
  672. OS << ", TARGET_VAL(" << EN->getOpcodeName() << "), 0";
  673. if (EN->hasChain()) OS << "|OPFL_Chain";
  674. if (EN->hasInFlag()) OS << "|OPFL_GlueInput";
  675. if (EN->hasOutFlag()) OS << "|OPFL_GlueOutput";
  676. if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
  677. if (EN->getNumFixedArityOperands() != -1)
  678. OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
  679. OS << ",\n";
  680. OS.indent(FullIndexWidth + Indent+4);
  681. if (!CompressVTs) {
  682. OS << EN->getNumVTs();
  683. if (!OmitComments)
  684. OS << "/*#VTs*/";
  685. OS << ", ";
  686. }
  687. for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
  688. OS << getEnumName(EN->getVT(i)) << ", ";
  689. OS << EN->getNumOperands();
  690. if (!OmitComments)
  691. OS << "/*#Ops*/";
  692. OS << ", ";
  693. unsigned NumOperandBytes = 0;
  694. for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i)
  695. NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
  696. if (!OmitComments) {
  697. // Print the result #'s for EmitNode.
  698. if (const EmitNodeMatcher *E = dyn_cast<EmitNodeMatcher>(EN)) {
  699. if (unsigned NumResults = EN->getNumVTs()) {
  700. OS << " // Results =";
  701. unsigned First = E->getFirstResultSlot();
  702. for (unsigned i = 0; i != NumResults; ++i)
  703. OS << " #" << First+i;
  704. }
  705. }
  706. OS << '\n';
  707. if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
  708. OS.indent(FullIndexWidth + Indent) << "// Src: "
  709. << *SNT->getPattern().getSrcPattern() << " - Complexity = "
  710. << SNT->getPattern().getPatternComplexity(CGP) << '\n';
  711. OS.indent(FullIndexWidth + Indent) << "// Dst: "
  712. << *SNT->getPattern().getDstPattern() << '\n';
  713. }
  714. } else
  715. OS << '\n';
  716. return 5 + !CompressVTs + EN->getNumVTs() + NumOperandBytes +
  717. NumCoveredBytes;
  718. }
  719. case Matcher::CompleteMatch: {
  720. const CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(N);
  721. auto NumCoveredBytes = 0;
  722. if (InstrumentCoverage) {
  723. NumCoveredBytes = 3;
  724. OS << "OPC_Coverage, ";
  725. std::string src =
  726. GetPatFromTreePatternNode(CM->getPattern().getSrcPattern());
  727. std::string dst =
  728. GetPatFromTreePatternNode(CM->getPattern().getDstPattern());
  729. Record *PatRecord = CM->getPattern().getSrcRecord();
  730. std::string include_src = getIncludePath(PatRecord);
  731. unsigned Offset =
  732. getPatternIdxFromTable(src + " -> " + dst, std::move(include_src));
  733. OS << "TARGET_VAL(" << Offset << "),\n";
  734. OS.indent(FullIndexWidth + Indent);
  735. }
  736. OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
  737. unsigned NumResultBytes = 0;
  738. for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
  739. NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
  740. OS << '\n';
  741. if (!OmitComments) {
  742. OS.indent(FullIndexWidth + Indent) << " // Src: "
  743. << *CM->getPattern().getSrcPattern() << " - Complexity = "
  744. << CM->getPattern().getPatternComplexity(CGP) << '\n';
  745. OS.indent(FullIndexWidth + Indent) << " // Dst: "
  746. << *CM->getPattern().getDstPattern();
  747. }
  748. OS << '\n';
  749. return 2 + NumResultBytes + NumCoveredBytes;
  750. }
  751. }
  752. llvm_unreachable("Unreachable");
  753. }
  754. /// This function traverses the matcher tree and emits all the nodes.
  755. /// The nodes have already been sized.
  756. unsigned MatcherTableEmitter::
  757. EmitMatcherList(const Matcher *N, const unsigned Indent, unsigned CurrentIdx,
  758. raw_ostream &OS) {
  759. unsigned Size = 0;
  760. while (N) {
  761. if (!OmitComments)
  762. OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
  763. unsigned MatcherSize = EmitMatcher(N, Indent, CurrentIdx, OS);
  764. Size += MatcherSize;
  765. CurrentIdx += MatcherSize;
  766. // If there are other nodes in this list, iterate to them, otherwise we're
  767. // done.
  768. N = N->getNext();
  769. }
  770. return Size;
  771. }
  772. void MatcherTableEmitter::EmitNodePredicatesFunction(
  773. const std::vector<TreePredicateFn> &Preds, StringRef Decl,
  774. raw_ostream &OS) {
  775. if (Preds.empty())
  776. return;
  777. BeginEmitFunction(OS, "bool", Decl, true/*AddOverride*/);
  778. OS << "{\n";
  779. OS << " switch (PredNo) {\n";
  780. OS << " default: llvm_unreachable(\"Invalid predicate in table?\");\n";
  781. for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
  782. // Emit the predicate code corresponding to this pattern.
  783. const TreePredicateFn PredFn = Preds[i];
  784. assert(!PredFn.isAlwaysTrue() && "No code in this predicate");
  785. std::string PredFnCodeStr = PredFn.getCodeToRunOnSDNode();
  786. OS << " case " << i << ": {\n";
  787. for (auto *SimilarPred : NodePredicatesByCodeToRun[PredFnCodeStr])
  788. OS << " // " << TreePredicateFn(SimilarPred).getFnName() << '\n';
  789. OS << PredFnCodeStr << "\n }\n";
  790. }
  791. OS << " }\n";
  792. OS << "}\n";
  793. EndEmitFunction(OS);
  794. }
  795. void MatcherTableEmitter::EmitPredicateFunctions(raw_ostream &OS) {
  796. // Emit pattern predicates.
  797. if (!PatternPredicates.empty()) {
  798. BeginEmitFunction(OS, "bool",
  799. "CheckPatternPredicate(unsigned PredNo) const", true/*AddOverride*/);
  800. OS << "{\n";
  801. OS << " switch (PredNo) {\n";
  802. OS << " default: llvm_unreachable(\"Invalid predicate in table?\");\n";
  803. for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
  804. OS << " case " << i << ": return " << PatternPredicates[i] << ";\n";
  805. OS << " }\n";
  806. OS << "}\n";
  807. EndEmitFunction(OS);
  808. }
  809. // Emit Node predicates.
  810. EmitNodePredicatesFunction(
  811. NodePredicates, "CheckNodePredicate(SDNode *Node, unsigned PredNo) const",
  812. OS);
  813. EmitNodePredicatesFunction(
  814. NodePredicatesWithOperands,
  815. "CheckNodePredicateWithOperands(SDNode *Node, unsigned PredNo, "
  816. "const SmallVectorImpl<SDValue> &Operands) const",
  817. OS);
  818. // Emit CompletePattern matchers.
  819. // FIXME: This should be const.
  820. if (!ComplexPatterns.empty()) {
  821. BeginEmitFunction(OS, "bool",
  822. "CheckComplexPattern(SDNode *Root, SDNode *Parent,\n"
  823. " SDValue N, unsigned PatternNo,\n"
  824. " SmallVectorImpl<std::pair<SDValue, SDNode *>> &Result)",
  825. true/*AddOverride*/);
  826. OS << "{\n";
  827. OS << " unsigned NextRes = Result.size();\n";
  828. OS << " switch (PatternNo) {\n";
  829. OS << " default: llvm_unreachable(\"Invalid pattern # in table?\");\n";
  830. for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
  831. const ComplexPattern &P = *ComplexPatterns[i];
  832. unsigned NumOps = P.getNumOperands();
  833. if (P.hasProperty(SDNPHasChain))
  834. ++NumOps; // Get the chained node too.
  835. OS << " case " << i << ":\n";
  836. if (InstrumentCoverage)
  837. OS << " {\n";
  838. OS << " Result.resize(NextRes+" << NumOps << ");\n";
  839. if (InstrumentCoverage)
  840. OS << " bool Succeeded = " << P.getSelectFunc();
  841. else
  842. OS << " return " << P.getSelectFunc();
  843. OS << "(";
  844. // If the complex pattern wants the root of the match, pass it in as the
  845. // first argument.
  846. if (P.hasProperty(SDNPWantRoot))
  847. OS << "Root, ";
  848. // If the complex pattern wants the parent of the operand being matched,
  849. // pass it in as the next argument.
  850. if (P.hasProperty(SDNPWantParent))
  851. OS << "Parent, ";
  852. OS << "N";
  853. for (unsigned i = 0; i != NumOps; ++i)
  854. OS << ", Result[NextRes+" << i << "].first";
  855. OS << ");\n";
  856. if (InstrumentCoverage) {
  857. OS << " if (Succeeded)\n";
  858. OS << " dbgs() << \"\\nCOMPLEX_PATTERN: " << P.getSelectFunc()
  859. << "\\n\" ;\n";
  860. OS << " return Succeeded;\n";
  861. OS << " }\n";
  862. }
  863. }
  864. OS << " }\n";
  865. OS << "}\n";
  866. EndEmitFunction(OS);
  867. }
  868. // Emit SDNodeXForm handlers.
  869. // FIXME: This should be const.
  870. if (!NodeXForms.empty()) {
  871. BeginEmitFunction(OS, "SDValue",
  872. "RunSDNodeXForm(SDValue V, unsigned XFormNo)", true/*AddOverride*/);
  873. OS << "{\n";
  874. OS << " switch (XFormNo) {\n";
  875. OS << " default: llvm_unreachable(\"Invalid xform # in table?\");\n";
  876. // FIXME: The node xform could take SDValue's instead of SDNode*'s.
  877. for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i) {
  878. const CodeGenDAGPatterns::NodeXForm &Entry =
  879. CGP.getSDNodeTransform(NodeXForms[i]);
  880. Record *SDNode = Entry.first;
  881. const std::string &Code = Entry.second;
  882. OS << " case " << i << ": { ";
  883. if (!OmitComments)
  884. OS << "// " << NodeXForms[i]->getName();
  885. OS << '\n';
  886. std::string ClassName =
  887. std::string(CGP.getSDNodeInfo(SDNode).getSDClassName());
  888. if (ClassName == "SDNode")
  889. OS << " SDNode *N = V.getNode();\n";
  890. else
  891. OS << " " << ClassName << " *N = cast<" << ClassName
  892. << ">(V.getNode());\n";
  893. OS << Code << "\n }\n";
  894. }
  895. OS << " }\n";
  896. OS << "}\n";
  897. EndEmitFunction(OS);
  898. }
  899. }
  900. static StringRef getOpcodeString(Matcher::KindTy Kind) {
  901. switch (Kind) {
  902. case Matcher::Scope: return "OPC_Scope"; break;
  903. case Matcher::RecordNode: return "OPC_RecordNode"; break;
  904. case Matcher::RecordChild: return "OPC_RecordChild"; break;
  905. case Matcher::RecordMemRef: return "OPC_RecordMemRef"; break;
  906. case Matcher::CaptureGlueInput: return "OPC_CaptureGlueInput"; break;
  907. case Matcher::MoveChild: return "OPC_MoveChild"; break;
  908. case Matcher::MoveParent: return "OPC_MoveParent"; break;
  909. case Matcher::CheckSame: return "OPC_CheckSame"; break;
  910. case Matcher::CheckChildSame: return "OPC_CheckChildSame"; break;
  911. case Matcher::CheckPatternPredicate:
  912. return "OPC_CheckPatternPredicate"; break;
  913. case Matcher::CheckPredicate: return "OPC_CheckPredicate"; break;
  914. case Matcher::CheckOpcode: return "OPC_CheckOpcode"; break;
  915. case Matcher::SwitchOpcode: return "OPC_SwitchOpcode"; break;
  916. case Matcher::CheckType: return "OPC_CheckType"; break;
  917. case Matcher::SwitchType: return "OPC_SwitchType"; break;
  918. case Matcher::CheckChildType: return "OPC_CheckChildType"; break;
  919. case Matcher::CheckInteger: return "OPC_CheckInteger"; break;
  920. case Matcher::CheckChildInteger: return "OPC_CheckChildInteger"; break;
  921. case Matcher::CheckCondCode: return "OPC_CheckCondCode"; break;
  922. case Matcher::CheckChild2CondCode: return "OPC_CheckChild2CondCode"; break;
  923. case Matcher::CheckValueType: return "OPC_CheckValueType"; break;
  924. case Matcher::CheckComplexPat: return "OPC_CheckComplexPat"; break;
  925. case Matcher::CheckAndImm: return "OPC_CheckAndImm"; break;
  926. case Matcher::CheckOrImm: return "OPC_CheckOrImm"; break;
  927. case Matcher::CheckFoldableChainNode:
  928. return "OPC_CheckFoldableChainNode"; break;
  929. case Matcher::CheckImmAllOnesV: return "OPC_CheckImmAllOnesV"; break;
  930. case Matcher::CheckImmAllZerosV: return "OPC_CheckImmAllZerosV"; break;
  931. case Matcher::EmitInteger: return "OPC_EmitInteger"; break;
  932. case Matcher::EmitStringInteger: return "OPC_EmitStringInteger"; break;
  933. case Matcher::EmitRegister: return "OPC_EmitRegister"; break;
  934. case Matcher::EmitConvertToTarget: return "OPC_EmitConvertToTarget"; break;
  935. case Matcher::EmitMergeInputChains: return "OPC_EmitMergeInputChains"; break;
  936. case Matcher::EmitCopyToReg: return "OPC_EmitCopyToReg"; break;
  937. case Matcher::EmitNode: return "OPC_EmitNode"; break;
  938. case Matcher::MorphNodeTo: return "OPC_MorphNodeTo"; break;
  939. case Matcher::EmitNodeXForm: return "OPC_EmitNodeXForm"; break;
  940. case Matcher::CompleteMatch: return "OPC_CompleteMatch"; break;
  941. }
  942. llvm_unreachable("Unhandled opcode?");
  943. }
  944. void MatcherTableEmitter::EmitHistogram(const Matcher *M,
  945. raw_ostream &OS) {
  946. if (OmitComments)
  947. return;
  948. OS << " // Opcode Histogram:\n";
  949. for (unsigned i = 0, e = OpcodeCounts.size(); i != e; ++i) {
  950. OS << " // #"
  951. << left_justify(getOpcodeString((Matcher::KindTy)i), HistOpcWidth)
  952. << " = " << OpcodeCounts[i] << '\n';
  953. }
  954. OS << '\n';
  955. }
  956. void llvm::EmitMatcherTable(Matcher *TheMatcher,
  957. const CodeGenDAGPatterns &CGP,
  958. raw_ostream &OS) {
  959. OS << "#if defined(GET_DAGISEL_DECL) && defined(GET_DAGISEL_BODY)\n";
  960. OS << "#error GET_DAGISEL_DECL and GET_DAGISEL_BODY cannot be both defined, ";
  961. OS << "undef both for inline definitions\n";
  962. OS << "#endif\n\n";
  963. // Emit a check for omitted class name.
  964. OS << "#ifdef GET_DAGISEL_BODY\n";
  965. OS << "#define LOCAL_DAGISEL_STRINGIZE(X) LOCAL_DAGISEL_STRINGIZE_(X)\n";
  966. OS << "#define LOCAL_DAGISEL_STRINGIZE_(X) #X\n";
  967. OS << "static_assert(sizeof(LOCAL_DAGISEL_STRINGIZE(GET_DAGISEL_BODY)) > 1,"
  968. "\n";
  969. OS << " \"GET_DAGISEL_BODY is empty: it should be defined with the class "
  970. "name\");\n";
  971. OS << "#undef LOCAL_DAGISEL_STRINGIZE_\n";
  972. OS << "#undef LOCAL_DAGISEL_STRINGIZE\n";
  973. OS << "#endif\n\n";
  974. OS << "#if !defined(GET_DAGISEL_DECL) && !defined(GET_DAGISEL_BODY)\n";
  975. OS << "#define DAGISEL_INLINE 1\n";
  976. OS << "#else\n";
  977. OS << "#define DAGISEL_INLINE 0\n";
  978. OS << "#endif\n\n";
  979. OS << "#if !DAGISEL_INLINE\n";
  980. OS << "#define DAGISEL_CLASS_COLONCOLON GET_DAGISEL_BODY ::\n";
  981. OS << "#else\n";
  982. OS << "#define DAGISEL_CLASS_COLONCOLON\n";
  983. OS << "#endif\n\n";
  984. BeginEmitFunction(OS, "void", "SelectCode(SDNode *N)", false/*AddOverride*/);
  985. MatcherTableEmitter MatcherEmitter(CGP);
  986. // First we size all the children of the three kinds of matchers that have
  987. // them. This is done by sharing the code in EmitMatcher(). but we don't
  988. // want to emit anything, so we turn off comments and use a null stream.
  989. bool SaveOmitComments = OmitComments;
  990. OmitComments = true;
  991. raw_null_ostream NullOS;
  992. unsigned TotalSize = MatcherEmitter.SizeMatcherList(TheMatcher, NullOS);
  993. OmitComments = SaveOmitComments;
  994. // Now that the matchers are sized, we can emit the code for them to the
  995. // final stream.
  996. OS << "{\n";
  997. OS << " // Some target values are emitted as 2 bytes, TARGET_VAL handles\n";
  998. OS << " // this.\n";
  999. OS << " #define TARGET_VAL(X) X & 255, unsigned(X) >> 8\n";
  1000. OS << " static const unsigned char MatcherTable[] = {\n";
  1001. TotalSize = MatcherEmitter.EmitMatcherList(TheMatcher, 1, 0, OS);
  1002. OS << " 0\n }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
  1003. MatcherEmitter.EmitHistogram(TheMatcher, OS);
  1004. OS << " #undef TARGET_VAL\n";
  1005. OS << " SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n";
  1006. OS << "}\n";
  1007. EndEmitFunction(OS);
  1008. // Next up, emit the function for node and pattern predicates:
  1009. MatcherEmitter.EmitPredicateFunctions(OS);
  1010. if (InstrumentCoverage)
  1011. MatcherEmitter.EmitPatternMatchTable(OS);
  1012. // Clean up the preprocessor macros.
  1013. OS << "\n";
  1014. OS << "#ifdef DAGISEL_INLINE\n";
  1015. OS << "#undef DAGISEL_INLINE\n";
  1016. OS << "#endif\n";
  1017. OS << "#ifdef DAGISEL_CLASS_COLONCOLON\n";
  1018. OS << "#undef DAGISEL_CLASS_COLONCOLON\n";
  1019. OS << "#endif\n";
  1020. OS << "#ifdef GET_DAGISEL_DECL\n";
  1021. OS << "#undef GET_DAGISEL_DECL\n";
  1022. OS << "#endif\n";
  1023. OS << "#ifdef GET_DAGISEL_BODY\n";
  1024. OS << "#undef GET_DAGISEL_BODY\n";
  1025. OS << "#endif\n";
  1026. }