FixedLenDecoderEmitter.cpp 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549
  1. //===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
  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. // It contains the tablegen backend that emits the decoder functions for
  10. // targets with fixed length instruction set.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenInstruction.h"
  14. #include "CodeGenTarget.h"
  15. #include "InfoByHwMode.h"
  16. #include "llvm/ADT/APInt.h"
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/CachedHashString.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SetVector.h"
  21. #include "llvm/ADT/SmallString.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/ADT/StringExtras.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/MC/MCFixedLenDisassembler.h"
  26. #include "llvm/Support/Casting.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include "llvm/Support/FormattedStream.h"
  30. #include "llvm/Support/LEB128.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include "llvm/TableGen/Error.h"
  33. #include "llvm/TableGen/Record.h"
  34. #include <algorithm>
  35. #include <cassert>
  36. #include <cstddef>
  37. #include <cstdint>
  38. #include <map>
  39. #include <memory>
  40. #include <set>
  41. #include <string>
  42. #include <utility>
  43. #include <vector>
  44. using namespace llvm;
  45. #define DEBUG_TYPE "decoder-emitter"
  46. namespace {
  47. STATISTIC(NumEncodings, "Number of encodings considered");
  48. STATISTIC(NumEncodingsLackingDisasm, "Number of encodings without disassembler info");
  49. STATISTIC(NumInstructions, "Number of instructions considered");
  50. STATISTIC(NumEncodingsSupported, "Number of encodings supported");
  51. STATISTIC(NumEncodingsOmitted, "Number of encodings omitted");
  52. struct EncodingField {
  53. unsigned Base, Width, Offset;
  54. EncodingField(unsigned B, unsigned W, unsigned O)
  55. : Base(B), Width(W), Offset(O) { }
  56. };
  57. struct OperandInfo {
  58. std::vector<EncodingField> Fields;
  59. std::string Decoder;
  60. bool HasCompleteDecoder;
  61. uint64_t InitValue;
  62. OperandInfo(std::string D, bool HCD)
  63. : Decoder(std::move(D)), HasCompleteDecoder(HCD), InitValue(0) {}
  64. void addField(unsigned Base, unsigned Width, unsigned Offset) {
  65. Fields.push_back(EncodingField(Base, Width, Offset));
  66. }
  67. unsigned numFields() const { return Fields.size(); }
  68. typedef std::vector<EncodingField>::const_iterator const_iterator;
  69. const_iterator begin() const { return Fields.begin(); }
  70. const_iterator end() const { return Fields.end(); }
  71. };
  72. typedef std::vector<uint8_t> DecoderTable;
  73. typedef uint32_t DecoderFixup;
  74. typedef std::vector<DecoderFixup> FixupList;
  75. typedef std::vector<FixupList> FixupScopeList;
  76. typedef SmallSetVector<CachedHashString, 16> PredicateSet;
  77. typedef SmallSetVector<CachedHashString, 16> DecoderSet;
  78. struct DecoderTableInfo {
  79. DecoderTable Table;
  80. FixupScopeList FixupStack;
  81. PredicateSet Predicates;
  82. DecoderSet Decoders;
  83. };
  84. struct EncodingAndInst {
  85. const Record *EncodingDef;
  86. const CodeGenInstruction *Inst;
  87. StringRef HwModeName;
  88. EncodingAndInst(const Record *EncodingDef, const CodeGenInstruction *Inst,
  89. StringRef HwModeName = "")
  90. : EncodingDef(EncodingDef), Inst(Inst), HwModeName(HwModeName) {}
  91. };
  92. struct EncodingIDAndOpcode {
  93. unsigned EncodingID;
  94. unsigned Opcode;
  95. EncodingIDAndOpcode() : EncodingID(0), Opcode(0) {}
  96. EncodingIDAndOpcode(unsigned EncodingID, unsigned Opcode)
  97. : EncodingID(EncodingID), Opcode(Opcode) {}
  98. };
  99. raw_ostream &operator<<(raw_ostream &OS, const EncodingAndInst &Value) {
  100. if (Value.EncodingDef != Value.Inst->TheDef)
  101. OS << Value.EncodingDef->getName() << ":";
  102. OS << Value.Inst->TheDef->getName();
  103. return OS;
  104. }
  105. class FixedLenDecoderEmitter {
  106. RecordKeeper &RK;
  107. std::vector<EncodingAndInst> NumberedEncodings;
  108. public:
  109. // Defaults preserved here for documentation, even though they aren't
  110. // strictly necessary given the way that this is currently being called.
  111. FixedLenDecoderEmitter(RecordKeeper &R, std::string PredicateNamespace,
  112. std::string GPrefix = "if (",
  113. std::string GPostfix = " == MCDisassembler::Fail)",
  114. std::string ROK = "MCDisassembler::Success",
  115. std::string RFail = "MCDisassembler::Fail",
  116. std::string L = "")
  117. : RK(R), Target(R), PredicateNamespace(std::move(PredicateNamespace)),
  118. GuardPrefix(std::move(GPrefix)), GuardPostfix(std::move(GPostfix)),
  119. ReturnOK(std::move(ROK)), ReturnFail(std::move(RFail)),
  120. Locals(std::move(L)) {}
  121. // Emit the decoder state machine table.
  122. void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
  123. unsigned Indentation, unsigned BitWidth,
  124. StringRef Namespace) const;
  125. void emitPredicateFunction(formatted_raw_ostream &OS,
  126. PredicateSet &Predicates,
  127. unsigned Indentation) const;
  128. void emitDecoderFunction(formatted_raw_ostream &OS,
  129. DecoderSet &Decoders,
  130. unsigned Indentation) const;
  131. // run - Output the code emitter
  132. void run(raw_ostream &o);
  133. private:
  134. CodeGenTarget Target;
  135. public:
  136. std::string PredicateNamespace;
  137. std::string GuardPrefix, GuardPostfix;
  138. std::string ReturnOK, ReturnFail;
  139. std::string Locals;
  140. };
  141. } // end anonymous namespace
  142. // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
  143. // for a bit value.
  144. //
  145. // BIT_UNFILTERED is used as the init value for a filter position. It is used
  146. // only for filter processings.
  147. typedef enum {
  148. BIT_TRUE, // '1'
  149. BIT_FALSE, // '0'
  150. BIT_UNSET, // '?'
  151. BIT_UNFILTERED // unfiltered
  152. } bit_value_t;
  153. static bool ValueSet(bit_value_t V) {
  154. return (V == BIT_TRUE || V == BIT_FALSE);
  155. }
  156. static bool ValueNotSet(bit_value_t V) {
  157. return (V == BIT_UNSET);
  158. }
  159. static int Value(bit_value_t V) {
  160. return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
  161. }
  162. static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
  163. if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
  164. return bit->getValue() ? BIT_TRUE : BIT_FALSE;
  165. // The bit is uninitialized.
  166. return BIT_UNSET;
  167. }
  168. // Prints the bit value for each position.
  169. static void dumpBits(raw_ostream &o, const BitsInit &bits) {
  170. for (unsigned index = bits.getNumBits(); index > 0; --index) {
  171. switch (bitFromBits(bits, index - 1)) {
  172. case BIT_TRUE:
  173. o << "1";
  174. break;
  175. case BIT_FALSE:
  176. o << "0";
  177. break;
  178. case BIT_UNSET:
  179. o << "_";
  180. break;
  181. default:
  182. llvm_unreachable("unexpected return value from bitFromBits");
  183. }
  184. }
  185. }
  186. static BitsInit &getBitsField(const Record &def, StringRef str) {
  187. BitsInit *bits = def.getValueAsBitsInit(str);
  188. return *bits;
  189. }
  190. // Representation of the instruction to work on.
  191. typedef std::vector<bit_value_t> insn_t;
  192. namespace {
  193. static const uint64_t NO_FIXED_SEGMENTS_SENTINEL = -1ULL;
  194. class FilterChooser;
  195. /// Filter - Filter works with FilterChooser to produce the decoding tree for
  196. /// the ISA.
  197. ///
  198. /// It is useful to think of a Filter as governing the switch stmts of the
  199. /// decoding tree in a certain level. Each case stmt delegates to an inferior
  200. /// FilterChooser to decide what further decoding logic to employ, or in another
  201. /// words, what other remaining bits to look at. The FilterChooser eventually
  202. /// chooses a best Filter to do its job.
  203. ///
  204. /// This recursive scheme ends when the number of Opcodes assigned to the
  205. /// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
  206. /// the Filter/FilterChooser combo does not know how to distinguish among the
  207. /// Opcodes assigned.
  208. ///
  209. /// An example of a conflict is
  210. ///
  211. /// Conflict:
  212. /// 111101000.00........00010000....
  213. /// 111101000.00........0001........
  214. /// 1111010...00........0001........
  215. /// 1111010...00....................
  216. /// 1111010.........................
  217. /// 1111............................
  218. /// ................................
  219. /// VST4q8a 111101000_00________00010000____
  220. /// VST4q8b 111101000_00________00010000____
  221. ///
  222. /// The Debug output shows the path that the decoding tree follows to reach the
  223. /// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
  224. /// even registers, while VST4q8b is a vst4 to double-spaced odd registers.
  225. ///
  226. /// The encoding info in the .td files does not specify this meta information,
  227. /// which could have been used by the decoder to resolve the conflict. The
  228. /// decoder could try to decode the even/odd register numbering and assign to
  229. /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
  230. /// version and return the Opcode since the two have the same Asm format string.
  231. class Filter {
  232. protected:
  233. const FilterChooser *Owner;// points to the FilterChooser who owns this filter
  234. unsigned StartBit; // the starting bit position
  235. unsigned NumBits; // number of bits to filter
  236. bool Mixed; // a mixed region contains both set and unset bits
  237. // Map of well-known segment value to the set of uid's with that value.
  238. std::map<uint64_t, std::vector<EncodingIDAndOpcode>>
  239. FilteredInstructions;
  240. // Set of uid's with non-constant segment values.
  241. std::vector<EncodingIDAndOpcode> VariableInstructions;
  242. // Map of well-known segment value to its delegate.
  243. std::map<uint64_t, std::unique_ptr<const FilterChooser>> FilterChooserMap;
  244. // Number of instructions which fall under FilteredInstructions category.
  245. unsigned NumFiltered;
  246. // Keeps track of the last opcode in the filtered bucket.
  247. EncodingIDAndOpcode LastOpcFiltered;
  248. public:
  249. Filter(Filter &&f);
  250. Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
  251. ~Filter() = default;
  252. unsigned getNumFiltered() const { return NumFiltered; }
  253. EncodingIDAndOpcode getSingletonOpc() const {
  254. assert(NumFiltered == 1);
  255. return LastOpcFiltered;
  256. }
  257. // Return the filter chooser for the group of instructions without constant
  258. // segment values.
  259. const FilterChooser &getVariableFC() const {
  260. assert(NumFiltered == 1);
  261. assert(FilterChooserMap.size() == 1);
  262. return *(FilterChooserMap.find(NO_FIXED_SEGMENTS_SENTINEL)->second);
  263. }
  264. // Divides the decoding task into sub tasks and delegates them to the
  265. // inferior FilterChooser's.
  266. //
  267. // A special case arises when there's only one entry in the filtered
  268. // instructions. In order to unambiguously decode the singleton, we need to
  269. // match the remaining undecoded encoding bits against the singleton.
  270. void recurse();
  271. // Emit table entries to decode instructions given a segment or segments of
  272. // bits.
  273. void emitTableEntry(DecoderTableInfo &TableInfo) const;
  274. // Returns the number of fanout produced by the filter. More fanout implies
  275. // the filter distinguishes more categories of instructions.
  276. unsigned usefulness() const;
  277. }; // end class Filter
  278. } // end anonymous namespace
  279. // These are states of our finite state machines used in FilterChooser's
  280. // filterProcessor() which produces the filter candidates to use.
  281. typedef enum {
  282. ATTR_NONE,
  283. ATTR_FILTERED,
  284. ATTR_ALL_SET,
  285. ATTR_ALL_UNSET,
  286. ATTR_MIXED
  287. } bitAttr_t;
  288. /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
  289. /// in order to perform the decoding of instructions at the current level.
  290. ///
  291. /// Decoding proceeds from the top down. Based on the well-known encoding bits
  292. /// of instructions available, FilterChooser builds up the possible Filters that
  293. /// can further the task of decoding by distinguishing among the remaining
  294. /// candidate instructions.
  295. ///
  296. /// Once a filter has been chosen, it is called upon to divide the decoding task
  297. /// into sub-tasks and delegates them to its inferior FilterChoosers for further
  298. /// processings.
  299. ///
  300. /// It is useful to think of a Filter as governing the switch stmts of the
  301. /// decoding tree. And each case is delegated to an inferior FilterChooser to
  302. /// decide what further remaining bits to look at.
  303. namespace {
  304. class FilterChooser {
  305. protected:
  306. friend class Filter;
  307. // Vector of codegen instructions to choose our filter.
  308. ArrayRef<EncodingAndInst> AllInstructions;
  309. // Vector of uid's for this filter chooser to work on.
  310. // The first member of the pair is the opcode id being decoded, the second is
  311. // the opcode id that should be emitted.
  312. const std::vector<EncodingIDAndOpcode> &Opcodes;
  313. // Lookup table for the operand decoding of instructions.
  314. const std::map<unsigned, std::vector<OperandInfo>> &Operands;
  315. // Vector of candidate filters.
  316. std::vector<Filter> Filters;
  317. // Array of bit values passed down from our parent.
  318. // Set to all BIT_UNFILTERED's for Parent == NULL.
  319. std::vector<bit_value_t> FilterBitValues;
  320. // Links to the FilterChooser above us in the decoding tree.
  321. const FilterChooser *Parent;
  322. // Index of the best filter from Filters.
  323. int BestIndex;
  324. // Width of instructions
  325. unsigned BitWidth;
  326. // Parent emitter
  327. const FixedLenDecoderEmitter *Emitter;
  328. public:
  329. FilterChooser(ArrayRef<EncodingAndInst> Insts,
  330. const std::vector<EncodingIDAndOpcode> &IDs,
  331. const std::map<unsigned, std::vector<OperandInfo>> &Ops,
  332. unsigned BW, const FixedLenDecoderEmitter *E)
  333. : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
  334. FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1),
  335. BitWidth(BW), Emitter(E) {
  336. doFilter();
  337. }
  338. FilterChooser(ArrayRef<EncodingAndInst> Insts,
  339. const std::vector<EncodingIDAndOpcode> &IDs,
  340. const std::map<unsigned, std::vector<OperandInfo>> &Ops,
  341. const std::vector<bit_value_t> &ParentFilterBitValues,
  342. const FilterChooser &parent)
  343. : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
  344. FilterBitValues(ParentFilterBitValues), Parent(&parent), BestIndex(-1),
  345. BitWidth(parent.BitWidth), Emitter(parent.Emitter) {
  346. doFilter();
  347. }
  348. FilterChooser(const FilterChooser &) = delete;
  349. void operator=(const FilterChooser &) = delete;
  350. unsigned getBitWidth() const { return BitWidth; }
  351. protected:
  352. // Populates the insn given the uid.
  353. void insnWithID(insn_t &Insn, unsigned Opcode) const {
  354. BitsInit &Bits = getBitsField(*AllInstructions[Opcode].EncodingDef, "Inst");
  355. // We may have a SoftFail bitmask, which specifies a mask where an encoding
  356. // may differ from the value in "Inst" and yet still be valid, but the
  357. // disassembler should return SoftFail instead of Success.
  358. //
  359. // This is used for marking UNPREDICTABLE instructions in the ARM world.
  360. BitsInit *SFBits =
  361. AllInstructions[Opcode].EncodingDef->getValueAsBitsInit("SoftFail");
  362. for (unsigned i = 0; i < BitWidth; ++i) {
  363. if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
  364. Insn.push_back(BIT_UNSET);
  365. else
  366. Insn.push_back(bitFromBits(Bits, i));
  367. }
  368. }
  369. // Emit the name of the encoding/instruction pair.
  370. void emitNameWithID(raw_ostream &OS, unsigned Opcode) const {
  371. const Record *EncodingDef = AllInstructions[Opcode].EncodingDef;
  372. const Record *InstDef = AllInstructions[Opcode].Inst->TheDef;
  373. if (EncodingDef != InstDef)
  374. OS << EncodingDef->getName() << ":";
  375. OS << InstDef->getName();
  376. }
  377. // Populates the field of the insn given the start position and the number of
  378. // consecutive bits to scan for.
  379. //
  380. // Returns false if there exists any uninitialized bit value in the range.
  381. // Returns true, otherwise.
  382. bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
  383. unsigned NumBits) const;
  384. /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
  385. /// filter array as a series of chars.
  386. void dumpFilterArray(raw_ostream &o,
  387. const std::vector<bit_value_t> & filter) const;
  388. /// dumpStack - dumpStack traverses the filter chooser chain and calls
  389. /// dumpFilterArray on each filter chooser up to the top level one.
  390. void dumpStack(raw_ostream &o, const char *prefix) const;
  391. Filter &bestFilter() {
  392. assert(BestIndex != -1 && "BestIndex not set");
  393. return Filters[BestIndex];
  394. }
  395. bool PositionFiltered(unsigned i) const {
  396. return ValueSet(FilterBitValues[i]);
  397. }
  398. // Calculates the island(s) needed to decode the instruction.
  399. // This returns a lit of undecoded bits of an instructions, for example,
  400. // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
  401. // decoded bits in order to verify that the instruction matches the Opcode.
  402. unsigned getIslands(std::vector<unsigned> &StartBits,
  403. std::vector<unsigned> &EndBits,
  404. std::vector<uint64_t> &FieldVals,
  405. const insn_t &Insn) const;
  406. // Emits code to check the Predicates member of an instruction are true.
  407. // Returns true if predicate matches were emitted, false otherwise.
  408. bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
  409. unsigned Opc) const;
  410. bool doesOpcodeNeedPredicate(unsigned Opc) const;
  411. unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
  412. void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
  413. unsigned Opc) const;
  414. void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
  415. unsigned Opc) const;
  416. // Emits table entries to decode the singleton.
  417. void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
  418. EncodingIDAndOpcode Opc) const;
  419. // Emits code to decode the singleton, and then to decode the rest.
  420. void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
  421. const Filter &Best) const;
  422. void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
  423. const OperandInfo &OpInfo,
  424. bool &OpHasCompleteDecoder) const;
  425. void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc,
  426. bool &HasCompleteDecoder) const;
  427. unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc,
  428. bool &HasCompleteDecoder) const;
  429. // Assign a single filter and run with it.
  430. void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
  431. // reportRegion is a helper function for filterProcessor to mark a region as
  432. // eligible for use as a filter region.
  433. void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
  434. bool AllowMixed);
  435. // FilterProcessor scans the well-known encoding bits of the instructions and
  436. // builds up a list of candidate filters. It chooses the best filter and
  437. // recursively descends down the decoding tree.
  438. bool filterProcessor(bool AllowMixed, bool Greedy = true);
  439. // Decides on the best configuration of filter(s) to use in order to decode
  440. // the instructions. A conflict of instructions may occur, in which case we
  441. // dump the conflict set to the standard error.
  442. void doFilter();
  443. public:
  444. // emitTableEntries - Emit state machine entries to decode our share of
  445. // instructions.
  446. void emitTableEntries(DecoderTableInfo &TableInfo) const;
  447. };
  448. } // end anonymous namespace
  449. ///////////////////////////
  450. // //
  451. // Filter Implementation //
  452. // //
  453. ///////////////////////////
  454. Filter::Filter(Filter &&f)
  455. : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
  456. FilteredInstructions(std::move(f.FilteredInstructions)),
  457. VariableInstructions(std::move(f.VariableInstructions)),
  458. FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
  459. LastOpcFiltered(f.LastOpcFiltered) {
  460. }
  461. Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
  462. bool mixed)
  463. : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
  464. assert(StartBit + NumBits - 1 < Owner->BitWidth);
  465. NumFiltered = 0;
  466. LastOpcFiltered = {0, 0};
  467. for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
  468. insn_t Insn;
  469. // Populates the insn given the uid.
  470. Owner->insnWithID(Insn, Owner->Opcodes[i].EncodingID);
  471. uint64_t Field;
  472. // Scans the segment for possibly well-specified encoding bits.
  473. bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
  474. if (ok) {
  475. // The encoding bits are well-known. Lets add the uid of the
  476. // instruction into the bucket keyed off the constant field value.
  477. LastOpcFiltered = Owner->Opcodes[i];
  478. FilteredInstructions[Field].push_back(LastOpcFiltered);
  479. ++NumFiltered;
  480. } else {
  481. // Some of the encoding bit(s) are unspecified. This contributes to
  482. // one additional member of "Variable" instructions.
  483. VariableInstructions.push_back(Owner->Opcodes[i]);
  484. }
  485. }
  486. assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
  487. && "Filter returns no instruction categories");
  488. }
  489. // Divides the decoding task into sub tasks and delegates them to the
  490. // inferior FilterChooser's.
  491. //
  492. // A special case arises when there's only one entry in the filtered
  493. // instructions. In order to unambiguously decode the singleton, we need to
  494. // match the remaining undecoded encoding bits against the singleton.
  495. void Filter::recurse() {
  496. // Starts by inheriting our parent filter chooser's filter bit values.
  497. std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
  498. if (!VariableInstructions.empty()) {
  499. // Conservatively marks each segment position as BIT_UNSET.
  500. for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
  501. BitValueArray[StartBit + bitIndex] = BIT_UNSET;
  502. // Delegates to an inferior filter chooser for further processing on this
  503. // group of instructions whose segment values are variable.
  504. FilterChooserMap.insert(std::make_pair(NO_FIXED_SEGMENTS_SENTINEL,
  505. std::make_unique<FilterChooser>(Owner->AllInstructions,
  506. VariableInstructions, Owner->Operands, BitValueArray, *Owner)));
  507. }
  508. // No need to recurse for a singleton filtered instruction.
  509. // See also Filter::emit*().
  510. if (getNumFiltered() == 1) {
  511. assert(FilterChooserMap.size() == 1);
  512. return;
  513. }
  514. // Otherwise, create sub choosers.
  515. for (const auto &Inst : FilteredInstructions) {
  516. // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
  517. for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
  518. if (Inst.first & (1ULL << bitIndex))
  519. BitValueArray[StartBit + bitIndex] = BIT_TRUE;
  520. else
  521. BitValueArray[StartBit + bitIndex] = BIT_FALSE;
  522. }
  523. // Delegates to an inferior filter chooser for further processing on this
  524. // category of instructions.
  525. FilterChooserMap.insert(std::make_pair(
  526. Inst.first, std::make_unique<FilterChooser>(
  527. Owner->AllInstructions, Inst.second,
  528. Owner->Operands, BitValueArray, *Owner)));
  529. }
  530. }
  531. static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
  532. uint32_t DestIdx) {
  533. // Any NumToSkip fixups in the current scope can resolve to the
  534. // current location.
  535. for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
  536. E = Fixups.rend();
  537. I != E; ++I) {
  538. // Calculate the distance from the byte following the fixup entry byte
  539. // to the destination. The Target is calculated from after the 16-bit
  540. // NumToSkip entry itself, so subtract two from the displacement here
  541. // to account for that.
  542. uint32_t FixupIdx = *I;
  543. uint32_t Delta = DestIdx - FixupIdx - 3;
  544. // Our NumToSkip entries are 24-bits. Make sure our table isn't too
  545. // big.
  546. assert(Delta < (1u << 24));
  547. Table[FixupIdx] = (uint8_t)Delta;
  548. Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
  549. Table[FixupIdx + 2] = (uint8_t)(Delta >> 16);
  550. }
  551. }
  552. // Emit table entries to decode instructions given a segment or segments
  553. // of bits.
  554. void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
  555. TableInfo.Table.push_back(MCD::OPC_ExtractField);
  556. TableInfo.Table.push_back(StartBit);
  557. TableInfo.Table.push_back(NumBits);
  558. // A new filter entry begins a new scope for fixup resolution.
  559. TableInfo.FixupStack.emplace_back();
  560. DecoderTable &Table = TableInfo.Table;
  561. size_t PrevFilter = 0;
  562. bool HasFallthrough = false;
  563. for (auto &Filter : FilterChooserMap) {
  564. // Field value -1 implies a non-empty set of variable instructions.
  565. // See also recurse().
  566. if (Filter.first == NO_FIXED_SEGMENTS_SENTINEL) {
  567. HasFallthrough = true;
  568. // Each scope should always have at least one filter value to check
  569. // for.
  570. assert(PrevFilter != 0 && "empty filter set!");
  571. FixupList &CurScope = TableInfo.FixupStack.back();
  572. // Resolve any NumToSkip fixups in the current scope.
  573. resolveTableFixups(Table, CurScope, Table.size());
  574. CurScope.clear();
  575. PrevFilter = 0; // Don't re-process the filter's fallthrough.
  576. } else {
  577. Table.push_back(MCD::OPC_FilterValue);
  578. // Encode and emit the value to filter against.
  579. uint8_t Buffer[16];
  580. unsigned Len = encodeULEB128(Filter.first, Buffer);
  581. Table.insert(Table.end(), Buffer, Buffer + Len);
  582. // Reserve space for the NumToSkip entry. We'll backpatch the value
  583. // later.
  584. PrevFilter = Table.size();
  585. Table.push_back(0);
  586. Table.push_back(0);
  587. Table.push_back(0);
  588. }
  589. // We arrive at a category of instructions with the same segment value.
  590. // Now delegate to the sub filter chooser for further decodings.
  591. // The case may fallthrough, which happens if the remaining well-known
  592. // encoding bits do not match exactly.
  593. Filter.second->emitTableEntries(TableInfo);
  594. // Now that we've emitted the body of the handler, update the NumToSkip
  595. // of the filter itself to be able to skip forward when false. Subtract
  596. // two as to account for the width of the NumToSkip field itself.
  597. if (PrevFilter) {
  598. uint32_t NumToSkip = Table.size() - PrevFilter - 3;
  599. assert(NumToSkip < (1u << 24) && "disassembler decoding table too large!");
  600. Table[PrevFilter] = (uint8_t)NumToSkip;
  601. Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
  602. Table[PrevFilter + 2] = (uint8_t)(NumToSkip >> 16);
  603. }
  604. }
  605. // Any remaining unresolved fixups bubble up to the parent fixup scope.
  606. assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
  607. FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
  608. FixupScopeList::iterator Dest = Source - 1;
  609. llvm::append_range(*Dest, *Source);
  610. TableInfo.FixupStack.pop_back();
  611. // If there is no fallthrough, then the final filter should get fixed
  612. // up according to the enclosing scope rather than the current position.
  613. if (!HasFallthrough)
  614. TableInfo.FixupStack.back().push_back(PrevFilter);
  615. }
  616. // Returns the number of fanout produced by the filter. More fanout implies
  617. // the filter distinguishes more categories of instructions.
  618. unsigned Filter::usefulness() const {
  619. if (!VariableInstructions.empty())
  620. return FilteredInstructions.size();
  621. else
  622. return FilteredInstructions.size() + 1;
  623. }
  624. //////////////////////////////////
  625. // //
  626. // Filterchooser Implementation //
  627. // //
  628. //////////////////////////////////
  629. // Emit the decoder state machine table.
  630. void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
  631. DecoderTable &Table,
  632. unsigned Indentation,
  633. unsigned BitWidth,
  634. StringRef Namespace) const {
  635. OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
  636. << BitWidth << "[] = {\n";
  637. Indentation += 2;
  638. // FIXME: We may be able to use the NumToSkip values to recover
  639. // appropriate indentation levels.
  640. DecoderTable::const_iterator I = Table.begin();
  641. DecoderTable::const_iterator E = Table.end();
  642. while (I != E) {
  643. assert (I < E && "incomplete decode table entry!");
  644. uint64_t Pos = I - Table.begin();
  645. OS << "/* " << Pos << " */";
  646. OS.PadToColumn(12);
  647. switch (*I) {
  648. default:
  649. PrintFatalError("invalid decode table opcode");
  650. case MCD::OPC_ExtractField: {
  651. ++I;
  652. unsigned Start = *I++;
  653. unsigned Len = *I++;
  654. OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
  655. << Len << ", // Inst{";
  656. if (Len > 1)
  657. OS << (Start + Len - 1) << "-";
  658. OS << Start << "} ...\n";
  659. break;
  660. }
  661. case MCD::OPC_FilterValue: {
  662. ++I;
  663. OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
  664. // The filter value is ULEB128 encoded.
  665. while (*I >= 128)
  666. OS << (unsigned)*I++ << ", ";
  667. OS << (unsigned)*I++ << ", ";
  668. // 24-bit numtoskip value.
  669. uint8_t Byte = *I++;
  670. uint32_t NumToSkip = Byte;
  671. OS << (unsigned)Byte << ", ";
  672. Byte = *I++;
  673. OS << (unsigned)Byte << ", ";
  674. NumToSkip |= Byte << 8;
  675. Byte = *I++;
  676. OS << utostr(Byte) << ", ";
  677. NumToSkip |= Byte << 16;
  678. OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
  679. break;
  680. }
  681. case MCD::OPC_CheckField: {
  682. ++I;
  683. unsigned Start = *I++;
  684. unsigned Len = *I++;
  685. OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
  686. << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
  687. // ULEB128 encoded field value.
  688. for (; *I >= 128; ++I)
  689. OS << (unsigned)*I << ", ";
  690. OS << (unsigned)*I++ << ", ";
  691. // 24-bit numtoskip value.
  692. uint8_t Byte = *I++;
  693. uint32_t NumToSkip = Byte;
  694. OS << (unsigned)Byte << ", ";
  695. Byte = *I++;
  696. OS << (unsigned)Byte << ", ";
  697. NumToSkip |= Byte << 8;
  698. Byte = *I++;
  699. OS << utostr(Byte) << ", ";
  700. NumToSkip |= Byte << 16;
  701. OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
  702. break;
  703. }
  704. case MCD::OPC_CheckPredicate: {
  705. ++I;
  706. OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
  707. for (; *I >= 128; ++I)
  708. OS << (unsigned)*I << ", ";
  709. OS << (unsigned)*I++ << ", ";
  710. // 24-bit numtoskip value.
  711. uint8_t Byte = *I++;
  712. uint32_t NumToSkip = Byte;
  713. OS << (unsigned)Byte << ", ";
  714. Byte = *I++;
  715. OS << (unsigned)Byte << ", ";
  716. NumToSkip |= Byte << 8;
  717. Byte = *I++;
  718. OS << utostr(Byte) << ", ";
  719. NumToSkip |= Byte << 16;
  720. OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
  721. break;
  722. }
  723. case MCD::OPC_Decode:
  724. case MCD::OPC_TryDecode: {
  725. bool IsTry = *I == MCD::OPC_TryDecode;
  726. ++I;
  727. // Extract the ULEB128 encoded Opcode to a buffer.
  728. uint8_t Buffer[16], *p = Buffer;
  729. while ((*p++ = *I++) >= 128)
  730. assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
  731. && "ULEB128 value too large!");
  732. // Decode the Opcode value.
  733. unsigned Opc = decodeULEB128(Buffer);
  734. OS.indent(Indentation) << "MCD::OPC_" << (IsTry ? "Try" : "")
  735. << "Decode, ";
  736. for (p = Buffer; *p >= 128; ++p)
  737. OS << (unsigned)*p << ", ";
  738. OS << (unsigned)*p << ", ";
  739. // Decoder index.
  740. for (; *I >= 128; ++I)
  741. OS << (unsigned)*I << ", ";
  742. OS << (unsigned)*I++ << ", ";
  743. if (!IsTry) {
  744. OS << "// Opcode: " << NumberedEncodings[Opc] << "\n";
  745. break;
  746. }
  747. // Fallthrough for OPC_TryDecode.
  748. // 24-bit numtoskip value.
  749. uint8_t Byte = *I++;
  750. uint32_t NumToSkip = Byte;
  751. OS << (unsigned)Byte << ", ";
  752. Byte = *I++;
  753. OS << (unsigned)Byte << ", ";
  754. NumToSkip |= Byte << 8;
  755. Byte = *I++;
  756. OS << utostr(Byte) << ", ";
  757. NumToSkip |= Byte << 16;
  758. OS << "// Opcode: " << NumberedEncodings[Opc]
  759. << ", skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
  760. break;
  761. }
  762. case MCD::OPC_SoftFail: {
  763. ++I;
  764. OS.indent(Indentation) << "MCD::OPC_SoftFail";
  765. // Positive mask
  766. uint64_t Value = 0;
  767. unsigned Shift = 0;
  768. do {
  769. OS << ", " << (unsigned)*I;
  770. Value += (*I & 0x7f) << Shift;
  771. Shift += 7;
  772. } while (*I++ >= 128);
  773. if (Value > 127) {
  774. OS << " /* 0x";
  775. OS.write_hex(Value);
  776. OS << " */";
  777. }
  778. // Negative mask
  779. Value = 0;
  780. Shift = 0;
  781. do {
  782. OS << ", " << (unsigned)*I;
  783. Value += (*I & 0x7f) << Shift;
  784. Shift += 7;
  785. } while (*I++ >= 128);
  786. if (Value > 127) {
  787. OS << " /* 0x";
  788. OS.write_hex(Value);
  789. OS << " */";
  790. }
  791. OS << ",\n";
  792. break;
  793. }
  794. case MCD::OPC_Fail: {
  795. ++I;
  796. OS.indent(Indentation) << "MCD::OPC_Fail,\n";
  797. break;
  798. }
  799. }
  800. }
  801. OS.indent(Indentation) << "0\n";
  802. Indentation -= 2;
  803. OS.indent(Indentation) << "};\n\n";
  804. }
  805. void FixedLenDecoderEmitter::
  806. emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
  807. unsigned Indentation) const {
  808. // The predicate function is just a big switch statement based on the
  809. // input predicate index.
  810. OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
  811. << "const FeatureBitset &Bits) {\n";
  812. Indentation += 2;
  813. if (!Predicates.empty()) {
  814. OS.indent(Indentation) << "switch (Idx) {\n";
  815. OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
  816. unsigned Index = 0;
  817. for (const auto &Predicate : Predicates) {
  818. OS.indent(Indentation) << "case " << Index++ << ":\n";
  819. OS.indent(Indentation+2) << "return (" << Predicate << ");\n";
  820. }
  821. OS.indent(Indentation) << "}\n";
  822. } else {
  823. // No case statement to emit
  824. OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
  825. }
  826. Indentation -= 2;
  827. OS.indent(Indentation) << "}\n\n";
  828. }
  829. void FixedLenDecoderEmitter::
  830. emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
  831. unsigned Indentation) const {
  832. // The decoder function is just a big switch statement based on the
  833. // input decoder index.
  834. OS.indent(Indentation) << "template <typename InsnType>\n";
  835. OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
  836. << " unsigned Idx, InsnType insn, MCInst &MI,\n";
  837. OS.indent(Indentation) << " uint64_t "
  838. << "Address, const void *Decoder, bool &DecodeComplete) {\n";
  839. Indentation += 2;
  840. OS.indent(Indentation) << "DecodeComplete = true;\n";
  841. OS.indent(Indentation) << "InsnType tmp;\n";
  842. OS.indent(Indentation) << "switch (Idx) {\n";
  843. OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
  844. unsigned Index = 0;
  845. for (const auto &Decoder : Decoders) {
  846. OS.indent(Indentation) << "case " << Index++ << ":\n";
  847. OS << Decoder;
  848. OS.indent(Indentation+2) << "return S;\n";
  849. }
  850. OS.indent(Indentation) << "}\n";
  851. Indentation -= 2;
  852. OS.indent(Indentation) << "}\n\n";
  853. }
  854. // Populates the field of the insn given the start position and the number of
  855. // consecutive bits to scan for.
  856. //
  857. // Returns false if and on the first uninitialized bit value encountered.
  858. // Returns true, otherwise.
  859. bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
  860. unsigned StartBit, unsigned NumBits) const {
  861. Field = 0;
  862. for (unsigned i = 0; i < NumBits; ++i) {
  863. if (Insn[StartBit + i] == BIT_UNSET)
  864. return false;
  865. if (Insn[StartBit + i] == BIT_TRUE)
  866. Field = Field | (1ULL << i);
  867. }
  868. return true;
  869. }
  870. /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
  871. /// filter array as a series of chars.
  872. void FilterChooser::dumpFilterArray(raw_ostream &o,
  873. const std::vector<bit_value_t> &filter) const {
  874. for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
  875. switch (filter[bitIndex - 1]) {
  876. case BIT_UNFILTERED:
  877. o << ".";
  878. break;
  879. case BIT_UNSET:
  880. o << "_";
  881. break;
  882. case BIT_TRUE:
  883. o << "1";
  884. break;
  885. case BIT_FALSE:
  886. o << "0";
  887. break;
  888. }
  889. }
  890. }
  891. /// dumpStack - dumpStack traverses the filter chooser chain and calls
  892. /// dumpFilterArray on each filter chooser up to the top level one.
  893. void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
  894. const FilterChooser *current = this;
  895. while (current) {
  896. o << prefix;
  897. dumpFilterArray(o, current->FilterBitValues);
  898. o << '\n';
  899. current = current->Parent;
  900. }
  901. }
  902. // Calculates the island(s) needed to decode the instruction.
  903. // This returns a list of undecoded bits of an instructions, for example,
  904. // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
  905. // decoded bits in order to verify that the instruction matches the Opcode.
  906. unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
  907. std::vector<unsigned> &EndBits,
  908. std::vector<uint64_t> &FieldVals,
  909. const insn_t &Insn) const {
  910. unsigned Num, BitNo;
  911. Num = BitNo = 0;
  912. uint64_t FieldVal = 0;
  913. // 0: Init
  914. // 1: Water (the bit value does not affect decoding)
  915. // 2: Island (well-known bit value needed for decoding)
  916. int State = 0;
  917. for (unsigned i = 0; i < BitWidth; ++i) {
  918. int64_t Val = Value(Insn[i]);
  919. bool Filtered = PositionFiltered(i);
  920. switch (State) {
  921. default: llvm_unreachable("Unreachable code!");
  922. case 0:
  923. case 1:
  924. if (Filtered || Val == -1)
  925. State = 1; // Still in Water
  926. else {
  927. State = 2; // Into the Island
  928. BitNo = 0;
  929. StartBits.push_back(i);
  930. FieldVal = Val;
  931. }
  932. break;
  933. case 2:
  934. if (Filtered || Val == -1) {
  935. State = 1; // Into the Water
  936. EndBits.push_back(i - 1);
  937. FieldVals.push_back(FieldVal);
  938. ++Num;
  939. } else {
  940. State = 2; // Still in Island
  941. ++BitNo;
  942. FieldVal = FieldVal | Val << BitNo;
  943. }
  944. break;
  945. }
  946. }
  947. // If we are still in Island after the loop, do some housekeeping.
  948. if (State == 2) {
  949. EndBits.push_back(BitWidth - 1);
  950. FieldVals.push_back(FieldVal);
  951. ++Num;
  952. }
  953. assert(StartBits.size() == Num && EndBits.size() == Num &&
  954. FieldVals.size() == Num);
  955. return Num;
  956. }
  957. void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
  958. const OperandInfo &OpInfo,
  959. bool &OpHasCompleteDecoder) const {
  960. const std::string &Decoder = OpInfo.Decoder;
  961. if (OpInfo.numFields() != 1 || OpInfo.InitValue != 0) {
  962. o.indent(Indentation) << "tmp = 0x";
  963. o.write_hex(OpInfo.InitValue);
  964. o << ";\n";
  965. }
  966. for (const EncodingField &EF : OpInfo) {
  967. o.indent(Indentation) << "tmp ";
  968. if (OpInfo.numFields() != 1 || OpInfo.InitValue != 0) o << '|';
  969. o << "= fieldFromInstruction"
  970. << "(insn, " << EF.Base << ", " << EF.Width << ')';
  971. if (OpInfo.numFields() != 1 || EF.Offset != 0)
  972. o << " << " << EF.Offset;
  973. o << ";\n";
  974. }
  975. if (Decoder != "") {
  976. OpHasCompleteDecoder = OpInfo.HasCompleteDecoder;
  977. o.indent(Indentation) << Emitter->GuardPrefix << Decoder
  978. << "(MI, tmp, Address, Decoder)"
  979. << Emitter->GuardPostfix
  980. << " { " << (OpHasCompleteDecoder ? "" : "DecodeComplete = false; ")
  981. << "return MCDisassembler::Fail; }\n";
  982. } else {
  983. OpHasCompleteDecoder = true;
  984. o.indent(Indentation) << "MI.addOperand(MCOperand::createImm(tmp));\n";
  985. }
  986. }
  987. void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
  988. unsigned Opc, bool &HasCompleteDecoder) const {
  989. HasCompleteDecoder = true;
  990. for (const auto &Op : Operands.find(Opc)->second) {
  991. // If a custom instruction decoder was specified, use that.
  992. if (Op.numFields() == 0 && !Op.Decoder.empty()) {
  993. HasCompleteDecoder = Op.HasCompleteDecoder;
  994. OS.indent(Indentation) << Emitter->GuardPrefix << Op.Decoder
  995. << "(MI, insn, Address, Decoder)"
  996. << Emitter->GuardPostfix
  997. << " { " << (HasCompleteDecoder ? "" : "DecodeComplete = false; ")
  998. << "return MCDisassembler::Fail; }\n";
  999. break;
  1000. }
  1001. bool OpHasCompleteDecoder;
  1002. emitBinaryParser(OS, Indentation, Op, OpHasCompleteDecoder);
  1003. if (!OpHasCompleteDecoder)
  1004. HasCompleteDecoder = false;
  1005. }
  1006. }
  1007. unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
  1008. unsigned Opc,
  1009. bool &HasCompleteDecoder) const {
  1010. // Build up the predicate string.
  1011. SmallString<256> Decoder;
  1012. // FIXME: emitDecoder() function can take a buffer directly rather than
  1013. // a stream.
  1014. raw_svector_ostream S(Decoder);
  1015. unsigned I = 4;
  1016. emitDecoder(S, I, Opc, HasCompleteDecoder);
  1017. // Using the full decoder string as the key value here is a bit
  1018. // heavyweight, but is effective. If the string comparisons become a
  1019. // performance concern, we can implement a mangling of the predicate
  1020. // data easily enough with a map back to the actual string. That's
  1021. // overkill for now, though.
  1022. // Make sure the predicate is in the table.
  1023. Decoders.insert(CachedHashString(Decoder));
  1024. // Now figure out the index for when we write out the table.
  1025. DecoderSet::const_iterator P = find(Decoders, Decoder.str());
  1026. return (unsigned)(P - Decoders.begin());
  1027. }
  1028. bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
  1029. unsigned Opc) const {
  1030. ListInit *Predicates =
  1031. AllInstructions[Opc].EncodingDef->getValueAsListInit("Predicates");
  1032. bool IsFirstEmission = true;
  1033. for (unsigned i = 0; i < Predicates->size(); ++i) {
  1034. Record *Pred = Predicates->getElementAsRecord(i);
  1035. if (!Pred->getValue("AssemblerMatcherPredicate"))
  1036. continue;
  1037. if (!isa<DagInit>(Pred->getValue("AssemblerCondDag")->getValue()))
  1038. continue;
  1039. const DagInit *D = Pred->getValueAsDag("AssemblerCondDag");
  1040. std::string CombineType = D->getOperator()->getAsString();
  1041. if (CombineType != "any_of" && CombineType != "all_of")
  1042. PrintFatalError(Pred->getLoc(), "Invalid AssemblerCondDag!");
  1043. if (D->getNumArgs() == 0)
  1044. PrintFatalError(Pred->getLoc(), "Invalid AssemblerCondDag!");
  1045. bool IsOr = CombineType == "any_of";
  1046. if (!IsFirstEmission)
  1047. o << " && ";
  1048. if (IsOr)
  1049. o << "(";
  1050. bool First = true;
  1051. for (auto *Arg : D->getArgs()) {
  1052. if (!First) {
  1053. if (IsOr)
  1054. o << " || ";
  1055. else
  1056. o << " && ";
  1057. }
  1058. if (auto *NotArg = dyn_cast<DagInit>(Arg)) {
  1059. if (NotArg->getOperator()->getAsString() != "not" ||
  1060. NotArg->getNumArgs() != 1)
  1061. PrintFatalError(Pred->getLoc(), "Invalid AssemblerCondDag!");
  1062. Arg = NotArg->getArg(0);
  1063. o << "!";
  1064. }
  1065. if (!isa<DefInit>(Arg) ||
  1066. !cast<DefInit>(Arg)->getDef()->isSubClassOf("SubtargetFeature"))
  1067. PrintFatalError(Pred->getLoc(), "Invalid AssemblerCondDag!");
  1068. o << "Bits[" << Emitter->PredicateNamespace << "::" << Arg->getAsString()
  1069. << "]";
  1070. First = false;
  1071. }
  1072. if (IsOr)
  1073. o << ")";
  1074. IsFirstEmission = false;
  1075. }
  1076. return !Predicates->empty();
  1077. }
  1078. bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
  1079. ListInit *Predicates =
  1080. AllInstructions[Opc].EncodingDef->getValueAsListInit("Predicates");
  1081. for (unsigned i = 0; i < Predicates->size(); ++i) {
  1082. Record *Pred = Predicates->getElementAsRecord(i);
  1083. if (!Pred->getValue("AssemblerMatcherPredicate"))
  1084. continue;
  1085. if (dyn_cast<DagInit>(Pred->getValue("AssemblerCondDag")->getValue()))
  1086. return true;
  1087. }
  1088. return false;
  1089. }
  1090. unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
  1091. StringRef Predicate) const {
  1092. // Using the full predicate string as the key value here is a bit
  1093. // heavyweight, but is effective. If the string comparisons become a
  1094. // performance concern, we can implement a mangling of the predicate
  1095. // data easily enough with a map back to the actual string. That's
  1096. // overkill for now, though.
  1097. // Make sure the predicate is in the table.
  1098. TableInfo.Predicates.insert(CachedHashString(Predicate));
  1099. // Now figure out the index for when we write out the table.
  1100. PredicateSet::const_iterator P = find(TableInfo.Predicates, Predicate);
  1101. return (unsigned)(P - TableInfo.Predicates.begin());
  1102. }
  1103. void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
  1104. unsigned Opc) const {
  1105. if (!doesOpcodeNeedPredicate(Opc))
  1106. return;
  1107. // Build up the predicate string.
  1108. SmallString<256> Predicate;
  1109. // FIXME: emitPredicateMatch() functions can take a buffer directly rather
  1110. // than a stream.
  1111. raw_svector_ostream PS(Predicate);
  1112. unsigned I = 0;
  1113. emitPredicateMatch(PS, I, Opc);
  1114. // Figure out the index into the predicate table for the predicate just
  1115. // computed.
  1116. unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
  1117. SmallString<16> PBytes;
  1118. raw_svector_ostream S(PBytes);
  1119. encodeULEB128(PIdx, S);
  1120. TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
  1121. // Predicate index
  1122. for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
  1123. TableInfo.Table.push_back(PBytes[i]);
  1124. // Push location for NumToSkip backpatching.
  1125. TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
  1126. TableInfo.Table.push_back(0);
  1127. TableInfo.Table.push_back(0);
  1128. TableInfo.Table.push_back(0);
  1129. }
  1130. void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
  1131. unsigned Opc) const {
  1132. BitsInit *SFBits =
  1133. AllInstructions[Opc].EncodingDef->getValueAsBitsInit("SoftFail");
  1134. if (!SFBits) return;
  1135. BitsInit *InstBits =
  1136. AllInstructions[Opc].EncodingDef->getValueAsBitsInit("Inst");
  1137. APInt PositiveMask(BitWidth, 0ULL);
  1138. APInt NegativeMask(BitWidth, 0ULL);
  1139. for (unsigned i = 0; i < BitWidth; ++i) {
  1140. bit_value_t B = bitFromBits(*SFBits, i);
  1141. bit_value_t IB = bitFromBits(*InstBits, i);
  1142. if (B != BIT_TRUE) continue;
  1143. switch (IB) {
  1144. case BIT_FALSE:
  1145. // The bit is meant to be false, so emit a check to see if it is true.
  1146. PositiveMask.setBit(i);
  1147. break;
  1148. case BIT_TRUE:
  1149. // The bit is meant to be true, so emit a check to see if it is false.
  1150. NegativeMask.setBit(i);
  1151. break;
  1152. default:
  1153. // The bit is not set; this must be an error!
  1154. errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in "
  1155. << AllInstructions[Opc] << " is set but Inst{" << i
  1156. << "} is unset!\n"
  1157. << " - You can only mark a bit as SoftFail if it is fully defined"
  1158. << " (1/0 - not '?') in Inst\n";
  1159. return;
  1160. }
  1161. }
  1162. bool NeedPositiveMask = PositiveMask.getBoolValue();
  1163. bool NeedNegativeMask = NegativeMask.getBoolValue();
  1164. if (!NeedPositiveMask && !NeedNegativeMask)
  1165. return;
  1166. TableInfo.Table.push_back(MCD::OPC_SoftFail);
  1167. SmallString<16> MaskBytes;
  1168. raw_svector_ostream S(MaskBytes);
  1169. if (NeedPositiveMask) {
  1170. encodeULEB128(PositiveMask.getZExtValue(), S);
  1171. for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
  1172. TableInfo.Table.push_back(MaskBytes[i]);
  1173. } else
  1174. TableInfo.Table.push_back(0);
  1175. if (NeedNegativeMask) {
  1176. MaskBytes.clear();
  1177. encodeULEB128(NegativeMask.getZExtValue(), S);
  1178. for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
  1179. TableInfo.Table.push_back(MaskBytes[i]);
  1180. } else
  1181. TableInfo.Table.push_back(0);
  1182. }
  1183. // Emits table entries to decode the singleton.
  1184. void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
  1185. EncodingIDAndOpcode Opc) const {
  1186. std::vector<unsigned> StartBits;
  1187. std::vector<unsigned> EndBits;
  1188. std::vector<uint64_t> FieldVals;
  1189. insn_t Insn;
  1190. insnWithID(Insn, Opc.EncodingID);
  1191. // Look for islands of undecoded bits of the singleton.
  1192. getIslands(StartBits, EndBits, FieldVals, Insn);
  1193. unsigned Size = StartBits.size();
  1194. // Emit the predicate table entry if one is needed.
  1195. emitPredicateTableEntry(TableInfo, Opc.EncodingID);
  1196. // Check any additional encoding fields needed.
  1197. for (unsigned I = Size; I != 0; --I) {
  1198. unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
  1199. TableInfo.Table.push_back(MCD::OPC_CheckField);
  1200. TableInfo.Table.push_back(StartBits[I-1]);
  1201. TableInfo.Table.push_back(NumBits);
  1202. uint8_t Buffer[16], *p;
  1203. encodeULEB128(FieldVals[I-1], Buffer);
  1204. for (p = Buffer; *p >= 128 ; ++p)
  1205. TableInfo.Table.push_back(*p);
  1206. TableInfo.Table.push_back(*p);
  1207. // Push location for NumToSkip backpatching.
  1208. TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
  1209. // The fixup is always 24-bits, so go ahead and allocate the space
  1210. // in the table so all our relative position calculations work OK even
  1211. // before we fully resolve the real value here.
  1212. TableInfo.Table.push_back(0);
  1213. TableInfo.Table.push_back(0);
  1214. TableInfo.Table.push_back(0);
  1215. }
  1216. // Check for soft failure of the match.
  1217. emitSoftFailTableEntry(TableInfo, Opc.EncodingID);
  1218. bool HasCompleteDecoder;
  1219. unsigned DIdx =
  1220. getDecoderIndex(TableInfo.Decoders, Opc.EncodingID, HasCompleteDecoder);
  1221. // Produce OPC_Decode or OPC_TryDecode opcode based on the information
  1222. // whether the instruction decoder is complete or not. If it is complete
  1223. // then it handles all possible values of remaining variable/unfiltered bits
  1224. // and for any value can determine if the bitpattern is a valid instruction
  1225. // or not. This means OPC_Decode will be the final step in the decoding
  1226. // process. If it is not complete, then the Fail return code from the
  1227. // decoder method indicates that additional processing should be done to see
  1228. // if there is any other instruction that also matches the bitpattern and
  1229. // can decode it.
  1230. TableInfo.Table.push_back(HasCompleteDecoder ? MCD::OPC_Decode :
  1231. MCD::OPC_TryDecode);
  1232. NumEncodingsSupported++;
  1233. uint8_t Buffer[16], *p;
  1234. encodeULEB128(Opc.Opcode, Buffer);
  1235. for (p = Buffer; *p >= 128 ; ++p)
  1236. TableInfo.Table.push_back(*p);
  1237. TableInfo.Table.push_back(*p);
  1238. SmallString<16> Bytes;
  1239. raw_svector_ostream S(Bytes);
  1240. encodeULEB128(DIdx, S);
  1241. // Decoder index
  1242. for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
  1243. TableInfo.Table.push_back(Bytes[i]);
  1244. if (!HasCompleteDecoder) {
  1245. // Push location for NumToSkip backpatching.
  1246. TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
  1247. // Allocate the space for the fixup.
  1248. TableInfo.Table.push_back(0);
  1249. TableInfo.Table.push_back(0);
  1250. TableInfo.Table.push_back(0);
  1251. }
  1252. }
  1253. // Emits table entries to decode the singleton, and then to decode the rest.
  1254. void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
  1255. const Filter &Best) const {
  1256. EncodingIDAndOpcode Opc = Best.getSingletonOpc();
  1257. // complex singletons need predicate checks from the first singleton
  1258. // to refer forward to the variable filterchooser that follows.
  1259. TableInfo.FixupStack.emplace_back();
  1260. emitSingletonTableEntry(TableInfo, Opc);
  1261. resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
  1262. TableInfo.Table.size());
  1263. TableInfo.FixupStack.pop_back();
  1264. Best.getVariableFC().emitTableEntries(TableInfo);
  1265. }
  1266. // Assign a single filter and run with it. Top level API client can initialize
  1267. // with a single filter to start the filtering process.
  1268. void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
  1269. bool mixed) {
  1270. Filters.clear();
  1271. Filters.emplace_back(*this, startBit, numBit, true);
  1272. BestIndex = 0; // Sole Filter instance to choose from.
  1273. bestFilter().recurse();
  1274. }
  1275. // reportRegion is a helper function for filterProcessor to mark a region as
  1276. // eligible for use as a filter region.
  1277. void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
  1278. unsigned BitIndex, bool AllowMixed) {
  1279. if (RA == ATTR_MIXED && AllowMixed)
  1280. Filters.emplace_back(*this, StartBit, BitIndex - StartBit, true);
  1281. else if (RA == ATTR_ALL_SET && !AllowMixed)
  1282. Filters.emplace_back(*this, StartBit, BitIndex - StartBit, false);
  1283. }
  1284. // FilterProcessor scans the well-known encoding bits of the instructions and
  1285. // builds up a list of candidate filters. It chooses the best filter and
  1286. // recursively descends down the decoding tree.
  1287. bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
  1288. Filters.clear();
  1289. BestIndex = -1;
  1290. unsigned numInstructions = Opcodes.size();
  1291. assert(numInstructions && "Filter created with no instructions");
  1292. // No further filtering is necessary.
  1293. if (numInstructions == 1)
  1294. return true;
  1295. // Heuristics. See also doFilter()'s "Heuristics" comment when num of
  1296. // instructions is 3.
  1297. if (AllowMixed && !Greedy) {
  1298. assert(numInstructions == 3);
  1299. for (unsigned i = 0; i < Opcodes.size(); ++i) {
  1300. std::vector<unsigned> StartBits;
  1301. std::vector<unsigned> EndBits;
  1302. std::vector<uint64_t> FieldVals;
  1303. insn_t Insn;
  1304. insnWithID(Insn, Opcodes[i].EncodingID);
  1305. // Look for islands of undecoded bits of any instruction.
  1306. if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
  1307. // Found an instruction with island(s). Now just assign a filter.
  1308. runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
  1309. return true;
  1310. }
  1311. }
  1312. }
  1313. unsigned BitIndex;
  1314. // We maintain BIT_WIDTH copies of the bitAttrs automaton.
  1315. // The automaton consumes the corresponding bit from each
  1316. // instruction.
  1317. //
  1318. // Input symbols: 0, 1, and _ (unset).
  1319. // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
  1320. // Initial state: NONE.
  1321. //
  1322. // (NONE) ------- [01] -> (ALL_SET)
  1323. // (NONE) ------- _ ----> (ALL_UNSET)
  1324. // (ALL_SET) ---- [01] -> (ALL_SET)
  1325. // (ALL_SET) ---- _ ----> (MIXED)
  1326. // (ALL_UNSET) -- [01] -> (MIXED)
  1327. // (ALL_UNSET) -- _ ----> (ALL_UNSET)
  1328. // (MIXED) ------ . ----> (MIXED)
  1329. // (FILTERED)---- . ----> (FILTERED)
  1330. std::vector<bitAttr_t> bitAttrs;
  1331. // FILTERED bit positions provide no entropy and are not worthy of pursuing.
  1332. // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
  1333. for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
  1334. if (FilterBitValues[BitIndex] == BIT_TRUE ||
  1335. FilterBitValues[BitIndex] == BIT_FALSE)
  1336. bitAttrs.push_back(ATTR_FILTERED);
  1337. else
  1338. bitAttrs.push_back(ATTR_NONE);
  1339. for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
  1340. insn_t insn;
  1341. insnWithID(insn, Opcodes[InsnIndex].EncodingID);
  1342. for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
  1343. switch (bitAttrs[BitIndex]) {
  1344. case ATTR_NONE:
  1345. if (insn[BitIndex] == BIT_UNSET)
  1346. bitAttrs[BitIndex] = ATTR_ALL_UNSET;
  1347. else
  1348. bitAttrs[BitIndex] = ATTR_ALL_SET;
  1349. break;
  1350. case ATTR_ALL_SET:
  1351. if (insn[BitIndex] == BIT_UNSET)
  1352. bitAttrs[BitIndex] = ATTR_MIXED;
  1353. break;
  1354. case ATTR_ALL_UNSET:
  1355. if (insn[BitIndex] != BIT_UNSET)
  1356. bitAttrs[BitIndex] = ATTR_MIXED;
  1357. break;
  1358. case ATTR_MIXED:
  1359. case ATTR_FILTERED:
  1360. break;
  1361. }
  1362. }
  1363. }
  1364. // The regionAttr automaton consumes the bitAttrs automatons' state,
  1365. // lowest-to-highest.
  1366. //
  1367. // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
  1368. // States: NONE, ALL_SET, MIXED
  1369. // Initial state: NONE
  1370. //
  1371. // (NONE) ----- F --> (NONE)
  1372. // (NONE) ----- S --> (ALL_SET) ; and set region start
  1373. // (NONE) ----- U --> (NONE)
  1374. // (NONE) ----- M --> (MIXED) ; and set region start
  1375. // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
  1376. // (ALL_SET) -- S --> (ALL_SET)
  1377. // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
  1378. // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
  1379. // (MIXED) ---- F --> (NONE) ; and report a MIXED region
  1380. // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
  1381. // (MIXED) ---- U --> (NONE) ; and report a MIXED region
  1382. // (MIXED) ---- M --> (MIXED)
  1383. bitAttr_t RA = ATTR_NONE;
  1384. unsigned StartBit = 0;
  1385. for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
  1386. bitAttr_t bitAttr = bitAttrs[BitIndex];
  1387. assert(bitAttr != ATTR_NONE && "Bit without attributes");
  1388. switch (RA) {
  1389. case ATTR_NONE:
  1390. switch (bitAttr) {
  1391. case ATTR_FILTERED:
  1392. break;
  1393. case ATTR_ALL_SET:
  1394. StartBit = BitIndex;
  1395. RA = ATTR_ALL_SET;
  1396. break;
  1397. case ATTR_ALL_UNSET:
  1398. break;
  1399. case ATTR_MIXED:
  1400. StartBit = BitIndex;
  1401. RA = ATTR_MIXED;
  1402. break;
  1403. default:
  1404. llvm_unreachable("Unexpected bitAttr!");
  1405. }
  1406. break;
  1407. case ATTR_ALL_SET:
  1408. switch (bitAttr) {
  1409. case ATTR_FILTERED:
  1410. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1411. RA = ATTR_NONE;
  1412. break;
  1413. case ATTR_ALL_SET:
  1414. break;
  1415. case ATTR_ALL_UNSET:
  1416. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1417. RA = ATTR_NONE;
  1418. break;
  1419. case ATTR_MIXED:
  1420. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1421. StartBit = BitIndex;
  1422. RA = ATTR_MIXED;
  1423. break;
  1424. default:
  1425. llvm_unreachable("Unexpected bitAttr!");
  1426. }
  1427. break;
  1428. case ATTR_MIXED:
  1429. switch (bitAttr) {
  1430. case ATTR_FILTERED:
  1431. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1432. StartBit = BitIndex;
  1433. RA = ATTR_NONE;
  1434. break;
  1435. case ATTR_ALL_SET:
  1436. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1437. StartBit = BitIndex;
  1438. RA = ATTR_ALL_SET;
  1439. break;
  1440. case ATTR_ALL_UNSET:
  1441. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1442. RA = ATTR_NONE;
  1443. break;
  1444. case ATTR_MIXED:
  1445. break;
  1446. default:
  1447. llvm_unreachable("Unexpected bitAttr!");
  1448. }
  1449. break;
  1450. case ATTR_ALL_UNSET:
  1451. llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
  1452. case ATTR_FILTERED:
  1453. llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
  1454. }
  1455. }
  1456. // At the end, if we're still in ALL_SET or MIXED states, report a region
  1457. switch (RA) {
  1458. case ATTR_NONE:
  1459. break;
  1460. case ATTR_FILTERED:
  1461. break;
  1462. case ATTR_ALL_SET:
  1463. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1464. break;
  1465. case ATTR_ALL_UNSET:
  1466. break;
  1467. case ATTR_MIXED:
  1468. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1469. break;
  1470. }
  1471. // We have finished with the filter processings. Now it's time to choose
  1472. // the best performing filter.
  1473. BestIndex = 0;
  1474. bool AllUseless = true;
  1475. unsigned BestScore = 0;
  1476. for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
  1477. unsigned Usefulness = Filters[i].usefulness();
  1478. if (Usefulness)
  1479. AllUseless = false;
  1480. if (Usefulness > BestScore) {
  1481. BestIndex = i;
  1482. BestScore = Usefulness;
  1483. }
  1484. }
  1485. if (!AllUseless)
  1486. bestFilter().recurse();
  1487. return !AllUseless;
  1488. } // end of FilterChooser::filterProcessor(bool)
  1489. // Decides on the best configuration of filter(s) to use in order to decode
  1490. // the instructions. A conflict of instructions may occur, in which case we
  1491. // dump the conflict set to the standard error.
  1492. void FilterChooser::doFilter() {
  1493. unsigned Num = Opcodes.size();
  1494. assert(Num && "FilterChooser created with no instructions");
  1495. // Try regions of consecutive known bit values first.
  1496. if (filterProcessor(false))
  1497. return;
  1498. // Then regions of mixed bits (both known and unitialized bit values allowed).
  1499. if (filterProcessor(true))
  1500. return;
  1501. // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
  1502. // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
  1503. // well-known encoding pattern. In such case, we backtrack and scan for the
  1504. // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
  1505. if (Num == 3 && filterProcessor(true, false))
  1506. return;
  1507. // If we come to here, the instruction decoding has failed.
  1508. // Set the BestIndex to -1 to indicate so.
  1509. BestIndex = -1;
  1510. }
  1511. // emitTableEntries - Emit state machine entries to decode our share of
  1512. // instructions.
  1513. void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
  1514. if (Opcodes.size() == 1) {
  1515. // There is only one instruction in the set, which is great!
  1516. // Call emitSingletonDecoder() to see whether there are any remaining
  1517. // encodings bits.
  1518. emitSingletonTableEntry(TableInfo, Opcodes[0]);
  1519. return;
  1520. }
  1521. // Choose the best filter to do the decodings!
  1522. if (BestIndex != -1) {
  1523. const Filter &Best = Filters[BestIndex];
  1524. if (Best.getNumFiltered() == 1)
  1525. emitSingletonTableEntry(TableInfo, Best);
  1526. else
  1527. Best.emitTableEntry(TableInfo);
  1528. return;
  1529. }
  1530. // We don't know how to decode these instructions! Dump the
  1531. // conflict set and bail.
  1532. // Print out useful conflict information for postmortem analysis.
  1533. errs() << "Decoding Conflict:\n";
  1534. dumpStack(errs(), "\t\t");
  1535. for (unsigned i = 0; i < Opcodes.size(); ++i) {
  1536. errs() << '\t';
  1537. emitNameWithID(errs(), Opcodes[i].EncodingID);
  1538. errs() << " ";
  1539. dumpBits(
  1540. errs(),
  1541. getBitsField(*AllInstructions[Opcodes[i].EncodingID].EncodingDef, "Inst"));
  1542. errs() << '\n';
  1543. }
  1544. }
  1545. static std::string findOperandDecoderMethod(TypedInit *TI) {
  1546. std::string Decoder;
  1547. Record *Record = cast<DefInit>(TI)->getDef();
  1548. RecordVal *DecoderString = Record->getValue("DecoderMethod");
  1549. StringInit *String = DecoderString ?
  1550. dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
  1551. if (String) {
  1552. Decoder = std::string(String->getValue());
  1553. if (!Decoder.empty())
  1554. return Decoder;
  1555. }
  1556. if (Record->isSubClassOf("RegisterOperand"))
  1557. Record = Record->getValueAsDef("RegClass");
  1558. if (Record->isSubClassOf("RegisterClass")) {
  1559. Decoder = "Decode" + Record->getName().str() + "RegisterClass";
  1560. } else if (Record->isSubClassOf("PointerLikeRegClass")) {
  1561. Decoder = "DecodePointerLikeRegClass" +
  1562. utostr(Record->getValueAsInt("RegClassKind"));
  1563. }
  1564. return Decoder;
  1565. }
  1566. static bool
  1567. populateInstruction(CodeGenTarget &Target, const Record &EncodingDef,
  1568. const CodeGenInstruction &CGI, unsigned Opc,
  1569. std::map<unsigned, std::vector<OperandInfo>> &Operands) {
  1570. const Record &Def = *CGI.TheDef;
  1571. // If all the bit positions are not specified; do not decode this instruction.
  1572. // We are bound to fail! For proper disassembly, the well-known encoding bits
  1573. // of the instruction must be fully specified.
  1574. BitsInit &Bits = getBitsField(EncodingDef, "Inst");
  1575. if (Bits.allInComplete()) return false;
  1576. std::vector<OperandInfo> InsnOperands;
  1577. // If the instruction has specified a custom decoding hook, use that instead
  1578. // of trying to auto-generate the decoder.
  1579. StringRef InstDecoder = EncodingDef.getValueAsString("DecoderMethod");
  1580. if (InstDecoder != "") {
  1581. bool HasCompleteInstDecoder = EncodingDef.getValueAsBit("hasCompleteDecoder");
  1582. InsnOperands.push_back(
  1583. OperandInfo(std::string(InstDecoder), HasCompleteInstDecoder));
  1584. Operands[Opc] = InsnOperands;
  1585. return true;
  1586. }
  1587. // Generate a description of the operand of the instruction that we know
  1588. // how to decode automatically.
  1589. // FIXME: We'll need to have a way to manually override this as needed.
  1590. // Gather the outputs/inputs of the instruction, so we can find their
  1591. // positions in the encoding. This assumes for now that they appear in the
  1592. // MCInst in the order that they're listed.
  1593. std::vector<std::pair<Init*, StringRef>> InOutOperands;
  1594. DagInit *Out = Def.getValueAsDag("OutOperandList");
  1595. DagInit *In = Def.getValueAsDag("InOperandList");
  1596. for (unsigned i = 0; i < Out->getNumArgs(); ++i)
  1597. InOutOperands.push_back(std::make_pair(Out->getArg(i),
  1598. Out->getArgNameStr(i)));
  1599. for (unsigned i = 0; i < In->getNumArgs(); ++i)
  1600. InOutOperands.push_back(std::make_pair(In->getArg(i),
  1601. In->getArgNameStr(i)));
  1602. // Search for tied operands, so that we can correctly instantiate
  1603. // operands that are not explicitly represented in the encoding.
  1604. std::map<std::string, std::string> TiedNames;
  1605. for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
  1606. int tiedTo = CGI.Operands[i].getTiedRegister();
  1607. if (tiedTo != -1) {
  1608. std::pair<unsigned, unsigned> SO =
  1609. CGI.Operands.getSubOperandNumber(tiedTo);
  1610. TiedNames[std::string(InOutOperands[i].second)] =
  1611. std::string(InOutOperands[SO.first].second);
  1612. TiedNames[std::string(InOutOperands[SO.first].second)] =
  1613. std::string(InOutOperands[i].second);
  1614. }
  1615. }
  1616. std::map<std::string, std::vector<OperandInfo>> NumberedInsnOperands;
  1617. std::set<std::string> NumberedInsnOperandsNoTie;
  1618. if (Target.getInstructionSet()->
  1619. getValueAsBit("decodePositionallyEncodedOperands")) {
  1620. const std::vector<RecordVal> &Vals = Def.getValues();
  1621. unsigned NumberedOp = 0;
  1622. std::set<unsigned> NamedOpIndices;
  1623. if (Target.getInstructionSet()->
  1624. getValueAsBit("noNamedPositionallyEncodedOperands"))
  1625. // Collect the set of operand indices that might correspond to named
  1626. // operand, and skip these when assigning operands based on position.
  1627. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  1628. unsigned OpIdx;
  1629. if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
  1630. continue;
  1631. NamedOpIndices.insert(OpIdx);
  1632. }
  1633. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  1634. // Ignore fixed fields in the record, we're looking for values like:
  1635. // bits<5> RST = { ?, ?, ?, ?, ? };
  1636. if (Vals[i].isNonconcreteOK() || Vals[i].getValue()->isComplete())
  1637. continue;
  1638. // Determine if Vals[i] actually contributes to the Inst encoding.
  1639. unsigned bi = 0;
  1640. for (; bi < Bits.getNumBits(); ++bi) {
  1641. VarInit *Var = nullptr;
  1642. VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
  1643. if (BI)
  1644. Var = dyn_cast<VarInit>(BI->getBitVar());
  1645. else
  1646. Var = dyn_cast<VarInit>(Bits.getBit(bi));
  1647. if (Var && Var->getName() == Vals[i].getName())
  1648. break;
  1649. }
  1650. if (bi == Bits.getNumBits())
  1651. continue;
  1652. // Skip variables that correspond to explicitly-named operands.
  1653. unsigned OpIdx;
  1654. if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
  1655. continue;
  1656. // Get the bit range for this operand:
  1657. unsigned bitStart = bi++, bitWidth = 1;
  1658. for (; bi < Bits.getNumBits(); ++bi) {
  1659. VarInit *Var = nullptr;
  1660. VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
  1661. if (BI)
  1662. Var = dyn_cast<VarInit>(BI->getBitVar());
  1663. else
  1664. Var = dyn_cast<VarInit>(Bits.getBit(bi));
  1665. if (!Var)
  1666. break;
  1667. if (Var->getName() != Vals[i].getName())
  1668. break;
  1669. ++bitWidth;
  1670. }
  1671. unsigned NumberOps = CGI.Operands.size();
  1672. while (NumberedOp < NumberOps &&
  1673. (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
  1674. (!NamedOpIndices.empty() && NamedOpIndices.count(
  1675. CGI.Operands.getSubOperandNumber(NumberedOp).first))))
  1676. ++NumberedOp;
  1677. OpIdx = NumberedOp++;
  1678. // OpIdx now holds the ordered operand number of Vals[i].
  1679. std::pair<unsigned, unsigned> SO =
  1680. CGI.Operands.getSubOperandNumber(OpIdx);
  1681. const std::string &Name = CGI.Operands[SO.first].Name;
  1682. LLVM_DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName()
  1683. << ": " << Name << "(" << SO.first << ", " << SO.second
  1684. << ") => " << Vals[i].getName() << "\n");
  1685. std::string Decoder;
  1686. Record *TypeRecord = CGI.Operands[SO.first].Rec;
  1687. RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
  1688. StringInit *String = DecoderString ?
  1689. dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
  1690. if (String && String->getValue() != "")
  1691. Decoder = std::string(String->getValue());
  1692. if (Decoder == "" &&
  1693. CGI.Operands[SO.first].MIOperandInfo &&
  1694. CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
  1695. Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
  1696. getArg(SO.second);
  1697. if (DefInit *DI = cast<DefInit>(Arg))
  1698. TypeRecord = DI->getDef();
  1699. }
  1700. bool isReg = false;
  1701. if (TypeRecord->isSubClassOf("RegisterOperand"))
  1702. TypeRecord = TypeRecord->getValueAsDef("RegClass");
  1703. if (TypeRecord->isSubClassOf("RegisterClass")) {
  1704. Decoder = "Decode" + TypeRecord->getName().str() + "RegisterClass";
  1705. isReg = true;
  1706. } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
  1707. Decoder = "DecodePointerLikeRegClass" +
  1708. utostr(TypeRecord->getValueAsInt("RegClassKind"));
  1709. isReg = true;
  1710. }
  1711. DecoderString = TypeRecord->getValue("DecoderMethod");
  1712. String = DecoderString ?
  1713. dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
  1714. if (!isReg && String && String->getValue() != "")
  1715. Decoder = std::string(String->getValue());
  1716. RecordVal *HasCompleteDecoderVal =
  1717. TypeRecord->getValue("hasCompleteDecoder");
  1718. BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
  1719. dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
  1720. bool HasCompleteDecoder = HasCompleteDecoderBit ?
  1721. HasCompleteDecoderBit->getValue() : true;
  1722. OperandInfo OpInfo(Decoder, HasCompleteDecoder);
  1723. OpInfo.addField(bitStart, bitWidth, 0);
  1724. NumberedInsnOperands[Name].push_back(OpInfo);
  1725. // FIXME: For complex operands with custom decoders we can't handle tied
  1726. // sub-operands automatically. Skip those here and assume that this is
  1727. // fixed up elsewhere.
  1728. if (CGI.Operands[SO.first].MIOperandInfo &&
  1729. CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
  1730. String && String->getValue() != "")
  1731. NumberedInsnOperandsNoTie.insert(Name);
  1732. }
  1733. }
  1734. // For each operand, see if we can figure out where it is encoded.
  1735. for (const auto &Op : InOutOperands) {
  1736. if (!NumberedInsnOperands[std::string(Op.second)].empty()) {
  1737. llvm::append_range(InsnOperands,
  1738. NumberedInsnOperands[std::string(Op.second)]);
  1739. continue;
  1740. }
  1741. if (!NumberedInsnOperands[TiedNames[std::string(Op.second)]].empty()) {
  1742. if (!NumberedInsnOperandsNoTie.count(TiedNames[std::string(Op.second)])) {
  1743. // Figure out to which (sub)operand we're tied.
  1744. unsigned i =
  1745. CGI.Operands.getOperandNamed(TiedNames[std::string(Op.second)]);
  1746. int tiedTo = CGI.Operands[i].getTiedRegister();
  1747. if (tiedTo == -1) {
  1748. i = CGI.Operands.getOperandNamed(Op.second);
  1749. tiedTo = CGI.Operands[i].getTiedRegister();
  1750. }
  1751. if (tiedTo != -1) {
  1752. std::pair<unsigned, unsigned> SO =
  1753. CGI.Operands.getSubOperandNumber(tiedTo);
  1754. InsnOperands.push_back(
  1755. NumberedInsnOperands[TiedNames[std::string(Op.second)]]
  1756. [SO.second]);
  1757. }
  1758. }
  1759. continue;
  1760. }
  1761. TypedInit *TI = cast<TypedInit>(Op.first);
  1762. // At this point, we can locate the decoder field, but we need to know how
  1763. // to interpret it. As a first step, require the target to provide
  1764. // callbacks for decoding register classes.
  1765. std::string Decoder = findOperandDecoderMethod(TI);
  1766. Record *TypeRecord = cast<DefInit>(TI)->getDef();
  1767. RecordVal *HasCompleteDecoderVal =
  1768. TypeRecord->getValue("hasCompleteDecoder");
  1769. BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
  1770. dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
  1771. bool HasCompleteDecoder = HasCompleteDecoderBit ?
  1772. HasCompleteDecoderBit->getValue() : true;
  1773. OperandInfo OpInfo(Decoder, HasCompleteDecoder);
  1774. // Some bits of the operand may be required to be 1 depending on the
  1775. // instruction's encoding. Collect those bits.
  1776. if (const RecordVal *EncodedValue = EncodingDef.getValue(Op.second))
  1777. if (const BitsInit *OpBits = dyn_cast<BitsInit>(EncodedValue->getValue()))
  1778. for (unsigned I = 0; I < OpBits->getNumBits(); ++I)
  1779. if (const BitInit *OpBit = dyn_cast<BitInit>(OpBits->getBit(I)))
  1780. if (OpBit->getValue())
  1781. OpInfo.InitValue |= 1ULL << I;
  1782. unsigned Base = ~0U;
  1783. unsigned Width = 0;
  1784. unsigned Offset = 0;
  1785. for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
  1786. VarInit *Var = nullptr;
  1787. VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
  1788. if (BI)
  1789. Var = dyn_cast<VarInit>(BI->getBitVar());
  1790. else
  1791. Var = dyn_cast<VarInit>(Bits.getBit(bi));
  1792. if (!Var) {
  1793. if (Base != ~0U) {
  1794. OpInfo.addField(Base, Width, Offset);
  1795. Base = ~0U;
  1796. Width = 0;
  1797. Offset = 0;
  1798. }
  1799. continue;
  1800. }
  1801. if (Var->getName() != Op.second &&
  1802. Var->getName() != TiedNames[std::string(Op.second)]) {
  1803. if (Base != ~0U) {
  1804. OpInfo.addField(Base, Width, Offset);
  1805. Base = ~0U;
  1806. Width = 0;
  1807. Offset = 0;
  1808. }
  1809. continue;
  1810. }
  1811. if (Base == ~0U) {
  1812. Base = bi;
  1813. Width = 1;
  1814. Offset = BI ? BI->getBitNum() : 0;
  1815. } else if (BI && BI->getBitNum() != Offset + Width) {
  1816. OpInfo.addField(Base, Width, Offset);
  1817. Base = bi;
  1818. Width = 1;
  1819. Offset = BI->getBitNum();
  1820. } else {
  1821. ++Width;
  1822. }
  1823. }
  1824. if (Base != ~0U)
  1825. OpInfo.addField(Base, Width, Offset);
  1826. if (OpInfo.numFields() > 0)
  1827. InsnOperands.push_back(OpInfo);
  1828. }
  1829. Operands[Opc] = InsnOperands;
  1830. #if 0
  1831. LLVM_DEBUG({
  1832. // Dumps the instruction encoding bits.
  1833. dumpBits(errs(), Bits);
  1834. errs() << '\n';
  1835. // Dumps the list of operand info.
  1836. for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
  1837. const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
  1838. const std::string &OperandName = Info.Name;
  1839. const Record &OperandDef = *Info.Rec;
  1840. errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
  1841. }
  1842. });
  1843. #endif
  1844. return true;
  1845. }
  1846. // emitFieldFromInstruction - Emit the templated helper function
  1847. // fieldFromInstruction().
  1848. // On Windows we make sure that this function is not inlined when
  1849. // using the VS compiler. It has a bug which causes the function
  1850. // to be optimized out in some circustances. See llvm.org/pr38292
  1851. static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
  1852. OS << "// Helper functions for extracting fields from encoded instructions.\n"
  1853. << "// InsnType must either be integral or an APInt-like object that "
  1854. "must:\n"
  1855. << "// * Have a static const max_size_in_bits equal to the number of bits "
  1856. "in the\n"
  1857. << "// encoding.\n"
  1858. << "// * be default-constructible and copy-constructible\n"
  1859. << "// * be constructible from a uint64_t\n"
  1860. << "// * be constructible from an APInt (this can be private)\n"
  1861. << "// * Support getBitsSet(loBit, hiBit)\n"
  1862. << "// * be convertible to uint64_t\n"
  1863. << "// * Support the ~, &, ==, !=, and |= operators with other objects of "
  1864. "the same type\n"
  1865. << "// * Support shift (<<, >>) with signed and unsigned integers on the "
  1866. "RHS\n"
  1867. << "// * Support put (<<) to raw_ostream&\n"
  1868. << "template <typename InsnType>\n"
  1869. << "#if defined(_MSC_VER) && !defined(__clang__)\n"
  1870. << "__declspec(noinline)\n"
  1871. << "#endif\n"
  1872. << "static InsnType fieldFromInstruction(InsnType insn, unsigned "
  1873. "startBit,\n"
  1874. << " unsigned numBits, "
  1875. "std::true_type) {\n"
  1876. << " assert(startBit + numBits <= 64 && \"Cannot support >64-bit "
  1877. "extractions!\");\n"
  1878. << " assert(startBit + numBits <= (sizeof(InsnType) * 8) &&\n"
  1879. << " \"Instruction field out of bounds!\");\n"
  1880. << " InsnType fieldMask;\n"
  1881. << " if (numBits == sizeof(InsnType) * 8)\n"
  1882. << " fieldMask = (InsnType)(-1LL);\n"
  1883. << " else\n"
  1884. << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
  1885. << " return (insn & fieldMask) >> startBit;\n"
  1886. << "}\n"
  1887. << "\n"
  1888. << "template <typename InsnType>\n"
  1889. << "static InsnType fieldFromInstruction(InsnType insn, unsigned "
  1890. "startBit,\n"
  1891. << " unsigned numBits, "
  1892. "std::false_type) {\n"
  1893. << " assert(startBit + numBits <= InsnType::max_size_in_bits && "
  1894. "\"Instruction field out of bounds!\");\n"
  1895. << " InsnType fieldMask = InsnType::getBitsSet(0, numBits);\n"
  1896. << " return (insn >> startBit) & fieldMask;\n"
  1897. << "}\n"
  1898. << "\n"
  1899. << "template <typename InsnType>\n"
  1900. << "static InsnType fieldFromInstruction(InsnType insn, unsigned "
  1901. "startBit,\n"
  1902. << " unsigned numBits) {\n"
  1903. << " return fieldFromInstruction(insn, startBit, numBits, "
  1904. "std::is_integral<InsnType>());\n"
  1905. << "}\n\n";
  1906. }
  1907. // emitDecodeInstruction - Emit the templated helper function
  1908. // decodeInstruction().
  1909. static void emitDecodeInstruction(formatted_raw_ostream &OS) {
  1910. OS << "template <typename InsnType>\n"
  1911. << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], "
  1912. "MCInst &MI,\n"
  1913. << " InsnType insn, uint64_t "
  1914. "Address,\n"
  1915. << " const void *DisAsm,\n"
  1916. << " const MCSubtargetInfo &STI) {\n"
  1917. << " const FeatureBitset &Bits = STI.getFeatureBits();\n"
  1918. << "\n"
  1919. << " const uint8_t *Ptr = DecodeTable;\n"
  1920. << " InsnType CurFieldValue = 0;\n"
  1921. << " DecodeStatus S = MCDisassembler::Success;\n"
  1922. << " while (true) {\n"
  1923. << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
  1924. << " switch (*Ptr) {\n"
  1925. << " default:\n"
  1926. << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
  1927. << " return MCDisassembler::Fail;\n"
  1928. << " case MCD::OPC_ExtractField: {\n"
  1929. << " unsigned Start = *++Ptr;\n"
  1930. << " unsigned Len = *++Ptr;\n"
  1931. << " ++Ptr;\n"
  1932. << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
  1933. << " LLVM_DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << "
  1934. "\", \"\n"
  1935. << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
  1936. << " break;\n"
  1937. << " }\n"
  1938. << " case MCD::OPC_FilterValue: {\n"
  1939. << " // Decode the field value.\n"
  1940. << " unsigned Len;\n"
  1941. << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
  1942. << " Ptr += Len;\n"
  1943. << " // NumToSkip is a plain 24-bit integer.\n"
  1944. << " unsigned NumToSkip = *Ptr++;\n"
  1945. << " NumToSkip |= (*Ptr++) << 8;\n"
  1946. << " NumToSkip |= (*Ptr++) << 16;\n"
  1947. << "\n"
  1948. << " // Perform the filter operation.\n"
  1949. << " if (Val != CurFieldValue)\n"
  1950. << " Ptr += NumToSkip;\n"
  1951. << " LLVM_DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << "
  1952. "\", \" << NumToSkip\n"
  1953. << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" "
  1954. ": \"PASS:\")\n"
  1955. << " << \" continuing at \" << (Ptr - DecodeTable) << "
  1956. "\"\\n\");\n"
  1957. << "\n"
  1958. << " break;\n"
  1959. << " }\n"
  1960. << " case MCD::OPC_CheckField: {\n"
  1961. << " unsigned Start = *++Ptr;\n"
  1962. << " unsigned Len = *++Ptr;\n"
  1963. << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
  1964. << " // Decode the field value.\n"
  1965. << " InsnType ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
  1966. << " Ptr += Len;\n"
  1967. << " // NumToSkip is a plain 24-bit integer.\n"
  1968. << " unsigned NumToSkip = *Ptr++;\n"
  1969. << " NumToSkip |= (*Ptr++) << 8;\n"
  1970. << " NumToSkip |= (*Ptr++) << 16;\n"
  1971. << "\n"
  1972. << " // If the actual and expected values don't match, skip.\n"
  1973. << " if (ExpectedValue != FieldValue)\n"
  1974. << " Ptr += NumToSkip;\n"
  1975. << " LLVM_DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << "
  1976. "\", \"\n"
  1977. << " << Len << \", \" << ExpectedValue << \", \" << "
  1978. "NumToSkip\n"
  1979. << " << \"): FieldValue = \" << FieldValue << \", "
  1980. "ExpectedValue = \"\n"
  1981. << " << ExpectedValue << \": \"\n"
  1982. << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : "
  1983. "\"FAIL\\n\"));\n"
  1984. << " break;\n"
  1985. << " }\n"
  1986. << " case MCD::OPC_CheckPredicate: {\n"
  1987. << " unsigned Len;\n"
  1988. << " // Decode the Predicate Index value.\n"
  1989. << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
  1990. << " Ptr += Len;\n"
  1991. << " // NumToSkip is a plain 24-bit integer.\n"
  1992. << " unsigned NumToSkip = *Ptr++;\n"
  1993. << " NumToSkip |= (*Ptr++) << 8;\n"
  1994. << " NumToSkip |= (*Ptr++) << 16;\n"
  1995. << " // Check the predicate.\n"
  1996. << " bool Pred;\n"
  1997. << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
  1998. << " Ptr += NumToSkip;\n"
  1999. << " (void)Pred;\n"
  2000. << " LLVM_DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx "
  2001. "<< \"): \"\n"
  2002. << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
  2003. << "\n"
  2004. << " break;\n"
  2005. << " }\n"
  2006. << " case MCD::OPC_Decode: {\n"
  2007. << " unsigned Len;\n"
  2008. << " // Decode the Opcode value.\n"
  2009. << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
  2010. << " Ptr += Len;\n"
  2011. << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
  2012. << " Ptr += Len;\n"
  2013. << "\n"
  2014. << " MI.clear();\n"
  2015. << " MI.setOpcode(Opc);\n"
  2016. << " bool DecodeComplete;\n"
  2017. << " S = decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm, "
  2018. "DecodeComplete);\n"
  2019. << " assert(DecodeComplete);\n"
  2020. << "\n"
  2021. << " LLVM_DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
  2022. << " << \", using decoder \" << DecodeIdx << \": \"\n"
  2023. << " << (S != MCDisassembler::Fail ? \"PASS\" : "
  2024. "\"FAIL\") << \"\\n\");\n"
  2025. << " return S;\n"
  2026. << " }\n"
  2027. << " case MCD::OPC_TryDecode: {\n"
  2028. << " unsigned Len;\n"
  2029. << " // Decode the Opcode value.\n"
  2030. << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
  2031. << " Ptr += Len;\n"
  2032. << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
  2033. << " Ptr += Len;\n"
  2034. << " // NumToSkip is a plain 24-bit integer.\n"
  2035. << " unsigned NumToSkip = *Ptr++;\n"
  2036. << " NumToSkip |= (*Ptr++) << 8;\n"
  2037. << " NumToSkip |= (*Ptr++) << 16;\n"
  2038. << "\n"
  2039. << " // Perform the decode operation.\n"
  2040. << " MCInst TmpMI;\n"
  2041. << " TmpMI.setOpcode(Opc);\n"
  2042. << " bool DecodeComplete;\n"
  2043. << " S = decodeToMCInst(S, DecodeIdx, insn, TmpMI, Address, DisAsm, "
  2044. "DecodeComplete);\n"
  2045. << " LLVM_DEBUG(dbgs() << Loc << \": OPC_TryDecode: opcode \" << "
  2046. "Opc\n"
  2047. << " << \", using decoder \" << DecodeIdx << \": \");\n"
  2048. << "\n"
  2049. << " if (DecodeComplete) {\n"
  2050. << " // Decoding complete.\n"
  2051. << " LLVM_DEBUG(dbgs() << (S != MCDisassembler::Fail ? \"PASS\" : "
  2052. "\"FAIL\") << \"\\n\");\n"
  2053. << " MI = TmpMI;\n"
  2054. << " return S;\n"
  2055. << " } else {\n"
  2056. << " assert(S == MCDisassembler::Fail);\n"
  2057. << " // If the decoding was incomplete, skip.\n"
  2058. << " Ptr += NumToSkip;\n"
  2059. << " LLVM_DEBUG(dbgs() << \"FAIL: continuing at \" << (Ptr - "
  2060. "DecodeTable) << \"\\n\");\n"
  2061. << " // Reset decode status. This also drops a SoftFail status "
  2062. "that could be\n"
  2063. << " // set before the decode attempt.\n"
  2064. << " S = MCDisassembler::Success;\n"
  2065. << " }\n"
  2066. << " break;\n"
  2067. << " }\n"
  2068. << " case MCD::OPC_SoftFail: {\n"
  2069. << " // Decode the mask values.\n"
  2070. << " unsigned Len;\n"
  2071. << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
  2072. << " Ptr += Len;\n"
  2073. << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
  2074. << " Ptr += Len;\n"
  2075. << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
  2076. << " if (Fail)\n"
  2077. << " S = MCDisassembler::SoftFail;\n"
  2078. << " LLVM_DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? "
  2079. "\"FAIL\\n\" : \"PASS\\n\"));\n"
  2080. << " break;\n"
  2081. << " }\n"
  2082. << " case MCD::OPC_Fail: {\n"
  2083. << " LLVM_DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
  2084. << " return MCDisassembler::Fail;\n"
  2085. << " }\n"
  2086. << " }\n"
  2087. << " }\n"
  2088. << " llvm_unreachable(\"bogosity detected in disassembler state "
  2089. "machine!\");\n"
  2090. << "}\n\n";
  2091. }
  2092. // Emits disassembler code for instruction decoding.
  2093. void FixedLenDecoderEmitter::run(raw_ostream &o) {
  2094. formatted_raw_ostream OS(o);
  2095. OS << "#include \"llvm/MC/MCInst.h\"\n";
  2096. OS << "#include \"llvm/Support/DataTypes.h\"\n";
  2097. OS << "#include \"llvm/Support/Debug.h\"\n";
  2098. OS << "#include \"llvm/Support/LEB128.h\"\n";
  2099. OS << "#include \"llvm/Support/raw_ostream.h\"\n";
  2100. OS << "#include <assert.h>\n";
  2101. OS << '\n';
  2102. OS << "namespace llvm {\n\n";
  2103. emitFieldFromInstruction(OS);
  2104. Target.reverseBitsForLittleEndianEncoding();
  2105. // Parameterize the decoders based on namespace and instruction width.
  2106. std::set<StringRef> HwModeNames;
  2107. const auto &NumberedInstructions = Target.getInstructionsByEnumValue();
  2108. NumberedEncodings.reserve(NumberedInstructions.size());
  2109. DenseMap<Record *, unsigned> IndexOfInstruction;
  2110. // First, collect all HwModes referenced by the target.
  2111. for (const auto &NumberedInstruction : NumberedInstructions) {
  2112. IndexOfInstruction[NumberedInstruction->TheDef] = NumberedEncodings.size();
  2113. if (const RecordVal *RV =
  2114. NumberedInstruction->TheDef->getValue("EncodingInfos")) {
  2115. if (auto *DI = dyn_cast_or_null<DefInit>(RV->getValue())) {
  2116. const CodeGenHwModes &HWM = Target.getHwModes();
  2117. EncodingInfoByHwMode EBM(DI->getDef(), HWM);
  2118. for (auto &KV : EBM.Map)
  2119. HwModeNames.insert(HWM.getMode(KV.first).Name);
  2120. }
  2121. }
  2122. }
  2123. // If HwModeNames is empty, add the empty string so we always have one HwMode.
  2124. if (HwModeNames.empty())
  2125. HwModeNames.insert("");
  2126. for (const auto &NumberedInstruction : NumberedInstructions) {
  2127. IndexOfInstruction[NumberedInstruction->TheDef] = NumberedEncodings.size();
  2128. if (const RecordVal *RV =
  2129. NumberedInstruction->TheDef->getValue("EncodingInfos")) {
  2130. if (DefInit *DI = dyn_cast_or_null<DefInit>(RV->getValue())) {
  2131. const CodeGenHwModes &HWM = Target.getHwModes();
  2132. EncodingInfoByHwMode EBM(DI->getDef(), HWM);
  2133. for (auto &KV : EBM.Map) {
  2134. NumberedEncodings.emplace_back(KV.second, NumberedInstruction,
  2135. HWM.getMode(KV.first).Name);
  2136. HwModeNames.insert(HWM.getMode(KV.first).Name);
  2137. }
  2138. continue;
  2139. }
  2140. }
  2141. // This instruction is encoded the same on all HwModes. Emit it for all
  2142. // HwModes.
  2143. for (StringRef HwModeName : HwModeNames)
  2144. NumberedEncodings.emplace_back(NumberedInstruction->TheDef,
  2145. NumberedInstruction, HwModeName);
  2146. }
  2147. for (const auto &NumberedAlias : RK.getAllDerivedDefinitions("AdditionalEncoding"))
  2148. NumberedEncodings.emplace_back(
  2149. NumberedAlias,
  2150. &Target.getInstruction(NumberedAlias->getValueAsDef("AliasOf")));
  2151. std::map<std::pair<std::string, unsigned>, std::vector<EncodingIDAndOpcode>>
  2152. OpcMap;
  2153. std::map<unsigned, std::vector<OperandInfo>> Operands;
  2154. for (unsigned i = 0; i < NumberedEncodings.size(); ++i) {
  2155. const Record *EncodingDef = NumberedEncodings[i].EncodingDef;
  2156. const CodeGenInstruction *Inst = NumberedEncodings[i].Inst;
  2157. const Record *Def = Inst->TheDef;
  2158. unsigned Size = EncodingDef->getValueAsInt("Size");
  2159. if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
  2160. Def->getValueAsBit("isPseudo") ||
  2161. Def->getValueAsBit("isAsmParserOnly") ||
  2162. Def->getValueAsBit("isCodeGenOnly")) {
  2163. NumEncodingsLackingDisasm++;
  2164. continue;
  2165. }
  2166. if (i < NumberedInstructions.size())
  2167. NumInstructions++;
  2168. NumEncodings++;
  2169. if (!Size)
  2170. continue;
  2171. if (populateInstruction(Target, *EncodingDef, *Inst, i, Operands)) {
  2172. std::string DecoderNamespace =
  2173. std::string(EncodingDef->getValueAsString("DecoderNamespace"));
  2174. if (!NumberedEncodings[i].HwModeName.empty())
  2175. DecoderNamespace +=
  2176. std::string("_") + NumberedEncodings[i].HwModeName.str();
  2177. OpcMap[std::make_pair(DecoderNamespace, Size)].emplace_back(
  2178. i, IndexOfInstruction.find(Def)->second);
  2179. } else {
  2180. NumEncodingsOmitted++;
  2181. }
  2182. }
  2183. DecoderTableInfo TableInfo;
  2184. for (const auto &Opc : OpcMap) {
  2185. // Emit the decoder for this namespace+width combination.
  2186. ArrayRef<EncodingAndInst> NumberedEncodingsRef(
  2187. NumberedEncodings.data(), NumberedEncodings.size());
  2188. FilterChooser FC(NumberedEncodingsRef, Opc.second, Operands,
  2189. 8 * Opc.first.second, this);
  2190. // The decode table is cleared for each top level decoder function. The
  2191. // predicates and decoders themselves, however, are shared across all
  2192. // decoders to give more opportunities for uniqueing.
  2193. TableInfo.Table.clear();
  2194. TableInfo.FixupStack.clear();
  2195. TableInfo.Table.reserve(16384);
  2196. TableInfo.FixupStack.emplace_back();
  2197. FC.emitTableEntries(TableInfo);
  2198. // Any NumToSkip fixups in the top level scope can resolve to the
  2199. // OPC_Fail at the end of the table.
  2200. assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
  2201. // Resolve any NumToSkip fixups in the current scope.
  2202. resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
  2203. TableInfo.Table.size());
  2204. TableInfo.FixupStack.clear();
  2205. TableInfo.Table.push_back(MCD::OPC_Fail);
  2206. // Print the table to the output stream.
  2207. emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first);
  2208. OS.flush();
  2209. }
  2210. // Emit the predicate function.
  2211. emitPredicateFunction(OS, TableInfo.Predicates, 0);
  2212. // Emit the decoder function.
  2213. emitDecoderFunction(OS, TableInfo.Decoders, 0);
  2214. // Emit the main entry point for the decoder, decodeInstruction().
  2215. emitDecodeInstruction(OS);
  2216. OS << "\n} // end namespace llvm\n";
  2217. }
  2218. namespace llvm {
  2219. void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
  2220. const std::string &PredicateNamespace,
  2221. const std::string &GPrefix,
  2222. const std::string &GPostfix, const std::string &ROK,
  2223. const std::string &RFail, const std::string &L) {
  2224. FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
  2225. ROK, RFail, L).run(OS);
  2226. }
  2227. } // end namespace llvm