AsmMatcherEmitter.cpp 153 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009
  1. //===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This tablegen backend emits a target specifier matcher for converting parsed
  10. // assembly operands in the MCInst structures. It also emits a matcher for
  11. // custom operand parsing.
  12. //
  13. // Converting assembly operands into MCInst structures
  14. // ---------------------------------------------------
  15. //
  16. // The input to the target specific matcher is a list of literal tokens and
  17. // operands. The target specific parser should generally eliminate any syntax
  18. // which is not relevant for matching; for example, comma tokens should have
  19. // already been consumed and eliminated by the parser. Most instructions will
  20. // end up with a single literal token (the instruction name) and some number of
  21. // operands.
  22. //
  23. // Some example inputs, for X86:
  24. // 'addl' (immediate ...) (register ...)
  25. // 'add' (immediate ...) (memory ...)
  26. // 'call' '*' %epc
  27. //
  28. // The assembly matcher is responsible for converting this input into a precise
  29. // machine instruction (i.e., an instruction with a well defined encoding). This
  30. // mapping has several properties which complicate matching:
  31. //
  32. // - It may be ambiguous; many architectures can legally encode particular
  33. // variants of an instruction in different ways (for example, using a smaller
  34. // encoding for small immediates). Such ambiguities should never be
  35. // arbitrarily resolved by the assembler, the assembler is always responsible
  36. // for choosing the "best" available instruction.
  37. //
  38. // - It may depend on the subtarget or the assembler context. Instructions
  39. // which are invalid for the current mode, but otherwise unambiguous (e.g.,
  40. // an SSE instruction in a file being assembled for i486) should be accepted
  41. // and rejected by the assembler front end. However, if the proper encoding
  42. // for an instruction is dependent on the assembler context then the matcher
  43. // is responsible for selecting the correct machine instruction for the
  44. // current mode.
  45. //
  46. // The core matching algorithm attempts to exploit the regularity in most
  47. // instruction sets to quickly determine the set of possibly matching
  48. // instructions, and the simplify the generated code. Additionally, this helps
  49. // to ensure that the ambiguities are intentionally resolved by the user.
  50. //
  51. // The matching is divided into two distinct phases:
  52. //
  53. // 1. Classification: Each operand is mapped to the unique set which (a)
  54. // contains it, and (b) is the largest such subset for which a single
  55. // instruction could match all members.
  56. //
  57. // For register classes, we can generate these subgroups automatically. For
  58. // arbitrary operands, we expect the user to define the classes and their
  59. // relations to one another (for example, 8-bit signed immediates as a
  60. // subset of 32-bit immediates).
  61. //
  62. // By partitioning the operands in this way, we guarantee that for any
  63. // tuple of classes, any single instruction must match either all or none
  64. // of the sets of operands which could classify to that tuple.
  65. //
  66. // In addition, the subset relation amongst classes induces a partial order
  67. // on such tuples, which we use to resolve ambiguities.
  68. //
  69. // 2. The input can now be treated as a tuple of classes (static tokens are
  70. // simple singleton sets). Each such tuple should generally map to a single
  71. // instruction (we currently ignore cases where this isn't true, whee!!!),
  72. // which we can emit a simple matcher for.
  73. //
  74. // Custom Operand Parsing
  75. // ----------------------
  76. //
  77. // Some targets need a custom way to parse operands, some specific instructions
  78. // can contain arguments that can represent processor flags and other kinds of
  79. // identifiers that need to be mapped to specific values in the final encoded
  80. // instructions. The target specific custom operand parsing works in the
  81. // following way:
  82. //
  83. // 1. A operand match table is built, each entry contains a mnemonic, an
  84. // operand class, a mask for all operand positions for that same
  85. // class/mnemonic and target features to be checked while trying to match.
  86. //
  87. // 2. The operand matcher will try every possible entry with the same
  88. // mnemonic and will check if the target feature for this mnemonic also
  89. // matches. After that, if the operand to be matched has its index
  90. // present in the mask, a successful match occurs. Otherwise, fallback
  91. // to the regular operand parsing.
  92. //
  93. // 3. For a match success, each operand class that has a 'ParserMethod'
  94. // becomes part of a switch from where the custom method is called.
  95. //
  96. //===----------------------------------------------------------------------===//
  97. #include "CodeGenInstruction.h"
  98. #include "CodeGenTarget.h"
  99. #include "SubtargetFeatureInfo.h"
  100. #include "Types.h"
  101. #include "llvm/ADT/CachedHashString.h"
  102. #include "llvm/ADT/PointerUnion.h"
  103. #include "llvm/ADT/STLExtras.h"
  104. #include "llvm/ADT/SmallPtrSet.h"
  105. #include "llvm/ADT/SmallVector.h"
  106. #include "llvm/ADT/StringExtras.h"
  107. #include "llvm/Config/llvm-config.h"
  108. #include "llvm/Support/CommandLine.h"
  109. #include "llvm/Support/Debug.h"
  110. #include "llvm/Support/ErrorHandling.h"
  111. #include "llvm/TableGen/Error.h"
  112. #include "llvm/TableGen/Record.h"
  113. #include "llvm/TableGen/StringMatcher.h"
  114. #include "llvm/TableGen/StringToOffsetTable.h"
  115. #include "llvm/TableGen/TableGenBackend.h"
  116. #include <cassert>
  117. #include <cctype>
  118. #include <forward_list>
  119. #include <map>
  120. #include <set>
  121. using namespace llvm;
  122. #define DEBUG_TYPE "asm-matcher-emitter"
  123. cl::OptionCategory AsmMatcherEmitterCat("Options for -gen-asm-matcher");
  124. static cl::opt<std::string>
  125. MatchPrefix("match-prefix", cl::init(""),
  126. cl::desc("Only match instructions with the given prefix"),
  127. cl::cat(AsmMatcherEmitterCat));
  128. namespace {
  129. class AsmMatcherInfo;
  130. // Register sets are used as keys in some second-order sets TableGen creates
  131. // when generating its data structures. This means that the order of two
  132. // RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and
  133. // can even affect compiler output (at least seen in diagnostics produced when
  134. // all matches fail). So we use a type that sorts them consistently.
  135. typedef std::set<Record*, LessRecordByID> RegisterSet;
  136. class AsmMatcherEmitter {
  137. RecordKeeper &Records;
  138. public:
  139. AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
  140. void run(raw_ostream &o);
  141. };
  142. /// ClassInfo - Helper class for storing the information about a particular
  143. /// class of operands which can be matched.
  144. struct ClassInfo {
  145. enum ClassInfoKind {
  146. /// Invalid kind, for use as a sentinel value.
  147. Invalid = 0,
  148. /// The class for a particular token.
  149. Token,
  150. /// The (first) register class, subsequent register classes are
  151. /// RegisterClass0+1, and so on.
  152. RegisterClass0,
  153. /// The (first) user defined class, subsequent user defined classes are
  154. /// UserClass0+1, and so on.
  155. UserClass0 = 1<<16
  156. };
  157. /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
  158. /// N) for the Nth user defined class.
  159. unsigned Kind;
  160. /// SuperClasses - The super classes of this class. Note that for simplicities
  161. /// sake user operands only record their immediate super class, while register
  162. /// operands include all superclasses.
  163. std::vector<ClassInfo*> SuperClasses;
  164. /// Name - The full class name, suitable for use in an enum.
  165. std::string Name;
  166. /// ClassName - The unadorned generic name for this class (e.g., Token).
  167. std::string ClassName;
  168. /// ValueName - The name of the value this class represents; for a token this
  169. /// is the literal token string, for an operand it is the TableGen class (or
  170. /// empty if this is a derived class).
  171. std::string ValueName;
  172. /// PredicateMethod - The name of the operand method to test whether the
  173. /// operand matches this class; this is not valid for Token or register kinds.
  174. std::string PredicateMethod;
  175. /// RenderMethod - The name of the operand method to add this operand to an
  176. /// MCInst; this is not valid for Token or register kinds.
  177. std::string RenderMethod;
  178. /// ParserMethod - The name of the operand method to do a target specific
  179. /// parsing on the operand.
  180. std::string ParserMethod;
  181. /// For register classes: the records for all the registers in this class.
  182. RegisterSet Registers;
  183. /// For custom match classes: the diagnostic kind for when the predicate fails.
  184. std::string DiagnosticType;
  185. /// For custom match classes: the diagnostic string for when the predicate fails.
  186. std::string DiagnosticString;
  187. /// Is this operand optional and not always required.
  188. bool IsOptional;
  189. /// DefaultMethod - The name of the method that returns the default operand
  190. /// for optional operand
  191. std::string DefaultMethod;
  192. public:
  193. /// isRegisterClass() - Check if this is a register class.
  194. bool isRegisterClass() const {
  195. return Kind >= RegisterClass0 && Kind < UserClass0;
  196. }
  197. /// isUserClass() - Check if this is a user defined class.
  198. bool isUserClass() const {
  199. return Kind >= UserClass0;
  200. }
  201. /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
  202. /// are related if they are in the same class hierarchy.
  203. bool isRelatedTo(const ClassInfo &RHS) const {
  204. // Tokens are only related to tokens.
  205. if (Kind == Token || RHS.Kind == Token)
  206. return Kind == Token && RHS.Kind == Token;
  207. // Registers classes are only related to registers classes, and only if
  208. // their intersection is non-empty.
  209. if (isRegisterClass() || RHS.isRegisterClass()) {
  210. if (!isRegisterClass() || !RHS.isRegisterClass())
  211. return false;
  212. RegisterSet Tmp;
  213. std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin());
  214. std::set_intersection(Registers.begin(), Registers.end(),
  215. RHS.Registers.begin(), RHS.Registers.end(),
  216. II, LessRecordByID());
  217. return !Tmp.empty();
  218. }
  219. // Otherwise we have two users operands; they are related if they are in the
  220. // same class hierarchy.
  221. //
  222. // FIXME: This is an oversimplification, they should only be related if they
  223. // intersect, however we don't have that information.
  224. assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
  225. const ClassInfo *Root = this;
  226. while (!Root->SuperClasses.empty())
  227. Root = Root->SuperClasses.front();
  228. const ClassInfo *RHSRoot = &RHS;
  229. while (!RHSRoot->SuperClasses.empty())
  230. RHSRoot = RHSRoot->SuperClasses.front();
  231. return Root == RHSRoot;
  232. }
  233. /// isSubsetOf - Test whether this class is a subset of \p RHS.
  234. bool isSubsetOf(const ClassInfo &RHS) const {
  235. // This is a subset of RHS if it is the same class...
  236. if (this == &RHS)
  237. return true;
  238. // ... or if any of its super classes are a subset of RHS.
  239. SmallVector<const ClassInfo *, 16> Worklist(SuperClasses.begin(),
  240. SuperClasses.end());
  241. SmallPtrSet<const ClassInfo *, 16> Visited;
  242. while (!Worklist.empty()) {
  243. auto *CI = Worklist.pop_back_val();
  244. if (CI == &RHS)
  245. return true;
  246. for (auto *Super : CI->SuperClasses)
  247. if (Visited.insert(Super).second)
  248. Worklist.push_back(Super);
  249. }
  250. return false;
  251. }
  252. int getTreeDepth() const {
  253. int Depth = 0;
  254. const ClassInfo *Root = this;
  255. while (!Root->SuperClasses.empty()) {
  256. Depth++;
  257. Root = Root->SuperClasses.front();
  258. }
  259. return Depth;
  260. }
  261. const ClassInfo *findRoot() const {
  262. const ClassInfo *Root = this;
  263. while (!Root->SuperClasses.empty())
  264. Root = Root->SuperClasses.front();
  265. return Root;
  266. }
  267. /// Compare two classes. This does not produce a total ordering, but does
  268. /// guarantee that subclasses are sorted before their parents, and that the
  269. /// ordering is transitive.
  270. bool operator<(const ClassInfo &RHS) const {
  271. if (this == &RHS)
  272. return false;
  273. // First, enforce the ordering between the three different types of class.
  274. // Tokens sort before registers, which sort before user classes.
  275. if (Kind == Token) {
  276. if (RHS.Kind != Token)
  277. return true;
  278. assert(RHS.Kind == Token);
  279. } else if (isRegisterClass()) {
  280. if (RHS.Kind == Token)
  281. return false;
  282. else if (RHS.isUserClass())
  283. return true;
  284. assert(RHS.isRegisterClass());
  285. } else if (isUserClass()) {
  286. if (!RHS.isUserClass())
  287. return false;
  288. assert(RHS.isUserClass());
  289. } else {
  290. llvm_unreachable("Unknown ClassInfoKind");
  291. }
  292. if (Kind == Token || isUserClass()) {
  293. // Related tokens and user classes get sorted by depth in the inheritence
  294. // tree (so that subclasses are before their parents).
  295. if (isRelatedTo(RHS)) {
  296. if (getTreeDepth() > RHS.getTreeDepth())
  297. return true;
  298. if (getTreeDepth() < RHS.getTreeDepth())
  299. return false;
  300. } else {
  301. // Unrelated tokens and user classes are ordered by the name of their
  302. // root nodes, so that there is a consistent ordering between
  303. // unconnected trees.
  304. return findRoot()->ValueName < RHS.findRoot()->ValueName;
  305. }
  306. } else if (isRegisterClass()) {
  307. // For register sets, sort by number of registers. This guarantees that
  308. // a set will always sort before all of it's strict supersets.
  309. if (Registers.size() != RHS.Registers.size())
  310. return Registers.size() < RHS.Registers.size();
  311. } else {
  312. llvm_unreachable("Unknown ClassInfoKind");
  313. }
  314. // FIXME: We should be able to just return false here, as we only need a
  315. // partial order (we use stable sorts, so this is deterministic) and the
  316. // name of a class shouldn't be significant. However, some of the backends
  317. // accidentally rely on this behaviour, so it will have to stay like this
  318. // until they are fixed.
  319. return ValueName < RHS.ValueName;
  320. }
  321. };
  322. class AsmVariantInfo {
  323. public:
  324. StringRef RegisterPrefix;
  325. StringRef TokenizingCharacters;
  326. StringRef SeparatorCharacters;
  327. StringRef BreakCharacters;
  328. StringRef Name;
  329. int AsmVariantNo;
  330. };
  331. /// MatchableInfo - Helper class for storing the necessary information for an
  332. /// instruction or alias which is capable of being matched.
  333. struct MatchableInfo {
  334. struct AsmOperand {
  335. /// Token - This is the token that the operand came from.
  336. StringRef Token;
  337. /// The unique class instance this operand should match.
  338. ClassInfo *Class;
  339. /// The operand name this is, if anything.
  340. StringRef SrcOpName;
  341. /// The operand name this is, before renaming for tied operands.
  342. StringRef OrigSrcOpName;
  343. /// The suboperand index within SrcOpName, or -1 for the entire operand.
  344. int SubOpIdx;
  345. /// Whether the token is "isolated", i.e., it is preceded and followed
  346. /// by separators.
  347. bool IsIsolatedToken;
  348. /// Register record if this token is singleton register.
  349. Record *SingletonReg;
  350. explicit AsmOperand(bool IsIsolatedToken, StringRef T)
  351. : Token(T), Class(nullptr), SubOpIdx(-1),
  352. IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {}
  353. };
  354. /// ResOperand - This represents a single operand in the result instruction
  355. /// generated by the match. In cases (like addressing modes) where a single
  356. /// assembler operand expands to multiple MCOperands, this represents the
  357. /// single assembler operand, not the MCOperand.
  358. struct ResOperand {
  359. enum {
  360. /// RenderAsmOperand - This represents an operand result that is
  361. /// generated by calling the render method on the assembly operand. The
  362. /// corresponding AsmOperand is specified by AsmOperandNum.
  363. RenderAsmOperand,
  364. /// TiedOperand - This represents a result operand that is a duplicate of
  365. /// a previous result operand.
  366. TiedOperand,
  367. /// ImmOperand - This represents an immediate value that is dumped into
  368. /// the operand.
  369. ImmOperand,
  370. /// RegOperand - This represents a fixed register that is dumped in.
  371. RegOperand
  372. } Kind;
  373. /// Tuple containing the index of the (earlier) result operand that should
  374. /// be copied from, as well as the indices of the corresponding (parsed)
  375. /// operands in the asm string.
  376. struct TiedOperandsTuple {
  377. unsigned ResOpnd;
  378. unsigned SrcOpnd1Idx;
  379. unsigned SrcOpnd2Idx;
  380. };
  381. union {
  382. /// This is the operand # in the AsmOperands list that this should be
  383. /// copied from.
  384. unsigned AsmOperandNum;
  385. /// Description of tied operands.
  386. TiedOperandsTuple TiedOperands;
  387. /// ImmVal - This is the immediate value added to the instruction.
  388. int64_t ImmVal;
  389. /// Register - This is the register record.
  390. Record *Register;
  391. };
  392. /// MINumOperands - The number of MCInst operands populated by this
  393. /// operand.
  394. unsigned MINumOperands;
  395. static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
  396. ResOperand X;
  397. X.Kind = RenderAsmOperand;
  398. X.AsmOperandNum = AsmOpNum;
  399. X.MINumOperands = NumOperands;
  400. return X;
  401. }
  402. static ResOperand getTiedOp(unsigned TiedOperandNum, unsigned SrcOperand1,
  403. unsigned SrcOperand2) {
  404. ResOperand X;
  405. X.Kind = TiedOperand;
  406. X.TiedOperands = { TiedOperandNum, SrcOperand1, SrcOperand2 };
  407. X.MINumOperands = 1;
  408. return X;
  409. }
  410. static ResOperand getImmOp(int64_t Val) {
  411. ResOperand X;
  412. X.Kind = ImmOperand;
  413. X.ImmVal = Val;
  414. X.MINumOperands = 1;
  415. return X;
  416. }
  417. static ResOperand getRegOp(Record *Reg) {
  418. ResOperand X;
  419. X.Kind = RegOperand;
  420. X.Register = Reg;
  421. X.MINumOperands = 1;
  422. return X;
  423. }
  424. };
  425. /// AsmVariantID - Target's assembly syntax variant no.
  426. int AsmVariantID;
  427. /// AsmString - The assembly string for this instruction (with variants
  428. /// removed), e.g. "movsx $src, $dst".
  429. std::string AsmString;
  430. /// TheDef - This is the definition of the instruction or InstAlias that this
  431. /// matchable came from.
  432. Record *const TheDef;
  433. /// DefRec - This is the definition that it came from.
  434. PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
  435. const CodeGenInstruction *getResultInst() const {
  436. if (DefRec.is<const CodeGenInstruction*>())
  437. return DefRec.get<const CodeGenInstruction*>();
  438. return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
  439. }
  440. /// ResOperands - This is the operand list that should be built for the result
  441. /// MCInst.
  442. SmallVector<ResOperand, 8> ResOperands;
  443. /// Mnemonic - This is the first token of the matched instruction, its
  444. /// mnemonic.
  445. StringRef Mnemonic;
  446. /// AsmOperands - The textual operands that this instruction matches,
  447. /// annotated with a class and where in the OperandList they were defined.
  448. /// This directly corresponds to the tokenized AsmString after the mnemonic is
  449. /// removed.
  450. SmallVector<AsmOperand, 8> AsmOperands;
  451. /// Predicates - The required subtarget features to match this instruction.
  452. SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures;
  453. /// ConversionFnKind - The enum value which is passed to the generated
  454. /// convertToMCInst to convert parsed operands into an MCInst for this
  455. /// function.
  456. std::string ConversionFnKind;
  457. /// If this instruction is deprecated in some form.
  458. bool HasDeprecation;
  459. /// If this is an alias, this is use to determine whether or not to using
  460. /// the conversion function defined by the instruction's AsmMatchConverter
  461. /// or to use the function generated by the alias.
  462. bool UseInstAsmMatchConverter;
  463. MatchableInfo(const CodeGenInstruction &CGI)
  464. : AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef), DefRec(&CGI),
  465. UseInstAsmMatchConverter(true) {
  466. }
  467. MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias)
  468. : AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef),
  469. DefRec(Alias.release()),
  470. UseInstAsmMatchConverter(
  471. TheDef->getValueAsBit("UseInstAsmMatchConverter")) {
  472. }
  473. // Could remove this and the dtor if PointerUnion supported unique_ptr
  474. // elements with a dynamic failure/assertion (like the one below) in the case
  475. // where it was copied while being in an owning state.
  476. MatchableInfo(const MatchableInfo &RHS)
  477. : AsmVariantID(RHS.AsmVariantID), AsmString(RHS.AsmString),
  478. TheDef(RHS.TheDef), DefRec(RHS.DefRec), ResOperands(RHS.ResOperands),
  479. Mnemonic(RHS.Mnemonic), AsmOperands(RHS.AsmOperands),
  480. RequiredFeatures(RHS.RequiredFeatures),
  481. ConversionFnKind(RHS.ConversionFnKind),
  482. HasDeprecation(RHS.HasDeprecation),
  483. UseInstAsmMatchConverter(RHS.UseInstAsmMatchConverter) {
  484. assert(!DefRec.is<const CodeGenInstAlias *>());
  485. }
  486. ~MatchableInfo() {
  487. delete DefRec.dyn_cast<const CodeGenInstAlias*>();
  488. }
  489. // Two-operand aliases clone from the main matchable, but mark the second
  490. // operand as a tied operand of the first for purposes of the assembler.
  491. void formTwoOperandAlias(StringRef Constraint);
  492. void initialize(const AsmMatcherInfo &Info,
  493. SmallPtrSetImpl<Record*> &SingletonRegisters,
  494. AsmVariantInfo const &Variant,
  495. bool HasMnemonicFirst);
  496. /// validate - Return true if this matchable is a valid thing to match against
  497. /// and perform a bunch of validity checking.
  498. bool validate(StringRef CommentDelimiter, bool IsAlias) const;
  499. /// findAsmOperand - Find the AsmOperand with the specified name and
  500. /// suboperand index.
  501. int findAsmOperand(StringRef N, int SubOpIdx) const {
  502. auto I = find_if(AsmOperands, [&](const AsmOperand &Op) {
  503. return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx;
  504. });
  505. return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
  506. }
  507. /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
  508. /// This does not check the suboperand index.
  509. int findAsmOperandNamed(StringRef N, int LastIdx = -1) const {
  510. auto I =
  511. llvm::find_if(llvm::drop_begin(AsmOperands, LastIdx + 1),
  512. [&](const AsmOperand &Op) { return Op.SrcOpName == N; });
  513. return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
  514. }
  515. int findAsmOperandOriginallyNamed(StringRef N) const {
  516. auto I =
  517. find_if(AsmOperands,
  518. [&](const AsmOperand &Op) { return Op.OrigSrcOpName == N; });
  519. return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
  520. }
  521. void buildInstructionResultOperands();
  522. void buildAliasResultOperands(bool AliasConstraintsAreChecked);
  523. /// operator< - Compare two matchables.
  524. bool operator<(const MatchableInfo &RHS) const {
  525. // The primary comparator is the instruction mnemonic.
  526. if (int Cmp = Mnemonic.compare_insensitive(RHS.Mnemonic))
  527. return Cmp == -1;
  528. if (AsmOperands.size() != RHS.AsmOperands.size())
  529. return AsmOperands.size() < RHS.AsmOperands.size();
  530. // Compare lexicographically by operand. The matcher validates that other
  531. // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
  532. for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
  533. if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
  534. return true;
  535. if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
  536. return false;
  537. }
  538. // Give matches that require more features higher precedence. This is useful
  539. // because we cannot define AssemblerPredicates with the negation of
  540. // processor features. For example, ARM v6 "nop" may be either a HINT or
  541. // MOV. With v6, we want to match HINT. The assembler has no way to
  542. // predicate MOV under "NoV6", but HINT will always match first because it
  543. // requires V6 while MOV does not.
  544. if (RequiredFeatures.size() != RHS.RequiredFeatures.size())
  545. return RequiredFeatures.size() > RHS.RequiredFeatures.size();
  546. // For X86 AVX/AVX512 instructions, we prefer vex encoding because the
  547. // vex encoding size is smaller. Since X86InstrSSE.td is included ahead
  548. // of X86InstrAVX512.td, the AVX instruction ID is less than AVX512 ID.
  549. // We use the ID to sort AVX instruction before AVX512 instruction in
  550. // matching table.
  551. if (TheDef->isSubClassOf("Instruction") &&
  552. TheDef->getValueAsBit("HasPositionOrder"))
  553. return TheDef->getID() < RHS.TheDef->getID();
  554. return false;
  555. }
  556. /// couldMatchAmbiguouslyWith - Check whether this matchable could
  557. /// ambiguously match the same set of operands as \p RHS (without being a
  558. /// strictly superior match).
  559. bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) const {
  560. // The primary comparator is the instruction mnemonic.
  561. if (Mnemonic != RHS.Mnemonic)
  562. return false;
  563. // Different variants can't conflict.
  564. if (AsmVariantID != RHS.AsmVariantID)
  565. return false;
  566. // The number of operands is unambiguous.
  567. if (AsmOperands.size() != RHS.AsmOperands.size())
  568. return false;
  569. // Otherwise, make sure the ordering of the two instructions is unambiguous
  570. // by checking that either (a) a token or operand kind discriminates them,
  571. // or (b) the ordering among equivalent kinds is consistent.
  572. // Tokens and operand kinds are unambiguous (assuming a correct target
  573. // specific parser).
  574. for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
  575. if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
  576. AsmOperands[i].Class->Kind == ClassInfo::Token)
  577. if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
  578. *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
  579. return false;
  580. // Otherwise, this operand could commute if all operands are equivalent, or
  581. // there is a pair of operands that compare less than and a pair that
  582. // compare greater than.
  583. bool HasLT = false, HasGT = false;
  584. for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
  585. if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
  586. HasLT = true;
  587. if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
  588. HasGT = true;
  589. }
  590. return HasLT == HasGT;
  591. }
  592. void dump() const;
  593. private:
  594. void tokenizeAsmString(AsmMatcherInfo const &Info,
  595. AsmVariantInfo const &Variant);
  596. void addAsmOperand(StringRef Token, bool IsIsolatedToken = false);
  597. };
  598. struct OperandMatchEntry {
  599. unsigned OperandMask;
  600. const MatchableInfo* MI;
  601. ClassInfo *CI;
  602. static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci,
  603. unsigned opMask) {
  604. OperandMatchEntry X;
  605. X.OperandMask = opMask;
  606. X.CI = ci;
  607. X.MI = mi;
  608. return X;
  609. }
  610. };
  611. class AsmMatcherInfo {
  612. public:
  613. /// Tracked Records
  614. RecordKeeper &Records;
  615. /// The tablegen AsmParser record.
  616. Record *AsmParser;
  617. /// Target - The target information.
  618. CodeGenTarget &Target;
  619. /// The classes which are needed for matching.
  620. std::forward_list<ClassInfo> Classes;
  621. /// The information on the matchables to match.
  622. std::vector<std::unique_ptr<MatchableInfo>> Matchables;
  623. /// Info for custom matching operands by user defined methods.
  624. std::vector<OperandMatchEntry> OperandMatchInfo;
  625. /// Map of Register records to their class information.
  626. typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy;
  627. RegisterClassesTy RegisterClasses;
  628. /// Map of Predicate records to their subtarget information.
  629. std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
  630. /// Map of AsmOperandClass records to their class information.
  631. std::map<Record*, ClassInfo*> AsmOperandClasses;
  632. /// Map of RegisterClass records to their class information.
  633. std::map<Record*, ClassInfo*> RegisterClassClasses;
  634. private:
  635. /// Map of token to class information which has already been constructed.
  636. std::map<std::string, ClassInfo*> TokenClasses;
  637. private:
  638. /// getTokenClass - Lookup or create the class for the given token.
  639. ClassInfo *getTokenClass(StringRef Token);
  640. /// getOperandClass - Lookup or create the class for the given operand.
  641. ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
  642. int SubOpIdx);
  643. ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
  644. /// buildRegisterClasses - Build the ClassInfo* instances for register
  645. /// classes.
  646. void buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters);
  647. /// buildOperandClasses - Build the ClassInfo* instances for user defined
  648. /// operand classes.
  649. void buildOperandClasses();
  650. void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
  651. unsigned AsmOpIdx);
  652. void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
  653. MatchableInfo::AsmOperand &Op);
  654. public:
  655. AsmMatcherInfo(Record *AsmParser,
  656. CodeGenTarget &Target,
  657. RecordKeeper &Records);
  658. /// Construct the various tables used during matching.
  659. void buildInfo();
  660. /// buildOperandMatchInfo - Build the necessary information to handle user
  661. /// defined operand parsing methods.
  662. void buildOperandMatchInfo();
  663. /// getSubtargetFeature - Lookup or create the subtarget feature info for the
  664. /// given operand.
  665. const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
  666. assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
  667. const auto &I = SubtargetFeatures.find(Def);
  668. return I == SubtargetFeatures.end() ? nullptr : &I->second;
  669. }
  670. RecordKeeper &getRecords() const {
  671. return Records;
  672. }
  673. bool hasOptionalOperands() const {
  674. return any_of(Classes,
  675. [](const ClassInfo &Class) { return Class.IsOptional; });
  676. }
  677. };
  678. } // end anonymous namespace
  679. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  680. LLVM_DUMP_METHOD void MatchableInfo::dump() const {
  681. errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
  682. errs() << " variant: " << AsmVariantID << "\n";
  683. for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
  684. const AsmOperand &Op = AsmOperands[i];
  685. errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
  686. errs() << '\"' << Op.Token << "\"\n";
  687. }
  688. }
  689. #endif
  690. static std::pair<StringRef, StringRef>
  691. parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
  692. // Split via the '='.
  693. std::pair<StringRef, StringRef> Ops = S.split('=');
  694. if (Ops.second == "")
  695. PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
  696. // Trim whitespace and the leading '$' on the operand names.
  697. size_t start = Ops.first.find_first_of('$');
  698. if (start == std::string::npos)
  699. PrintFatalError(Loc, "expected '$' prefix on asm operand name");
  700. Ops.first = Ops.first.slice(start + 1, std::string::npos);
  701. size_t end = Ops.first.find_last_of(" \t");
  702. Ops.first = Ops.first.slice(0, end);
  703. // Now the second operand.
  704. start = Ops.second.find_first_of('$');
  705. if (start == std::string::npos)
  706. PrintFatalError(Loc, "expected '$' prefix on asm operand name");
  707. Ops.second = Ops.second.slice(start + 1, std::string::npos);
  708. end = Ops.second.find_last_of(" \t");
  709. Ops.first = Ops.first.slice(0, end);
  710. return Ops;
  711. }
  712. void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
  713. // Figure out which operands are aliased and mark them as tied.
  714. std::pair<StringRef, StringRef> Ops =
  715. parseTwoOperandConstraint(Constraint, TheDef->getLoc());
  716. // Find the AsmOperands that refer to the operands we're aliasing.
  717. int SrcAsmOperand = findAsmOperandNamed(Ops.first);
  718. int DstAsmOperand = findAsmOperandNamed(Ops.second);
  719. if (SrcAsmOperand == -1)
  720. PrintFatalError(TheDef->getLoc(),
  721. "unknown source two-operand alias operand '" + Ops.first +
  722. "'.");
  723. if (DstAsmOperand == -1)
  724. PrintFatalError(TheDef->getLoc(),
  725. "unknown destination two-operand alias operand '" +
  726. Ops.second + "'.");
  727. // Find the ResOperand that refers to the operand we're aliasing away
  728. // and update it to refer to the combined operand instead.
  729. for (ResOperand &Op : ResOperands) {
  730. if (Op.Kind == ResOperand::RenderAsmOperand &&
  731. Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
  732. Op.AsmOperandNum = DstAsmOperand;
  733. break;
  734. }
  735. }
  736. // Remove the AsmOperand for the alias operand.
  737. AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
  738. // Adjust the ResOperand references to any AsmOperands that followed
  739. // the one we just deleted.
  740. for (ResOperand &Op : ResOperands) {
  741. switch(Op.Kind) {
  742. default:
  743. // Nothing to do for operands that don't reference AsmOperands.
  744. break;
  745. case ResOperand::RenderAsmOperand:
  746. if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
  747. --Op.AsmOperandNum;
  748. break;
  749. }
  750. }
  751. }
  752. /// extractSingletonRegisterForAsmOperand - Extract singleton register,
  753. /// if present, from specified token.
  754. static void
  755. extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand &Op,
  756. const AsmMatcherInfo &Info,
  757. StringRef RegisterPrefix) {
  758. StringRef Tok = Op.Token;
  759. // If this token is not an isolated token, i.e., it isn't separated from
  760. // other tokens (e.g. with whitespace), don't interpret it as a register name.
  761. if (!Op.IsIsolatedToken)
  762. return;
  763. if (RegisterPrefix.empty()) {
  764. std::string LoweredTok = Tok.lower();
  765. if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
  766. Op.SingletonReg = Reg->TheDef;
  767. return;
  768. }
  769. if (!Tok.startswith(RegisterPrefix))
  770. return;
  771. StringRef RegName = Tok.substr(RegisterPrefix.size());
  772. if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
  773. Op.SingletonReg = Reg->TheDef;
  774. // If there is no register prefix (i.e. "%" in "%eax"), then this may
  775. // be some random non-register token, just ignore it.
  776. }
  777. void MatchableInfo::initialize(const AsmMatcherInfo &Info,
  778. SmallPtrSetImpl<Record*> &SingletonRegisters,
  779. AsmVariantInfo const &Variant,
  780. bool HasMnemonicFirst) {
  781. AsmVariantID = Variant.AsmVariantNo;
  782. AsmString =
  783. CodeGenInstruction::FlattenAsmStringVariants(AsmString,
  784. Variant.AsmVariantNo);
  785. tokenizeAsmString(Info, Variant);
  786. // The first token of the instruction is the mnemonic, which must be a
  787. // simple string, not a $foo variable or a singleton register.
  788. if (AsmOperands.empty())
  789. PrintFatalError(TheDef->getLoc(),
  790. "Instruction '" + TheDef->getName() + "' has no tokens");
  791. assert(!AsmOperands[0].Token.empty());
  792. if (HasMnemonicFirst) {
  793. Mnemonic = AsmOperands[0].Token;
  794. if (Mnemonic[0] == '$')
  795. PrintFatalError(TheDef->getLoc(),
  796. "Invalid instruction mnemonic '" + Mnemonic + "'!");
  797. // Remove the first operand, it is tracked in the mnemonic field.
  798. AsmOperands.erase(AsmOperands.begin());
  799. } else if (AsmOperands[0].Token[0] != '$')
  800. Mnemonic = AsmOperands[0].Token;
  801. // Compute the require features.
  802. for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates"))
  803. if (const SubtargetFeatureInfo *Feature =
  804. Info.getSubtargetFeature(Predicate))
  805. RequiredFeatures.push_back(Feature);
  806. // Collect singleton registers, if used.
  807. for (MatchableInfo::AsmOperand &Op : AsmOperands) {
  808. extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix);
  809. if (Record *Reg = Op.SingletonReg)
  810. SingletonRegisters.insert(Reg);
  811. }
  812. const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask");
  813. if (!DepMask)
  814. DepMask = TheDef->getValue("ComplexDeprecationPredicate");
  815. HasDeprecation =
  816. DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false;
  817. }
  818. /// Append an AsmOperand for the given substring of AsmString.
  819. void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) {
  820. AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token));
  821. }
  822. /// tokenizeAsmString - Tokenize a simplified assembly string.
  823. void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info,
  824. AsmVariantInfo const &Variant) {
  825. StringRef String = AsmString;
  826. size_t Prev = 0;
  827. bool InTok = false;
  828. bool IsIsolatedToken = true;
  829. for (size_t i = 0, e = String.size(); i != e; ++i) {
  830. char Char = String[i];
  831. if (Variant.BreakCharacters.find(Char) != std::string::npos) {
  832. if (InTok) {
  833. addAsmOperand(String.slice(Prev, i), false);
  834. Prev = i;
  835. IsIsolatedToken = false;
  836. }
  837. InTok = true;
  838. continue;
  839. }
  840. if (Variant.TokenizingCharacters.find(Char) != std::string::npos) {
  841. if (InTok) {
  842. addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
  843. InTok = false;
  844. IsIsolatedToken = false;
  845. }
  846. addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
  847. Prev = i + 1;
  848. IsIsolatedToken = true;
  849. continue;
  850. }
  851. if (Variant.SeparatorCharacters.find(Char) != std::string::npos) {
  852. if (InTok) {
  853. addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
  854. InTok = false;
  855. }
  856. Prev = i + 1;
  857. IsIsolatedToken = true;
  858. continue;
  859. }
  860. switch (Char) {
  861. case '\\':
  862. if (InTok) {
  863. addAsmOperand(String.slice(Prev, i), false);
  864. InTok = false;
  865. IsIsolatedToken = false;
  866. }
  867. ++i;
  868. assert(i != String.size() && "Invalid quoted character");
  869. addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
  870. Prev = i + 1;
  871. IsIsolatedToken = false;
  872. break;
  873. case '$': {
  874. if (InTok) {
  875. addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
  876. InTok = false;
  877. IsIsolatedToken = false;
  878. }
  879. // If this isn't "${", start new identifier looking like "$xxx"
  880. if (i + 1 == String.size() || String[i + 1] != '{') {
  881. Prev = i;
  882. break;
  883. }
  884. size_t EndPos = String.find('}', i);
  885. assert(EndPos != StringRef::npos &&
  886. "Missing brace in operand reference!");
  887. addAsmOperand(String.slice(i, EndPos+1), IsIsolatedToken);
  888. Prev = EndPos + 1;
  889. i = EndPos;
  890. IsIsolatedToken = false;
  891. break;
  892. }
  893. default:
  894. InTok = true;
  895. break;
  896. }
  897. }
  898. if (InTok && Prev != String.size())
  899. addAsmOperand(String.substr(Prev), IsIsolatedToken);
  900. }
  901. bool MatchableInfo::validate(StringRef CommentDelimiter, bool IsAlias) const {
  902. // Reject matchables with no .s string.
  903. if (AsmString.empty())
  904. PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
  905. // Reject any matchables with a newline in them, they should be marked
  906. // isCodeGenOnly if they are pseudo instructions.
  907. if (AsmString.find('\n') != std::string::npos)
  908. PrintFatalError(TheDef->getLoc(),
  909. "multiline instruction is not valid for the asmparser, "
  910. "mark it isCodeGenOnly");
  911. // Remove comments from the asm string. We know that the asmstring only
  912. // has one line.
  913. if (!CommentDelimiter.empty() &&
  914. StringRef(AsmString).contains(CommentDelimiter))
  915. PrintFatalError(TheDef->getLoc(),
  916. "asmstring for instruction has comment character in it, "
  917. "mark it isCodeGenOnly");
  918. // Reject matchables with operand modifiers, these aren't something we can
  919. // handle, the target should be refactored to use operands instead of
  920. // modifiers.
  921. //
  922. // Also, check for instructions which reference the operand multiple times,
  923. // if they don't define a custom AsmMatcher: this implies a constraint that
  924. // the built-in matching code would not honor.
  925. std::set<std::string> OperandNames;
  926. for (const AsmOperand &Op : AsmOperands) {
  927. StringRef Tok = Op.Token;
  928. if (Tok[0] == '$' && Tok.contains(':'))
  929. PrintFatalError(TheDef->getLoc(),
  930. "matchable with operand modifier '" + Tok +
  931. "' not supported by asm matcher. Mark isCodeGenOnly!");
  932. // Verify that any operand is only mentioned once.
  933. // We reject aliases and ignore instructions for now.
  934. if (!IsAlias && TheDef->getValueAsString("AsmMatchConverter").empty() &&
  935. Tok[0] == '$' && !OperandNames.insert(std::string(Tok)).second) {
  936. LLVM_DEBUG({
  937. errs() << "warning: '" << TheDef->getName() << "': "
  938. << "ignoring instruction with tied operand '"
  939. << Tok << "'\n";
  940. });
  941. return false;
  942. }
  943. }
  944. return true;
  945. }
  946. static std::string getEnumNameForToken(StringRef Str) {
  947. std::string Res;
  948. for (char C : Str) {
  949. switch (C) {
  950. case '*': Res += "_STAR_"; break;
  951. case '%': Res += "_PCT_"; break;
  952. case ':': Res += "_COLON_"; break;
  953. case '!': Res += "_EXCLAIM_"; break;
  954. case '.': Res += "_DOT_"; break;
  955. case '<': Res += "_LT_"; break;
  956. case '>': Res += "_GT_"; break;
  957. case '-': Res += "_MINUS_"; break;
  958. case '#': Res += "_HASH_"; break;
  959. default:
  960. if (isAlnum(C))
  961. Res += C;
  962. else
  963. Res += "_" + utostr((unsigned)C) + "_";
  964. }
  965. }
  966. return Res;
  967. }
  968. ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
  969. ClassInfo *&Entry = TokenClasses[std::string(Token)];
  970. if (!Entry) {
  971. Classes.emplace_front();
  972. Entry = &Classes.front();
  973. Entry->Kind = ClassInfo::Token;
  974. Entry->ClassName = "Token";
  975. Entry->Name = "MCK_" + getEnumNameForToken(Token);
  976. Entry->ValueName = std::string(Token);
  977. Entry->PredicateMethod = "<invalid>";
  978. Entry->RenderMethod = "<invalid>";
  979. Entry->ParserMethod = "";
  980. Entry->DiagnosticType = "";
  981. Entry->IsOptional = false;
  982. Entry->DefaultMethod = "<invalid>";
  983. }
  984. return Entry;
  985. }
  986. ClassInfo *
  987. AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
  988. int SubOpIdx) {
  989. Record *Rec = OI.Rec;
  990. if (SubOpIdx != -1)
  991. Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
  992. return getOperandClass(Rec, SubOpIdx);
  993. }
  994. ClassInfo *
  995. AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
  996. if (Rec->isSubClassOf("RegisterOperand")) {
  997. // RegisterOperand may have an associated ParserMatchClass. If it does,
  998. // use it, else just fall back to the underlying register class.
  999. const RecordVal *R = Rec->getValue("ParserMatchClass");
  1000. if (!R || !R->getValue())
  1001. PrintFatalError(Rec->getLoc(),
  1002. "Record `" + Rec->getName() +
  1003. "' does not have a ParserMatchClass!\n");
  1004. if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
  1005. Record *MatchClass = DI->getDef();
  1006. if (ClassInfo *CI = AsmOperandClasses[MatchClass])
  1007. return CI;
  1008. }
  1009. // No custom match class. Just use the register class.
  1010. Record *ClassRec = Rec->getValueAsDef("RegClass");
  1011. if (!ClassRec)
  1012. PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
  1013. "' has no associated register class!\n");
  1014. if (ClassInfo *CI = RegisterClassClasses[ClassRec])
  1015. return CI;
  1016. PrintFatalError(Rec->getLoc(), "register class has no class info!");
  1017. }
  1018. if (Rec->isSubClassOf("RegisterClass")) {
  1019. if (ClassInfo *CI = RegisterClassClasses[Rec])
  1020. return CI;
  1021. PrintFatalError(Rec->getLoc(), "register class has no class info!");
  1022. }
  1023. if (!Rec->isSubClassOf("Operand"))
  1024. PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
  1025. "' does not derive from class Operand!\n");
  1026. Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
  1027. if (ClassInfo *CI = AsmOperandClasses[MatchClass])
  1028. return CI;
  1029. PrintFatalError(Rec->getLoc(), "operand has no match class!");
  1030. }
  1031. struct LessRegisterSet {
  1032. bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
  1033. // std::set<T> defines its own compariso "operator<", but it
  1034. // performs a lexicographical comparison by T's innate comparison
  1035. // for some reason. We don't want non-deterministic pointer
  1036. // comparisons so use this instead.
  1037. return std::lexicographical_compare(LHS.begin(), LHS.end(),
  1038. RHS.begin(), RHS.end(),
  1039. LessRecordByID());
  1040. }
  1041. };
  1042. void AsmMatcherInfo::
  1043. buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) {
  1044. const auto &Registers = Target.getRegBank().getRegisters();
  1045. auto &RegClassList = Target.getRegBank().getRegClasses();
  1046. typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
  1047. // The register sets used for matching.
  1048. RegisterSetSet RegisterSets;
  1049. // Gather the defined sets.
  1050. for (const CodeGenRegisterClass &RC : RegClassList)
  1051. RegisterSets.insert(
  1052. RegisterSet(RC.getOrder().begin(), RC.getOrder().end()));
  1053. // Add any required singleton sets.
  1054. for (Record *Rec : SingletonRegisters) {
  1055. RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
  1056. }
  1057. // Introduce derived sets where necessary (when a register does not determine
  1058. // a unique register set class), and build the mapping of registers to the set
  1059. // they should classify to.
  1060. std::map<Record*, RegisterSet> RegisterMap;
  1061. for (const CodeGenRegister &CGR : Registers) {
  1062. // Compute the intersection of all sets containing this register.
  1063. RegisterSet ContainingSet;
  1064. for (const RegisterSet &RS : RegisterSets) {
  1065. if (!RS.count(CGR.TheDef))
  1066. continue;
  1067. if (ContainingSet.empty()) {
  1068. ContainingSet = RS;
  1069. continue;
  1070. }
  1071. RegisterSet Tmp;
  1072. std::swap(Tmp, ContainingSet);
  1073. std::insert_iterator<RegisterSet> II(ContainingSet,
  1074. ContainingSet.begin());
  1075. std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II,
  1076. LessRecordByID());
  1077. }
  1078. if (!ContainingSet.empty()) {
  1079. RegisterSets.insert(ContainingSet);
  1080. RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
  1081. }
  1082. }
  1083. // Construct the register classes.
  1084. std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
  1085. unsigned Index = 0;
  1086. for (const RegisterSet &RS : RegisterSets) {
  1087. Classes.emplace_front();
  1088. ClassInfo *CI = &Classes.front();
  1089. CI->Kind = ClassInfo::RegisterClass0 + Index;
  1090. CI->ClassName = "Reg" + utostr(Index);
  1091. CI->Name = "MCK_Reg" + utostr(Index);
  1092. CI->ValueName = "";
  1093. CI->PredicateMethod = ""; // unused
  1094. CI->RenderMethod = "addRegOperands";
  1095. CI->Registers = RS;
  1096. // FIXME: diagnostic type.
  1097. CI->DiagnosticType = "";
  1098. CI->IsOptional = false;
  1099. CI->DefaultMethod = ""; // unused
  1100. RegisterSetClasses.insert(std::make_pair(RS, CI));
  1101. ++Index;
  1102. }
  1103. // Find the superclasses; we could compute only the subgroup lattice edges,
  1104. // but there isn't really a point.
  1105. for (const RegisterSet &RS : RegisterSets) {
  1106. ClassInfo *CI = RegisterSetClasses[RS];
  1107. for (const RegisterSet &RS2 : RegisterSets)
  1108. if (RS != RS2 &&
  1109. std::includes(RS2.begin(), RS2.end(), RS.begin(), RS.end(),
  1110. LessRecordByID()))
  1111. CI->SuperClasses.push_back(RegisterSetClasses[RS2]);
  1112. }
  1113. // Name the register classes which correspond to a user defined RegisterClass.
  1114. for (const CodeGenRegisterClass &RC : RegClassList) {
  1115. // Def will be NULL for non-user defined register classes.
  1116. Record *Def = RC.getDef();
  1117. if (!Def)
  1118. continue;
  1119. ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
  1120. RC.getOrder().end())];
  1121. if (CI->ValueName.empty()) {
  1122. CI->ClassName = RC.getName();
  1123. CI->Name = "MCK_" + RC.getName();
  1124. CI->ValueName = RC.getName();
  1125. } else
  1126. CI->ValueName = CI->ValueName + "," + RC.getName();
  1127. Init *DiagnosticType = Def->getValueInit("DiagnosticType");
  1128. if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
  1129. CI->DiagnosticType = std::string(SI->getValue());
  1130. Init *DiagnosticString = Def->getValueInit("DiagnosticString");
  1131. if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
  1132. CI->DiagnosticString = std::string(SI->getValue());
  1133. // If we have a diagnostic string but the diagnostic type is not specified
  1134. // explicitly, create an anonymous diagnostic type.
  1135. if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
  1136. CI->DiagnosticType = RC.getName();
  1137. RegisterClassClasses.insert(std::make_pair(Def, CI));
  1138. }
  1139. // Populate the map for individual registers.
  1140. for (auto &It : RegisterMap)
  1141. RegisterClasses[It.first] = RegisterSetClasses[It.second];
  1142. // Name the register classes which correspond to singleton registers.
  1143. for (Record *Rec : SingletonRegisters) {
  1144. ClassInfo *CI = RegisterClasses[Rec];
  1145. assert(CI && "Missing singleton register class info!");
  1146. if (CI->ValueName.empty()) {
  1147. CI->ClassName = std::string(Rec->getName());
  1148. CI->Name = "MCK_" + Rec->getName().str();
  1149. CI->ValueName = std::string(Rec->getName());
  1150. } else
  1151. CI->ValueName = CI->ValueName + "," + Rec->getName().str();
  1152. }
  1153. }
  1154. void AsmMatcherInfo::buildOperandClasses() {
  1155. std::vector<Record*> AsmOperands =
  1156. Records.getAllDerivedDefinitions("AsmOperandClass");
  1157. // Pre-populate AsmOperandClasses map.
  1158. for (Record *Rec : AsmOperands) {
  1159. Classes.emplace_front();
  1160. AsmOperandClasses[Rec] = &Classes.front();
  1161. }
  1162. unsigned Index = 0;
  1163. for (Record *Rec : AsmOperands) {
  1164. ClassInfo *CI = AsmOperandClasses[Rec];
  1165. CI->Kind = ClassInfo::UserClass0 + Index;
  1166. ListInit *Supers = Rec->getValueAsListInit("SuperClasses");
  1167. for (Init *I : Supers->getValues()) {
  1168. DefInit *DI = dyn_cast<DefInit>(I);
  1169. if (!DI) {
  1170. PrintError(Rec->getLoc(), "Invalid super class reference!");
  1171. continue;
  1172. }
  1173. ClassInfo *SC = AsmOperandClasses[DI->getDef()];
  1174. if (!SC)
  1175. PrintError(Rec->getLoc(), "Invalid super class reference!");
  1176. else
  1177. CI->SuperClasses.push_back(SC);
  1178. }
  1179. CI->ClassName = std::string(Rec->getValueAsString("Name"));
  1180. CI->Name = "MCK_" + CI->ClassName;
  1181. CI->ValueName = std::string(Rec->getName());
  1182. // Get or construct the predicate method name.
  1183. Init *PMName = Rec->getValueInit("PredicateMethod");
  1184. if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
  1185. CI->PredicateMethod = std::string(SI->getValue());
  1186. } else {
  1187. assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
  1188. CI->PredicateMethod = "is" + CI->ClassName;
  1189. }
  1190. // Get or construct the render method name.
  1191. Init *RMName = Rec->getValueInit("RenderMethod");
  1192. if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
  1193. CI->RenderMethod = std::string(SI->getValue());
  1194. } else {
  1195. assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
  1196. CI->RenderMethod = "add" + CI->ClassName + "Operands";
  1197. }
  1198. // Get the parse method name or leave it as empty.
  1199. Init *PRMName = Rec->getValueInit("ParserMethod");
  1200. if (StringInit *SI = dyn_cast<StringInit>(PRMName))
  1201. CI->ParserMethod = std::string(SI->getValue());
  1202. // Get the diagnostic type and string or leave them as empty.
  1203. Init *DiagnosticType = Rec->getValueInit("DiagnosticType");
  1204. if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
  1205. CI->DiagnosticType = std::string(SI->getValue());
  1206. Init *DiagnosticString = Rec->getValueInit("DiagnosticString");
  1207. if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
  1208. CI->DiagnosticString = std::string(SI->getValue());
  1209. // If we have a DiagnosticString, we need a DiagnosticType for use within
  1210. // the matcher.
  1211. if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
  1212. CI->DiagnosticType = CI->ClassName;
  1213. Init *IsOptional = Rec->getValueInit("IsOptional");
  1214. if (BitInit *BI = dyn_cast<BitInit>(IsOptional))
  1215. CI->IsOptional = BI->getValue();
  1216. // Get or construct the default method name.
  1217. Init *DMName = Rec->getValueInit("DefaultMethod");
  1218. if (StringInit *SI = dyn_cast<StringInit>(DMName)) {
  1219. CI->DefaultMethod = std::string(SI->getValue());
  1220. } else {
  1221. assert(isa<UnsetInit>(DMName) && "Unexpected DefaultMethod field!");
  1222. CI->DefaultMethod = "default" + CI->ClassName + "Operands";
  1223. }
  1224. ++Index;
  1225. }
  1226. }
  1227. AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
  1228. CodeGenTarget &target,
  1229. RecordKeeper &records)
  1230. : Records(records), AsmParser(asmParser), Target(target) {
  1231. }
  1232. /// buildOperandMatchInfo - Build the necessary information to handle user
  1233. /// defined operand parsing methods.
  1234. void AsmMatcherInfo::buildOperandMatchInfo() {
  1235. /// Map containing a mask with all operands indices that can be found for
  1236. /// that class inside a instruction.
  1237. typedef std::map<ClassInfo *, unsigned, deref<std::less<>>> OpClassMaskTy;
  1238. OpClassMaskTy OpClassMask;
  1239. bool CallCustomParserForAllOperands =
  1240. AsmParser->getValueAsBit("CallCustomParserForAllOperands");
  1241. for (const auto &MI : Matchables) {
  1242. OpClassMask.clear();
  1243. // Keep track of all operands of this instructions which belong to the
  1244. // same class.
  1245. unsigned NumOptionalOps = 0;
  1246. for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
  1247. const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
  1248. if (CallCustomParserForAllOperands || !Op.Class->ParserMethod.empty()) {
  1249. unsigned &OperandMask = OpClassMask[Op.Class];
  1250. OperandMask |= maskTrailingOnes<unsigned>(NumOptionalOps + 1)
  1251. << (i - NumOptionalOps);
  1252. }
  1253. if (Op.Class->IsOptional)
  1254. ++NumOptionalOps;
  1255. }
  1256. // Generate operand match info for each mnemonic/operand class pair.
  1257. for (const auto &OCM : OpClassMask) {
  1258. unsigned OpMask = OCM.second;
  1259. ClassInfo *CI = OCM.first;
  1260. OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI,
  1261. OpMask));
  1262. }
  1263. }
  1264. }
  1265. void AsmMatcherInfo::buildInfo() {
  1266. // Build information about all of the AssemblerPredicates.
  1267. const std::vector<std::pair<Record *, SubtargetFeatureInfo>>
  1268. &SubtargetFeaturePairs = SubtargetFeatureInfo::getAll(Records);
  1269. SubtargetFeatures.insert(SubtargetFeaturePairs.begin(),
  1270. SubtargetFeaturePairs.end());
  1271. #ifndef NDEBUG
  1272. for (const auto &Pair : SubtargetFeatures)
  1273. LLVM_DEBUG(Pair.second.dump());
  1274. #endif // NDEBUG
  1275. bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
  1276. bool ReportMultipleNearMisses =
  1277. AsmParser->getValueAsBit("ReportMultipleNearMisses");
  1278. // Parse the instructions; we need to do this first so that we can gather the
  1279. // singleton register classes.
  1280. SmallPtrSet<Record*, 16> SingletonRegisters;
  1281. unsigned VariantCount = Target.getAsmParserVariantCount();
  1282. for (unsigned VC = 0; VC != VariantCount; ++VC) {
  1283. Record *AsmVariant = Target.getAsmParserVariant(VC);
  1284. StringRef CommentDelimiter =
  1285. AsmVariant->getValueAsString("CommentDelimiter");
  1286. AsmVariantInfo Variant;
  1287. Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
  1288. Variant.TokenizingCharacters =
  1289. AsmVariant->getValueAsString("TokenizingCharacters");
  1290. Variant.SeparatorCharacters =
  1291. AsmVariant->getValueAsString("SeparatorCharacters");
  1292. Variant.BreakCharacters =
  1293. AsmVariant->getValueAsString("BreakCharacters");
  1294. Variant.Name = AsmVariant->getValueAsString("Name");
  1295. Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant");
  1296. for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) {
  1297. // If the tblgen -match-prefix option is specified (for tblgen hackers),
  1298. // filter the set of instructions we consider.
  1299. if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix))
  1300. continue;
  1301. // Ignore "codegen only" instructions.
  1302. if (CGI->TheDef->getValueAsBit("isCodeGenOnly"))
  1303. continue;
  1304. // Ignore instructions for different instructions
  1305. StringRef V = CGI->TheDef->getValueAsString("AsmVariantName");
  1306. if (!V.empty() && V != Variant.Name)
  1307. continue;
  1308. auto II = std::make_unique<MatchableInfo>(*CGI);
  1309. II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
  1310. // Ignore instructions which shouldn't be matched and diagnose invalid
  1311. // instruction definitions with an error.
  1312. if (!II->validate(CommentDelimiter, false))
  1313. continue;
  1314. Matchables.push_back(std::move(II));
  1315. }
  1316. // Parse all of the InstAlias definitions and stick them in the list of
  1317. // matchables.
  1318. std::vector<Record*> AllInstAliases =
  1319. Records.getAllDerivedDefinitions("InstAlias");
  1320. for (Record *InstAlias : AllInstAliases) {
  1321. auto Alias = std::make_unique<CodeGenInstAlias>(InstAlias, Target);
  1322. // If the tblgen -match-prefix option is specified (for tblgen hackers),
  1323. // filter the set of instruction aliases we consider, based on the target
  1324. // instruction.
  1325. if (!StringRef(Alias->ResultInst->TheDef->getName())
  1326. .startswith( MatchPrefix))
  1327. continue;
  1328. StringRef V = Alias->TheDef->getValueAsString("AsmVariantName");
  1329. if (!V.empty() && V != Variant.Name)
  1330. continue;
  1331. auto II = std::make_unique<MatchableInfo>(std::move(Alias));
  1332. II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
  1333. // Validate the alias definitions.
  1334. II->validate(CommentDelimiter, true);
  1335. Matchables.push_back(std::move(II));
  1336. }
  1337. }
  1338. // Build info for the register classes.
  1339. buildRegisterClasses(SingletonRegisters);
  1340. // Build info for the user defined assembly operand classes.
  1341. buildOperandClasses();
  1342. // Build the information about matchables, now that we have fully formed
  1343. // classes.
  1344. std::vector<std::unique_ptr<MatchableInfo>> NewMatchables;
  1345. for (auto &II : Matchables) {
  1346. // Parse the tokens after the mnemonic.
  1347. // Note: buildInstructionOperandReference may insert new AsmOperands, so
  1348. // don't precompute the loop bound.
  1349. for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
  1350. MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
  1351. StringRef Token = Op.Token;
  1352. // Check for singleton registers.
  1353. if (Record *RegRecord = Op.SingletonReg) {
  1354. Op.Class = RegisterClasses[RegRecord];
  1355. assert(Op.Class && Op.Class->Registers.size() == 1 &&
  1356. "Unexpected class for singleton register");
  1357. continue;
  1358. }
  1359. // Check for simple tokens.
  1360. if (Token[0] != '$') {
  1361. Op.Class = getTokenClass(Token);
  1362. continue;
  1363. }
  1364. if (Token.size() > 1 && isdigit(Token[1])) {
  1365. Op.Class = getTokenClass(Token);
  1366. continue;
  1367. }
  1368. // Otherwise this is an operand reference.
  1369. StringRef OperandName;
  1370. if (Token[1] == '{')
  1371. OperandName = Token.substr(2, Token.size() - 3);
  1372. else
  1373. OperandName = Token.substr(1);
  1374. if (II->DefRec.is<const CodeGenInstruction*>())
  1375. buildInstructionOperandReference(II.get(), OperandName, i);
  1376. else
  1377. buildAliasOperandReference(II.get(), OperandName, Op);
  1378. }
  1379. if (II->DefRec.is<const CodeGenInstruction*>()) {
  1380. II->buildInstructionResultOperands();
  1381. // If the instruction has a two-operand alias, build up the
  1382. // matchable here. We'll add them in bulk at the end to avoid
  1383. // confusing this loop.
  1384. StringRef Constraint =
  1385. II->TheDef->getValueAsString("TwoOperandAliasConstraint");
  1386. if (Constraint != "") {
  1387. // Start by making a copy of the original matchable.
  1388. auto AliasII = std::make_unique<MatchableInfo>(*II);
  1389. // Adjust it to be a two-operand alias.
  1390. AliasII->formTwoOperandAlias(Constraint);
  1391. // Add the alias to the matchables list.
  1392. NewMatchables.push_back(std::move(AliasII));
  1393. }
  1394. } else
  1395. // FIXME: The tied operands checking is not yet integrated with the
  1396. // framework for reporting multiple near misses. To prevent invalid
  1397. // formats from being matched with an alias if a tied-operands check
  1398. // would otherwise have disallowed it, we just disallow such constructs
  1399. // in TableGen completely.
  1400. II->buildAliasResultOperands(!ReportMultipleNearMisses);
  1401. }
  1402. if (!NewMatchables.empty())
  1403. Matchables.insert(Matchables.end(),
  1404. std::make_move_iterator(NewMatchables.begin()),
  1405. std::make_move_iterator(NewMatchables.end()));
  1406. // Process token alias definitions and set up the associated superclass
  1407. // information.
  1408. std::vector<Record*> AllTokenAliases =
  1409. Records.getAllDerivedDefinitions("TokenAlias");
  1410. for (Record *Rec : AllTokenAliases) {
  1411. ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
  1412. ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
  1413. if (FromClass == ToClass)
  1414. PrintFatalError(Rec->getLoc(),
  1415. "error: Destination value identical to source value.");
  1416. FromClass->SuperClasses.push_back(ToClass);
  1417. }
  1418. // Reorder classes so that classes precede super classes.
  1419. Classes.sort();
  1420. #ifdef EXPENSIVE_CHECKS
  1421. // Verify that the table is sorted and operator < works transitively.
  1422. for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) {
  1423. for (auto J = I; J != E; ++J) {
  1424. assert(!(*J < *I));
  1425. assert(I == J || !J->isSubsetOf(*I));
  1426. }
  1427. }
  1428. #endif
  1429. }
  1430. /// buildInstructionOperandReference - The specified operand is a reference to a
  1431. /// named operand such as $src. Resolve the Class and OperandInfo pointers.
  1432. void AsmMatcherInfo::
  1433. buildInstructionOperandReference(MatchableInfo *II,
  1434. StringRef OperandName,
  1435. unsigned AsmOpIdx) {
  1436. const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
  1437. const CGIOperandList &Operands = CGI.Operands;
  1438. MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
  1439. // Map this token to an operand.
  1440. unsigned Idx;
  1441. if (!Operands.hasOperandNamed(OperandName, Idx))
  1442. PrintFatalError(II->TheDef->getLoc(),
  1443. "error: unable to find operand: '" + OperandName + "'");
  1444. // If the instruction operand has multiple suboperands, but the parser
  1445. // match class for the asm operand is still the default "ImmAsmOperand",
  1446. // then handle each suboperand separately.
  1447. if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
  1448. Record *Rec = Operands[Idx].Rec;
  1449. assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
  1450. Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
  1451. if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
  1452. // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
  1453. StringRef Token = Op->Token; // save this in case Op gets moved
  1454. for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
  1455. MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token);
  1456. NewAsmOp.SubOpIdx = SI;
  1457. II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
  1458. }
  1459. // Replace Op with first suboperand.
  1460. Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
  1461. Op->SubOpIdx = 0;
  1462. }
  1463. }
  1464. // Set up the operand class.
  1465. Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
  1466. Op->OrigSrcOpName = OperandName;
  1467. // If the named operand is tied, canonicalize it to the untied operand.
  1468. // For example, something like:
  1469. // (outs GPR:$dst), (ins GPR:$src)
  1470. // with an asmstring of
  1471. // "inc $src"
  1472. // we want to canonicalize to:
  1473. // "inc $dst"
  1474. // so that we know how to provide the $dst operand when filling in the result.
  1475. int OITied = -1;
  1476. if (Operands[Idx].MINumOperands == 1)
  1477. OITied = Operands[Idx].getTiedRegister();
  1478. if (OITied != -1) {
  1479. // The tied operand index is an MIOperand index, find the operand that
  1480. // contains it.
  1481. std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
  1482. OperandName = Operands[Idx.first].Name;
  1483. Op->SubOpIdx = Idx.second;
  1484. }
  1485. Op->SrcOpName = OperandName;
  1486. }
  1487. /// buildAliasOperandReference - When parsing an operand reference out of the
  1488. /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
  1489. /// operand reference is by looking it up in the result pattern definition.
  1490. void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
  1491. StringRef OperandName,
  1492. MatchableInfo::AsmOperand &Op) {
  1493. const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
  1494. // Set up the operand class.
  1495. for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
  1496. if (CGA.ResultOperands[i].isRecord() &&
  1497. CGA.ResultOperands[i].getName() == OperandName) {
  1498. // It's safe to go with the first one we find, because CodeGenInstAlias
  1499. // validates that all operands with the same name have the same record.
  1500. Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
  1501. // Use the match class from the Alias definition, not the
  1502. // destination instruction, as we may have an immediate that's
  1503. // being munged by the match class.
  1504. Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
  1505. Op.SubOpIdx);
  1506. Op.SrcOpName = OperandName;
  1507. Op.OrigSrcOpName = OperandName;
  1508. return;
  1509. }
  1510. PrintFatalError(II->TheDef->getLoc(),
  1511. "error: unable to find operand: '" + OperandName + "'");
  1512. }
  1513. void MatchableInfo::buildInstructionResultOperands() {
  1514. const CodeGenInstruction *ResultInst = getResultInst();
  1515. // Loop over all operands of the result instruction, determining how to
  1516. // populate them.
  1517. for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) {
  1518. // If this is a tied operand, just copy from the previously handled operand.
  1519. int TiedOp = -1;
  1520. if (OpInfo.MINumOperands == 1)
  1521. TiedOp = OpInfo.getTiedRegister();
  1522. if (TiedOp != -1) {
  1523. int TiedSrcOperand = findAsmOperandOriginallyNamed(OpInfo.Name);
  1524. if (TiedSrcOperand != -1 &&
  1525. ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand)
  1526. ResOperands.push_back(ResOperand::getTiedOp(
  1527. TiedOp, ResOperands[TiedOp].AsmOperandNum, TiedSrcOperand));
  1528. else
  1529. ResOperands.push_back(ResOperand::getTiedOp(TiedOp, 0, 0));
  1530. continue;
  1531. }
  1532. int SrcOperand = findAsmOperandNamed(OpInfo.Name);
  1533. if (OpInfo.Name.empty() || SrcOperand == -1) {
  1534. // This may happen for operands that are tied to a suboperand of a
  1535. // complex operand. Simply use a dummy value here; nobody should
  1536. // use this operand slot.
  1537. // FIXME: The long term goal is for the MCOperand list to not contain
  1538. // tied operands at all.
  1539. ResOperands.push_back(ResOperand::getImmOp(0));
  1540. continue;
  1541. }
  1542. // Check if the one AsmOperand populates the entire operand.
  1543. unsigned NumOperands = OpInfo.MINumOperands;
  1544. if (AsmOperands[SrcOperand].SubOpIdx == -1) {
  1545. ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
  1546. continue;
  1547. }
  1548. // Add a separate ResOperand for each suboperand.
  1549. for (unsigned AI = 0; AI < NumOperands; ++AI) {
  1550. assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
  1551. AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
  1552. "unexpected AsmOperands for suboperands");
  1553. ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
  1554. }
  1555. }
  1556. }
  1557. void MatchableInfo::buildAliasResultOperands(bool AliasConstraintsAreChecked) {
  1558. const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
  1559. const CodeGenInstruction *ResultInst = getResultInst();
  1560. // Map of: $reg -> #lastref
  1561. // where $reg is the name of the operand in the asm string
  1562. // where #lastref is the last processed index where $reg was referenced in
  1563. // the asm string.
  1564. SmallDenseMap<StringRef, int> OperandRefs;
  1565. // Loop over all operands of the result instruction, determining how to
  1566. // populate them.
  1567. unsigned AliasOpNo = 0;
  1568. unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
  1569. for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
  1570. const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
  1571. // If this is a tied operand, just copy from the previously handled operand.
  1572. int TiedOp = -1;
  1573. if (OpInfo->MINumOperands == 1)
  1574. TiedOp = OpInfo->getTiedRegister();
  1575. if (TiedOp != -1) {
  1576. unsigned SrcOp1 = 0;
  1577. unsigned SrcOp2 = 0;
  1578. // If an operand has been specified twice in the asm string,
  1579. // add the two source operand's indices to the TiedOp so that
  1580. // at runtime the 'tied' constraint is checked.
  1581. if (ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand) {
  1582. SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
  1583. // Find the next operand (similarly named operand) in the string.
  1584. StringRef Name = AsmOperands[SrcOp1].SrcOpName;
  1585. auto Insert = OperandRefs.try_emplace(Name, SrcOp1);
  1586. SrcOp2 = findAsmOperandNamed(Name, Insert.first->second);
  1587. // Not updating the record in OperandRefs will cause TableGen
  1588. // to fail with an error at the end of this function.
  1589. if (AliasConstraintsAreChecked)
  1590. Insert.first->second = SrcOp2;
  1591. // In case it only has one reference in the asm string,
  1592. // it doesn't need to be checked for tied constraints.
  1593. SrcOp2 = (SrcOp2 == (unsigned)-1) ? SrcOp1 : SrcOp2;
  1594. }
  1595. // If the alias operand is of a different operand class, we only want
  1596. // to benefit from the tied-operands check and just match the operand
  1597. // as a normal, but not copy the original (TiedOp) to the result
  1598. // instruction. We do this by passing -1 as the tied operand to copy.
  1599. if (ResultInst->Operands[i].Rec->getName() !=
  1600. ResultInst->Operands[TiedOp].Rec->getName()) {
  1601. SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
  1602. int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
  1603. StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
  1604. SrcOp2 = findAsmOperand(Name, SubIdx);
  1605. ResOperands.push_back(
  1606. ResOperand::getTiedOp((unsigned)-1, SrcOp1, SrcOp2));
  1607. } else {
  1608. ResOperands.push_back(ResOperand::getTiedOp(TiedOp, SrcOp1, SrcOp2));
  1609. continue;
  1610. }
  1611. }
  1612. // Handle all the suboperands for this operand.
  1613. const std::string &OpName = OpInfo->Name;
  1614. for ( ; AliasOpNo < LastOpNo &&
  1615. CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
  1616. int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
  1617. // Find out what operand from the asmparser that this MCInst operand
  1618. // comes from.
  1619. switch (CGA.ResultOperands[AliasOpNo].Kind) {
  1620. case CodeGenInstAlias::ResultOperand::K_Record: {
  1621. StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
  1622. int SrcOperand = findAsmOperand(Name, SubIdx);
  1623. if (SrcOperand == -1)
  1624. PrintFatalError(TheDef->getLoc(), "Instruction '" +
  1625. TheDef->getName() + "' has operand '" + OpName +
  1626. "' that doesn't appear in asm string!");
  1627. // Add it to the operand references. If it is added a second time, the
  1628. // record won't be updated and it will fail later on.
  1629. OperandRefs.try_emplace(Name, SrcOperand);
  1630. unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
  1631. ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
  1632. NumOperands));
  1633. break;
  1634. }
  1635. case CodeGenInstAlias::ResultOperand::K_Imm: {
  1636. int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
  1637. ResOperands.push_back(ResOperand::getImmOp(ImmVal));
  1638. break;
  1639. }
  1640. case CodeGenInstAlias::ResultOperand::K_Reg: {
  1641. Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
  1642. ResOperands.push_back(ResOperand::getRegOp(Reg));
  1643. break;
  1644. }
  1645. }
  1646. }
  1647. }
  1648. // Check that operands are not repeated more times than is supported.
  1649. for (auto &T : OperandRefs) {
  1650. if (T.second != -1 && findAsmOperandNamed(T.first, T.second) != -1)
  1651. PrintFatalError(TheDef->getLoc(),
  1652. "Operand '" + T.first + "' can never be matched");
  1653. }
  1654. }
  1655. static unsigned
  1656. getConverterOperandID(const std::string &Name,
  1657. SmallSetVector<CachedHashString, 16> &Table,
  1658. bool &IsNew) {
  1659. IsNew = Table.insert(CachedHashString(Name));
  1660. unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin();
  1661. assert(ID < Table.size());
  1662. return ID;
  1663. }
  1664. static unsigned
  1665. emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
  1666. std::vector<std::unique_ptr<MatchableInfo>> &Infos,
  1667. bool HasMnemonicFirst, bool HasOptionalOperands,
  1668. raw_ostream &OS) {
  1669. SmallSetVector<CachedHashString, 16> OperandConversionKinds;
  1670. SmallSetVector<CachedHashString, 16> InstructionConversionKinds;
  1671. std::vector<std::vector<uint8_t> > ConversionTable;
  1672. size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
  1673. // TargetOperandClass - This is the target's operand class, like X86Operand.
  1674. std::string TargetOperandClass = Target.getName().str() + "Operand";
  1675. // Write the convert function to a separate stream, so we can drop it after
  1676. // the enum. We'll build up the conversion handlers for the individual
  1677. // operand types opportunistically as we encounter them.
  1678. std::string ConvertFnBody;
  1679. raw_string_ostream CvtOS(ConvertFnBody);
  1680. // Start the unified conversion function.
  1681. if (HasOptionalOperands) {
  1682. CvtOS << "void " << Target.getName() << ClassName << "::\n"
  1683. << "convertToMCInst(unsigned Kind, MCInst &Inst, "
  1684. << "unsigned Opcode,\n"
  1685. << " const OperandVector &Operands,\n"
  1686. << " const SmallBitVector &OptionalOperandsMask) {\n";
  1687. } else {
  1688. CvtOS << "void " << Target.getName() << ClassName << "::\n"
  1689. << "convertToMCInst(unsigned Kind, MCInst &Inst, "
  1690. << "unsigned Opcode,\n"
  1691. << " const OperandVector &Operands) {\n";
  1692. }
  1693. CvtOS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
  1694. CvtOS << " const uint8_t *Converter = ConversionTable[Kind];\n";
  1695. if (HasOptionalOperands) {
  1696. size_t MaxNumOperands = 0;
  1697. for (const auto &MI : Infos) {
  1698. MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
  1699. }
  1700. CvtOS << " unsigned DefaultsOffset[" << (MaxNumOperands + 1)
  1701. << "] = { 0 };\n";
  1702. CvtOS << " assert(OptionalOperandsMask.size() == " << (MaxNumOperands)
  1703. << ");\n";
  1704. CvtOS << " for (unsigned i = 0, NumDefaults = 0; i < " << (MaxNumOperands)
  1705. << "; ++i) {\n";
  1706. CvtOS << " DefaultsOffset[i + 1] = NumDefaults;\n";
  1707. CvtOS << " NumDefaults += (OptionalOperandsMask[i] ? 1 : 0);\n";
  1708. CvtOS << " }\n";
  1709. }
  1710. CvtOS << " unsigned OpIdx;\n";
  1711. CvtOS << " Inst.setOpcode(Opcode);\n";
  1712. CvtOS << " for (const uint8_t *p = Converter; *p; p += 2) {\n";
  1713. if (HasOptionalOperands) {
  1714. CvtOS << " OpIdx = *(p + 1) - DefaultsOffset[*(p + 1)];\n";
  1715. } else {
  1716. CvtOS << " OpIdx = *(p + 1);\n";
  1717. }
  1718. CvtOS << " switch (*p) {\n";
  1719. CvtOS << " default: llvm_unreachable(\"invalid conversion entry!\");\n";
  1720. CvtOS << " case CVT_Reg:\n";
  1721. CvtOS << " static_cast<" << TargetOperandClass
  1722. << " &>(*Operands[OpIdx]).addRegOperands(Inst, 1);\n";
  1723. CvtOS << " break;\n";
  1724. CvtOS << " case CVT_Tied: {\n";
  1725. CvtOS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
  1726. CvtOS << " std::begin(TiedAsmOperandTable)) &&\n";
  1727. CvtOS << " \"Tied operand not found\");\n";
  1728. CvtOS << " unsigned TiedResOpnd = TiedAsmOperandTable[OpIdx][0];\n";
  1729. CvtOS << " if (TiedResOpnd != (uint8_t)-1)\n";
  1730. CvtOS << " Inst.addOperand(Inst.getOperand(TiedResOpnd));\n";
  1731. CvtOS << " break;\n";
  1732. CvtOS << " }\n";
  1733. std::string OperandFnBody;
  1734. raw_string_ostream OpOS(OperandFnBody);
  1735. // Start the operand number lookup function.
  1736. OpOS << "void " << Target.getName() << ClassName << "::\n"
  1737. << "convertToMapAndConstraints(unsigned Kind,\n";
  1738. OpOS.indent(27);
  1739. OpOS << "const OperandVector &Operands) {\n"
  1740. << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
  1741. << " unsigned NumMCOperands = 0;\n"
  1742. << " const uint8_t *Converter = ConversionTable[Kind];\n"
  1743. << " for (const uint8_t *p = Converter; *p; p += 2) {\n"
  1744. << " switch (*p) {\n"
  1745. << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
  1746. << " case CVT_Reg:\n"
  1747. << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
  1748. << " Operands[*(p + 1)]->setConstraint(\"r\");\n"
  1749. << " ++NumMCOperands;\n"
  1750. << " break;\n"
  1751. << " case CVT_Tied:\n"
  1752. << " ++NumMCOperands;\n"
  1753. << " break;\n";
  1754. // Pre-populate the operand conversion kinds with the standard always
  1755. // available entries.
  1756. OperandConversionKinds.insert(CachedHashString("CVT_Done"));
  1757. OperandConversionKinds.insert(CachedHashString("CVT_Reg"));
  1758. OperandConversionKinds.insert(CachedHashString("CVT_Tied"));
  1759. enum { CVT_Done, CVT_Reg, CVT_Tied };
  1760. // Map of e.g. <0, 2, 3> -> "Tie_0_2_3" enum label.
  1761. std::map<std::tuple<uint8_t, uint8_t, uint8_t>, std::string>
  1762. TiedOperandsEnumMap;
  1763. for (auto &II : Infos) {
  1764. // Check if we have a custom match function.
  1765. StringRef AsmMatchConverter =
  1766. II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
  1767. if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) {
  1768. std::string Signature = ("ConvertCustom_" + AsmMatchConverter).str();
  1769. II->ConversionFnKind = Signature;
  1770. // Check if we have already generated this signature.
  1771. if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
  1772. continue;
  1773. // Remember this converter for the kind enum.
  1774. unsigned KindID = OperandConversionKinds.size();
  1775. OperandConversionKinds.insert(
  1776. CachedHashString("CVT_" + getEnumNameForToken(AsmMatchConverter)));
  1777. // Add the converter row for this instruction.
  1778. ConversionTable.emplace_back();
  1779. ConversionTable.back().push_back(KindID);
  1780. ConversionTable.back().push_back(CVT_Done);
  1781. // Add the handler to the conversion driver function.
  1782. CvtOS << " case CVT_"
  1783. << getEnumNameForToken(AsmMatchConverter) << ":\n"
  1784. << " " << AsmMatchConverter << "(Inst, Operands);\n"
  1785. << " break;\n";
  1786. // FIXME: Handle the operand number lookup for custom match functions.
  1787. continue;
  1788. }
  1789. // Build the conversion function signature.
  1790. std::string Signature = "Convert";
  1791. std::vector<uint8_t> ConversionRow;
  1792. // Compute the convert enum and the case body.
  1793. MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 );
  1794. for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) {
  1795. const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i];
  1796. // Generate code to populate each result operand.
  1797. switch (OpInfo.Kind) {
  1798. case MatchableInfo::ResOperand::RenderAsmOperand: {
  1799. // This comes from something we parsed.
  1800. const MatchableInfo::AsmOperand &Op =
  1801. II->AsmOperands[OpInfo.AsmOperandNum];
  1802. // Registers are always converted the same, don't duplicate the
  1803. // conversion function based on them.
  1804. Signature += "__";
  1805. std::string Class;
  1806. Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
  1807. Signature += Class;
  1808. Signature += utostr(OpInfo.MINumOperands);
  1809. Signature += "_" + itostr(OpInfo.AsmOperandNum);
  1810. // Add the conversion kind, if necessary, and get the associated ID
  1811. // the index of its entry in the vector).
  1812. std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" :
  1813. Op.Class->RenderMethod);
  1814. if (Op.Class->IsOptional) {
  1815. // For optional operands we must also care about DefaultMethod
  1816. assert(HasOptionalOperands);
  1817. Name += "_" + Op.Class->DefaultMethod;
  1818. }
  1819. Name = getEnumNameForToken(Name);
  1820. bool IsNewConverter = false;
  1821. unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
  1822. IsNewConverter);
  1823. // Add the operand entry to the instruction kind conversion row.
  1824. ConversionRow.push_back(ID);
  1825. ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst);
  1826. if (!IsNewConverter)
  1827. break;
  1828. // This is a new operand kind. Add a handler for it to the
  1829. // converter driver.
  1830. CvtOS << " case " << Name << ":\n";
  1831. if (Op.Class->IsOptional) {
  1832. // If optional operand is not present in actual instruction then we
  1833. // should call its DefaultMethod before RenderMethod
  1834. assert(HasOptionalOperands);
  1835. CvtOS << " if (OptionalOperandsMask[*(p + 1) - 1]) {\n"
  1836. << " " << Op.Class->DefaultMethod << "()"
  1837. << "->" << Op.Class->RenderMethod << "(Inst, "
  1838. << OpInfo.MINumOperands << ");\n"
  1839. << " } else {\n"
  1840. << " static_cast<" << TargetOperandClass
  1841. << " &>(*Operands[OpIdx])." << Op.Class->RenderMethod
  1842. << "(Inst, " << OpInfo.MINumOperands << ");\n"
  1843. << " }\n";
  1844. } else {
  1845. CvtOS << " static_cast<" << TargetOperandClass
  1846. << " &>(*Operands[OpIdx])." << Op.Class->RenderMethod
  1847. << "(Inst, " << OpInfo.MINumOperands << ");\n";
  1848. }
  1849. CvtOS << " break;\n";
  1850. // Add a handler for the operand number lookup.
  1851. OpOS << " case " << Name << ":\n"
  1852. << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
  1853. if (Op.Class->isRegisterClass())
  1854. OpOS << " Operands[*(p + 1)]->setConstraint(\"r\");\n";
  1855. else
  1856. OpOS << " Operands[*(p + 1)]->setConstraint(\"m\");\n";
  1857. OpOS << " NumMCOperands += " << OpInfo.MINumOperands << ";\n"
  1858. << " break;\n";
  1859. break;
  1860. }
  1861. case MatchableInfo::ResOperand::TiedOperand: {
  1862. // If this operand is tied to a previous one, just copy the MCInst
  1863. // operand from the earlier one.We can only tie single MCOperand values.
  1864. assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
  1865. uint8_t TiedOp = OpInfo.TiedOperands.ResOpnd;
  1866. uint8_t SrcOp1 =
  1867. OpInfo.TiedOperands.SrcOpnd1Idx + HasMnemonicFirst;
  1868. uint8_t SrcOp2 =
  1869. OpInfo.TiedOperands.SrcOpnd2Idx + HasMnemonicFirst;
  1870. assert((i > TiedOp || TiedOp == (uint8_t)-1) &&
  1871. "Tied operand precedes its target!");
  1872. auto TiedTupleName = std::string("Tie") + utostr(TiedOp) + '_' +
  1873. utostr(SrcOp1) + '_' + utostr(SrcOp2);
  1874. Signature += "__" + TiedTupleName;
  1875. ConversionRow.push_back(CVT_Tied);
  1876. ConversionRow.push_back(TiedOp);
  1877. ConversionRow.push_back(SrcOp1);
  1878. ConversionRow.push_back(SrcOp2);
  1879. // Also create an 'enum' for this combination of tied operands.
  1880. auto Key = std::make_tuple(TiedOp, SrcOp1, SrcOp2);
  1881. TiedOperandsEnumMap.emplace(Key, TiedTupleName);
  1882. break;
  1883. }
  1884. case MatchableInfo::ResOperand::ImmOperand: {
  1885. int64_t Val = OpInfo.ImmVal;
  1886. std::string Ty = "imm_" + itostr(Val);
  1887. Ty = getEnumNameForToken(Ty);
  1888. Signature += "__" + Ty;
  1889. std::string Name = "CVT_" + Ty;
  1890. bool IsNewConverter = false;
  1891. unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
  1892. IsNewConverter);
  1893. // Add the operand entry to the instruction kind conversion row.
  1894. ConversionRow.push_back(ID);
  1895. ConversionRow.push_back(0);
  1896. if (!IsNewConverter)
  1897. break;
  1898. CvtOS << " case " << Name << ":\n"
  1899. << " Inst.addOperand(MCOperand::createImm(" << Val << "));\n"
  1900. << " break;\n";
  1901. OpOS << " case " << Name << ":\n"
  1902. << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
  1903. << " Operands[*(p + 1)]->setConstraint(\"\");\n"
  1904. << " ++NumMCOperands;\n"
  1905. << " break;\n";
  1906. break;
  1907. }
  1908. case MatchableInfo::ResOperand::RegOperand: {
  1909. std::string Reg, Name;
  1910. if (!OpInfo.Register) {
  1911. Name = "reg0";
  1912. Reg = "0";
  1913. } else {
  1914. Reg = getQualifiedName(OpInfo.Register);
  1915. Name = "reg" + OpInfo.Register->getName().str();
  1916. }
  1917. Signature += "__" + Name;
  1918. Name = "CVT_" + Name;
  1919. bool IsNewConverter = false;
  1920. unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
  1921. IsNewConverter);
  1922. // Add the operand entry to the instruction kind conversion row.
  1923. ConversionRow.push_back(ID);
  1924. ConversionRow.push_back(0);
  1925. if (!IsNewConverter)
  1926. break;
  1927. CvtOS << " case " << Name << ":\n"
  1928. << " Inst.addOperand(MCOperand::createReg(" << Reg << "));\n"
  1929. << " break;\n";
  1930. OpOS << " case " << Name << ":\n"
  1931. << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
  1932. << " Operands[*(p + 1)]->setConstraint(\"m\");\n"
  1933. << " ++NumMCOperands;\n"
  1934. << " break;\n";
  1935. }
  1936. }
  1937. }
  1938. // If there were no operands, add to the signature to that effect
  1939. if (Signature == "Convert")
  1940. Signature += "_NoOperands";
  1941. II->ConversionFnKind = Signature;
  1942. // Save the signature. If we already have it, don't add a new row
  1943. // to the table.
  1944. if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
  1945. continue;
  1946. // Add the row to the table.
  1947. ConversionTable.push_back(std::move(ConversionRow));
  1948. }
  1949. // Finish up the converter driver function.
  1950. CvtOS << " }\n }\n}\n\n";
  1951. // Finish up the operand number lookup function.
  1952. OpOS << " }\n }\n}\n\n";
  1953. // Output a static table for tied operands.
  1954. if (TiedOperandsEnumMap.size()) {
  1955. // The number of tied operand combinations will be small in practice,
  1956. // but just add the assert to be sure.
  1957. assert(TiedOperandsEnumMap.size() <= 254 &&
  1958. "Too many tied-operand combinations to reference with "
  1959. "an 8bit offset from the conversion table, where index "
  1960. "'255' is reserved as operand not to be copied.");
  1961. OS << "enum {\n";
  1962. for (auto &KV : TiedOperandsEnumMap) {
  1963. OS << " " << KV.second << ",\n";
  1964. }
  1965. OS << "};\n\n";
  1966. OS << "static const uint8_t TiedAsmOperandTable[][3] = {\n";
  1967. for (auto &KV : TiedOperandsEnumMap) {
  1968. OS << " /* " << KV.second << " */ { "
  1969. << utostr(std::get<0>(KV.first)) << ", "
  1970. << utostr(std::get<1>(KV.first)) << ", "
  1971. << utostr(std::get<2>(KV.first)) << " },\n";
  1972. }
  1973. OS << "};\n\n";
  1974. } else
  1975. OS << "static const uint8_t TiedAsmOperandTable[][3] = "
  1976. "{ /* empty */ {0, 0, 0} };\n\n";
  1977. OS << "namespace {\n";
  1978. // Output the operand conversion kind enum.
  1979. OS << "enum OperatorConversionKind {\n";
  1980. for (const auto &Converter : OperandConversionKinds)
  1981. OS << " " << Converter << ",\n";
  1982. OS << " CVT_NUM_CONVERTERS\n";
  1983. OS << "};\n\n";
  1984. // Output the instruction conversion kind enum.
  1985. OS << "enum InstructionConversionKind {\n";
  1986. for (const auto &Signature : InstructionConversionKinds)
  1987. OS << " " << Signature << ",\n";
  1988. OS << " CVT_NUM_SIGNATURES\n";
  1989. OS << "};\n\n";
  1990. OS << "} // end anonymous namespace\n\n";
  1991. // Output the conversion table.
  1992. OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
  1993. << MaxRowLength << "] = {\n";
  1994. for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) {
  1995. assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!");
  1996. OS << " // " << InstructionConversionKinds[Row] << "\n";
  1997. OS << " { ";
  1998. for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2) {
  1999. OS << OperandConversionKinds[ConversionTable[Row][i]] << ", ";
  2000. if (OperandConversionKinds[ConversionTable[Row][i]] !=
  2001. CachedHashString("CVT_Tied")) {
  2002. OS << (unsigned)(ConversionTable[Row][i + 1]) << ", ";
  2003. continue;
  2004. }
  2005. // For a tied operand, emit a reference to the TiedAsmOperandTable
  2006. // that contains the operand to copy, and the parsed operands to
  2007. // check for their tied constraints.
  2008. auto Key = std::make_tuple((uint8_t)ConversionTable[Row][i + 1],
  2009. (uint8_t)ConversionTable[Row][i + 2],
  2010. (uint8_t)ConversionTable[Row][i + 3]);
  2011. auto TiedOpndEnum = TiedOperandsEnumMap.find(Key);
  2012. assert(TiedOpndEnum != TiedOperandsEnumMap.end() &&
  2013. "No record for tied operand pair");
  2014. OS << TiedOpndEnum->second << ", ";
  2015. i += 2;
  2016. }
  2017. OS << "CVT_Done },\n";
  2018. }
  2019. OS << "};\n\n";
  2020. // Spit out the conversion driver function.
  2021. OS << CvtOS.str();
  2022. // Spit out the operand number lookup function.
  2023. OS << OpOS.str();
  2024. return ConversionTable.size();
  2025. }
  2026. /// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
  2027. static void emitMatchClassEnumeration(CodeGenTarget &Target,
  2028. std::forward_list<ClassInfo> &Infos,
  2029. raw_ostream &OS) {
  2030. OS << "namespace {\n\n";
  2031. OS << "/// MatchClassKind - The kinds of classes which participate in\n"
  2032. << "/// instruction matching.\n";
  2033. OS << "enum MatchClassKind {\n";
  2034. OS << " InvalidMatchClass = 0,\n";
  2035. OS << " OptionalMatchClass = 1,\n";
  2036. ClassInfo::ClassInfoKind LastKind = ClassInfo::Token;
  2037. StringRef LastName = "OptionalMatchClass";
  2038. for (const auto &CI : Infos) {
  2039. if (LastKind == ClassInfo::Token && CI.Kind != ClassInfo::Token) {
  2040. OS << " MCK_LAST_TOKEN = " << LastName << ",\n";
  2041. } else if (LastKind < ClassInfo::UserClass0 &&
  2042. CI.Kind >= ClassInfo::UserClass0) {
  2043. OS << " MCK_LAST_REGISTER = " << LastName << ",\n";
  2044. }
  2045. LastKind = (ClassInfo::ClassInfoKind)CI.Kind;
  2046. LastName = CI.Name;
  2047. OS << " " << CI.Name << ", // ";
  2048. if (CI.Kind == ClassInfo::Token) {
  2049. OS << "'" << CI.ValueName << "'\n";
  2050. } else if (CI.isRegisterClass()) {
  2051. if (!CI.ValueName.empty())
  2052. OS << "register class '" << CI.ValueName << "'\n";
  2053. else
  2054. OS << "derived register class\n";
  2055. } else {
  2056. OS << "user defined class '" << CI.ValueName << "'\n";
  2057. }
  2058. }
  2059. OS << " NumMatchClassKinds\n";
  2060. OS << "};\n\n";
  2061. OS << "} // end anonymous namespace\n\n";
  2062. }
  2063. /// emitMatchClassDiagStrings - Emit a function to get the diagnostic text to be
  2064. /// used when an assembly operand does not match the expected operand class.
  2065. static void emitOperandMatchErrorDiagStrings(AsmMatcherInfo &Info, raw_ostream &OS) {
  2066. // If the target does not use DiagnosticString for any operands, don't emit
  2067. // an unused function.
  2068. if (llvm::all_of(Info.Classes, [](const ClassInfo &CI) {
  2069. return CI.DiagnosticString.empty();
  2070. }))
  2071. return;
  2072. OS << "static const char *getMatchKindDiag(" << Info.Target.getName()
  2073. << "AsmParser::" << Info.Target.getName()
  2074. << "MatchResultTy MatchResult) {\n";
  2075. OS << " switch (MatchResult) {\n";
  2076. for (const auto &CI: Info.Classes) {
  2077. if (!CI.DiagnosticString.empty()) {
  2078. assert(!CI.DiagnosticType.empty() &&
  2079. "DiagnosticString set without DiagnosticType");
  2080. OS << " case " << Info.Target.getName()
  2081. << "AsmParser::Match_" << CI.DiagnosticType << ":\n";
  2082. OS << " return \"" << CI.DiagnosticString << "\";\n";
  2083. }
  2084. }
  2085. OS << " default:\n";
  2086. OS << " return nullptr;\n";
  2087. OS << " }\n";
  2088. OS << "}\n\n";
  2089. }
  2090. static void emitRegisterMatchErrorFunc(AsmMatcherInfo &Info, raw_ostream &OS) {
  2091. OS << "static unsigned getDiagKindFromRegisterClass(MatchClassKind "
  2092. "RegisterClass) {\n";
  2093. if (none_of(Info.Classes, [](const ClassInfo &CI) {
  2094. return CI.isRegisterClass() && !CI.DiagnosticType.empty();
  2095. })) {
  2096. OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
  2097. } else {
  2098. OS << " switch (RegisterClass) {\n";
  2099. for (const auto &CI: Info.Classes) {
  2100. if (CI.isRegisterClass() && !CI.DiagnosticType.empty()) {
  2101. OS << " case " << CI.Name << ":\n";
  2102. OS << " return " << Info.Target.getName() << "AsmParser::Match_"
  2103. << CI.DiagnosticType << ";\n";
  2104. }
  2105. }
  2106. OS << " default:\n";
  2107. OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
  2108. OS << " }\n";
  2109. }
  2110. OS << "}\n\n";
  2111. }
  2112. /// emitValidateOperandClass - Emit the function to validate an operand class.
  2113. static void emitValidateOperandClass(AsmMatcherInfo &Info,
  2114. raw_ostream &OS) {
  2115. OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
  2116. << "MatchClassKind Kind) {\n";
  2117. OS << " " << Info.Target.getName() << "Operand &Operand = ("
  2118. << Info.Target.getName() << "Operand &)GOp;\n";
  2119. // The InvalidMatchClass is not to match any operand.
  2120. OS << " if (Kind == InvalidMatchClass)\n";
  2121. OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
  2122. // Check for Token operands first.
  2123. // FIXME: Use a more specific diagnostic type.
  2124. OS << " if (Operand.isToken() && Kind <= MCK_LAST_TOKEN)\n";
  2125. OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
  2126. << " MCTargetAsmParser::Match_Success :\n"
  2127. << " MCTargetAsmParser::Match_InvalidOperand;\n\n";
  2128. // Check the user classes. We don't care what order since we're only
  2129. // actually matching against one of them.
  2130. OS << " switch (Kind) {\n"
  2131. " default: break;\n";
  2132. for (const auto &CI : Info.Classes) {
  2133. if (!CI.isUserClass())
  2134. continue;
  2135. OS << " // '" << CI.ClassName << "' class\n";
  2136. OS << " case " << CI.Name << ": {\n";
  2137. OS << " DiagnosticPredicate DP(Operand." << CI.PredicateMethod
  2138. << "());\n";
  2139. OS << " if (DP.isMatch())\n";
  2140. OS << " return MCTargetAsmParser::Match_Success;\n";
  2141. if (!CI.DiagnosticType.empty()) {
  2142. OS << " if (DP.isNearMatch())\n";
  2143. OS << " return " << Info.Target.getName() << "AsmParser::Match_"
  2144. << CI.DiagnosticType << ";\n";
  2145. OS << " break;\n";
  2146. }
  2147. else
  2148. OS << " break;\n";
  2149. OS << " }\n";
  2150. }
  2151. OS << " } // end switch (Kind)\n\n";
  2152. // Check for register operands, including sub-classes.
  2153. OS << " if (Operand.isReg()) {\n";
  2154. OS << " MatchClassKind OpKind;\n";
  2155. OS << " switch (Operand.getReg()) {\n";
  2156. OS << " default: OpKind = InvalidMatchClass; break;\n";
  2157. for (const auto &RC : Info.RegisterClasses)
  2158. OS << " case " << RC.first->getValueAsString("Namespace") << "::"
  2159. << RC.first->getName() << ": OpKind = " << RC.second->Name
  2160. << "; break;\n";
  2161. OS << " }\n";
  2162. OS << " return isSubclass(OpKind, Kind) ? "
  2163. << "(unsigned)MCTargetAsmParser::Match_Success :\n "
  2164. << " getDiagKindFromRegisterClass(Kind);\n }\n\n";
  2165. // Expected operand is a register, but actual is not.
  2166. OS << " if (Kind > MCK_LAST_TOKEN && Kind <= MCK_LAST_REGISTER)\n";
  2167. OS << " return getDiagKindFromRegisterClass(Kind);\n\n";
  2168. // Generic fallthrough match failure case for operands that don't have
  2169. // specialized diagnostic types.
  2170. OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
  2171. OS << "}\n\n";
  2172. }
  2173. /// emitIsSubclass - Emit the subclass predicate function.
  2174. static void emitIsSubclass(CodeGenTarget &Target,
  2175. std::forward_list<ClassInfo> &Infos,
  2176. raw_ostream &OS) {
  2177. OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
  2178. OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
  2179. OS << " if (A == B)\n";
  2180. OS << " return true;\n\n";
  2181. bool EmittedSwitch = false;
  2182. for (const auto &A : Infos) {
  2183. std::vector<StringRef> SuperClasses;
  2184. if (A.IsOptional)
  2185. SuperClasses.push_back("OptionalMatchClass");
  2186. for (const auto &B : Infos) {
  2187. if (&A != &B && A.isSubsetOf(B))
  2188. SuperClasses.push_back(B.Name);
  2189. }
  2190. if (SuperClasses.empty())
  2191. continue;
  2192. // If this is the first SuperClass, emit the switch header.
  2193. if (!EmittedSwitch) {
  2194. OS << " switch (A) {\n";
  2195. OS << " default:\n";
  2196. OS << " return false;\n";
  2197. EmittedSwitch = true;
  2198. }
  2199. OS << "\n case " << A.Name << ":\n";
  2200. if (SuperClasses.size() == 1) {
  2201. OS << " return B == " << SuperClasses.back() << ";\n";
  2202. continue;
  2203. }
  2204. if (!SuperClasses.empty()) {
  2205. OS << " switch (B) {\n";
  2206. OS << " default: return false;\n";
  2207. for (StringRef SC : SuperClasses)
  2208. OS << " case " << SC << ": return true;\n";
  2209. OS << " }\n";
  2210. } else {
  2211. // No case statement to emit
  2212. OS << " return false;\n";
  2213. }
  2214. }
  2215. // If there were case statements emitted into the string stream write the
  2216. // default.
  2217. if (EmittedSwitch)
  2218. OS << " }\n";
  2219. else
  2220. OS << " return false;\n";
  2221. OS << "}\n\n";
  2222. }
  2223. /// emitMatchTokenString - Emit the function to match a token string to the
  2224. /// appropriate match class value.
  2225. static void emitMatchTokenString(CodeGenTarget &Target,
  2226. std::forward_list<ClassInfo> &Infos,
  2227. raw_ostream &OS) {
  2228. // Construct the match list.
  2229. std::vector<StringMatcher::StringPair> Matches;
  2230. for (const auto &CI : Infos) {
  2231. if (CI.Kind == ClassInfo::Token)
  2232. Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";");
  2233. }
  2234. OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
  2235. StringMatcher("Name", Matches, OS).Emit();
  2236. OS << " return InvalidMatchClass;\n";
  2237. OS << "}\n\n";
  2238. }
  2239. /// emitMatchRegisterName - Emit the function to match a string to the target
  2240. /// specific register enum.
  2241. static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
  2242. raw_ostream &OS) {
  2243. // Construct the match list.
  2244. std::vector<StringMatcher::StringPair> Matches;
  2245. const auto &Regs = Target.getRegBank().getRegisters();
  2246. for (const CodeGenRegister &Reg : Regs) {
  2247. if (Reg.TheDef->getValueAsString("AsmName").empty())
  2248. continue;
  2249. Matches.emplace_back(std::string(Reg.TheDef->getValueAsString("AsmName")),
  2250. "return " + utostr(Reg.EnumValue) + ";");
  2251. }
  2252. OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
  2253. bool IgnoreDuplicates =
  2254. AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
  2255. StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
  2256. OS << " return 0;\n";
  2257. OS << "}\n\n";
  2258. }
  2259. /// Emit the function to match a string to the target
  2260. /// specific register enum.
  2261. static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser,
  2262. raw_ostream &OS) {
  2263. // Construct the match list.
  2264. std::vector<StringMatcher::StringPair> Matches;
  2265. const auto &Regs = Target.getRegBank().getRegisters();
  2266. for (const CodeGenRegister &Reg : Regs) {
  2267. auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames");
  2268. for (auto AltName : AltNames) {
  2269. AltName = StringRef(AltName).trim();
  2270. // don't handle empty alternative names
  2271. if (AltName.empty())
  2272. continue;
  2273. Matches.emplace_back(std::string(AltName),
  2274. "return " + utostr(Reg.EnumValue) + ";");
  2275. }
  2276. }
  2277. OS << "static unsigned MatchRegisterAltName(StringRef Name) {\n";
  2278. bool IgnoreDuplicates =
  2279. AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
  2280. StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
  2281. OS << " return 0;\n";
  2282. OS << "}\n\n";
  2283. }
  2284. /// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
  2285. static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
  2286. // Get the set of diagnostic types from all of the operand classes.
  2287. std::set<StringRef> Types;
  2288. for (const auto &OpClassEntry : Info.AsmOperandClasses) {
  2289. if (!OpClassEntry.second->DiagnosticType.empty())
  2290. Types.insert(OpClassEntry.second->DiagnosticType);
  2291. }
  2292. for (const auto &OpClassEntry : Info.RegisterClassClasses) {
  2293. if (!OpClassEntry.second->DiagnosticType.empty())
  2294. Types.insert(OpClassEntry.second->DiagnosticType);
  2295. }
  2296. if (Types.empty()) return;
  2297. // Now emit the enum entries.
  2298. for (StringRef Type : Types)
  2299. OS << " Match_" << Type << ",\n";
  2300. OS << " END_OPERAND_DIAGNOSTIC_TYPES\n";
  2301. }
  2302. /// emitGetSubtargetFeatureName - Emit the helper function to get the
  2303. /// user-level name for a subtarget feature.
  2304. static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
  2305. OS << "// User-level names for subtarget features that participate in\n"
  2306. << "// instruction matching.\n"
  2307. << "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
  2308. if (!Info.SubtargetFeatures.empty()) {
  2309. OS << " switch(Val) {\n";
  2310. for (const auto &SF : Info.SubtargetFeatures) {
  2311. const SubtargetFeatureInfo &SFI = SF.second;
  2312. // FIXME: Totally just a placeholder name to get the algorithm working.
  2313. OS << " case " << SFI.getEnumBitName() << ": return \""
  2314. << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
  2315. }
  2316. OS << " default: return \"(unknown)\";\n";
  2317. OS << " }\n";
  2318. } else {
  2319. // Nothing to emit, so skip the switch
  2320. OS << " return \"(unknown)\";\n";
  2321. }
  2322. OS << "}\n\n";
  2323. }
  2324. static std::string GetAliasRequiredFeatures(Record *R,
  2325. const AsmMatcherInfo &Info) {
  2326. std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
  2327. std::string Result;
  2328. if (ReqFeatures.empty())
  2329. return Result;
  2330. for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
  2331. const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
  2332. if (!F)
  2333. PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
  2334. "' is not marked as an AssemblerPredicate!");
  2335. if (i)
  2336. Result += " && ";
  2337. Result += "Features.test(" + F->getEnumBitName() + ')';
  2338. }
  2339. return Result;
  2340. }
  2341. static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
  2342. std::vector<Record*> &Aliases,
  2343. unsigned Indent = 0,
  2344. StringRef AsmParserVariantName = StringRef()){
  2345. // Keep track of all the aliases from a mnemonic. Use an std::map so that the
  2346. // iteration order of the map is stable.
  2347. std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
  2348. for (Record *R : Aliases) {
  2349. // FIXME: Allow AssemblerVariantName to be a comma separated list.
  2350. StringRef AsmVariantName = R->getValueAsString("AsmVariantName");
  2351. if (AsmVariantName != AsmParserVariantName)
  2352. continue;
  2353. AliasesFromMnemonic[R->getValueAsString("FromMnemonic").lower()]
  2354. .push_back(R);
  2355. }
  2356. if (AliasesFromMnemonic.empty())
  2357. return;
  2358. // Process each alias a "from" mnemonic at a time, building the code executed
  2359. // by the string remapper.
  2360. std::vector<StringMatcher::StringPair> Cases;
  2361. for (const auto &AliasEntry : AliasesFromMnemonic) {
  2362. const std::vector<Record*> &ToVec = AliasEntry.second;
  2363. // Loop through each alias and emit code that handles each case. If there
  2364. // are two instructions without predicates, emit an error. If there is one,
  2365. // emit it last.
  2366. std::string MatchCode;
  2367. int AliasWithNoPredicate = -1;
  2368. for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
  2369. Record *R = ToVec[i];
  2370. std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
  2371. // If this unconditionally matches, remember it for later and diagnose
  2372. // duplicates.
  2373. if (FeatureMask.empty()) {
  2374. if (AliasWithNoPredicate != -1 &&
  2375. R->getValueAsString("ToMnemonic") !=
  2376. ToVec[AliasWithNoPredicate]->getValueAsString("ToMnemonic")) {
  2377. // We can't have two different aliases from the same mnemonic with no
  2378. // predicate.
  2379. PrintError(
  2380. ToVec[AliasWithNoPredicate]->getLoc(),
  2381. "two different MnemonicAliases with the same 'from' mnemonic!");
  2382. PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
  2383. }
  2384. AliasWithNoPredicate = i;
  2385. continue;
  2386. }
  2387. if (R->getValueAsString("ToMnemonic") == AliasEntry.first)
  2388. PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
  2389. if (!MatchCode.empty())
  2390. MatchCode += "else ";
  2391. MatchCode += "if (" + FeatureMask + ")\n";
  2392. MatchCode += " Mnemonic = \"";
  2393. MatchCode += R->getValueAsString("ToMnemonic").lower();
  2394. MatchCode += "\";\n";
  2395. }
  2396. if (AliasWithNoPredicate != -1) {
  2397. Record *R = ToVec[AliasWithNoPredicate];
  2398. if (!MatchCode.empty())
  2399. MatchCode += "else\n ";
  2400. MatchCode += "Mnemonic = \"";
  2401. MatchCode += R->getValueAsString("ToMnemonic").lower();
  2402. MatchCode += "\";\n";
  2403. }
  2404. MatchCode += "return;";
  2405. Cases.push_back(std::make_pair(AliasEntry.first, MatchCode));
  2406. }
  2407. StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
  2408. }
  2409. /// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
  2410. /// emit a function for them and return true, otherwise return false.
  2411. static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
  2412. CodeGenTarget &Target) {
  2413. // Ignore aliases when match-prefix is set.
  2414. if (!MatchPrefix.empty())
  2415. return false;
  2416. std::vector<Record*> Aliases =
  2417. Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
  2418. if (Aliases.empty()) return false;
  2419. OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
  2420. "const FeatureBitset &Features, unsigned VariantID) {\n";
  2421. OS << " switch (VariantID) {\n";
  2422. unsigned VariantCount = Target.getAsmParserVariantCount();
  2423. for (unsigned VC = 0; VC != VariantCount; ++VC) {
  2424. Record *AsmVariant = Target.getAsmParserVariant(VC);
  2425. int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
  2426. StringRef AsmParserVariantName = AsmVariant->getValueAsString("Name");
  2427. OS << " case " << AsmParserVariantNo << ":\n";
  2428. emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
  2429. AsmParserVariantName);
  2430. OS << " break;\n";
  2431. }
  2432. OS << " }\n";
  2433. // Emit aliases that apply to all variants.
  2434. emitMnemonicAliasVariant(OS, Info, Aliases);
  2435. OS << "}\n\n";
  2436. return true;
  2437. }
  2438. static void
  2439. emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
  2440. const AsmMatcherInfo &Info, StringRef ClassName,
  2441. StringToOffsetTable &StringTable,
  2442. unsigned MaxMnemonicIndex, unsigned MaxFeaturesIndex,
  2443. bool HasMnemonicFirst, const Record &AsmParser) {
  2444. unsigned MaxMask = 0;
  2445. for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
  2446. MaxMask |= OMI.OperandMask;
  2447. }
  2448. // Emit the static custom operand parsing table;
  2449. OS << "namespace {\n";
  2450. OS << " struct OperandMatchEntry {\n";
  2451. OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
  2452. << " Mnemonic;\n";
  2453. OS << " " << getMinimalTypeForRange(MaxMask)
  2454. << " OperandMask;\n";
  2455. OS << " " << getMinimalTypeForRange(std::distance(
  2456. Info.Classes.begin(), Info.Classes.end())) << " Class;\n";
  2457. OS << " " << getMinimalTypeForRange(MaxFeaturesIndex)
  2458. << " RequiredFeaturesIdx;\n\n";
  2459. OS << " StringRef getMnemonic() const {\n";
  2460. OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
  2461. OS << " MnemonicTable[Mnemonic]);\n";
  2462. OS << " }\n";
  2463. OS << " };\n\n";
  2464. OS << " // Predicate for searching for an opcode.\n";
  2465. OS << " struct LessOpcodeOperand {\n";
  2466. OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
  2467. OS << " return LHS.getMnemonic() < RHS;\n";
  2468. OS << " }\n";
  2469. OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
  2470. OS << " return LHS < RHS.getMnemonic();\n";
  2471. OS << " }\n";
  2472. OS << " bool operator()(const OperandMatchEntry &LHS,";
  2473. OS << " const OperandMatchEntry &RHS) {\n";
  2474. OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
  2475. OS << " }\n";
  2476. OS << " };\n";
  2477. OS << "} // end anonymous namespace\n\n";
  2478. OS << "static const OperandMatchEntry OperandMatchTable["
  2479. << Info.OperandMatchInfo.size() << "] = {\n";
  2480. OS << " /* Operand List Mnemonic, Mask, Operand Class, Features */\n";
  2481. for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
  2482. const MatchableInfo &II = *OMI.MI;
  2483. OS << " { ";
  2484. // Store a pascal-style length byte in the mnemonic.
  2485. std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.lower();
  2486. OS << StringTable.GetOrAddStringOffset(LenMnemonic, false)
  2487. << " /* " << II.Mnemonic << " */, ";
  2488. OS << OMI.OperandMask;
  2489. OS << " /* ";
  2490. ListSeparator LS;
  2491. for (int i = 0, e = 31; i !=e; ++i)
  2492. if (OMI.OperandMask & (1 << i))
  2493. OS << LS << i;
  2494. OS << " */, ";
  2495. OS << OMI.CI->Name;
  2496. // Write the required features mask.
  2497. OS << ", AMFBS";
  2498. if (II.RequiredFeatures.empty())
  2499. OS << "_None";
  2500. else
  2501. for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i)
  2502. OS << '_' << II.RequiredFeatures[i]->TheDef->getName();
  2503. OS << " },\n";
  2504. }
  2505. OS << "};\n\n";
  2506. // Emit the operand class switch to call the correct custom parser for
  2507. // the found operand class.
  2508. OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
  2509. << "tryCustomParseOperand(OperandVector"
  2510. << " &Operands,\n unsigned MCK) {\n\n"
  2511. << " switch(MCK) {\n";
  2512. for (const auto &CI : Info.Classes) {
  2513. if (CI.ParserMethod.empty())
  2514. continue;
  2515. OS << " case " << CI.Name << ":\n"
  2516. << " return " << CI.ParserMethod << "(Operands);\n";
  2517. }
  2518. OS << " default:\n";
  2519. OS << " return MatchOperand_NoMatch;\n";
  2520. OS << " }\n";
  2521. OS << " return MatchOperand_NoMatch;\n";
  2522. OS << "}\n\n";
  2523. // Emit the static custom operand parser. This code is very similar with
  2524. // the other matcher. Also use MatchResultTy here just in case we go for
  2525. // a better error handling.
  2526. OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
  2527. << "MatchOperandParserImpl(OperandVector"
  2528. << " &Operands,\n StringRef Mnemonic,\n"
  2529. << " bool ParseForAllFeatures) {\n";
  2530. // Emit code to get the available features.
  2531. OS << " // Get the current feature set.\n";
  2532. OS << " const FeatureBitset &AvailableFeatures = getAvailableFeatures();\n\n";
  2533. OS << " // Get the next operand index.\n";
  2534. OS << " unsigned NextOpNum = Operands.size()"
  2535. << (HasMnemonicFirst ? " - 1" : "") << ";\n";
  2536. // Emit code to search the table.
  2537. OS << " // Search the table.\n";
  2538. if (HasMnemonicFirst) {
  2539. OS << " auto MnemonicRange =\n";
  2540. OS << " std::equal_range(std::begin(OperandMatchTable), "
  2541. "std::end(OperandMatchTable),\n";
  2542. OS << " Mnemonic, LessOpcodeOperand());\n\n";
  2543. } else {
  2544. OS << " auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable),"
  2545. " std::end(OperandMatchTable));\n";
  2546. OS << " if (!Mnemonic.empty())\n";
  2547. OS << " MnemonicRange =\n";
  2548. OS << " std::equal_range(std::begin(OperandMatchTable), "
  2549. "std::end(OperandMatchTable),\n";
  2550. OS << " Mnemonic, LessOpcodeOperand());\n\n";
  2551. }
  2552. OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
  2553. OS << " return MatchOperand_NoMatch;\n\n";
  2554. OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
  2555. << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
  2556. OS << " // equal_range guarantees that instruction mnemonic matches.\n";
  2557. OS << " assert(Mnemonic == it->getMnemonic());\n\n";
  2558. // Emit check that the required features are available.
  2559. OS << " // check if the available features match\n";
  2560. OS << " const FeatureBitset &RequiredFeatures = "
  2561. "FeatureBitsets[it->RequiredFeaturesIdx];\n";
  2562. OS << " if (!ParseForAllFeatures && (AvailableFeatures & "
  2563. "RequiredFeatures) != RequiredFeatures)\n";
  2564. OS << " continue;\n\n";
  2565. // Emit check to ensure the operand number matches.
  2566. OS << " // check if the operand in question has a custom parser.\n";
  2567. OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
  2568. OS << " continue;\n\n";
  2569. // Emit call to the custom parser method
  2570. StringRef ParserName = AsmParser.getValueAsString("OperandParserMethod");
  2571. if (ParserName.empty())
  2572. ParserName = "tryCustomParseOperand";
  2573. OS << " // call custom parse method to handle the operand\n";
  2574. OS << " OperandMatchResultTy Result = " << ParserName
  2575. << "(Operands, it->Class);\n";
  2576. OS << " if (Result != MatchOperand_NoMatch)\n";
  2577. OS << " return Result;\n";
  2578. OS << " }\n\n";
  2579. OS << " // Okay, we had no match.\n";
  2580. OS << " return MatchOperand_NoMatch;\n";
  2581. OS << "}\n\n";
  2582. }
  2583. static void emitAsmTiedOperandConstraints(CodeGenTarget &Target,
  2584. AsmMatcherInfo &Info,
  2585. raw_ostream &OS) {
  2586. std::string AsmParserName =
  2587. std::string(Info.AsmParser->getValueAsString("AsmParserClassName"));
  2588. OS << "static bool ";
  2589. OS << "checkAsmTiedOperandConstraints(const " << Target.getName()
  2590. << AsmParserName << "&AsmParser,\n";
  2591. OS << " unsigned Kind,\n";
  2592. OS << " const OperandVector &Operands,\n";
  2593. OS << " uint64_t &ErrorInfo) {\n";
  2594. OS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
  2595. OS << " const uint8_t *Converter = ConversionTable[Kind];\n";
  2596. OS << " for (const uint8_t *p = Converter; *p; p += 2) {\n";
  2597. OS << " switch (*p) {\n";
  2598. OS << " case CVT_Tied: {\n";
  2599. OS << " unsigned OpIdx = *(p + 1);\n";
  2600. OS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
  2601. OS << " std::begin(TiedAsmOperandTable)) &&\n";
  2602. OS << " \"Tied operand not found\");\n";
  2603. OS << " unsigned OpndNum1 = TiedAsmOperandTable[OpIdx][1];\n";
  2604. OS << " unsigned OpndNum2 = TiedAsmOperandTable[OpIdx][2];\n";
  2605. OS << " if (OpndNum1 != OpndNum2) {\n";
  2606. OS << " auto &SrcOp1 = Operands[OpndNum1];\n";
  2607. OS << " auto &SrcOp2 = Operands[OpndNum2];\n";
  2608. OS << " if (!AsmParser.areEqualRegs(*SrcOp1, *SrcOp2)) {\n";
  2609. OS << " ErrorInfo = OpndNum2;\n";
  2610. OS << " return false;\n";
  2611. OS << " }\n";
  2612. OS << " }\n";
  2613. OS << " break;\n";
  2614. OS << " }\n";
  2615. OS << " default:\n";
  2616. OS << " break;\n";
  2617. OS << " }\n";
  2618. OS << " }\n";
  2619. OS << " return true;\n";
  2620. OS << "}\n\n";
  2621. }
  2622. static void emitMnemonicSpellChecker(raw_ostream &OS, CodeGenTarget &Target,
  2623. unsigned VariantCount) {
  2624. OS << "static std::string " << Target.getName()
  2625. << "MnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,"
  2626. << " unsigned VariantID) {\n";
  2627. if (!VariantCount)
  2628. OS << " return \"\";";
  2629. else {
  2630. OS << " const unsigned MaxEditDist = 2;\n";
  2631. OS << " std::vector<StringRef> Candidates;\n";
  2632. OS << " StringRef Prev = \"\";\n\n";
  2633. OS << " // Find the appropriate table for this asm variant.\n";
  2634. OS << " const MatchEntry *Start, *End;\n";
  2635. OS << " switch (VariantID) {\n";
  2636. OS << " default: llvm_unreachable(\"invalid variant!\");\n";
  2637. for (unsigned VC = 0; VC != VariantCount; ++VC) {
  2638. Record *AsmVariant = Target.getAsmParserVariant(VC);
  2639. int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
  2640. OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
  2641. << "); End = std::end(MatchTable" << VC << "); break;\n";
  2642. }
  2643. OS << " }\n\n";
  2644. OS << " for (auto I = Start; I < End; I++) {\n";
  2645. OS << " // Ignore unsupported instructions.\n";
  2646. OS << " const FeatureBitset &RequiredFeatures = "
  2647. "FeatureBitsets[I->RequiredFeaturesIdx];\n";
  2648. OS << " if ((FBS & RequiredFeatures) != RequiredFeatures)\n";
  2649. OS << " continue;\n";
  2650. OS << "\n";
  2651. OS << " StringRef T = I->getMnemonic();\n";
  2652. OS << " // Avoid recomputing the edit distance for the same string.\n";
  2653. OS << " if (T.equals(Prev))\n";
  2654. OS << " continue;\n";
  2655. OS << "\n";
  2656. OS << " Prev = T;\n";
  2657. OS << " unsigned Dist = S.edit_distance(T, false, MaxEditDist);\n";
  2658. OS << " if (Dist <= MaxEditDist)\n";
  2659. OS << " Candidates.push_back(T);\n";
  2660. OS << " }\n";
  2661. OS << "\n";
  2662. OS << " if (Candidates.empty())\n";
  2663. OS << " return \"\";\n";
  2664. OS << "\n";
  2665. OS << " std::string Res = \", did you mean: \";\n";
  2666. OS << " unsigned i = 0;\n";
  2667. OS << " for (; i < Candidates.size() - 1; i++)\n";
  2668. OS << " Res += Candidates[i].str() + \", \";\n";
  2669. OS << " return Res + Candidates[i].str() + \"?\";\n";
  2670. }
  2671. OS << "}\n";
  2672. OS << "\n";
  2673. }
  2674. static void emitMnemonicChecker(raw_ostream &OS,
  2675. CodeGenTarget &Target,
  2676. unsigned VariantCount,
  2677. bool HasMnemonicFirst,
  2678. bool HasMnemonicAliases) {
  2679. OS << "static bool " << Target.getName()
  2680. << "CheckMnemonic(StringRef Mnemonic,\n";
  2681. OS << " "
  2682. << "const FeatureBitset &AvailableFeatures,\n";
  2683. OS << " "
  2684. << "unsigned VariantID) {\n";
  2685. if (!VariantCount) {
  2686. OS << " return false;\n";
  2687. } else {
  2688. if (HasMnemonicAliases) {
  2689. OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
  2690. OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);";
  2691. OS << "\n\n";
  2692. }
  2693. OS << " // Find the appropriate table for this asm variant.\n";
  2694. OS << " const MatchEntry *Start, *End;\n";
  2695. OS << " switch (VariantID) {\n";
  2696. OS << " default: llvm_unreachable(\"invalid variant!\");\n";
  2697. for (unsigned VC = 0; VC != VariantCount; ++VC) {
  2698. Record *AsmVariant = Target.getAsmParserVariant(VC);
  2699. int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
  2700. OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
  2701. << "); End = std::end(MatchTable" << VC << "); break;\n";
  2702. }
  2703. OS << " }\n\n";
  2704. OS << " // Search the table.\n";
  2705. if (HasMnemonicFirst) {
  2706. OS << " auto MnemonicRange = "
  2707. "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
  2708. } else {
  2709. OS << " auto MnemonicRange = std::make_pair(Start, End);\n";
  2710. OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
  2711. OS << " if (!Mnemonic.empty())\n";
  2712. OS << " MnemonicRange = "
  2713. << "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
  2714. }
  2715. OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
  2716. OS << " return false;\n\n";
  2717. OS << " for (const MatchEntry *it = MnemonicRange.first, "
  2718. << "*ie = MnemonicRange.second;\n";
  2719. OS << " it != ie; ++it) {\n";
  2720. OS << " const FeatureBitset &RequiredFeatures =\n";
  2721. OS << " FeatureBitsets[it->RequiredFeaturesIdx];\n";
  2722. OS << " if ((AvailableFeatures & RequiredFeatures) == ";
  2723. OS << "RequiredFeatures)\n";
  2724. OS << " return true;\n";
  2725. OS << " }\n";
  2726. OS << " return false;\n";
  2727. }
  2728. OS << "}\n";
  2729. OS << "\n";
  2730. }
  2731. // Emit a function mapping match classes to strings, for debugging.
  2732. static void emitMatchClassKindNames(std::forward_list<ClassInfo> &Infos,
  2733. raw_ostream &OS) {
  2734. OS << "#ifndef NDEBUG\n";
  2735. OS << "const char *getMatchClassName(MatchClassKind Kind) {\n";
  2736. OS << " switch (Kind) {\n";
  2737. OS << " case InvalidMatchClass: return \"InvalidMatchClass\";\n";
  2738. OS << " case OptionalMatchClass: return \"OptionalMatchClass\";\n";
  2739. for (const auto &CI : Infos) {
  2740. OS << " case " << CI.Name << ": return \"" << CI.Name << "\";\n";
  2741. }
  2742. OS << " case NumMatchClassKinds: return \"NumMatchClassKinds\";\n";
  2743. OS << " }\n";
  2744. OS << " llvm_unreachable(\"unhandled MatchClassKind!\");\n";
  2745. OS << "}\n\n";
  2746. OS << "#endif // NDEBUG\n";
  2747. }
  2748. static std::string
  2749. getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
  2750. std::string Name = "AMFBS";
  2751. for (const auto &Feature : FeatureBitset)
  2752. Name += ("_" + Feature->getName()).str();
  2753. return Name;
  2754. }
  2755. void AsmMatcherEmitter::run(raw_ostream &OS) {
  2756. CodeGenTarget Target(Records);
  2757. Record *AsmParser = Target.getAsmParser();
  2758. StringRef ClassName = AsmParser->getValueAsString("AsmParserClassName");
  2759. // Compute the information on the instructions to match.
  2760. AsmMatcherInfo Info(AsmParser, Target, Records);
  2761. Info.buildInfo();
  2762. // Sort the instruction table using the partial order on classes. We use
  2763. // stable_sort to ensure that ambiguous instructions are still
  2764. // deterministically ordered.
  2765. llvm::stable_sort(
  2766. Info.Matchables,
  2767. [](const std::unique_ptr<MatchableInfo> &a,
  2768. const std::unique_ptr<MatchableInfo> &b) { return *a < *b; });
  2769. #ifdef EXPENSIVE_CHECKS
  2770. // Verify that the table is sorted and operator < works transitively.
  2771. for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
  2772. ++I) {
  2773. for (auto J = I; J != E; ++J) {
  2774. assert(!(**J < **I));
  2775. }
  2776. }
  2777. #endif
  2778. DEBUG_WITH_TYPE("instruction_info", {
  2779. for (const auto &MI : Info.Matchables)
  2780. MI->dump();
  2781. });
  2782. // Check for ambiguous matchables.
  2783. DEBUG_WITH_TYPE("ambiguous_instrs", {
  2784. unsigned NumAmbiguous = 0;
  2785. for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
  2786. ++I) {
  2787. for (auto J = std::next(I); J != E; ++J) {
  2788. const MatchableInfo &A = **I;
  2789. const MatchableInfo &B = **J;
  2790. if (A.couldMatchAmbiguouslyWith(B)) {
  2791. errs() << "warning: ambiguous matchables:\n";
  2792. A.dump();
  2793. errs() << "\nis incomparable with:\n";
  2794. B.dump();
  2795. errs() << "\n\n";
  2796. ++NumAmbiguous;
  2797. }
  2798. }
  2799. }
  2800. if (NumAmbiguous)
  2801. errs() << "warning: " << NumAmbiguous
  2802. << " ambiguous matchables!\n";
  2803. });
  2804. // Compute the information on the custom operand parsing.
  2805. Info.buildOperandMatchInfo();
  2806. bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
  2807. bool HasOptionalOperands = Info.hasOptionalOperands();
  2808. bool ReportMultipleNearMisses =
  2809. AsmParser->getValueAsBit("ReportMultipleNearMisses");
  2810. // Write the output.
  2811. // Information for the class declaration.
  2812. OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
  2813. OS << "#undef GET_ASSEMBLER_HEADER\n";
  2814. OS << " // This should be included into the middle of the declaration of\n";
  2815. OS << " // your subclasses implementation of MCTargetAsmParser.\n";
  2816. OS << " FeatureBitset ComputeAvailableFeatures(const FeatureBitset &FB) const;\n";
  2817. if (HasOptionalOperands) {
  2818. OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
  2819. << "unsigned Opcode,\n"
  2820. << " const OperandVector &Operands,\n"
  2821. << " const SmallBitVector &OptionalOperandsMask);\n";
  2822. } else {
  2823. OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
  2824. << "unsigned Opcode,\n"
  2825. << " const OperandVector &Operands);\n";
  2826. }
  2827. OS << " void convertToMapAndConstraints(unsigned Kind,\n ";
  2828. OS << " const OperandVector &Operands) override;\n";
  2829. OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
  2830. << " MCInst &Inst,\n";
  2831. if (ReportMultipleNearMisses)
  2832. OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
  2833. else
  2834. OS << " uint64_t &ErrorInfo,\n"
  2835. << " FeatureBitset &MissingFeatures,\n";
  2836. OS << " bool matchingInlineAsm,\n"
  2837. << " unsigned VariantID = 0);\n";
  2838. if (!ReportMultipleNearMisses)
  2839. OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
  2840. << " MCInst &Inst,\n"
  2841. << " uint64_t &ErrorInfo,\n"
  2842. << " bool matchingInlineAsm,\n"
  2843. << " unsigned VariantID = 0) {\n"
  2844. << " FeatureBitset MissingFeatures;\n"
  2845. << " return MatchInstructionImpl(Operands, Inst, ErrorInfo, MissingFeatures,\n"
  2846. << " matchingInlineAsm, VariantID);\n"
  2847. << " }\n\n";
  2848. if (!Info.OperandMatchInfo.empty()) {
  2849. OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
  2850. OS << " OperandVector &Operands,\n";
  2851. OS << " StringRef Mnemonic,\n";
  2852. OS << " bool ParseForAllFeatures = false);\n";
  2853. OS << " OperandMatchResultTy tryCustomParseOperand(\n";
  2854. OS << " OperandVector &Operands,\n";
  2855. OS << " unsigned MCK);\n\n";
  2856. }
  2857. OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
  2858. // Emit the operand match diagnostic enum names.
  2859. OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
  2860. OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
  2861. emitOperandDiagnosticTypes(Info, OS);
  2862. OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
  2863. OS << "\n#ifdef GET_REGISTER_MATCHER\n";
  2864. OS << "#undef GET_REGISTER_MATCHER\n\n";
  2865. // Emit the subtarget feature enumeration.
  2866. SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(
  2867. Info.SubtargetFeatures, OS);
  2868. // Emit the function to match a register name to number.
  2869. // This should be omitted for Mips target
  2870. if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
  2871. emitMatchRegisterName(Target, AsmParser, OS);
  2872. if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName"))
  2873. emitMatchRegisterAltName(Target, AsmParser, OS);
  2874. OS << "#endif // GET_REGISTER_MATCHER\n\n";
  2875. OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
  2876. OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
  2877. // Generate the helper function to get the names for subtarget features.
  2878. emitGetSubtargetFeatureName(Info, OS);
  2879. OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
  2880. OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
  2881. OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
  2882. // Generate the function that remaps for mnemonic aliases.
  2883. bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
  2884. // Generate the convertToMCInst function to convert operands into an MCInst.
  2885. // Also, generate the convertToMapAndConstraints function for MS-style inline
  2886. // assembly. The latter doesn't actually generate a MCInst.
  2887. unsigned NumConverters = emitConvertFuncs(Target, ClassName, Info.Matchables,
  2888. HasMnemonicFirst,
  2889. HasOptionalOperands, OS);
  2890. // Emit the enumeration for classes which participate in matching.
  2891. emitMatchClassEnumeration(Target, Info.Classes, OS);
  2892. // Emit a function to get the user-visible string to describe an operand
  2893. // match failure in diagnostics.
  2894. emitOperandMatchErrorDiagStrings(Info, OS);
  2895. // Emit a function to map register classes to operand match failure codes.
  2896. emitRegisterMatchErrorFunc(Info, OS);
  2897. // Emit the routine to match token strings to their match class.
  2898. emitMatchTokenString(Target, Info.Classes, OS);
  2899. // Emit the subclass predicate routine.
  2900. emitIsSubclass(Target, Info.Classes, OS);
  2901. // Emit the routine to validate an operand against a match class.
  2902. emitValidateOperandClass(Info, OS);
  2903. emitMatchClassKindNames(Info.Classes, OS);
  2904. // Emit the available features compute function.
  2905. SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
  2906. Info.Target.getName(), ClassName, "ComputeAvailableFeatures",
  2907. Info.SubtargetFeatures, OS);
  2908. if (!ReportMultipleNearMisses)
  2909. emitAsmTiedOperandConstraints(Target, Info, OS);
  2910. StringToOffsetTable StringTable;
  2911. size_t MaxNumOperands = 0;
  2912. unsigned MaxMnemonicIndex = 0;
  2913. bool HasDeprecation = false;
  2914. for (const auto &MI : Info.Matchables) {
  2915. MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
  2916. HasDeprecation |= MI->HasDeprecation;
  2917. // Store a pascal-style length byte in the mnemonic.
  2918. std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.lower();
  2919. MaxMnemonicIndex = std::max(MaxMnemonicIndex,
  2920. StringTable.GetOrAddStringOffset(LenMnemonic, false));
  2921. }
  2922. OS << "static const char MnemonicTable[] =\n";
  2923. StringTable.EmitString(OS);
  2924. OS << ";\n\n";
  2925. std::vector<std::vector<Record *>> FeatureBitsets;
  2926. for (const auto &MI : Info.Matchables) {
  2927. if (MI->RequiredFeatures.empty())
  2928. continue;
  2929. FeatureBitsets.emplace_back();
  2930. for (unsigned I = 0, E = MI->RequiredFeatures.size(); I != E; ++I)
  2931. FeatureBitsets.back().push_back(MI->RequiredFeatures[I]->TheDef);
  2932. }
  2933. llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
  2934. const std::vector<Record *> &B) {
  2935. if (A.size() < B.size())
  2936. return true;
  2937. if (A.size() > B.size())
  2938. return false;
  2939. for (auto Pair : zip(A, B)) {
  2940. if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
  2941. return true;
  2942. if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
  2943. return false;
  2944. }
  2945. return false;
  2946. });
  2947. FeatureBitsets.erase(
  2948. std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
  2949. FeatureBitsets.end());
  2950. OS << "// Feature bitsets.\n"
  2951. << "enum : " << getMinimalTypeForRange(FeatureBitsets.size()) << " {\n"
  2952. << " AMFBS_None,\n";
  2953. for (const auto &FeatureBitset : FeatureBitsets) {
  2954. if (FeatureBitset.empty())
  2955. continue;
  2956. OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
  2957. }
  2958. OS << "};\n\n"
  2959. << "static constexpr FeatureBitset FeatureBitsets[] = {\n"
  2960. << " {}, // AMFBS_None\n";
  2961. for (const auto &FeatureBitset : FeatureBitsets) {
  2962. if (FeatureBitset.empty())
  2963. continue;
  2964. OS << " {";
  2965. for (const auto &Feature : FeatureBitset) {
  2966. const auto &I = Info.SubtargetFeatures.find(Feature);
  2967. assert(I != Info.SubtargetFeatures.end() && "Didn't import predicate?");
  2968. OS << I->second.getEnumBitName() << ", ";
  2969. }
  2970. OS << "},\n";
  2971. }
  2972. OS << "};\n\n";
  2973. // Emit the static match table; unused classes get initialized to 0 which is
  2974. // guaranteed to be InvalidMatchClass.
  2975. //
  2976. // FIXME: We can reduce the size of this table very easily. First, we change
  2977. // it so that store the kinds in separate bit-fields for each index, which
  2978. // only needs to be the max width used for classes at that index (we also need
  2979. // to reject based on this during classification). If we then make sure to
  2980. // order the match kinds appropriately (putting mnemonics last), then we
  2981. // should only end up using a few bits for each class, especially the ones
  2982. // following the mnemonic.
  2983. OS << "namespace {\n";
  2984. OS << " struct MatchEntry {\n";
  2985. OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
  2986. << " Mnemonic;\n";
  2987. OS << " uint16_t Opcode;\n";
  2988. OS << " " << getMinimalTypeForRange(NumConverters)
  2989. << " ConvertFn;\n";
  2990. OS << " " << getMinimalTypeForRange(FeatureBitsets.size())
  2991. << " RequiredFeaturesIdx;\n";
  2992. OS << " " << getMinimalTypeForRange(
  2993. std::distance(Info.Classes.begin(), Info.Classes.end()))
  2994. << " Classes[" << MaxNumOperands << "];\n";
  2995. OS << " StringRef getMnemonic() const {\n";
  2996. OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
  2997. OS << " MnemonicTable[Mnemonic]);\n";
  2998. OS << " }\n";
  2999. OS << " };\n\n";
  3000. OS << " // Predicate for searching for an opcode.\n";
  3001. OS << " struct LessOpcode {\n";
  3002. OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
  3003. OS << " return LHS.getMnemonic() < RHS;\n";
  3004. OS << " }\n";
  3005. OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
  3006. OS << " return LHS < RHS.getMnemonic();\n";
  3007. OS << " }\n";
  3008. OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
  3009. OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
  3010. OS << " }\n";
  3011. OS << " };\n";
  3012. OS << "} // end anonymous namespace\n\n";
  3013. unsigned VariantCount = Target.getAsmParserVariantCount();
  3014. for (unsigned VC = 0; VC != VariantCount; ++VC) {
  3015. Record *AsmVariant = Target.getAsmParserVariant(VC);
  3016. int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
  3017. OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
  3018. for (const auto &MI : Info.Matchables) {
  3019. if (MI->AsmVariantID != AsmVariantNo)
  3020. continue;
  3021. // Store a pascal-style length byte in the mnemonic.
  3022. std::string LenMnemonic =
  3023. char(MI->Mnemonic.size()) + MI->Mnemonic.lower();
  3024. OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
  3025. << " /* " << MI->Mnemonic << " */, "
  3026. << Target.getInstNamespace() << "::"
  3027. << MI->getResultInst()->TheDef->getName() << ", "
  3028. << MI->ConversionFnKind << ", ";
  3029. // Write the required features mask.
  3030. OS << "AMFBS";
  3031. if (MI->RequiredFeatures.empty())
  3032. OS << "_None";
  3033. else
  3034. for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i)
  3035. OS << '_' << MI->RequiredFeatures[i]->TheDef->getName();
  3036. OS << ", { ";
  3037. ListSeparator LS;
  3038. for (const MatchableInfo::AsmOperand &Op : MI->AsmOperands)
  3039. OS << LS << Op.Class->Name;
  3040. OS << " }, },\n";
  3041. }
  3042. OS << "};\n\n";
  3043. }
  3044. OS << "#include \"llvm/Support/Debug.h\"\n";
  3045. OS << "#include \"llvm/Support/Format.h\"\n\n";
  3046. // Finally, build the match function.
  3047. OS << "unsigned " << Target.getName() << ClassName << "::\n"
  3048. << "MatchInstructionImpl(const OperandVector &Operands,\n";
  3049. OS << " MCInst &Inst,\n";
  3050. if (ReportMultipleNearMisses)
  3051. OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
  3052. else
  3053. OS << " uint64_t &ErrorInfo,\n"
  3054. << " FeatureBitset &MissingFeatures,\n";
  3055. OS << " bool matchingInlineAsm, unsigned VariantID) {\n";
  3056. if (!ReportMultipleNearMisses) {
  3057. OS << " // Eliminate obvious mismatches.\n";
  3058. OS << " if (Operands.size() > "
  3059. << (MaxNumOperands + HasMnemonicFirst) << ") {\n";
  3060. OS << " ErrorInfo = "
  3061. << (MaxNumOperands + HasMnemonicFirst) << ";\n";
  3062. OS << " return Match_InvalidOperand;\n";
  3063. OS << " }\n\n";
  3064. }
  3065. // Emit code to get the available features.
  3066. OS << " // Get the current feature set.\n";
  3067. OS << " const FeatureBitset &AvailableFeatures = getAvailableFeatures();\n\n";
  3068. OS << " // Get the instruction mnemonic, which is the first token.\n";
  3069. if (HasMnemonicFirst) {
  3070. OS << " StringRef Mnemonic = ((" << Target.getName()
  3071. << "Operand &)*Operands[0]).getToken();\n\n";
  3072. } else {
  3073. OS << " StringRef Mnemonic;\n";
  3074. OS << " if (Operands[0]->isToken())\n";
  3075. OS << " Mnemonic = ((" << Target.getName()
  3076. << "Operand &)*Operands[0]).getToken();\n\n";
  3077. }
  3078. if (HasMnemonicAliases) {
  3079. OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
  3080. OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
  3081. }
  3082. // Emit code to compute the class list for this operand vector.
  3083. if (!ReportMultipleNearMisses) {
  3084. OS << " // Some state to try to produce better error messages.\n";
  3085. OS << " bool HadMatchOtherThanFeatures = false;\n";
  3086. OS << " bool HadMatchOtherThanPredicate = false;\n";
  3087. OS << " unsigned RetCode = Match_InvalidOperand;\n";
  3088. OS << " MissingFeatures.set();\n";
  3089. OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
  3090. OS << " // wrong for all instances of the instruction.\n";
  3091. OS << " ErrorInfo = ~0ULL;\n";
  3092. }
  3093. if (HasOptionalOperands) {
  3094. OS << " SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n";
  3095. }
  3096. // Emit code to search the table.
  3097. OS << " // Find the appropriate table for this asm variant.\n";
  3098. OS << " const MatchEntry *Start, *End;\n";
  3099. OS << " switch (VariantID) {\n";
  3100. OS << " default: llvm_unreachable(\"invalid variant!\");\n";
  3101. for (unsigned VC = 0; VC != VariantCount; ++VC) {
  3102. Record *AsmVariant = Target.getAsmParserVariant(VC);
  3103. int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
  3104. OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
  3105. << "); End = std::end(MatchTable" << VC << "); break;\n";
  3106. }
  3107. OS << " }\n";
  3108. OS << " // Search the table.\n";
  3109. if (HasMnemonicFirst) {
  3110. OS << " auto MnemonicRange = "
  3111. "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
  3112. } else {
  3113. OS << " auto MnemonicRange = std::make_pair(Start, End);\n";
  3114. OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
  3115. OS << " if (!Mnemonic.empty())\n";
  3116. OS << " MnemonicRange = "
  3117. "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
  3118. }
  3119. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"AsmMatcher: found \" <<\n"
  3120. << " std::distance(MnemonicRange.first, MnemonicRange.second) <<\n"
  3121. << " \" encodings with mnemonic '\" << Mnemonic << \"'\\n\");\n\n";
  3122. OS << " // Return a more specific error code if no mnemonics match.\n";
  3123. OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
  3124. OS << " return Match_MnemonicFail;\n\n";
  3125. OS << " for (const MatchEntry *it = MnemonicRange.first, "
  3126. << "*ie = MnemonicRange.second;\n";
  3127. OS << " it != ie; ++it) {\n";
  3128. OS << " const FeatureBitset &RequiredFeatures = "
  3129. "FeatureBitsets[it->RequiredFeaturesIdx];\n";
  3130. OS << " bool HasRequiredFeatures =\n";
  3131. OS << " (AvailableFeatures & RequiredFeatures) == RequiredFeatures;\n";
  3132. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Trying to match opcode \"\n";
  3133. OS << " << MII.getName(it->Opcode) << \"\\n\");\n";
  3134. if (ReportMultipleNearMisses) {
  3135. OS << " // Some state to record ways in which this instruction did not match.\n";
  3136. OS << " NearMissInfo OperandNearMiss = NearMissInfo::getSuccess();\n";
  3137. OS << " NearMissInfo FeaturesNearMiss = NearMissInfo::getSuccess();\n";
  3138. OS << " NearMissInfo EarlyPredicateNearMiss = NearMissInfo::getSuccess();\n";
  3139. OS << " NearMissInfo LatePredicateNearMiss = NearMissInfo::getSuccess();\n";
  3140. OS << " bool MultipleInvalidOperands = false;\n";
  3141. }
  3142. if (HasMnemonicFirst) {
  3143. OS << " // equal_range guarantees that instruction mnemonic matches.\n";
  3144. OS << " assert(Mnemonic == it->getMnemonic());\n";
  3145. }
  3146. // Emit check that the subclasses match.
  3147. if (!ReportMultipleNearMisses)
  3148. OS << " bool OperandsValid = true;\n";
  3149. if (HasOptionalOperands) {
  3150. OS << " OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n";
  3151. }
  3152. OS << " for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex")
  3153. << ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex")
  3154. << "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n";
  3155. OS << " auto Formal = "
  3156. << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
  3157. OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
  3158. OS << " dbgs() << \" Matching formal operand class \" << getMatchClassName(Formal)\n";
  3159. OS << " << \" against actual operand at index \" << ActualIdx);\n";
  3160. OS << " if (ActualIdx < Operands.size())\n";
  3161. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \" (\";\n";
  3162. OS << " Operands[ActualIdx]->print(dbgs()); dbgs() << \"): \");\n";
  3163. OS << " else\n";
  3164. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \": \");\n";
  3165. OS << " if (ActualIdx >= Operands.size()) {\n";
  3166. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"actual operand "
  3167. "index out of range\\n\");\n";
  3168. if (ReportMultipleNearMisses) {
  3169. OS << " bool ThisOperandValid = (Formal == " <<"InvalidMatchClass) || "
  3170. "isSubclass(Formal, OptionalMatchClass);\n";
  3171. OS << " if (!ThisOperandValid) {\n";
  3172. OS << " if (!OperandNearMiss) {\n";
  3173. OS << " // Record info about match failure for later use.\n";
  3174. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"recording too-few-operands near miss\\n\");\n";
  3175. OS << " OperandNearMiss =\n";
  3176. OS << " NearMissInfo::getTooFewOperands(Formal, it->Opcode);\n";
  3177. OS << " } else if (OperandNearMiss.getKind() != NearMissInfo::NearMissTooFewOperands) {\n";
  3178. OS << " // If more than one operand is invalid, give up on this match entry.\n";
  3179. OS << " DEBUG_WITH_TYPE(\n";
  3180. OS << " \"asm-matcher\",\n";
  3181. OS << " dbgs() << \"second invalid operand, giving up on this opcode\\n\");\n";
  3182. OS << " MultipleInvalidOperands = true;\n";
  3183. OS << " break;\n";
  3184. OS << " }\n";
  3185. OS << " } else {\n";
  3186. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"but formal "
  3187. "operand not required\\n\");\n";
  3188. OS << " }\n";
  3189. OS << " continue;\n";
  3190. } else {
  3191. OS << " if (Formal == InvalidMatchClass) {\n";
  3192. if (HasOptionalOperands) {
  3193. OS << " OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
  3194. << ");\n";
  3195. }
  3196. OS << " break;\n";
  3197. OS << " }\n";
  3198. OS << " if (isSubclass(Formal, OptionalMatchClass)) {\n";
  3199. if (HasOptionalOperands) {
  3200. OS << " OptionalOperandsMask.set(FormalIdx);\n";
  3201. }
  3202. OS << " continue;\n";
  3203. OS << " }\n";
  3204. OS << " OperandsValid = false;\n";
  3205. OS << " ErrorInfo = ActualIdx;\n";
  3206. OS << " break;\n";
  3207. }
  3208. OS << " }\n";
  3209. OS << " MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
  3210. OS << " unsigned Diag = validateOperandClass(Actual, Formal);\n";
  3211. OS << " if (Diag == Match_Success) {\n";
  3212. OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
  3213. OS << " dbgs() << \"match success using generic matcher\\n\");\n";
  3214. OS << " ++ActualIdx;\n";
  3215. OS << " continue;\n";
  3216. OS << " }\n";
  3217. OS << " // If the generic handler indicates an invalid operand\n";
  3218. OS << " // failure, check for a special case.\n";
  3219. OS << " if (Diag != Match_Success) {\n";
  3220. OS << " unsigned TargetDiag = validateTargetOperandClass(Actual, Formal);\n";
  3221. OS << " if (TargetDiag == Match_Success) {\n";
  3222. OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
  3223. OS << " dbgs() << \"match success using target matcher\\n\");\n";
  3224. OS << " ++ActualIdx;\n";
  3225. OS << " continue;\n";
  3226. OS << " }\n";
  3227. OS << " // If the target matcher returned a specific error code use\n";
  3228. OS << " // that, else use the one from the generic matcher.\n";
  3229. OS << " if (TargetDiag != Match_InvalidOperand && "
  3230. "HasRequiredFeatures)\n";
  3231. OS << " Diag = TargetDiag;\n";
  3232. OS << " }\n";
  3233. OS << " // If current formal operand wasn't matched and it is optional\n"
  3234. << " // then try to match next formal operand\n";
  3235. OS << " if (Diag == Match_InvalidOperand "
  3236. << "&& isSubclass(Formal, OptionalMatchClass)) {\n";
  3237. if (HasOptionalOperands) {
  3238. OS << " OptionalOperandsMask.set(FormalIdx);\n";
  3239. }
  3240. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"ignoring optional operand\\n\");\n";
  3241. OS << " continue;\n";
  3242. OS << " }\n";
  3243. if (ReportMultipleNearMisses) {
  3244. OS << " if (!OperandNearMiss) {\n";
  3245. OS << " // If this is the first invalid operand we have seen, record some\n";
  3246. OS << " // information about it.\n";
  3247. OS << " DEBUG_WITH_TYPE(\n";
  3248. OS << " \"asm-matcher\",\n";
  3249. OS << " dbgs()\n";
  3250. OS << " << \"operand match failed, recording near-miss with diag code \"\n";
  3251. OS << " << Diag << \"\\n\");\n";
  3252. OS << " OperandNearMiss =\n";
  3253. OS << " NearMissInfo::getMissedOperand(Diag, Formal, it->Opcode, ActualIdx);\n";
  3254. OS << " ++ActualIdx;\n";
  3255. OS << " } else {\n";
  3256. OS << " // If more than one operand is invalid, give up on this match entry.\n";
  3257. OS << " DEBUG_WITH_TYPE(\n";
  3258. OS << " \"asm-matcher\",\n";
  3259. OS << " dbgs() << \"second operand mismatch, skipping this opcode\\n\");\n";
  3260. OS << " MultipleInvalidOperands = true;\n";
  3261. OS << " break;\n";
  3262. OS << " }\n";
  3263. OS << " }\n\n";
  3264. } else {
  3265. OS << " // If this operand is broken for all of the instances of this\n";
  3266. OS << " // mnemonic, keep track of it so we can report loc info.\n";
  3267. OS << " // If we already had a match that only failed due to a\n";
  3268. OS << " // target predicate, that diagnostic is preferred.\n";
  3269. OS << " if (!HadMatchOtherThanPredicate &&\n";
  3270. OS << " (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n";
  3271. OS << " if (HasRequiredFeatures && (ErrorInfo != ActualIdx || Diag "
  3272. "!= Match_InvalidOperand))\n";
  3273. OS << " RetCode = Diag;\n";
  3274. OS << " ErrorInfo = ActualIdx;\n";
  3275. OS << " }\n";
  3276. OS << " // Otherwise, just reject this instance of the mnemonic.\n";
  3277. OS << " OperandsValid = false;\n";
  3278. OS << " break;\n";
  3279. OS << " }\n\n";
  3280. }
  3281. if (ReportMultipleNearMisses)
  3282. OS << " if (MultipleInvalidOperands) {\n";
  3283. else
  3284. OS << " if (!OperandsValid) {\n";
  3285. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
  3286. OS << " \"operand mismatches, ignoring \"\n";
  3287. OS << " \"this opcode\\n\");\n";
  3288. OS << " continue;\n";
  3289. OS << " }\n";
  3290. // Emit check that the required features are available.
  3291. OS << " if (!HasRequiredFeatures) {\n";
  3292. if (!ReportMultipleNearMisses)
  3293. OS << " HadMatchOtherThanFeatures = true;\n";
  3294. OS << " FeatureBitset NewMissingFeatures = RequiredFeatures & "
  3295. "~AvailableFeatures;\n";
  3296. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Missing target features:\";\n";
  3297. OS << " for (unsigned I = 0, E = NewMissingFeatures.size(); I != E; ++I)\n";
  3298. OS << " if (NewMissingFeatures[I])\n";
  3299. OS << " dbgs() << ' ' << I;\n";
  3300. OS << " dbgs() << \"\\n\");\n";
  3301. if (ReportMultipleNearMisses) {
  3302. OS << " FeaturesNearMiss = NearMissInfo::getMissedFeature(NewMissingFeatures);\n";
  3303. } else {
  3304. OS << " if (NewMissingFeatures.count() <=\n"
  3305. " MissingFeatures.count())\n";
  3306. OS << " MissingFeatures = NewMissingFeatures;\n";
  3307. OS << " continue;\n";
  3308. }
  3309. OS << " }\n";
  3310. OS << "\n";
  3311. OS << " Inst.clear();\n\n";
  3312. OS << " Inst.setOpcode(it->Opcode);\n";
  3313. // Verify the instruction with the target-specific match predicate function.
  3314. OS << " // We have a potential match but have not rendered the operands.\n"
  3315. << " // Check the target predicate to handle any context sensitive\n"
  3316. " // constraints.\n"
  3317. << " // For example, Ties that are referenced multiple times must be\n"
  3318. " // checked here to ensure the input is the same for each match\n"
  3319. " // constraints. If we leave it any later the ties will have been\n"
  3320. " // canonicalized\n"
  3321. << " unsigned MatchResult;\n"
  3322. << " if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, "
  3323. "Operands)) != Match_Success) {\n"
  3324. << " Inst.clear();\n";
  3325. OS << " DEBUG_WITH_TYPE(\n";
  3326. OS << " \"asm-matcher\",\n";
  3327. OS << " dbgs() << \"Early target match predicate failed with diag code \"\n";
  3328. OS << " << MatchResult << \"\\n\");\n";
  3329. if (ReportMultipleNearMisses) {
  3330. OS << " EarlyPredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
  3331. } else {
  3332. OS << " RetCode = MatchResult;\n"
  3333. << " HadMatchOtherThanPredicate = true;\n"
  3334. << " continue;\n";
  3335. }
  3336. OS << " }\n\n";
  3337. if (ReportMultipleNearMisses) {
  3338. OS << " // If we did not successfully match the operands, then we can't convert to\n";
  3339. OS << " // an MCInst, so bail out on this instruction variant now.\n";
  3340. OS << " if (OperandNearMiss) {\n";
  3341. OS << " // If the operand mismatch was the only problem, reprrt it as a near-miss.\n";
  3342. OS << " if (NearMisses && !FeaturesNearMiss && !EarlyPredicateNearMiss) {\n";
  3343. OS << " DEBUG_WITH_TYPE(\n";
  3344. OS << " \"asm-matcher\",\n";
  3345. OS << " dbgs()\n";
  3346. OS << " << \"Opcode result: one mismatched operand, adding near-miss\\n\");\n";
  3347. OS << " NearMisses->push_back(OperandNearMiss);\n";
  3348. OS << " } else {\n";
  3349. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
  3350. OS << " \"types of mismatch, so not \"\n";
  3351. OS << " \"reporting near-miss\\n\");\n";
  3352. OS << " }\n";
  3353. OS << " continue;\n";
  3354. OS << " }\n\n";
  3355. }
  3356. OS << " if (matchingInlineAsm) {\n";
  3357. OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n";
  3358. if (!ReportMultipleNearMisses) {
  3359. OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
  3360. "Operands, ErrorInfo))\n";
  3361. OS << " return Match_InvalidTiedOperand;\n";
  3362. OS << "\n";
  3363. }
  3364. OS << " return Match_Success;\n";
  3365. OS << " }\n\n";
  3366. OS << " // We have selected a definite instruction, convert the parsed\n"
  3367. << " // operands into the appropriate MCInst.\n";
  3368. if (HasOptionalOperands) {
  3369. OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
  3370. << " OptionalOperandsMask);\n";
  3371. } else {
  3372. OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
  3373. }
  3374. OS << "\n";
  3375. // Verify the instruction with the target-specific match predicate function.
  3376. OS << " // We have a potential match. Check the target predicate to\n"
  3377. << " // handle any context sensitive constraints.\n"
  3378. << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
  3379. << " Match_Success) {\n"
  3380. << " DEBUG_WITH_TYPE(\"asm-matcher\",\n"
  3381. << " dbgs() << \"Target match predicate failed with diag code \"\n"
  3382. << " << MatchResult << \"\\n\");\n"
  3383. << " Inst.clear();\n";
  3384. if (ReportMultipleNearMisses) {
  3385. OS << " LatePredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
  3386. } else {
  3387. OS << " RetCode = MatchResult;\n"
  3388. << " HadMatchOtherThanPredicate = true;\n"
  3389. << " continue;\n";
  3390. }
  3391. OS << " }\n\n";
  3392. if (ReportMultipleNearMisses) {
  3393. OS << " int NumNearMisses = ((int)(bool)OperandNearMiss +\n";
  3394. OS << " (int)(bool)FeaturesNearMiss +\n";
  3395. OS << " (int)(bool)EarlyPredicateNearMiss +\n";
  3396. OS << " (int)(bool)LatePredicateNearMiss);\n";
  3397. OS << " if (NumNearMisses == 1) {\n";
  3398. OS << " // We had exactly one type of near-miss, so add that to the list.\n";
  3399. OS << " assert(!OperandNearMiss && \"OperandNearMiss was handled earlier\");\n";
  3400. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: found one type of \"\n";
  3401. OS << " \"mismatch, so reporting a \"\n";
  3402. OS << " \"near-miss\\n\");\n";
  3403. OS << " if (NearMisses && FeaturesNearMiss)\n";
  3404. OS << " NearMisses->push_back(FeaturesNearMiss);\n";
  3405. OS << " else if (NearMisses && EarlyPredicateNearMiss)\n";
  3406. OS << " NearMisses->push_back(EarlyPredicateNearMiss);\n";
  3407. OS << " else if (NearMisses && LatePredicateNearMiss)\n";
  3408. OS << " NearMisses->push_back(LatePredicateNearMiss);\n";
  3409. OS << "\n";
  3410. OS << " continue;\n";
  3411. OS << " } else if (NumNearMisses > 1) {\n";
  3412. OS << " // This instruction missed in more than one way, so ignore it.\n";
  3413. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
  3414. OS << " \"types of mismatch, so not \"\n";
  3415. OS << " \"reporting near-miss\\n\");\n";
  3416. OS << " continue;\n";
  3417. OS << " }\n";
  3418. }
  3419. // Call the post-processing function, if used.
  3420. StringRef InsnCleanupFn = AsmParser->getValueAsString("AsmParserInstCleanup");
  3421. if (!InsnCleanupFn.empty())
  3422. OS << " " << InsnCleanupFn << "(Inst);\n";
  3423. if (HasDeprecation) {
  3424. OS << " std::string Info;\n";
  3425. OS << " if (!getParser().getTargetParser().getTargetOptions().MCNoDeprecatedWarn &&\n";
  3426. OS << " MII.getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
  3427. OS << " SMLoc Loc = ((" << Target.getName()
  3428. << "Operand &)*Operands[0]).getStartLoc();\n";
  3429. OS << " getParser().Warning(Loc, Info, std::nullopt);\n";
  3430. OS << " }\n";
  3431. }
  3432. if (!ReportMultipleNearMisses) {
  3433. OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
  3434. "Operands, ErrorInfo))\n";
  3435. OS << " return Match_InvalidTiedOperand;\n";
  3436. OS << "\n";
  3437. }
  3438. OS << " DEBUG_WITH_TYPE(\n";
  3439. OS << " \"asm-matcher\",\n";
  3440. OS << " dbgs() << \"Opcode result: complete match, selecting this opcode\\n\");\n";
  3441. OS << " return Match_Success;\n";
  3442. OS << " }\n\n";
  3443. if (ReportMultipleNearMisses) {
  3444. OS << " // No instruction variants matched exactly.\n";
  3445. OS << " return Match_NearMisses;\n";
  3446. } else {
  3447. OS << " // Okay, we had no match. Try to return a useful error code.\n";
  3448. OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
  3449. OS << " return RetCode;\n\n";
  3450. OS << " ErrorInfo = 0;\n";
  3451. OS << " return Match_MissingFeature;\n";
  3452. }
  3453. OS << "}\n\n";
  3454. if (!Info.OperandMatchInfo.empty())
  3455. emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
  3456. MaxMnemonicIndex, FeatureBitsets.size(),
  3457. HasMnemonicFirst, *AsmParser);
  3458. OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
  3459. OS << "\n#ifdef GET_MNEMONIC_SPELL_CHECKER\n";
  3460. OS << "#undef GET_MNEMONIC_SPELL_CHECKER\n\n";
  3461. emitMnemonicSpellChecker(OS, Target, VariantCount);
  3462. OS << "#endif // GET_MNEMONIC_SPELL_CHECKER\n\n";
  3463. OS << "\n#ifdef GET_MNEMONIC_CHECKER\n";
  3464. OS << "#undef GET_MNEMONIC_CHECKER\n\n";
  3465. emitMnemonicChecker(OS, Target, VariantCount,
  3466. HasMnemonicFirst, HasMnemonicAliases);
  3467. OS << "#endif // GET_MNEMONIC_CHECKER\n\n";
  3468. }
  3469. namespace llvm {
  3470. void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
  3471. emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
  3472. AsmMatcherEmitter(RK).run(OS);
  3473. }
  3474. } // end namespace llvm