StringMatcher.cpp 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. //===- StringMatcher.cpp - Generate a matcher for input strings -----------===//
  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 implements the StringMatcher class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/TableGen/StringMatcher.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/Support/raw_ostream.h"
  15. #include <cassert>
  16. #include <map>
  17. #include <string>
  18. #include <utility>
  19. #include <vector>
  20. using namespace llvm;
  21. /// FindFirstNonCommonLetter - Find the first character in the keys of the
  22. /// string pairs that is not shared across the whole set of strings. All
  23. /// strings are assumed to have the same length.
  24. static unsigned
  25. FindFirstNonCommonLetter(const std::vector<const
  26. StringMatcher::StringPair*> &Matches) {
  27. assert(!Matches.empty());
  28. for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
  29. // Check to see if letter i is the same across the set.
  30. char Letter = Matches[0]->first[i];
  31. for (const StringMatcher::StringPair *Match : Matches)
  32. if (Match->first[i] != Letter)
  33. return i;
  34. }
  35. return Matches[0]->first.size();
  36. }
  37. /// EmitStringMatcherForChar - Given a set of strings that are known to be the
  38. /// same length and whose characters leading up to CharNo are the same, emit
  39. /// code to verify that CharNo and later are the same.
  40. ///
  41. /// \return - True if control can leave the emitted code fragment.
  42. bool StringMatcher::EmitStringMatcherForChar(
  43. const std::vector<const StringPair *> &Matches, unsigned CharNo,
  44. unsigned IndentCount, bool IgnoreDuplicates) const {
  45. assert(!Matches.empty() && "Must have at least one string to match!");
  46. std::string Indent(IndentCount * 2 + 4, ' ');
  47. // If we have verified that the entire string matches, we're done: output the
  48. // matching code.
  49. if (CharNo == Matches[0]->first.size()) {
  50. if (Matches.size() > 1 && !IgnoreDuplicates)
  51. report_fatal_error("Had duplicate keys to match on");
  52. // If the to-execute code has \n's in it, indent each subsequent line.
  53. StringRef Code = Matches[0]->second;
  54. std::pair<StringRef, StringRef> Split = Code.split('\n');
  55. OS << Indent << Split.first << "\t // \"" << Matches[0]->first << "\"\n";
  56. Code = Split.second;
  57. while (!Code.empty()) {
  58. Split = Code.split('\n');
  59. OS << Indent << Split.first << "\n";
  60. Code = Split.second;
  61. }
  62. return false;
  63. }
  64. // Bucket the matches by the character we are comparing.
  65. std::map<char, std::vector<const StringPair*>> MatchesByLetter;
  66. for (const StringPair *Match : Matches)
  67. MatchesByLetter[Match->first[CharNo]].push_back(Match);
  68. // If we have exactly one bucket to match, see how many characters are common
  69. // across the whole set and match all of them at once.
  70. if (MatchesByLetter.size() == 1) {
  71. unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
  72. unsigned NumChars = FirstNonCommonLetter-CharNo;
  73. // Emit code to break out if the prefix doesn't match.
  74. if (NumChars == 1) {
  75. // Do the comparison with if (Str[1] != 'f')
  76. // FIXME: Need to escape general characters.
  77. OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
  78. << Matches[0]->first[CharNo] << "')\n";
  79. OS << Indent << " break;\n";
  80. } else {
  81. // Do the comparison with if memcmp(Str.data()+1, "foo", 3).
  82. // FIXME: Need to escape general strings.
  83. OS << Indent << "if (memcmp(" << StrVariableName << ".data()+" << CharNo
  84. << ", \"" << Matches[0]->first.substr(CharNo, NumChars) << "\", "
  85. << NumChars << ") != 0)\n";
  86. OS << Indent << " break;\n";
  87. }
  88. return EmitStringMatcherForChar(Matches, FirstNonCommonLetter, IndentCount,
  89. IgnoreDuplicates);
  90. }
  91. // Otherwise, we have multiple possible things, emit a switch on the
  92. // character.
  93. OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
  94. OS << Indent << "default: break;\n";
  95. for (const auto &LI : MatchesByLetter) {
  96. // TODO: escape hard stuff (like \n) if we ever care about it.
  97. OS << Indent << "case '" << LI.first << "':\t // " << LI.second.size()
  98. << " string";
  99. if (LI.second.size() != 1)
  100. OS << 's';
  101. OS << " to match.\n";
  102. if (EmitStringMatcherForChar(LI.second, CharNo + 1, IndentCount + 1,
  103. IgnoreDuplicates))
  104. OS << Indent << " break;\n";
  105. }
  106. OS << Indent << "}\n";
  107. return true;
  108. }
  109. /// Emit - Top level entry point.
  110. ///
  111. void StringMatcher::Emit(unsigned Indent, bool IgnoreDuplicates) const {
  112. // If nothing to match, just fall through.
  113. if (Matches.empty()) return;
  114. // First level categorization: group strings by length.
  115. std::map<unsigned, std::vector<const StringPair*>> MatchesByLength;
  116. for (const StringPair &Match : Matches)
  117. MatchesByLength[Match.first.size()].push_back(&Match);
  118. // Output a switch statement on length and categorize the elements within each
  119. // bin.
  120. OS.indent(Indent*2+2) << "switch (" << StrVariableName << ".size()) {\n";
  121. OS.indent(Indent*2+2) << "default: break;\n";
  122. for (const auto &LI : MatchesByLength) {
  123. OS.indent(Indent * 2 + 2)
  124. << "case " << LI.first << ":\t // " << LI.second.size() << " string"
  125. << (LI.second.size() == 1 ? "" : "s") << " to match.\n";
  126. if (EmitStringMatcherForChar(LI.second, 0, Indent, IgnoreDuplicates))
  127. OS.indent(Indent*2+4) << "break;\n";
  128. }
  129. OS.indent(Indent*2+2) << "}\n";
  130. }