CodeGenDAGPatterns.cpp 170 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752
  1. //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the CodeGenDAGPatterns class, which is used to read and
  10. // represent the patterns present in a .td file for instructions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenDAGPatterns.h"
  14. #include "llvm/ADT/DenseSet.h"
  15. #include "llvm/ADT/MapVector.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/ADT/StringExtras.h"
  20. #include "llvm/ADT/StringMap.h"
  21. #include "llvm/ADT/Twine.h"
  22. #include "llvm/Support/Debug.h"
  23. #include "llvm/Support/ErrorHandling.h"
  24. #include "llvm/Support/TypeSize.h"
  25. #include "llvm/TableGen/Error.h"
  26. #include "llvm/TableGen/Record.h"
  27. #include <algorithm>
  28. #include <cstdio>
  29. #include <iterator>
  30. #include <set>
  31. using namespace llvm;
  32. #define DEBUG_TYPE "dag-patterns"
  33. static inline bool isIntegerOrPtr(MVT VT) {
  34. return VT.isInteger() || VT == MVT::iPTR;
  35. }
  36. static inline bool isFloatingPoint(MVT VT) {
  37. return VT.isFloatingPoint();
  38. }
  39. static inline bool isVector(MVT VT) {
  40. return VT.isVector();
  41. }
  42. static inline bool isScalar(MVT VT) {
  43. return !VT.isVector();
  44. }
  45. template <typename Predicate>
  46. static bool berase_if(MachineValueTypeSet &S, Predicate P) {
  47. bool Erased = false;
  48. // It is ok to iterate over MachineValueTypeSet and remove elements from it
  49. // at the same time.
  50. for (MVT T : S) {
  51. if (!P(T))
  52. continue;
  53. Erased = true;
  54. S.erase(T);
  55. }
  56. return Erased;
  57. }
  58. // --- TypeSetByHwMode
  59. // This is a parameterized type-set class. For each mode there is a list
  60. // of types that are currently possible for a given tree node. Type
  61. // inference will apply to each mode separately.
  62. TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
  63. for (const ValueTypeByHwMode &VVT : VTList) {
  64. insert(VVT);
  65. AddrSpaces.push_back(VVT.PtrAddrSpace);
  66. }
  67. }
  68. bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
  69. for (const auto &I : *this) {
  70. if (I.second.size() > 1)
  71. return false;
  72. if (!AllowEmpty && I.second.empty())
  73. return false;
  74. }
  75. return true;
  76. }
  77. ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
  78. assert(isValueTypeByHwMode(true) &&
  79. "The type set has multiple types for at least one HW mode");
  80. ValueTypeByHwMode VVT;
  81. auto ASI = AddrSpaces.begin();
  82. for (const auto &I : *this) {
  83. MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
  84. VVT.getOrCreateTypeForMode(I.first, T);
  85. if (ASI != AddrSpaces.end())
  86. VVT.PtrAddrSpace = *ASI++;
  87. }
  88. return VVT;
  89. }
  90. bool TypeSetByHwMode::isPossible() const {
  91. for (const auto &I : *this)
  92. if (!I.second.empty())
  93. return true;
  94. return false;
  95. }
  96. bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
  97. bool Changed = false;
  98. bool ContainsDefault = false;
  99. MVT DT = MVT::Other;
  100. for (const auto &P : VVT) {
  101. unsigned M = P.first;
  102. // Make sure there exists a set for each specific mode from VVT.
  103. Changed |= getOrCreate(M).insert(P.second).second;
  104. // Cache VVT's default mode.
  105. if (DefaultMode == M) {
  106. ContainsDefault = true;
  107. DT = P.second;
  108. }
  109. }
  110. // If VVT has a default mode, add the corresponding type to all
  111. // modes in "this" that do not exist in VVT.
  112. if (ContainsDefault)
  113. for (auto &I : *this)
  114. if (!VVT.hasMode(I.first))
  115. Changed |= I.second.insert(DT).second;
  116. return Changed;
  117. }
  118. // Constrain the type set to be the intersection with VTS.
  119. bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
  120. bool Changed = false;
  121. if (hasDefault()) {
  122. for (const auto &I : VTS) {
  123. unsigned M = I.first;
  124. if (M == DefaultMode || hasMode(M))
  125. continue;
  126. Map.insert({M, Map.at(DefaultMode)});
  127. Changed = true;
  128. }
  129. }
  130. for (auto &I : *this) {
  131. unsigned M = I.first;
  132. SetType &S = I.second;
  133. if (VTS.hasMode(M) || VTS.hasDefault()) {
  134. Changed |= intersect(I.second, VTS.get(M));
  135. } else if (!S.empty()) {
  136. S.clear();
  137. Changed = true;
  138. }
  139. }
  140. return Changed;
  141. }
  142. template <typename Predicate>
  143. bool TypeSetByHwMode::constrain(Predicate P) {
  144. bool Changed = false;
  145. for (auto &I : *this)
  146. Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
  147. return Changed;
  148. }
  149. template <typename Predicate>
  150. bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
  151. assert(empty());
  152. for (const auto &I : VTS) {
  153. SetType &S = getOrCreate(I.first);
  154. for (auto J : I.second)
  155. if (P(J))
  156. S.insert(J);
  157. }
  158. return !empty();
  159. }
  160. void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
  161. SmallVector<unsigned, 4> Modes;
  162. Modes.reserve(Map.size());
  163. for (const auto &I : *this)
  164. Modes.push_back(I.first);
  165. if (Modes.empty()) {
  166. OS << "{}";
  167. return;
  168. }
  169. array_pod_sort(Modes.begin(), Modes.end());
  170. OS << '{';
  171. for (unsigned M : Modes) {
  172. OS << ' ' << getModeName(M) << ':';
  173. writeToStream(get(M), OS);
  174. }
  175. OS << " }";
  176. }
  177. void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) {
  178. SmallVector<MVT, 4> Types(S.begin(), S.end());
  179. array_pod_sort(Types.begin(), Types.end());
  180. OS << '[';
  181. ListSeparator LS(" ");
  182. for (const MVT &T : Types)
  183. OS << LS << ValueTypeByHwMode::getMVTName(T);
  184. OS << ']';
  185. }
  186. bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
  187. // The isSimple call is much quicker than hasDefault - check this first.
  188. bool IsSimple = isSimple();
  189. bool VTSIsSimple = VTS.isSimple();
  190. if (IsSimple && VTSIsSimple)
  191. return *begin() == *VTS.begin();
  192. // Speedup: We have a default if the set is simple.
  193. bool HaveDefault = IsSimple || hasDefault();
  194. bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();
  195. if (HaveDefault != VTSHaveDefault)
  196. return false;
  197. SmallSet<unsigned, 4> Modes;
  198. for (auto &I : *this)
  199. Modes.insert(I.first);
  200. for (const auto &I : VTS)
  201. Modes.insert(I.first);
  202. if (HaveDefault) {
  203. // Both sets have default mode.
  204. for (unsigned M : Modes) {
  205. if (get(M) != VTS.get(M))
  206. return false;
  207. }
  208. } else {
  209. // Neither set has default mode.
  210. for (unsigned M : Modes) {
  211. // If there is no default mode, an empty set is equivalent to not having
  212. // the corresponding mode.
  213. bool NoModeThis = !hasMode(M) || get(M).empty();
  214. bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
  215. if (NoModeThis != NoModeVTS)
  216. return false;
  217. if (!NoModeThis)
  218. if (get(M) != VTS.get(M))
  219. return false;
  220. }
  221. }
  222. return true;
  223. }
  224. namespace llvm {
  225. raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
  226. T.writeToStream(OS);
  227. return OS;
  228. }
  229. }
  230. LLVM_DUMP_METHOD
  231. void TypeSetByHwMode::dump() const {
  232. dbgs() << *this << '\n';
  233. }
  234. bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
  235. bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
  236. auto Int = [&In](MVT T) -> bool { return !In.count(T); };
  237. if (OutP == InP)
  238. return berase_if(Out, Int);
  239. // Compute the intersection of scalars separately to account for only
  240. // one set containing iPTR.
  241. // The intersection of iPTR with a set of integer scalar types that does not
  242. // include iPTR will result in the most specific scalar type:
  243. // - iPTR is more specific than any set with two elements or more
  244. // - iPTR is less specific than any single integer scalar type.
  245. // For example
  246. // { iPTR } * { i32 } -> { i32 }
  247. // { iPTR } * { i32 i64 } -> { iPTR }
  248. // and
  249. // { iPTR i32 } * { i32 } -> { i32 }
  250. // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
  251. // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
  252. // Compute the difference between the two sets in such a way that the
  253. // iPTR is in the set that is being subtracted. This is to see if there
  254. // are any extra scalars in the set without iPTR that are not in the
  255. // set containing iPTR. Then the iPTR could be considered a "wildcard"
  256. // matching these scalars. If there is only one such scalar, it would
  257. // replace the iPTR, if there are more, the iPTR would be retained.
  258. SetType Diff;
  259. if (InP) {
  260. Diff = Out;
  261. berase_if(Diff, [&In](MVT T) { return In.count(T); });
  262. // Pre-remove these elements and rely only on InP/OutP to determine
  263. // whether a change has been made.
  264. berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
  265. } else {
  266. Diff = In;
  267. berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
  268. Out.erase(MVT::iPTR);
  269. }
  270. // The actual intersection.
  271. bool Changed = berase_if(Out, Int);
  272. unsigned NumD = Diff.size();
  273. if (NumD == 0)
  274. return Changed;
  275. if (NumD == 1) {
  276. Out.insert(*Diff.begin());
  277. // This is a change only if Out was the one with iPTR (which is now
  278. // being replaced).
  279. Changed |= OutP;
  280. } else {
  281. // Multiple elements from Out are now replaced with iPTR.
  282. Out.insert(MVT::iPTR);
  283. Changed |= !OutP;
  284. }
  285. return Changed;
  286. }
  287. bool TypeSetByHwMode::validate() const {
  288. #ifndef NDEBUG
  289. if (empty())
  290. return true;
  291. bool AllEmpty = true;
  292. for (const auto &I : *this)
  293. AllEmpty &= I.second.empty();
  294. return !AllEmpty;
  295. #endif
  296. return true;
  297. }
  298. // --- TypeInfer
  299. bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
  300. const TypeSetByHwMode &In) {
  301. ValidateOnExit _1(Out, *this);
  302. In.validate();
  303. if (In.empty() || Out == In || TP.hasError())
  304. return false;
  305. if (Out.empty()) {
  306. Out = In;
  307. return true;
  308. }
  309. bool Changed = Out.constrain(In);
  310. if (Changed && Out.empty())
  311. TP.error("Type contradiction");
  312. return Changed;
  313. }
  314. bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
  315. ValidateOnExit _1(Out, *this);
  316. if (TP.hasError())
  317. return false;
  318. assert(!Out.empty() && "cannot pick from an empty set");
  319. bool Changed = false;
  320. for (auto &I : Out) {
  321. TypeSetByHwMode::SetType &S = I.second;
  322. if (S.size() <= 1)
  323. continue;
  324. MVT T = *S.begin(); // Pick the first element.
  325. S.clear();
  326. S.insert(T);
  327. Changed = true;
  328. }
  329. return Changed;
  330. }
  331. bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
  332. ValidateOnExit _1(Out, *this);
  333. if (TP.hasError())
  334. return false;
  335. if (!Out.empty())
  336. return Out.constrain(isIntegerOrPtr);
  337. return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
  338. }
  339. bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
  340. ValidateOnExit _1(Out, *this);
  341. if (TP.hasError())
  342. return false;
  343. if (!Out.empty())
  344. return Out.constrain(isFloatingPoint);
  345. return Out.assign_if(getLegalTypes(), isFloatingPoint);
  346. }
  347. bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
  348. ValidateOnExit _1(Out, *this);
  349. if (TP.hasError())
  350. return false;
  351. if (!Out.empty())
  352. return Out.constrain(isScalar);
  353. return Out.assign_if(getLegalTypes(), isScalar);
  354. }
  355. bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
  356. ValidateOnExit _1(Out, *this);
  357. if (TP.hasError())
  358. return false;
  359. if (!Out.empty())
  360. return Out.constrain(isVector);
  361. return Out.assign_if(getLegalTypes(), isVector);
  362. }
  363. bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
  364. ValidateOnExit _1(Out, *this);
  365. if (TP.hasError() || !Out.empty())
  366. return false;
  367. Out = getLegalTypes();
  368. return true;
  369. }
  370. template <typename Iter, typename Pred, typename Less>
  371. static Iter min_if(Iter B, Iter E, Pred P, Less L) {
  372. if (B == E)
  373. return E;
  374. Iter Min = E;
  375. for (Iter I = B; I != E; ++I) {
  376. if (!P(*I))
  377. continue;
  378. if (Min == E || L(*I, *Min))
  379. Min = I;
  380. }
  381. return Min;
  382. }
  383. template <typename Iter, typename Pred, typename Less>
  384. static Iter max_if(Iter B, Iter E, Pred P, Less L) {
  385. if (B == E)
  386. return E;
  387. Iter Max = E;
  388. for (Iter I = B; I != E; ++I) {
  389. if (!P(*I))
  390. continue;
  391. if (Max == E || L(*Max, *I))
  392. Max = I;
  393. }
  394. return Max;
  395. }
  396. /// Make sure that for each type in Small, there exists a larger type in Big.
  397. bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small, TypeSetByHwMode &Big,
  398. bool SmallIsVT) {
  399. ValidateOnExit _1(Small, *this), _2(Big, *this);
  400. if (TP.hasError())
  401. return false;
  402. bool Changed = false;
  403. assert((!SmallIsVT || !Small.empty()) &&
  404. "Small should not be empty for SDTCisVTSmallerThanOp");
  405. if (Small.empty())
  406. Changed |= EnforceAny(Small);
  407. if (Big.empty())
  408. Changed |= EnforceAny(Big);
  409. assert(Small.hasDefault() && Big.hasDefault());
  410. SmallVector<unsigned, 4> Modes;
  411. union_modes(Small, Big, Modes);
  412. // 1. Only allow integer or floating point types and make sure that
  413. // both sides are both integer or both floating point.
  414. // 2. Make sure that either both sides have vector types, or neither
  415. // of them does.
  416. for (unsigned M : Modes) {
  417. TypeSetByHwMode::SetType &S = Small.get(M);
  418. TypeSetByHwMode::SetType &B = Big.get(M);
  419. assert((!SmallIsVT || !S.empty()) && "Expected non-empty type");
  420. if (any_of(S, isIntegerOrPtr) && any_of(B, isIntegerOrPtr)) {
  421. auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
  422. Changed |= berase_if(S, NotInt);
  423. Changed |= berase_if(B, NotInt);
  424. } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
  425. auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
  426. Changed |= berase_if(S, NotFP);
  427. Changed |= berase_if(B, NotFP);
  428. } else if (SmallIsVT && B.empty()) {
  429. // B is empty and since S is a specific VT, it will never be empty. Don't
  430. // report this as a change, just clear S and continue. This prevents an
  431. // infinite loop.
  432. S.clear();
  433. } else if (S.empty() || B.empty()) {
  434. Changed = !S.empty() || !B.empty();
  435. S.clear();
  436. B.clear();
  437. } else {
  438. TP.error("Incompatible types");
  439. return Changed;
  440. }
  441. if (none_of(S, isVector) || none_of(B, isVector)) {
  442. Changed |= berase_if(S, isVector);
  443. Changed |= berase_if(B, isVector);
  444. }
  445. }
  446. auto LT = [](MVT A, MVT B) -> bool {
  447. // Always treat non-scalable MVTs as smaller than scalable MVTs for the
  448. // purposes of ordering.
  449. auto ASize = std::make_tuple(A.isScalableVector(), A.getScalarSizeInBits(),
  450. A.getSizeInBits().getKnownMinSize());
  451. auto BSize = std::make_tuple(B.isScalableVector(), B.getScalarSizeInBits(),
  452. B.getSizeInBits().getKnownMinSize());
  453. return ASize < BSize;
  454. };
  455. auto SameKindLE = [](MVT A, MVT B) -> bool {
  456. // This function is used when removing elements: when a vector is compared
  457. // to a non-vector or a scalable vector to any non-scalable MVT, it should
  458. // return false (to avoid removal).
  459. if (std::make_tuple(A.isVector(), A.isScalableVector()) !=
  460. std::make_tuple(B.isVector(), B.isScalableVector()))
  461. return false;
  462. return std::make_tuple(A.getScalarSizeInBits(),
  463. A.getSizeInBits().getKnownMinSize()) <=
  464. std::make_tuple(B.getScalarSizeInBits(),
  465. B.getSizeInBits().getKnownMinSize());
  466. };
  467. for (unsigned M : Modes) {
  468. TypeSetByHwMode::SetType &S = Small.get(M);
  469. TypeSetByHwMode::SetType &B = Big.get(M);
  470. // MinS = min scalar in Small, remove all scalars from Big that are
  471. // smaller-or-equal than MinS.
  472. auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
  473. if (MinS != S.end())
  474. Changed |= berase_if(B, std::bind(SameKindLE,
  475. std::placeholders::_1, *MinS));
  476. // MaxS = max scalar in Big, remove all scalars from Small that are
  477. // larger than MaxS.
  478. auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
  479. if (MaxS != B.end())
  480. Changed |= berase_if(S, std::bind(SameKindLE,
  481. *MaxS, std::placeholders::_1));
  482. // MinV = min vector in Small, remove all vectors from Big that are
  483. // smaller-or-equal than MinV.
  484. auto MinV = min_if(S.begin(), S.end(), isVector, LT);
  485. if (MinV != S.end())
  486. Changed |= berase_if(B, std::bind(SameKindLE,
  487. std::placeholders::_1, *MinV));
  488. // MaxV = max vector in Big, remove all vectors from Small that are
  489. // larger than MaxV.
  490. auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
  491. if (MaxV != B.end())
  492. Changed |= berase_if(S, std::bind(SameKindLE,
  493. *MaxV, std::placeholders::_1));
  494. }
  495. return Changed;
  496. }
  497. /// 1. Ensure that for each type T in Vec, T is a vector type, and that
  498. /// for each type U in Elem, U is a scalar type.
  499. /// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
  500. /// type T in Vec, such that U is the element type of T.
  501. bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
  502. TypeSetByHwMode &Elem) {
  503. ValidateOnExit _1(Vec, *this), _2(Elem, *this);
  504. if (TP.hasError())
  505. return false;
  506. bool Changed = false;
  507. if (Vec.empty())
  508. Changed |= EnforceVector(Vec);
  509. if (Elem.empty())
  510. Changed |= EnforceScalar(Elem);
  511. SmallVector<unsigned, 4> Modes;
  512. union_modes(Vec, Elem, Modes);
  513. for (unsigned M : Modes) {
  514. TypeSetByHwMode::SetType &V = Vec.get(M);
  515. TypeSetByHwMode::SetType &E = Elem.get(M);
  516. Changed |= berase_if(V, isScalar); // Scalar = !vector
  517. Changed |= berase_if(E, isVector); // Vector = !scalar
  518. assert(!V.empty() && !E.empty());
  519. MachineValueTypeSet VT, ST;
  520. // Collect element types from the "vector" set.
  521. for (MVT T : V)
  522. VT.insert(T.getVectorElementType());
  523. // Collect scalar types from the "element" set.
  524. for (MVT T : E)
  525. ST.insert(T);
  526. // Remove from V all (vector) types whose element type is not in S.
  527. Changed |= berase_if(V, [&ST](MVT T) -> bool {
  528. return !ST.count(T.getVectorElementType());
  529. });
  530. // Remove from E all (scalar) types, for which there is no corresponding
  531. // type in V.
  532. Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
  533. }
  534. return Changed;
  535. }
  536. bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
  537. const ValueTypeByHwMode &VVT) {
  538. TypeSetByHwMode Tmp(VVT);
  539. ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
  540. return EnforceVectorEltTypeIs(Vec, Tmp);
  541. }
  542. /// Ensure that for each type T in Sub, T is a vector type, and there
  543. /// exists a type U in Vec such that U is a vector type with the same
  544. /// element type as T and at least as many elements as T.
  545. bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
  546. TypeSetByHwMode &Sub) {
  547. ValidateOnExit _1(Vec, *this), _2(Sub, *this);
  548. if (TP.hasError())
  549. return false;
  550. /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
  551. auto IsSubVec = [](MVT B, MVT P) -> bool {
  552. if (!B.isVector() || !P.isVector())
  553. return false;
  554. // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
  555. // but until there are obvious use-cases for this, keep the
  556. // types separate.
  557. if (B.isScalableVector() != P.isScalableVector())
  558. return false;
  559. if (B.getVectorElementType() != P.getVectorElementType())
  560. return false;
  561. return B.getVectorMinNumElements() < P.getVectorMinNumElements();
  562. };
  563. /// Return true if S has no element (vector type) that T is a sub-vector of,
  564. /// i.e. has the same element type as T and more elements.
  565. auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
  566. for (auto I : S)
  567. if (IsSubVec(T, I))
  568. return false;
  569. return true;
  570. };
  571. /// Return true if S has no element (vector type) that T is a super-vector
  572. /// of, i.e. has the same element type as T and fewer elements.
  573. auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
  574. for (auto I : S)
  575. if (IsSubVec(I, T))
  576. return false;
  577. return true;
  578. };
  579. bool Changed = false;
  580. if (Vec.empty())
  581. Changed |= EnforceVector(Vec);
  582. if (Sub.empty())
  583. Changed |= EnforceVector(Sub);
  584. SmallVector<unsigned, 4> Modes;
  585. union_modes(Vec, Sub, Modes);
  586. for (unsigned M : Modes) {
  587. TypeSetByHwMode::SetType &S = Sub.get(M);
  588. TypeSetByHwMode::SetType &V = Vec.get(M);
  589. Changed |= berase_if(S, isScalar);
  590. // Erase all types from S that are not sub-vectors of a type in V.
  591. Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
  592. // Erase all types from V that are not super-vectors of a type in S.
  593. Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
  594. }
  595. return Changed;
  596. }
  597. /// 1. Ensure that V has a scalar type iff W has a scalar type.
  598. /// 2. Ensure that for each vector type T in V, there exists a vector
  599. /// type U in W, such that T and U have the same number of elements.
  600. /// 3. Ensure that for each vector type U in W, there exists a vector
  601. /// type T in V, such that T and U have the same number of elements
  602. /// (reverse of 2).
  603. bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
  604. ValidateOnExit _1(V, *this), _2(W, *this);
  605. if (TP.hasError())
  606. return false;
  607. bool Changed = false;
  608. if (V.empty())
  609. Changed |= EnforceAny(V);
  610. if (W.empty())
  611. Changed |= EnforceAny(W);
  612. // An actual vector type cannot have 0 elements, so we can treat scalars
  613. // as zero-length vectors. This way both vectors and scalars can be
  614. // processed identically.
  615. auto NoLength = [](const SmallDenseSet<ElementCount> &Lengths,
  616. MVT T) -> bool {
  617. return !Lengths.count(T.isVector() ? T.getVectorElementCount()
  618. : ElementCount::getNull());
  619. };
  620. SmallVector<unsigned, 4> Modes;
  621. union_modes(V, W, Modes);
  622. for (unsigned M : Modes) {
  623. TypeSetByHwMode::SetType &VS = V.get(M);
  624. TypeSetByHwMode::SetType &WS = W.get(M);
  625. SmallDenseSet<ElementCount> VN, WN;
  626. for (MVT T : VS)
  627. VN.insert(T.isVector() ? T.getVectorElementCount()
  628. : ElementCount::getNull());
  629. for (MVT T : WS)
  630. WN.insert(T.isVector() ? T.getVectorElementCount()
  631. : ElementCount::getNull());
  632. Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
  633. Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
  634. }
  635. return Changed;
  636. }
  637. namespace {
  638. struct TypeSizeComparator {
  639. bool operator()(const TypeSize &LHS, const TypeSize &RHS) const {
  640. return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
  641. std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
  642. }
  643. };
  644. } // end anonymous namespace
  645. /// 1. Ensure that for each type T in A, there exists a type U in B,
  646. /// such that T and U have equal size in bits.
  647. /// 2. Ensure that for each type U in B, there exists a type T in A
  648. /// such that T and U have equal size in bits (reverse of 1).
  649. bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
  650. ValidateOnExit _1(A, *this), _2(B, *this);
  651. if (TP.hasError())
  652. return false;
  653. bool Changed = false;
  654. if (A.empty())
  655. Changed |= EnforceAny(A);
  656. if (B.empty())
  657. Changed |= EnforceAny(B);
  658. typedef SmallSet<TypeSize, 2, TypeSizeComparator> TypeSizeSet;
  659. auto NoSize = [](const TypeSizeSet &Sizes, MVT T) -> bool {
  660. return !Sizes.count(T.getSizeInBits());
  661. };
  662. SmallVector<unsigned, 4> Modes;
  663. union_modes(A, B, Modes);
  664. for (unsigned M : Modes) {
  665. TypeSetByHwMode::SetType &AS = A.get(M);
  666. TypeSetByHwMode::SetType &BS = B.get(M);
  667. TypeSizeSet AN, BN;
  668. for (MVT T : AS)
  669. AN.insert(T.getSizeInBits());
  670. for (MVT T : BS)
  671. BN.insert(T.getSizeInBits());
  672. Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
  673. Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
  674. }
  675. return Changed;
  676. }
  677. void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
  678. ValidateOnExit _1(VTS, *this);
  679. const TypeSetByHwMode &Legal = getLegalTypes();
  680. assert(Legal.isDefaultOnly() && "Default-mode only expected");
  681. const TypeSetByHwMode::SetType &LegalTypes = Legal.get(DefaultMode);
  682. for (auto &I : VTS)
  683. expandOverloads(I.second, LegalTypes);
  684. }
  685. void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
  686. const TypeSetByHwMode::SetType &Legal) {
  687. std::set<MVT> Ovs;
  688. for (MVT T : Out) {
  689. if (!T.isOverloaded())
  690. continue;
  691. Ovs.insert(T);
  692. // MachineValueTypeSet allows iteration and erasing.
  693. Out.erase(T);
  694. }
  695. for (MVT Ov : Ovs) {
  696. switch (Ov.SimpleTy) {
  697. case MVT::iPTRAny:
  698. Out.insert(MVT::iPTR);
  699. return;
  700. case MVT::iAny:
  701. for (MVT T : MVT::integer_valuetypes())
  702. if (Legal.count(T))
  703. Out.insert(T);
  704. for (MVT T : MVT::integer_fixedlen_vector_valuetypes())
  705. if (Legal.count(T))
  706. Out.insert(T);
  707. for (MVT T : MVT::integer_scalable_vector_valuetypes())
  708. if (Legal.count(T))
  709. Out.insert(T);
  710. return;
  711. case MVT::fAny:
  712. for (MVT T : MVT::fp_valuetypes())
  713. if (Legal.count(T))
  714. Out.insert(T);
  715. for (MVT T : MVT::fp_fixedlen_vector_valuetypes())
  716. if (Legal.count(T))
  717. Out.insert(T);
  718. for (MVT T : MVT::fp_scalable_vector_valuetypes())
  719. if (Legal.count(T))
  720. Out.insert(T);
  721. return;
  722. case MVT::vAny:
  723. for (MVT T : MVT::vector_valuetypes())
  724. if (Legal.count(T))
  725. Out.insert(T);
  726. return;
  727. case MVT::Any:
  728. for (MVT T : MVT::all_valuetypes())
  729. if (Legal.count(T))
  730. Out.insert(T);
  731. return;
  732. default:
  733. break;
  734. }
  735. }
  736. }
  737. const TypeSetByHwMode &TypeInfer::getLegalTypes() {
  738. if (!LegalTypesCached) {
  739. TypeSetByHwMode::SetType &LegalTypes = LegalCache.getOrCreate(DefaultMode);
  740. // Stuff all types from all modes into the default mode.
  741. const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
  742. for (const auto &I : LTS)
  743. LegalTypes.insert(I.second);
  744. LegalTypesCached = true;
  745. }
  746. assert(LegalCache.isDefaultOnly() && "Default-mode only expected");
  747. return LegalCache;
  748. }
  749. #ifndef NDEBUG
  750. TypeInfer::ValidateOnExit::~ValidateOnExit() {
  751. if (Infer.Validate && !VTS.validate()) {
  752. dbgs() << "Type set is empty for each HW mode:\n"
  753. "possible type contradiction in the pattern below "
  754. "(use -print-records with llvm-tblgen to see all "
  755. "expanded records).\n";
  756. Infer.TP.dump();
  757. dbgs() << "Generated from record:\n";
  758. Infer.TP.getRecord()->dump();
  759. PrintFatalError(Infer.TP.getRecord()->getLoc(),
  760. "Type set is empty for each HW mode in '" +
  761. Infer.TP.getRecord()->getName() + "'");
  762. }
  763. }
  764. #endif
  765. //===----------------------------------------------------------------------===//
  766. // ScopedName Implementation
  767. //===----------------------------------------------------------------------===//
  768. bool ScopedName::operator==(const ScopedName &o) const {
  769. return Scope == o.Scope && Identifier == o.Identifier;
  770. }
  771. bool ScopedName::operator!=(const ScopedName &o) const {
  772. return !(*this == o);
  773. }
  774. //===----------------------------------------------------------------------===//
  775. // TreePredicateFn Implementation
  776. //===----------------------------------------------------------------------===//
  777. /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
  778. TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
  779. assert(
  780. (!hasPredCode() || !hasImmCode()) &&
  781. ".td file corrupt: can't have a node predicate *and* an imm predicate");
  782. }
  783. bool TreePredicateFn::hasPredCode() const {
  784. return isLoad() || isStore() || isAtomic() ||
  785. !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
  786. }
  787. std::string TreePredicateFn::getPredCode() const {
  788. std::string Code;
  789. if (!isLoad() && !isStore() && !isAtomic()) {
  790. Record *MemoryVT = getMemoryVT();
  791. if (MemoryVT)
  792. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  793. "MemoryVT requires IsLoad or IsStore");
  794. }
  795. if (!isLoad() && !isStore()) {
  796. if (isUnindexed())
  797. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  798. "IsUnindexed requires IsLoad or IsStore");
  799. Record *ScalarMemoryVT = getScalarMemoryVT();
  800. if (ScalarMemoryVT)
  801. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  802. "ScalarMemoryVT requires IsLoad or IsStore");
  803. }
  804. if (isLoad() + isStore() + isAtomic() > 1)
  805. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  806. "IsLoad, IsStore, and IsAtomic are mutually exclusive");
  807. if (isLoad()) {
  808. if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
  809. !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
  810. getScalarMemoryVT() == nullptr && getAddressSpaces() == nullptr &&
  811. getMinAlignment() < 1)
  812. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  813. "IsLoad cannot be used by itself");
  814. } else {
  815. if (isNonExtLoad())
  816. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  817. "IsNonExtLoad requires IsLoad");
  818. if (isAnyExtLoad())
  819. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  820. "IsAnyExtLoad requires IsLoad");
  821. if (isSignExtLoad())
  822. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  823. "IsSignExtLoad requires IsLoad");
  824. if (isZeroExtLoad())
  825. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  826. "IsZeroExtLoad requires IsLoad");
  827. }
  828. if (isStore()) {
  829. if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
  830. getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr &&
  831. getAddressSpaces() == nullptr && getMinAlignment() < 1)
  832. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  833. "IsStore cannot be used by itself");
  834. } else {
  835. if (isNonTruncStore())
  836. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  837. "IsNonTruncStore requires IsStore");
  838. if (isTruncStore())
  839. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  840. "IsTruncStore requires IsStore");
  841. }
  842. if (isAtomic()) {
  843. if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
  844. getAddressSpaces() == nullptr &&
  845. !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
  846. !isAtomicOrderingAcquireRelease() &&
  847. !isAtomicOrderingSequentiallyConsistent() &&
  848. !isAtomicOrderingAcquireOrStronger() &&
  849. !isAtomicOrderingReleaseOrStronger() &&
  850. !isAtomicOrderingWeakerThanAcquire() &&
  851. !isAtomicOrderingWeakerThanRelease())
  852. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  853. "IsAtomic cannot be used by itself");
  854. } else {
  855. if (isAtomicOrderingMonotonic())
  856. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  857. "IsAtomicOrderingMonotonic requires IsAtomic");
  858. if (isAtomicOrderingAcquire())
  859. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  860. "IsAtomicOrderingAcquire requires IsAtomic");
  861. if (isAtomicOrderingRelease())
  862. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  863. "IsAtomicOrderingRelease requires IsAtomic");
  864. if (isAtomicOrderingAcquireRelease())
  865. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  866. "IsAtomicOrderingAcquireRelease requires IsAtomic");
  867. if (isAtomicOrderingSequentiallyConsistent())
  868. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  869. "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
  870. if (isAtomicOrderingAcquireOrStronger())
  871. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  872. "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
  873. if (isAtomicOrderingReleaseOrStronger())
  874. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  875. "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
  876. if (isAtomicOrderingWeakerThanAcquire())
  877. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  878. "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
  879. }
  880. if (isLoad() || isStore() || isAtomic()) {
  881. if (ListInit *AddressSpaces = getAddressSpaces()) {
  882. Code += "unsigned AddrSpace = cast<MemSDNode>(N)->getAddressSpace();\n"
  883. " if (";
  884. ListSeparator LS(" && ");
  885. for (Init *Val : AddressSpaces->getValues()) {
  886. Code += LS;
  887. IntInit *IntVal = dyn_cast<IntInit>(Val);
  888. if (!IntVal) {
  889. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  890. "AddressSpaces element must be integer");
  891. }
  892. Code += "AddrSpace != " + utostr(IntVal->getValue());
  893. }
  894. Code += ")\nreturn false;\n";
  895. }
  896. int64_t MinAlign = getMinAlignment();
  897. if (MinAlign > 0) {
  898. Code += "if (cast<MemSDNode>(N)->getAlign() < Align(";
  899. Code += utostr(MinAlign);
  900. Code += "))\nreturn false;\n";
  901. }
  902. Record *MemoryVT = getMemoryVT();
  903. if (MemoryVT)
  904. Code += ("if (cast<MemSDNode>(N)->getMemoryVT() != MVT::" +
  905. MemoryVT->getName() + ") return false;\n")
  906. .str();
  907. }
  908. if (isAtomic() && isAtomicOrderingMonotonic())
  909. Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
  910. "AtomicOrdering::Monotonic) return false;\n";
  911. if (isAtomic() && isAtomicOrderingAcquire())
  912. Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
  913. "AtomicOrdering::Acquire) return false;\n";
  914. if (isAtomic() && isAtomicOrderingRelease())
  915. Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
  916. "AtomicOrdering::Release) return false;\n";
  917. if (isAtomic() && isAtomicOrderingAcquireRelease())
  918. Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
  919. "AtomicOrdering::AcquireRelease) return false;\n";
  920. if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
  921. Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
  922. "AtomicOrdering::SequentiallyConsistent) return false;\n";
  923. if (isAtomic() && isAtomicOrderingAcquireOrStronger())
  924. Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
  925. "return false;\n";
  926. if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
  927. Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
  928. "return false;\n";
  929. if (isAtomic() && isAtomicOrderingReleaseOrStronger())
  930. Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
  931. "return false;\n";
  932. if (isAtomic() && isAtomicOrderingWeakerThanRelease())
  933. Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
  934. "return false;\n";
  935. if (isLoad() || isStore()) {
  936. StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
  937. if (isUnindexed())
  938. Code += ("if (cast<" + SDNodeName +
  939. ">(N)->getAddressingMode() != ISD::UNINDEXED) "
  940. "return false;\n")
  941. .str();
  942. if (isLoad()) {
  943. if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
  944. isZeroExtLoad()) > 1)
  945. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  946. "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
  947. "IsZeroExtLoad are mutually exclusive");
  948. if (isNonExtLoad())
  949. Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
  950. "ISD::NON_EXTLOAD) return false;\n";
  951. if (isAnyExtLoad())
  952. Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
  953. "return false;\n";
  954. if (isSignExtLoad())
  955. Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
  956. "return false;\n";
  957. if (isZeroExtLoad())
  958. Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
  959. "return false;\n";
  960. } else {
  961. if ((isNonTruncStore() + isTruncStore()) > 1)
  962. PrintFatalError(
  963. getOrigPatFragRecord()->getRecord()->getLoc(),
  964. "IsNonTruncStore, and IsTruncStore are mutually exclusive");
  965. if (isNonTruncStore())
  966. Code +=
  967. " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
  968. if (isTruncStore())
  969. Code +=
  970. " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
  971. }
  972. Record *ScalarMemoryVT = getScalarMemoryVT();
  973. if (ScalarMemoryVT)
  974. Code += ("if (cast<" + SDNodeName +
  975. ">(N)->getMemoryVT().getScalarType() != MVT::" +
  976. ScalarMemoryVT->getName() + ") return false;\n")
  977. .str();
  978. }
  979. std::string PredicateCode =
  980. std::string(PatFragRec->getRecord()->getValueAsString("PredicateCode"));
  981. Code += PredicateCode;
  982. if (PredicateCode.empty() && !Code.empty())
  983. Code += "return true;\n";
  984. return Code;
  985. }
  986. bool TreePredicateFn::hasImmCode() const {
  987. return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
  988. }
  989. std::string TreePredicateFn::getImmCode() const {
  990. return std::string(
  991. PatFragRec->getRecord()->getValueAsString("ImmediateCode"));
  992. }
  993. bool TreePredicateFn::immCodeUsesAPInt() const {
  994. return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
  995. }
  996. bool TreePredicateFn::immCodeUsesAPFloat() const {
  997. bool Unset;
  998. // The return value will be false when IsAPFloat is unset.
  999. return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
  1000. Unset);
  1001. }
  1002. bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
  1003. bool Value) const {
  1004. bool Unset;
  1005. bool Result =
  1006. getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
  1007. if (Unset)
  1008. return false;
  1009. return Result == Value;
  1010. }
  1011. bool TreePredicateFn::usesOperands() const {
  1012. return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);
  1013. }
  1014. bool TreePredicateFn::isLoad() const {
  1015. return isPredefinedPredicateEqualTo("IsLoad", true);
  1016. }
  1017. bool TreePredicateFn::isStore() const {
  1018. return isPredefinedPredicateEqualTo("IsStore", true);
  1019. }
  1020. bool TreePredicateFn::isAtomic() const {
  1021. return isPredefinedPredicateEqualTo("IsAtomic", true);
  1022. }
  1023. bool TreePredicateFn::isUnindexed() const {
  1024. return isPredefinedPredicateEqualTo("IsUnindexed", true);
  1025. }
  1026. bool TreePredicateFn::isNonExtLoad() const {
  1027. return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
  1028. }
  1029. bool TreePredicateFn::isAnyExtLoad() const {
  1030. return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
  1031. }
  1032. bool TreePredicateFn::isSignExtLoad() const {
  1033. return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
  1034. }
  1035. bool TreePredicateFn::isZeroExtLoad() const {
  1036. return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
  1037. }
  1038. bool TreePredicateFn::isNonTruncStore() const {
  1039. return isPredefinedPredicateEqualTo("IsTruncStore", false);
  1040. }
  1041. bool TreePredicateFn::isTruncStore() const {
  1042. return isPredefinedPredicateEqualTo("IsTruncStore", true);
  1043. }
  1044. bool TreePredicateFn::isAtomicOrderingMonotonic() const {
  1045. return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
  1046. }
  1047. bool TreePredicateFn::isAtomicOrderingAcquire() const {
  1048. return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
  1049. }
  1050. bool TreePredicateFn::isAtomicOrderingRelease() const {
  1051. return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
  1052. }
  1053. bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
  1054. return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
  1055. }
  1056. bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
  1057. return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
  1058. true);
  1059. }
  1060. bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
  1061. return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
  1062. }
  1063. bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
  1064. return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
  1065. }
  1066. bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
  1067. return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
  1068. }
  1069. bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
  1070. return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
  1071. }
  1072. Record *TreePredicateFn::getMemoryVT() const {
  1073. Record *R = getOrigPatFragRecord()->getRecord();
  1074. if (R->isValueUnset("MemoryVT"))
  1075. return nullptr;
  1076. return R->getValueAsDef("MemoryVT");
  1077. }
  1078. ListInit *TreePredicateFn::getAddressSpaces() const {
  1079. Record *R = getOrigPatFragRecord()->getRecord();
  1080. if (R->isValueUnset("AddressSpaces"))
  1081. return nullptr;
  1082. return R->getValueAsListInit("AddressSpaces");
  1083. }
  1084. int64_t TreePredicateFn::getMinAlignment() const {
  1085. Record *R = getOrigPatFragRecord()->getRecord();
  1086. if (R->isValueUnset("MinAlignment"))
  1087. return 0;
  1088. return R->getValueAsInt("MinAlignment");
  1089. }
  1090. Record *TreePredicateFn::getScalarMemoryVT() const {
  1091. Record *R = getOrigPatFragRecord()->getRecord();
  1092. if (R->isValueUnset("ScalarMemoryVT"))
  1093. return nullptr;
  1094. return R->getValueAsDef("ScalarMemoryVT");
  1095. }
  1096. bool TreePredicateFn::hasGISelPredicateCode() const {
  1097. return !PatFragRec->getRecord()
  1098. ->getValueAsString("GISelPredicateCode")
  1099. .empty();
  1100. }
  1101. std::string TreePredicateFn::getGISelPredicateCode() const {
  1102. return std::string(
  1103. PatFragRec->getRecord()->getValueAsString("GISelPredicateCode"));
  1104. }
  1105. StringRef TreePredicateFn::getImmType() const {
  1106. if (immCodeUsesAPInt())
  1107. return "const APInt &";
  1108. if (immCodeUsesAPFloat())
  1109. return "const APFloat &";
  1110. return "int64_t";
  1111. }
  1112. StringRef TreePredicateFn::getImmTypeIdentifier() const {
  1113. if (immCodeUsesAPInt())
  1114. return "APInt";
  1115. if (immCodeUsesAPFloat())
  1116. return "APFloat";
  1117. return "I64";
  1118. }
  1119. /// isAlwaysTrue - Return true if this is a noop predicate.
  1120. bool TreePredicateFn::isAlwaysTrue() const {
  1121. return !hasPredCode() && !hasImmCode();
  1122. }
  1123. /// Return the name to use in the generated code to reference this, this is
  1124. /// "Predicate_foo" if from a pattern fragment "foo".
  1125. std::string TreePredicateFn::getFnName() const {
  1126. return "Predicate_" + PatFragRec->getRecord()->getName().str();
  1127. }
  1128. /// getCodeToRunOnSDNode - Return the code for the function body that
  1129. /// evaluates this predicate. The argument is expected to be in "Node",
  1130. /// not N. This handles casting and conversion to a concrete node type as
  1131. /// appropriate.
  1132. std::string TreePredicateFn::getCodeToRunOnSDNode() const {
  1133. // Handle immediate predicates first.
  1134. std::string ImmCode = getImmCode();
  1135. if (!ImmCode.empty()) {
  1136. if (isLoad())
  1137. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  1138. "IsLoad cannot be used with ImmLeaf or its subclasses");
  1139. if (isStore())
  1140. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  1141. "IsStore cannot be used with ImmLeaf or its subclasses");
  1142. if (isUnindexed())
  1143. PrintFatalError(
  1144. getOrigPatFragRecord()->getRecord()->getLoc(),
  1145. "IsUnindexed cannot be used with ImmLeaf or its subclasses");
  1146. if (isNonExtLoad())
  1147. PrintFatalError(
  1148. getOrigPatFragRecord()->getRecord()->getLoc(),
  1149. "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
  1150. if (isAnyExtLoad())
  1151. PrintFatalError(
  1152. getOrigPatFragRecord()->getRecord()->getLoc(),
  1153. "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
  1154. if (isSignExtLoad())
  1155. PrintFatalError(
  1156. getOrigPatFragRecord()->getRecord()->getLoc(),
  1157. "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
  1158. if (isZeroExtLoad())
  1159. PrintFatalError(
  1160. getOrigPatFragRecord()->getRecord()->getLoc(),
  1161. "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
  1162. if (isNonTruncStore())
  1163. PrintFatalError(
  1164. getOrigPatFragRecord()->getRecord()->getLoc(),
  1165. "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
  1166. if (isTruncStore())
  1167. PrintFatalError(
  1168. getOrigPatFragRecord()->getRecord()->getLoc(),
  1169. "IsTruncStore cannot be used with ImmLeaf or its subclasses");
  1170. if (getMemoryVT())
  1171. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  1172. "MemoryVT cannot be used with ImmLeaf or its subclasses");
  1173. if (getScalarMemoryVT())
  1174. PrintFatalError(
  1175. getOrigPatFragRecord()->getRecord()->getLoc(),
  1176. "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
  1177. std::string Result = (" " + getImmType() + " Imm = ").str();
  1178. if (immCodeUsesAPFloat())
  1179. Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
  1180. else if (immCodeUsesAPInt())
  1181. Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
  1182. else
  1183. Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
  1184. return Result + ImmCode;
  1185. }
  1186. // Handle arbitrary node predicates.
  1187. assert(hasPredCode() && "Don't have any predicate code!");
  1188. // If this is using PatFrags, there are multiple trees to search. They should
  1189. // all have the same class. FIXME: Is there a way to find a common
  1190. // superclass?
  1191. StringRef ClassName;
  1192. for (const auto &Tree : PatFragRec->getTrees()) {
  1193. StringRef TreeClassName;
  1194. if (Tree->isLeaf())
  1195. TreeClassName = "SDNode";
  1196. else {
  1197. Record *Op = Tree->getOperator();
  1198. const SDNodeInfo &Info = PatFragRec->getDAGPatterns().getSDNodeInfo(Op);
  1199. TreeClassName = Info.getSDClassName();
  1200. }
  1201. if (ClassName.empty())
  1202. ClassName = TreeClassName;
  1203. else if (ClassName != TreeClassName) {
  1204. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  1205. "PatFrags trees do not have consistent class");
  1206. }
  1207. }
  1208. std::string Result;
  1209. if (ClassName == "SDNode")
  1210. Result = " SDNode *N = Node;\n";
  1211. else
  1212. Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
  1213. return (Twine(Result) + " (void)N;\n" + getPredCode()).str();
  1214. }
  1215. //===----------------------------------------------------------------------===//
  1216. // PatternToMatch implementation
  1217. //
  1218. static bool isImmAllOnesAllZerosMatch(const TreePatternNode *P) {
  1219. if (!P->isLeaf())
  1220. return false;
  1221. DefInit *DI = dyn_cast<DefInit>(P->getLeafValue());
  1222. if (!DI)
  1223. return false;
  1224. Record *R = DI->getDef();
  1225. return R->getName() == "immAllOnesV" || R->getName() == "immAllZerosV";
  1226. }
  1227. /// getPatternSize - Return the 'size' of this pattern. We want to match large
  1228. /// patterns before small ones. This is used to determine the size of a
  1229. /// pattern.
  1230. static unsigned getPatternSize(const TreePatternNode *P,
  1231. const CodeGenDAGPatterns &CGP) {
  1232. unsigned Size = 3; // The node itself.
  1233. // If the root node is a ConstantSDNode, increases its size.
  1234. // e.g. (set R32:$dst, 0).
  1235. if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
  1236. Size += 2;
  1237. if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
  1238. Size += AM->getComplexity();
  1239. // We don't want to count any children twice, so return early.
  1240. return Size;
  1241. }
  1242. // If this node has some predicate function that must match, it adds to the
  1243. // complexity of this node.
  1244. if (!P->getPredicateCalls().empty())
  1245. ++Size;
  1246. // Count children in the count if they are also nodes.
  1247. for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
  1248. const TreePatternNode *Child = P->getChild(i);
  1249. if (!Child->isLeaf() && Child->getNumTypes()) {
  1250. const TypeSetByHwMode &T0 = Child->getExtType(0);
  1251. // At this point, all variable type sets should be simple, i.e. only
  1252. // have a default mode.
  1253. if (T0.getMachineValueType() != MVT::Other) {
  1254. Size += getPatternSize(Child, CGP);
  1255. continue;
  1256. }
  1257. }
  1258. if (Child->isLeaf()) {
  1259. if (isa<IntInit>(Child->getLeafValue()))
  1260. Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
  1261. else if (Child->getComplexPatternInfo(CGP))
  1262. Size += getPatternSize(Child, CGP);
  1263. else if (isImmAllOnesAllZerosMatch(Child))
  1264. Size += 4; // Matches a build_vector(+3) and a predicate (+1).
  1265. else if (!Child->getPredicateCalls().empty())
  1266. ++Size;
  1267. }
  1268. }
  1269. return Size;
  1270. }
  1271. /// Compute the complexity metric for the input pattern. This roughly
  1272. /// corresponds to the number of nodes that are covered.
  1273. int PatternToMatch::
  1274. getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
  1275. return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
  1276. }
  1277. void PatternToMatch::getPredicateRecords(
  1278. SmallVectorImpl<Record *> &PredicateRecs) const {
  1279. for (Init *I : Predicates->getValues()) {
  1280. if (DefInit *Pred = dyn_cast<DefInit>(I)) {
  1281. Record *Def = Pred->getDef();
  1282. if (!Def->isSubClassOf("Predicate")) {
  1283. #ifndef NDEBUG
  1284. Def->dump();
  1285. #endif
  1286. llvm_unreachable("Unknown predicate type!");
  1287. }
  1288. PredicateRecs.push_back(Def);
  1289. }
  1290. }
  1291. // Sort so that different orders get canonicalized to the same string.
  1292. llvm::sort(PredicateRecs, LessRecord());
  1293. }
  1294. /// getPredicateCheck - Return a single string containing all of this
  1295. /// pattern's predicates concatenated with "&&" operators.
  1296. ///
  1297. std::string PatternToMatch::getPredicateCheck() const {
  1298. SmallVector<Record *, 4> PredicateRecs;
  1299. getPredicateRecords(PredicateRecs);
  1300. SmallString<128> PredicateCheck;
  1301. for (Record *Pred : PredicateRecs) {
  1302. StringRef CondString = Pred->getValueAsString("CondString");
  1303. if (CondString.empty())
  1304. continue;
  1305. if (!PredicateCheck.empty())
  1306. PredicateCheck += " && ";
  1307. PredicateCheck += "(";
  1308. PredicateCheck += CondString;
  1309. PredicateCheck += ")";
  1310. }
  1311. if (!HwModeFeatures.empty()) {
  1312. if (!PredicateCheck.empty())
  1313. PredicateCheck += " && ";
  1314. PredicateCheck += HwModeFeatures;
  1315. }
  1316. return std::string(PredicateCheck);
  1317. }
  1318. //===----------------------------------------------------------------------===//
  1319. // SDTypeConstraint implementation
  1320. //
  1321. SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
  1322. OperandNo = R->getValueAsInt("OperandNum");
  1323. if (R->isSubClassOf("SDTCisVT")) {
  1324. ConstraintType = SDTCisVT;
  1325. VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
  1326. for (const auto &P : VVT)
  1327. if (P.second == MVT::isVoid)
  1328. PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
  1329. } else if (R->isSubClassOf("SDTCisPtrTy")) {
  1330. ConstraintType = SDTCisPtrTy;
  1331. } else if (R->isSubClassOf("SDTCisInt")) {
  1332. ConstraintType = SDTCisInt;
  1333. } else if (R->isSubClassOf("SDTCisFP")) {
  1334. ConstraintType = SDTCisFP;
  1335. } else if (R->isSubClassOf("SDTCisVec")) {
  1336. ConstraintType = SDTCisVec;
  1337. } else if (R->isSubClassOf("SDTCisSameAs")) {
  1338. ConstraintType = SDTCisSameAs;
  1339. x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
  1340. } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
  1341. ConstraintType = SDTCisVTSmallerThanOp;
  1342. x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
  1343. R->getValueAsInt("OtherOperandNum");
  1344. } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
  1345. ConstraintType = SDTCisOpSmallerThanOp;
  1346. x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
  1347. R->getValueAsInt("BigOperandNum");
  1348. } else if (R->isSubClassOf("SDTCisEltOfVec")) {
  1349. ConstraintType = SDTCisEltOfVec;
  1350. x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
  1351. } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
  1352. ConstraintType = SDTCisSubVecOfVec;
  1353. x.SDTCisSubVecOfVec_Info.OtherOperandNum =
  1354. R->getValueAsInt("OtherOpNum");
  1355. } else if (R->isSubClassOf("SDTCVecEltisVT")) {
  1356. ConstraintType = SDTCVecEltisVT;
  1357. VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
  1358. for (const auto &P : VVT) {
  1359. MVT T = P.second;
  1360. if (T.isVector())
  1361. PrintFatalError(R->getLoc(),
  1362. "Cannot use vector type as SDTCVecEltisVT");
  1363. if (!T.isInteger() && !T.isFloatingPoint())
  1364. PrintFatalError(R->getLoc(), "Must use integer or floating point type "
  1365. "as SDTCVecEltisVT");
  1366. }
  1367. } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
  1368. ConstraintType = SDTCisSameNumEltsAs;
  1369. x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
  1370. R->getValueAsInt("OtherOperandNum");
  1371. } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
  1372. ConstraintType = SDTCisSameSizeAs;
  1373. x.SDTCisSameSizeAs_Info.OtherOperandNum =
  1374. R->getValueAsInt("OtherOperandNum");
  1375. } else {
  1376. PrintFatalError(R->getLoc(),
  1377. "Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
  1378. }
  1379. }
  1380. /// getOperandNum - Return the node corresponding to operand #OpNo in tree
  1381. /// N, and the result number in ResNo.
  1382. static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
  1383. const SDNodeInfo &NodeInfo,
  1384. unsigned &ResNo) {
  1385. unsigned NumResults = NodeInfo.getNumResults();
  1386. if (OpNo < NumResults) {
  1387. ResNo = OpNo;
  1388. return N;
  1389. }
  1390. OpNo -= NumResults;
  1391. if (OpNo >= N->getNumChildren()) {
  1392. std::string S;
  1393. raw_string_ostream OS(S);
  1394. OS << "Invalid operand number in type constraint "
  1395. << (OpNo+NumResults) << " ";
  1396. N->print(OS);
  1397. PrintFatalError(S);
  1398. }
  1399. return N->getChild(OpNo);
  1400. }
  1401. /// ApplyTypeConstraint - Given a node in a pattern, apply this type
  1402. /// constraint to the nodes operands. This returns true if it makes a
  1403. /// change, false otherwise. If a type contradiction is found, flag an error.
  1404. bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
  1405. const SDNodeInfo &NodeInfo,
  1406. TreePattern &TP) const {
  1407. if (TP.hasError())
  1408. return false;
  1409. unsigned ResNo = 0; // The result number being referenced.
  1410. TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
  1411. TypeInfer &TI = TP.getInfer();
  1412. switch (ConstraintType) {
  1413. case SDTCisVT:
  1414. // Operand must be a particular type.
  1415. return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
  1416. case SDTCisPtrTy:
  1417. // Operand must be same as target pointer type.
  1418. return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
  1419. case SDTCisInt:
  1420. // Require it to be one of the legal integer VTs.
  1421. return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
  1422. case SDTCisFP:
  1423. // Require it to be one of the legal fp VTs.
  1424. return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
  1425. case SDTCisVec:
  1426. // Require it to be one of the legal vector VTs.
  1427. return TI.EnforceVector(NodeToApply->getExtType(ResNo));
  1428. case SDTCisSameAs: {
  1429. unsigned OResNo = 0;
  1430. TreePatternNode *OtherNode =
  1431. getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
  1432. return (int)NodeToApply->UpdateNodeType(ResNo,
  1433. OtherNode->getExtType(OResNo), TP) |
  1434. (int)OtherNode->UpdateNodeType(OResNo,
  1435. NodeToApply->getExtType(ResNo), TP);
  1436. }
  1437. case SDTCisVTSmallerThanOp: {
  1438. // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
  1439. // have an integer type that is smaller than the VT.
  1440. if (!NodeToApply->isLeaf() ||
  1441. !isa<DefInit>(NodeToApply->getLeafValue()) ||
  1442. !cast<DefInit>(NodeToApply->getLeafValue())->getDef()
  1443. ->isSubClassOf("ValueType")) {
  1444. TP.error(N->getOperator()->getName() + " expects a VT operand!");
  1445. return false;
  1446. }
  1447. DefInit *DI = cast<DefInit>(NodeToApply->getLeafValue());
  1448. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1449. auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
  1450. TypeSetByHwMode TypeListTmp(VVT);
  1451. unsigned OResNo = 0;
  1452. TreePatternNode *OtherNode =
  1453. getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
  1454. OResNo);
  1455. return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo),
  1456. /*SmallIsVT*/ true);
  1457. }
  1458. case SDTCisOpSmallerThanOp: {
  1459. unsigned BResNo = 0;
  1460. TreePatternNode *BigOperand =
  1461. getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
  1462. BResNo);
  1463. return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
  1464. BigOperand->getExtType(BResNo));
  1465. }
  1466. case SDTCisEltOfVec: {
  1467. unsigned VResNo = 0;
  1468. TreePatternNode *VecOperand =
  1469. getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
  1470. VResNo);
  1471. // Filter vector types out of VecOperand that don't have the right element
  1472. // type.
  1473. return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
  1474. NodeToApply->getExtType(ResNo));
  1475. }
  1476. case SDTCisSubVecOfVec: {
  1477. unsigned VResNo = 0;
  1478. TreePatternNode *BigVecOperand =
  1479. getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
  1480. VResNo);
  1481. // Filter vector types out of BigVecOperand that don't have the
  1482. // right subvector type.
  1483. return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
  1484. NodeToApply->getExtType(ResNo));
  1485. }
  1486. case SDTCVecEltisVT: {
  1487. return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
  1488. }
  1489. case SDTCisSameNumEltsAs: {
  1490. unsigned OResNo = 0;
  1491. TreePatternNode *OtherNode =
  1492. getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
  1493. N, NodeInfo, OResNo);
  1494. return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
  1495. NodeToApply->getExtType(ResNo));
  1496. }
  1497. case SDTCisSameSizeAs: {
  1498. unsigned OResNo = 0;
  1499. TreePatternNode *OtherNode =
  1500. getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
  1501. N, NodeInfo, OResNo);
  1502. return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
  1503. NodeToApply->getExtType(ResNo));
  1504. }
  1505. }
  1506. llvm_unreachable("Invalid ConstraintType!");
  1507. }
  1508. // Update the node type to match an instruction operand or result as specified
  1509. // in the ins or outs lists on the instruction definition. Return true if the
  1510. // type was actually changed.
  1511. bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
  1512. Record *Operand,
  1513. TreePattern &TP) {
  1514. // The 'unknown' operand indicates that types should be inferred from the
  1515. // context.
  1516. if (Operand->isSubClassOf("unknown_class"))
  1517. return false;
  1518. // The Operand class specifies a type directly.
  1519. if (Operand->isSubClassOf("Operand")) {
  1520. Record *R = Operand->getValueAsDef("Type");
  1521. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1522. return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
  1523. }
  1524. // PointerLikeRegClass has a type that is determined at runtime.
  1525. if (Operand->isSubClassOf("PointerLikeRegClass"))
  1526. return UpdateNodeType(ResNo, MVT::iPTR, TP);
  1527. // Both RegisterClass and RegisterOperand operands derive their types from a
  1528. // register class def.
  1529. Record *RC = nullptr;
  1530. if (Operand->isSubClassOf("RegisterClass"))
  1531. RC = Operand;
  1532. else if (Operand->isSubClassOf("RegisterOperand"))
  1533. RC = Operand->getValueAsDef("RegClass");
  1534. assert(RC && "Unknown operand type");
  1535. CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
  1536. return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
  1537. }
  1538. bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
  1539. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  1540. if (!TP.getInfer().isConcrete(Types[i], true))
  1541. return true;
  1542. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1543. if (getChild(i)->ContainsUnresolvedType(TP))
  1544. return true;
  1545. return false;
  1546. }
  1547. bool TreePatternNode::hasProperTypeByHwMode() const {
  1548. for (const TypeSetByHwMode &S : Types)
  1549. if (!S.isDefaultOnly())
  1550. return true;
  1551. for (const TreePatternNodePtr &C : Children)
  1552. if (C->hasProperTypeByHwMode())
  1553. return true;
  1554. return false;
  1555. }
  1556. bool TreePatternNode::hasPossibleType() const {
  1557. for (const TypeSetByHwMode &S : Types)
  1558. if (!S.isPossible())
  1559. return false;
  1560. for (const TreePatternNodePtr &C : Children)
  1561. if (!C->hasPossibleType())
  1562. return false;
  1563. return true;
  1564. }
  1565. bool TreePatternNode::setDefaultMode(unsigned Mode) {
  1566. for (TypeSetByHwMode &S : Types) {
  1567. S.makeSimple(Mode);
  1568. // Check if the selected mode had a type conflict.
  1569. if (S.get(DefaultMode).empty())
  1570. return false;
  1571. }
  1572. for (const TreePatternNodePtr &C : Children)
  1573. if (!C->setDefaultMode(Mode))
  1574. return false;
  1575. return true;
  1576. }
  1577. //===----------------------------------------------------------------------===//
  1578. // SDNodeInfo implementation
  1579. //
  1580. SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
  1581. EnumName = R->getValueAsString("Opcode");
  1582. SDClassName = R->getValueAsString("SDClass");
  1583. Record *TypeProfile = R->getValueAsDef("TypeProfile");
  1584. NumResults = TypeProfile->getValueAsInt("NumResults");
  1585. NumOperands = TypeProfile->getValueAsInt("NumOperands");
  1586. // Parse the properties.
  1587. Properties = parseSDPatternOperatorProperties(R);
  1588. // Parse the type constraints.
  1589. std::vector<Record*> ConstraintList =
  1590. TypeProfile->getValueAsListOfDefs("Constraints");
  1591. for (Record *R : ConstraintList)
  1592. TypeConstraints.emplace_back(R, CGH);
  1593. }
  1594. /// getKnownType - If the type constraints on this node imply a fixed type
  1595. /// (e.g. all stores return void, etc), then return it as an
  1596. /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
  1597. MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
  1598. unsigned NumResults = getNumResults();
  1599. assert(NumResults <= 1 &&
  1600. "We only work with nodes with zero or one result so far!");
  1601. assert(ResNo == 0 && "Only handles single result nodes so far");
  1602. for (const SDTypeConstraint &Constraint : TypeConstraints) {
  1603. // Make sure that this applies to the correct node result.
  1604. if (Constraint.OperandNo >= NumResults) // FIXME: need value #
  1605. continue;
  1606. switch (Constraint.ConstraintType) {
  1607. default: break;
  1608. case SDTypeConstraint::SDTCisVT:
  1609. if (Constraint.VVT.isSimple())
  1610. return Constraint.VVT.getSimple().SimpleTy;
  1611. break;
  1612. case SDTypeConstraint::SDTCisPtrTy:
  1613. return MVT::iPTR;
  1614. }
  1615. }
  1616. return MVT::Other;
  1617. }
  1618. //===----------------------------------------------------------------------===//
  1619. // TreePatternNode implementation
  1620. //
  1621. static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
  1622. if (Operator->getName() == "set" ||
  1623. Operator->getName() == "implicit")
  1624. return 0; // All return nothing.
  1625. if (Operator->isSubClassOf("Intrinsic"))
  1626. return CDP.getIntrinsic(Operator).IS.RetVTs.size();
  1627. if (Operator->isSubClassOf("SDNode"))
  1628. return CDP.getSDNodeInfo(Operator).getNumResults();
  1629. if (Operator->isSubClassOf("PatFrags")) {
  1630. // If we've already parsed this pattern fragment, get it. Otherwise, handle
  1631. // the forward reference case where one pattern fragment references another
  1632. // before it is processed.
  1633. if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
  1634. // The number of results of a fragment with alternative records is the
  1635. // maximum number of results across all alternatives.
  1636. unsigned NumResults = 0;
  1637. for (const auto &T : PFRec->getTrees())
  1638. NumResults = std::max(NumResults, T->getNumTypes());
  1639. return NumResults;
  1640. }
  1641. ListInit *LI = Operator->getValueAsListInit("Fragments");
  1642. assert(LI && "Invalid Fragment");
  1643. unsigned NumResults = 0;
  1644. for (Init *I : LI->getValues()) {
  1645. Record *Op = nullptr;
  1646. if (DagInit *Dag = dyn_cast<DagInit>(I))
  1647. if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
  1648. Op = DI->getDef();
  1649. assert(Op && "Invalid Fragment");
  1650. NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
  1651. }
  1652. return NumResults;
  1653. }
  1654. if (Operator->isSubClassOf("Instruction")) {
  1655. CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
  1656. unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
  1657. // Subtract any defaulted outputs.
  1658. for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
  1659. Record *OperandNode = InstInfo.Operands[i].Rec;
  1660. if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
  1661. !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
  1662. --NumDefsToAdd;
  1663. }
  1664. // Add on one implicit def if it has a resolvable type.
  1665. if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
  1666. ++NumDefsToAdd;
  1667. return NumDefsToAdd;
  1668. }
  1669. if (Operator->isSubClassOf("SDNodeXForm"))
  1670. return 1; // FIXME: Generalize SDNodeXForm
  1671. if (Operator->isSubClassOf("ValueType"))
  1672. return 1; // A type-cast of one result.
  1673. if (Operator->isSubClassOf("ComplexPattern"))
  1674. return 1;
  1675. errs() << *Operator;
  1676. PrintFatalError("Unhandled node in GetNumNodeResults");
  1677. }
  1678. void TreePatternNode::print(raw_ostream &OS) const {
  1679. if (isLeaf())
  1680. OS << *getLeafValue();
  1681. else
  1682. OS << '(' << getOperator()->getName();
  1683. for (unsigned i = 0, e = Types.size(); i != e; ++i) {
  1684. OS << ':';
  1685. getExtType(i).writeToStream(OS);
  1686. }
  1687. if (!isLeaf()) {
  1688. if (getNumChildren() != 0) {
  1689. OS << " ";
  1690. ListSeparator LS;
  1691. for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
  1692. OS << LS;
  1693. getChild(i)->print(OS);
  1694. }
  1695. }
  1696. OS << ")";
  1697. }
  1698. for (const TreePredicateCall &Pred : PredicateCalls) {
  1699. OS << "<<P:";
  1700. if (Pred.Scope)
  1701. OS << Pred.Scope << ":";
  1702. OS << Pred.Fn.getFnName() << ">>";
  1703. }
  1704. if (TransformFn)
  1705. OS << "<<X:" << TransformFn->getName() << ">>";
  1706. if (!getName().empty())
  1707. OS << ":$" << getName();
  1708. for (const ScopedName &Name : NamesAsPredicateArg)
  1709. OS << ":$pred:" << Name.getScope() << ":" << Name.getIdentifier();
  1710. }
  1711. void TreePatternNode::dump() const {
  1712. print(errs());
  1713. }
  1714. /// isIsomorphicTo - Return true if this node is recursively
  1715. /// isomorphic to the specified node. For this comparison, the node's
  1716. /// entire state is considered. The assigned name is ignored, since
  1717. /// nodes with differing names are considered isomorphic. However, if
  1718. /// the assigned name is present in the dependent variable set, then
  1719. /// the assigned name is considered significant and the node is
  1720. /// isomorphic if the names match.
  1721. bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
  1722. const MultipleUseVarSet &DepVars) const {
  1723. if (N == this) return true;
  1724. if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
  1725. getPredicateCalls() != N->getPredicateCalls() ||
  1726. getTransformFn() != N->getTransformFn())
  1727. return false;
  1728. if (isLeaf()) {
  1729. if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
  1730. if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
  1731. return ((DI->getDef() == NDI->getDef())
  1732. && (DepVars.find(getName()) == DepVars.end()
  1733. || getName() == N->getName()));
  1734. }
  1735. }
  1736. return getLeafValue() == N->getLeafValue();
  1737. }
  1738. if (N->getOperator() != getOperator() ||
  1739. N->getNumChildren() != getNumChildren()) return false;
  1740. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1741. if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
  1742. return false;
  1743. return true;
  1744. }
  1745. /// clone - Make a copy of this tree and all of its children.
  1746. ///
  1747. TreePatternNodePtr TreePatternNode::clone() const {
  1748. TreePatternNodePtr New;
  1749. if (isLeaf()) {
  1750. New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes());
  1751. } else {
  1752. std::vector<TreePatternNodePtr> CChildren;
  1753. CChildren.reserve(Children.size());
  1754. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1755. CChildren.push_back(getChild(i)->clone());
  1756. New = std::make_shared<TreePatternNode>(getOperator(), std::move(CChildren),
  1757. getNumTypes());
  1758. }
  1759. New->setName(getName());
  1760. New->setNamesAsPredicateArg(getNamesAsPredicateArg());
  1761. New->Types = Types;
  1762. New->setPredicateCalls(getPredicateCalls());
  1763. New->setTransformFn(getTransformFn());
  1764. return New;
  1765. }
  1766. /// RemoveAllTypes - Recursively strip all the types of this tree.
  1767. void TreePatternNode::RemoveAllTypes() {
  1768. // Reset to unknown type.
  1769. std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
  1770. if (isLeaf()) return;
  1771. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1772. getChild(i)->RemoveAllTypes();
  1773. }
  1774. /// SubstituteFormalArguments - Replace the formal arguments in this tree
  1775. /// with actual values specified by ArgMap.
  1776. void TreePatternNode::SubstituteFormalArguments(
  1777. std::map<std::string, TreePatternNodePtr> &ArgMap) {
  1778. if (isLeaf()) return;
  1779. for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
  1780. TreePatternNode *Child = getChild(i);
  1781. if (Child->isLeaf()) {
  1782. Init *Val = Child->getLeafValue();
  1783. // Note that, when substituting into an output pattern, Val might be an
  1784. // UnsetInit.
  1785. if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
  1786. cast<DefInit>(Val)->getDef()->getName() == "node")) {
  1787. // We found a use of a formal argument, replace it with its value.
  1788. TreePatternNodePtr NewChild = ArgMap[Child->getName()];
  1789. assert(NewChild && "Couldn't find formal argument!");
  1790. assert((Child->getPredicateCalls().empty() ||
  1791. NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
  1792. "Non-empty child predicate clobbered!");
  1793. setChild(i, std::move(NewChild));
  1794. }
  1795. } else {
  1796. getChild(i)->SubstituteFormalArguments(ArgMap);
  1797. }
  1798. }
  1799. }
  1800. /// InlinePatternFragments - If this pattern refers to any pattern
  1801. /// fragments, return the set of inlined versions (this can be more than
  1802. /// one if a PatFrags record has multiple alternatives).
  1803. void TreePatternNode::InlinePatternFragments(
  1804. TreePatternNodePtr T, TreePattern &TP,
  1805. std::vector<TreePatternNodePtr> &OutAlternatives) {
  1806. if (TP.hasError())
  1807. return;
  1808. if (isLeaf()) {
  1809. OutAlternatives.push_back(T); // nothing to do.
  1810. return;
  1811. }
  1812. Record *Op = getOperator();
  1813. if (!Op->isSubClassOf("PatFrags")) {
  1814. if (getNumChildren() == 0) {
  1815. OutAlternatives.push_back(T);
  1816. return;
  1817. }
  1818. // Recursively inline children nodes.
  1819. std::vector<std::vector<TreePatternNodePtr> > ChildAlternatives;
  1820. ChildAlternatives.resize(getNumChildren());
  1821. for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
  1822. TreePatternNodePtr Child = getChildShared(i);
  1823. Child->InlinePatternFragments(Child, TP, ChildAlternatives[i]);
  1824. // If there are no alternatives for any child, there are no
  1825. // alternatives for this expression as whole.
  1826. if (ChildAlternatives[i].empty())
  1827. return;
  1828. assert((Child->getPredicateCalls().empty() ||
  1829. llvm::all_of(ChildAlternatives[i],
  1830. [&](const TreePatternNodePtr &NewChild) {
  1831. return NewChild->getPredicateCalls() ==
  1832. Child->getPredicateCalls();
  1833. })) &&
  1834. "Non-empty child predicate clobbered!");
  1835. }
  1836. // The end result is an all-pairs construction of the resultant pattern.
  1837. std::vector<unsigned> Idxs;
  1838. Idxs.resize(ChildAlternatives.size());
  1839. bool NotDone;
  1840. do {
  1841. // Create the variant and add it to the output list.
  1842. std::vector<TreePatternNodePtr> NewChildren;
  1843. for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
  1844. NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
  1845. TreePatternNodePtr R = std::make_shared<TreePatternNode>(
  1846. getOperator(), std::move(NewChildren), getNumTypes());
  1847. // Copy over properties.
  1848. R->setName(getName());
  1849. R->setNamesAsPredicateArg(getNamesAsPredicateArg());
  1850. R->setPredicateCalls(getPredicateCalls());
  1851. R->setTransformFn(getTransformFn());
  1852. for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
  1853. R->setType(i, getExtType(i));
  1854. for (unsigned i = 0, e = getNumResults(); i != e; ++i)
  1855. R->setResultIndex(i, getResultIndex(i));
  1856. // Register alternative.
  1857. OutAlternatives.push_back(R);
  1858. // Increment indices to the next permutation by incrementing the
  1859. // indices from last index backward, e.g., generate the sequence
  1860. // [0, 0], [0, 1], [1, 0], [1, 1].
  1861. int IdxsIdx;
  1862. for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
  1863. if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
  1864. Idxs[IdxsIdx] = 0;
  1865. else
  1866. break;
  1867. }
  1868. NotDone = (IdxsIdx >= 0);
  1869. } while (NotDone);
  1870. return;
  1871. }
  1872. // Otherwise, we found a reference to a fragment. First, look up its
  1873. // TreePattern record.
  1874. TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
  1875. // Verify that we are passing the right number of operands.
  1876. if (Frag->getNumArgs() != Children.size()) {
  1877. TP.error("'" + Op->getName() + "' fragment requires " +
  1878. Twine(Frag->getNumArgs()) + " operands!");
  1879. return;
  1880. }
  1881. TreePredicateFn PredFn(Frag);
  1882. unsigned Scope = 0;
  1883. if (TreePredicateFn(Frag).usesOperands())
  1884. Scope = TP.getDAGPatterns().allocateScope();
  1885. // Compute the map of formal to actual arguments.
  1886. std::map<std::string, TreePatternNodePtr> ArgMap;
  1887. for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
  1888. TreePatternNodePtr Child = getChildShared(i);
  1889. if (Scope != 0) {
  1890. Child = Child->clone();
  1891. Child->addNameAsPredicateArg(ScopedName(Scope, Frag->getArgName(i)));
  1892. }
  1893. ArgMap[Frag->getArgName(i)] = Child;
  1894. }
  1895. // Loop over all fragment alternatives.
  1896. for (const auto &Alternative : Frag->getTrees()) {
  1897. TreePatternNodePtr FragTree = Alternative->clone();
  1898. if (!PredFn.isAlwaysTrue())
  1899. FragTree->addPredicateCall(PredFn, Scope);
  1900. // Resolve formal arguments to their actual value.
  1901. if (Frag->getNumArgs())
  1902. FragTree->SubstituteFormalArguments(ArgMap);
  1903. // Transfer types. Note that the resolved alternative may have fewer
  1904. // (but not more) results than the PatFrags node.
  1905. FragTree->setName(getName());
  1906. for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
  1907. FragTree->UpdateNodeType(i, getExtType(i), TP);
  1908. // Transfer in the old predicates.
  1909. for (const TreePredicateCall &Pred : getPredicateCalls())
  1910. FragTree->addPredicateCall(Pred);
  1911. // The fragment we inlined could have recursive inlining that is needed. See
  1912. // if there are any pattern fragments in it and inline them as needed.
  1913. FragTree->InlinePatternFragments(FragTree, TP, OutAlternatives);
  1914. }
  1915. }
  1916. /// getImplicitType - Check to see if the specified record has an implicit
  1917. /// type which should be applied to it. This will infer the type of register
  1918. /// references from the register file information, for example.
  1919. ///
  1920. /// When Unnamed is set, return the type of a DAG operand with no name, such as
  1921. /// the F8RC register class argument in:
  1922. ///
  1923. /// (COPY_TO_REGCLASS GPR:$src, F8RC)
  1924. ///
  1925. /// When Unnamed is false, return the type of a named DAG operand such as the
  1926. /// GPR:$src operand above.
  1927. ///
  1928. static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
  1929. bool NotRegisters,
  1930. bool Unnamed,
  1931. TreePattern &TP) {
  1932. CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
  1933. // Check to see if this is a register operand.
  1934. if (R->isSubClassOf("RegisterOperand")) {
  1935. assert(ResNo == 0 && "Regoperand ref only has one result!");
  1936. if (NotRegisters)
  1937. return TypeSetByHwMode(); // Unknown.
  1938. Record *RegClass = R->getValueAsDef("RegClass");
  1939. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1940. return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
  1941. }
  1942. // Check to see if this is a register or a register class.
  1943. if (R->isSubClassOf("RegisterClass")) {
  1944. assert(ResNo == 0 && "Regclass ref only has one result!");
  1945. // An unnamed register class represents itself as an i32 immediate, for
  1946. // example on a COPY_TO_REGCLASS instruction.
  1947. if (Unnamed)
  1948. return TypeSetByHwMode(MVT::i32);
  1949. // In a named operand, the register class provides the possible set of
  1950. // types.
  1951. if (NotRegisters)
  1952. return TypeSetByHwMode(); // Unknown.
  1953. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1954. return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
  1955. }
  1956. if (R->isSubClassOf("PatFrags")) {
  1957. assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
  1958. // Pattern fragment types will be resolved when they are inlined.
  1959. return TypeSetByHwMode(); // Unknown.
  1960. }
  1961. if (R->isSubClassOf("Register")) {
  1962. assert(ResNo == 0 && "Registers only produce one result!");
  1963. if (NotRegisters)
  1964. return TypeSetByHwMode(); // Unknown.
  1965. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1966. return TypeSetByHwMode(T.getRegisterVTs(R));
  1967. }
  1968. if (R->isSubClassOf("SubRegIndex")) {
  1969. assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
  1970. return TypeSetByHwMode(MVT::i32);
  1971. }
  1972. if (R->isSubClassOf("ValueType")) {
  1973. assert(ResNo == 0 && "This node only has one result!");
  1974. // An unnamed VTSDNode represents itself as an MVT::Other immediate.
  1975. //
  1976. // (sext_inreg GPR:$src, i16)
  1977. // ~~~
  1978. if (Unnamed)
  1979. return TypeSetByHwMode(MVT::Other);
  1980. // With a name, the ValueType simply provides the type of the named
  1981. // variable.
  1982. //
  1983. // (sext_inreg i32:$src, i16)
  1984. // ~~~~~~~~
  1985. if (NotRegisters)
  1986. return TypeSetByHwMode(); // Unknown.
  1987. const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
  1988. return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
  1989. }
  1990. if (R->isSubClassOf("CondCode")) {
  1991. assert(ResNo == 0 && "This node only has one result!");
  1992. // Using a CondCodeSDNode.
  1993. return TypeSetByHwMode(MVT::Other);
  1994. }
  1995. if (R->isSubClassOf("ComplexPattern")) {
  1996. assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
  1997. if (NotRegisters)
  1998. return TypeSetByHwMode(); // Unknown.
  1999. Record *T = CDP.getComplexPattern(R).getValueType();
  2000. const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
  2001. return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
  2002. }
  2003. if (R->isSubClassOf("PointerLikeRegClass")) {
  2004. assert(ResNo == 0 && "Regclass can only have one result!");
  2005. TypeSetByHwMode VTS(MVT::iPTR);
  2006. TP.getInfer().expandOverloads(VTS);
  2007. return VTS;
  2008. }
  2009. if (R->getName() == "node" || R->getName() == "srcvalue" ||
  2010. R->getName() == "zero_reg" || R->getName() == "immAllOnesV" ||
  2011. R->getName() == "immAllZerosV" || R->getName() == "undef_tied_input") {
  2012. // Placeholder.
  2013. return TypeSetByHwMode(); // Unknown.
  2014. }
  2015. if (R->isSubClassOf("Operand")) {
  2016. const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
  2017. Record *T = R->getValueAsDef("Type");
  2018. return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
  2019. }
  2020. TP.error("Unknown node flavor used in pattern: " + R->getName());
  2021. return TypeSetByHwMode(MVT::Other);
  2022. }
  2023. /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
  2024. /// CodeGenIntrinsic information for it, otherwise return a null pointer.
  2025. const CodeGenIntrinsic *TreePatternNode::
  2026. getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
  2027. if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
  2028. getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
  2029. getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
  2030. return nullptr;
  2031. unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
  2032. return &CDP.getIntrinsicInfo(IID);
  2033. }
  2034. /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
  2035. /// return the ComplexPattern information, otherwise return null.
  2036. const ComplexPattern *
  2037. TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
  2038. Record *Rec;
  2039. if (isLeaf()) {
  2040. DefInit *DI = dyn_cast<DefInit>(getLeafValue());
  2041. if (!DI)
  2042. return nullptr;
  2043. Rec = DI->getDef();
  2044. } else
  2045. Rec = getOperator();
  2046. if (!Rec->isSubClassOf("ComplexPattern"))
  2047. return nullptr;
  2048. return &CGP.getComplexPattern(Rec);
  2049. }
  2050. unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
  2051. // A ComplexPattern specifically declares how many results it fills in.
  2052. if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
  2053. return CP->getNumOperands();
  2054. // If MIOperandInfo is specified, that gives the count.
  2055. if (isLeaf()) {
  2056. DefInit *DI = dyn_cast<DefInit>(getLeafValue());
  2057. if (DI && DI->getDef()->isSubClassOf("Operand")) {
  2058. DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
  2059. if (MIOps->getNumArgs())
  2060. return MIOps->getNumArgs();
  2061. }
  2062. }
  2063. // Otherwise there is just one result.
  2064. return 1;
  2065. }
  2066. /// NodeHasProperty - Return true if this node has the specified property.
  2067. bool TreePatternNode::NodeHasProperty(SDNP Property,
  2068. const CodeGenDAGPatterns &CGP) const {
  2069. if (isLeaf()) {
  2070. if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
  2071. return CP->hasProperty(Property);
  2072. return false;
  2073. }
  2074. if (Property != SDNPHasChain) {
  2075. // The chain proprety is already present on the different intrinsic node
  2076. // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
  2077. // on the intrinsic. Anything else is specific to the individual intrinsic.
  2078. if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
  2079. return Int->hasProperty(Property);
  2080. }
  2081. if (!Operator->isSubClassOf("SDPatternOperator"))
  2082. return false;
  2083. return CGP.getSDNodeInfo(Operator).hasProperty(Property);
  2084. }
  2085. /// TreeHasProperty - Return true if any node in this tree has the specified
  2086. /// property.
  2087. bool TreePatternNode::TreeHasProperty(SDNP Property,
  2088. const CodeGenDAGPatterns &CGP) const {
  2089. if (NodeHasProperty(Property, CGP))
  2090. return true;
  2091. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  2092. if (getChild(i)->TreeHasProperty(Property, CGP))
  2093. return true;
  2094. return false;
  2095. }
  2096. /// isCommutativeIntrinsic - Return true if the node corresponds to a
  2097. /// commutative intrinsic.
  2098. bool
  2099. TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
  2100. if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
  2101. return Int->isCommutative;
  2102. return false;
  2103. }
  2104. static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
  2105. if (!N->isLeaf())
  2106. return N->getOperator()->isSubClassOf(Class);
  2107. DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
  2108. if (DI && DI->getDef()->isSubClassOf(Class))
  2109. return true;
  2110. return false;
  2111. }
  2112. static void emitTooManyOperandsError(TreePattern &TP,
  2113. StringRef InstName,
  2114. unsigned Expected,
  2115. unsigned Actual) {
  2116. TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
  2117. " operands but expected only " + Twine(Expected) + "!");
  2118. }
  2119. static void emitTooFewOperandsError(TreePattern &TP,
  2120. StringRef InstName,
  2121. unsigned Actual) {
  2122. TP.error("Instruction '" + InstName +
  2123. "' expects more than the provided " + Twine(Actual) + " operands!");
  2124. }
  2125. /// ApplyTypeConstraints - Apply all of the type constraints relevant to
  2126. /// this node and its children in the tree. This returns true if it makes a
  2127. /// change, false otherwise. If a type contradiction is found, flag an error.
  2128. bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
  2129. if (TP.hasError())
  2130. return false;
  2131. CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
  2132. if (isLeaf()) {
  2133. if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
  2134. // If it's a regclass or something else known, include the type.
  2135. bool MadeChange = false;
  2136. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  2137. MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
  2138. NotRegisters,
  2139. !hasName(), TP), TP);
  2140. return MadeChange;
  2141. }
  2142. if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
  2143. assert(Types.size() == 1 && "Invalid IntInit");
  2144. // Int inits are always integers. :)
  2145. bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
  2146. if (!TP.getInfer().isConcrete(Types[0], false))
  2147. return MadeChange;
  2148. ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
  2149. for (auto &P : VVT) {
  2150. MVT::SimpleValueType VT = P.second.SimpleTy;
  2151. if (VT == MVT::iPTR || VT == MVT::iPTRAny)
  2152. continue;
  2153. unsigned Size = MVT(VT).getFixedSizeInBits();
  2154. // Make sure that the value is representable for this type.
  2155. if (Size >= 32)
  2156. continue;
  2157. // Check that the value doesn't use more bits than we have. It must
  2158. // either be a sign- or zero-extended equivalent of the original.
  2159. int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
  2160. if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
  2161. SignBitAndAbove == 1)
  2162. continue;
  2163. TP.error("Integer value '" + Twine(II->getValue()) +
  2164. "' is out of range for type '" + getEnumName(VT) + "'!");
  2165. break;
  2166. }
  2167. return MadeChange;
  2168. }
  2169. return false;
  2170. }
  2171. if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
  2172. bool MadeChange = false;
  2173. // Apply the result type to the node.
  2174. unsigned NumRetVTs = Int->IS.RetVTs.size();
  2175. unsigned NumParamVTs = Int->IS.ParamVTs.size();
  2176. for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
  2177. MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
  2178. if (getNumChildren() != NumParamVTs + 1) {
  2179. TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
  2180. " operands, not " + Twine(getNumChildren() - 1) + " operands!");
  2181. return false;
  2182. }
  2183. // Apply type info to the intrinsic ID.
  2184. MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
  2185. for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
  2186. MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
  2187. MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
  2188. assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
  2189. MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
  2190. }
  2191. return MadeChange;
  2192. }
  2193. if (getOperator()->isSubClassOf("SDNode")) {
  2194. const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
  2195. // Check that the number of operands is sane. Negative operands -> varargs.
  2196. if (NI.getNumOperands() >= 0 &&
  2197. getNumChildren() != (unsigned)NI.getNumOperands()) {
  2198. TP.error(getOperator()->getName() + " node requires exactly " +
  2199. Twine(NI.getNumOperands()) + " operands!");
  2200. return false;
  2201. }
  2202. bool MadeChange = false;
  2203. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  2204. MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
  2205. MadeChange |= NI.ApplyTypeConstraints(this, TP);
  2206. return MadeChange;
  2207. }
  2208. if (getOperator()->isSubClassOf("Instruction")) {
  2209. const DAGInstruction &Inst = CDP.getInstruction(getOperator());
  2210. CodeGenInstruction &InstInfo =
  2211. CDP.getTargetInfo().getInstruction(getOperator());
  2212. bool MadeChange = false;
  2213. // Apply the result types to the node, these come from the things in the
  2214. // (outs) list of the instruction.
  2215. unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
  2216. Inst.getNumResults());
  2217. for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
  2218. MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
  2219. // If the instruction has implicit defs, we apply the first one as a result.
  2220. // FIXME: This sucks, it should apply all implicit defs.
  2221. if (!InstInfo.ImplicitDefs.empty()) {
  2222. unsigned ResNo = NumResultsToAdd;
  2223. // FIXME: Generalize to multiple possible types and multiple possible
  2224. // ImplicitDefs.
  2225. MVT::SimpleValueType VT =
  2226. InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
  2227. if (VT != MVT::Other)
  2228. MadeChange |= UpdateNodeType(ResNo, VT, TP);
  2229. }
  2230. // If this is an INSERT_SUBREG, constrain the source and destination VTs to
  2231. // be the same.
  2232. if (getOperator()->getName() == "INSERT_SUBREG") {
  2233. assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
  2234. MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
  2235. MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
  2236. } else if (getOperator()->getName() == "REG_SEQUENCE") {
  2237. // We need to do extra, custom typechecking for REG_SEQUENCE since it is
  2238. // variadic.
  2239. unsigned NChild = getNumChildren();
  2240. if (NChild < 3) {
  2241. TP.error("REG_SEQUENCE requires at least 3 operands!");
  2242. return false;
  2243. }
  2244. if (NChild % 2 == 0) {
  2245. TP.error("REG_SEQUENCE requires an odd number of operands!");
  2246. return false;
  2247. }
  2248. if (!isOperandClass(getChild(0), "RegisterClass")) {
  2249. TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
  2250. return false;
  2251. }
  2252. for (unsigned I = 1; I < NChild; I += 2) {
  2253. TreePatternNode *SubIdxChild = getChild(I + 1);
  2254. if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
  2255. TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
  2256. Twine(I + 1) + "!");
  2257. return false;
  2258. }
  2259. }
  2260. }
  2261. unsigned NumResults = Inst.getNumResults();
  2262. unsigned NumFixedOperands = InstInfo.Operands.size();
  2263. // If one or more operands with a default value appear at the end of the
  2264. // formal operand list for an instruction, we allow them to be overridden
  2265. // by optional operands provided in the pattern.
  2266. //
  2267. // But if an operand B without a default appears at any point after an
  2268. // operand A with a default, then we don't allow A to be overridden,
  2269. // because there would be no way to specify whether the next operand in
  2270. // the pattern was intended to override A or skip it.
  2271. unsigned NonOverridableOperands = NumFixedOperands;
  2272. while (NonOverridableOperands > NumResults &&
  2273. CDP.operandHasDefault(InstInfo.Operands[NonOverridableOperands-1].Rec))
  2274. --NonOverridableOperands;
  2275. unsigned ChildNo = 0;
  2276. assert(NumResults <= NumFixedOperands);
  2277. for (unsigned i = NumResults, e = NumFixedOperands; i != e; ++i) {
  2278. Record *OperandNode = InstInfo.Operands[i].Rec;
  2279. // If the operand has a default value, do we use it? We must use the
  2280. // default if we've run out of children of the pattern DAG to consume,
  2281. // or if the operand is followed by a non-defaulted one.
  2282. if (CDP.operandHasDefault(OperandNode) &&
  2283. (i < NonOverridableOperands || ChildNo >= getNumChildren()))
  2284. continue;
  2285. // If we have run out of child nodes and there _isn't_ a default
  2286. // value we can use for the next operand, give an error.
  2287. if (ChildNo >= getNumChildren()) {
  2288. emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
  2289. return false;
  2290. }
  2291. TreePatternNode *Child = getChild(ChildNo++);
  2292. unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
  2293. // If the operand has sub-operands, they may be provided by distinct
  2294. // child patterns, so attempt to match each sub-operand separately.
  2295. if (OperandNode->isSubClassOf("Operand")) {
  2296. DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
  2297. if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
  2298. // But don't do that if the whole operand is being provided by
  2299. // a single ComplexPattern-related Operand.
  2300. if (Child->getNumMIResults(CDP) < NumArgs) {
  2301. // Match first sub-operand against the child we already have.
  2302. Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
  2303. MadeChange |=
  2304. Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
  2305. // And the remaining sub-operands against subsequent children.
  2306. for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
  2307. if (ChildNo >= getNumChildren()) {
  2308. emitTooFewOperandsError(TP, getOperator()->getName(),
  2309. getNumChildren());
  2310. return false;
  2311. }
  2312. Child = getChild(ChildNo++);
  2313. SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
  2314. MadeChange |=
  2315. Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
  2316. }
  2317. continue;
  2318. }
  2319. }
  2320. }
  2321. // If we didn't match by pieces above, attempt to match the whole
  2322. // operand now.
  2323. MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
  2324. }
  2325. if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
  2326. emitTooManyOperandsError(TP, getOperator()->getName(),
  2327. ChildNo, getNumChildren());
  2328. return false;
  2329. }
  2330. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  2331. MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
  2332. return MadeChange;
  2333. }
  2334. if (getOperator()->isSubClassOf("ComplexPattern")) {
  2335. bool MadeChange = false;
  2336. if (!NotRegisters) {
  2337. assert(Types.size() == 1 && "ComplexPatterns only produce one result!");
  2338. Record *T = CDP.getComplexPattern(getOperator()).getValueType();
  2339. const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
  2340. const ValueTypeByHwMode VVT = getValueTypeByHwMode(T, CGH);
  2341. // TODO: AArch64 and AMDGPU use ComplexPattern<untyped, ...> and then
  2342. // exclusively use those as non-leaf nodes with explicit type casts, so
  2343. // for backwards compatibility we do no inference in that case. This is
  2344. // not supported when the ComplexPattern is used as a leaf value,
  2345. // however; this inconsistency should be resolved, either by adding this
  2346. // case there or by altering the backends to not do this (e.g. using Any
  2347. // instead may work).
  2348. if (!VVT.isSimple() || VVT.getSimple() != MVT::Untyped)
  2349. MadeChange |= UpdateNodeType(0, VVT, TP);
  2350. }
  2351. for (unsigned i = 0; i < getNumChildren(); ++i)
  2352. MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
  2353. return MadeChange;
  2354. }
  2355. assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
  2356. // Node transforms always take one operand.
  2357. if (getNumChildren() != 1) {
  2358. TP.error("Node transform '" + getOperator()->getName() +
  2359. "' requires one operand!");
  2360. return false;
  2361. }
  2362. bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
  2363. return MadeChange;
  2364. }
  2365. /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
  2366. /// RHS of a commutative operation, not the on LHS.
  2367. static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
  2368. if (!N->isLeaf() && N->getOperator()->getName() == "imm")
  2369. return true;
  2370. if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
  2371. return true;
  2372. if (isImmAllOnesAllZerosMatch(N))
  2373. return true;
  2374. return false;
  2375. }
  2376. /// canPatternMatch - If it is impossible for this pattern to match on this
  2377. /// target, fill in Reason and return false. Otherwise, return true. This is
  2378. /// used as a sanity check for .td files (to prevent people from writing stuff
  2379. /// that can never possibly work), and to prevent the pattern permuter from
  2380. /// generating stuff that is useless.
  2381. bool TreePatternNode::canPatternMatch(std::string &Reason,
  2382. const CodeGenDAGPatterns &CDP) {
  2383. if (isLeaf()) return true;
  2384. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  2385. if (!getChild(i)->canPatternMatch(Reason, CDP))
  2386. return false;
  2387. // If this is an intrinsic, handle cases that would make it not match. For
  2388. // example, if an operand is required to be an immediate.
  2389. if (getOperator()->isSubClassOf("Intrinsic")) {
  2390. // TODO:
  2391. return true;
  2392. }
  2393. if (getOperator()->isSubClassOf("ComplexPattern"))
  2394. return true;
  2395. // If this node is a commutative operator, check that the LHS isn't an
  2396. // immediate.
  2397. const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
  2398. bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
  2399. if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
  2400. // Scan all of the operands of the node and make sure that only the last one
  2401. // is a constant node, unless the RHS also is.
  2402. if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
  2403. unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
  2404. for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
  2405. if (OnlyOnRHSOfCommutative(getChild(i))) {
  2406. Reason="Immediate value must be on the RHS of commutative operators!";
  2407. return false;
  2408. }
  2409. }
  2410. }
  2411. return true;
  2412. }
  2413. //===----------------------------------------------------------------------===//
  2414. // TreePattern implementation
  2415. //
  2416. TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
  2417. CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
  2418. isInputPattern(isInput), HasError(false),
  2419. Infer(*this) {
  2420. for (Init *I : RawPat->getValues())
  2421. Trees.push_back(ParseTreePattern(I, ""));
  2422. }
  2423. TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
  2424. CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
  2425. isInputPattern(isInput), HasError(false),
  2426. Infer(*this) {
  2427. Trees.push_back(ParseTreePattern(Pat, ""));
  2428. }
  2429. TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
  2430. CodeGenDAGPatterns &cdp)
  2431. : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
  2432. Infer(*this) {
  2433. Trees.push_back(Pat);
  2434. }
  2435. void TreePattern::error(const Twine &Msg) {
  2436. if (HasError)
  2437. return;
  2438. dump();
  2439. PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
  2440. HasError = true;
  2441. }
  2442. void TreePattern::ComputeNamedNodes() {
  2443. for (TreePatternNodePtr &Tree : Trees)
  2444. ComputeNamedNodes(Tree.get());
  2445. }
  2446. void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
  2447. if (!N->getName().empty())
  2448. NamedNodes[N->getName()].push_back(N);
  2449. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  2450. ComputeNamedNodes(N->getChild(i));
  2451. }
  2452. TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
  2453. StringRef OpName) {
  2454. if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
  2455. Record *R = DI->getDef();
  2456. // Direct reference to a leaf DagNode or PatFrag? Turn it into a
  2457. // TreePatternNode of its own. For example:
  2458. /// (foo GPR, imm) -> (foo GPR, (imm))
  2459. if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
  2460. return ParseTreePattern(
  2461. DagInit::get(DI, nullptr,
  2462. std::vector<std::pair<Init*, StringInit*> >()),
  2463. OpName);
  2464. // Input argument?
  2465. TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1);
  2466. if (R->getName() == "node" && !OpName.empty()) {
  2467. if (OpName.empty())
  2468. error("'node' argument requires a name to match with operand list");
  2469. Args.push_back(std::string(OpName));
  2470. }
  2471. Res->setName(OpName);
  2472. return Res;
  2473. }
  2474. // ?:$name or just $name.
  2475. if (isa<UnsetInit>(TheInit)) {
  2476. if (OpName.empty())
  2477. error("'?' argument requires a name to match with operand list");
  2478. TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1);
  2479. Args.push_back(std::string(OpName));
  2480. Res->setName(OpName);
  2481. return Res;
  2482. }
  2483. if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
  2484. if (!OpName.empty())
  2485. error("Constant int or bit argument should not have a name!");
  2486. if (isa<BitInit>(TheInit))
  2487. TheInit = TheInit->convertInitializerTo(IntRecTy::get());
  2488. return std::make_shared<TreePatternNode>(TheInit, 1);
  2489. }
  2490. if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
  2491. // Turn this into an IntInit.
  2492. Init *II = BI->convertInitializerTo(IntRecTy::get());
  2493. if (!II || !isa<IntInit>(II))
  2494. error("Bits value must be constants!");
  2495. return ParseTreePattern(II, OpName);
  2496. }
  2497. DagInit *Dag = dyn_cast<DagInit>(TheInit);
  2498. if (!Dag) {
  2499. TheInit->print(errs());
  2500. error("Pattern has unexpected init kind!");
  2501. }
  2502. DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
  2503. if (!OpDef) error("Pattern has unexpected operator type!");
  2504. Record *Operator = OpDef->getDef();
  2505. if (Operator->isSubClassOf("ValueType")) {
  2506. // If the operator is a ValueType, then this must be "type cast" of a leaf
  2507. // node.
  2508. if (Dag->getNumArgs() != 1)
  2509. error("Type cast only takes one operand!");
  2510. TreePatternNodePtr New =
  2511. ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
  2512. // Apply the type cast.
  2513. if (New->getNumTypes() != 1)
  2514. error("Type cast can only have one type!");
  2515. const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
  2516. New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
  2517. if (!OpName.empty())
  2518. error("ValueType cast should not have a name!");
  2519. return New;
  2520. }
  2521. // Verify that this is something that makes sense for an operator.
  2522. if (!Operator->isSubClassOf("PatFrags") &&
  2523. !Operator->isSubClassOf("SDNode") &&
  2524. !Operator->isSubClassOf("Instruction") &&
  2525. !Operator->isSubClassOf("SDNodeXForm") &&
  2526. !Operator->isSubClassOf("Intrinsic") &&
  2527. !Operator->isSubClassOf("ComplexPattern") &&
  2528. Operator->getName() != "set" &&
  2529. Operator->getName() != "implicit")
  2530. error("Unrecognized node '" + Operator->getName() + "'!");
  2531. // Check to see if this is something that is illegal in an input pattern.
  2532. if (isInputPattern) {
  2533. if (Operator->isSubClassOf("Instruction") ||
  2534. Operator->isSubClassOf("SDNodeXForm"))
  2535. error("Cannot use '" + Operator->getName() + "' in an input pattern!");
  2536. } else {
  2537. if (Operator->isSubClassOf("Intrinsic"))
  2538. error("Cannot use '" + Operator->getName() + "' in an output pattern!");
  2539. if (Operator->isSubClassOf("SDNode") &&
  2540. Operator->getName() != "imm" &&
  2541. Operator->getName() != "timm" &&
  2542. Operator->getName() != "fpimm" &&
  2543. Operator->getName() != "tglobaltlsaddr" &&
  2544. Operator->getName() != "tconstpool" &&
  2545. Operator->getName() != "tjumptable" &&
  2546. Operator->getName() != "tframeindex" &&
  2547. Operator->getName() != "texternalsym" &&
  2548. Operator->getName() != "tblockaddress" &&
  2549. Operator->getName() != "tglobaladdr" &&
  2550. Operator->getName() != "bb" &&
  2551. Operator->getName() != "vt" &&
  2552. Operator->getName() != "mcsym")
  2553. error("Cannot use '" + Operator->getName() + "' in an output pattern!");
  2554. }
  2555. std::vector<TreePatternNodePtr> Children;
  2556. // Parse all the operands.
  2557. for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
  2558. Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
  2559. // Get the actual number of results before Operator is converted to an intrinsic
  2560. // node (which is hard-coded to have either zero or one result).
  2561. unsigned NumResults = GetNumNodeResults(Operator, CDP);
  2562. // If the operator is an intrinsic, then this is just syntactic sugar for
  2563. // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
  2564. // convert the intrinsic name to a number.
  2565. if (Operator->isSubClassOf("Intrinsic")) {
  2566. const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
  2567. unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
  2568. // If this intrinsic returns void, it must have side-effects and thus a
  2569. // chain.
  2570. if (Int.IS.RetVTs.empty())
  2571. Operator = getDAGPatterns().get_intrinsic_void_sdnode();
  2572. else if (Int.ModRef != CodeGenIntrinsic::NoMem || Int.hasSideEffects)
  2573. // Has side-effects, requires chain.
  2574. Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
  2575. else // Otherwise, no chain.
  2576. Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
  2577. Children.insert(Children.begin(),
  2578. std::make_shared<TreePatternNode>(IntInit::get(IID), 1));
  2579. }
  2580. if (Operator->isSubClassOf("ComplexPattern")) {
  2581. for (unsigned i = 0; i < Children.size(); ++i) {
  2582. TreePatternNodePtr Child = Children[i];
  2583. if (Child->getName().empty())
  2584. error("All arguments to a ComplexPattern must be named");
  2585. // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
  2586. // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
  2587. // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
  2588. auto OperandId = std::make_pair(Operator, i);
  2589. auto PrevOp = ComplexPatternOperands.find(Child->getName());
  2590. if (PrevOp != ComplexPatternOperands.end()) {
  2591. if (PrevOp->getValue() != OperandId)
  2592. error("All ComplexPattern operands must appear consistently: "
  2593. "in the same order in just one ComplexPattern instance.");
  2594. } else
  2595. ComplexPatternOperands[Child->getName()] = OperandId;
  2596. }
  2597. }
  2598. TreePatternNodePtr Result =
  2599. std::make_shared<TreePatternNode>(Operator, std::move(Children),
  2600. NumResults);
  2601. Result->setName(OpName);
  2602. if (Dag->getName()) {
  2603. assert(Result->getName().empty());
  2604. Result->setName(Dag->getNameStr());
  2605. }
  2606. return Result;
  2607. }
  2608. /// SimplifyTree - See if we can simplify this tree to eliminate something that
  2609. /// will never match in favor of something obvious that will. This is here
  2610. /// strictly as a convenience to target authors because it allows them to write
  2611. /// more type generic things and have useless type casts fold away.
  2612. ///
  2613. /// This returns true if any change is made.
  2614. static bool SimplifyTree(TreePatternNodePtr &N) {
  2615. if (N->isLeaf())
  2616. return false;
  2617. // If we have a bitconvert with a resolved type and if the source and
  2618. // destination types are the same, then the bitconvert is useless, remove it.
  2619. //
  2620. // We make an exception if the types are completely empty. This can come up
  2621. // when the pattern being simplified is in the Fragments list of a PatFrags,
  2622. // so that the operand is just an untyped "node". In that situation we leave
  2623. // bitconverts unsimplified, and simplify them later once the fragment is
  2624. // expanded into its true context.
  2625. if (N->getOperator()->getName() == "bitconvert" &&
  2626. N->getExtType(0).isValueTypeByHwMode(false) &&
  2627. !N->getExtType(0).empty() &&
  2628. N->getExtType(0) == N->getChild(0)->getExtType(0) &&
  2629. N->getName().empty()) {
  2630. N = N->getChildShared(0);
  2631. SimplifyTree(N);
  2632. return true;
  2633. }
  2634. // Walk all children.
  2635. bool MadeChange = false;
  2636. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
  2637. TreePatternNodePtr Child = N->getChildShared(i);
  2638. MadeChange |= SimplifyTree(Child);
  2639. N->setChild(i, std::move(Child));
  2640. }
  2641. return MadeChange;
  2642. }
  2643. /// InferAllTypes - Infer/propagate as many types throughout the expression
  2644. /// patterns as possible. Return true if all types are inferred, false
  2645. /// otherwise. Flags an error if a type contradiction is found.
  2646. bool TreePattern::
  2647. InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
  2648. if (NamedNodes.empty())
  2649. ComputeNamedNodes();
  2650. bool MadeChange = true;
  2651. while (MadeChange) {
  2652. MadeChange = false;
  2653. for (TreePatternNodePtr &Tree : Trees) {
  2654. MadeChange |= Tree->ApplyTypeConstraints(*this, false);
  2655. MadeChange |= SimplifyTree(Tree);
  2656. }
  2657. // If there are constraints on our named nodes, apply them.
  2658. for (auto &Entry : NamedNodes) {
  2659. SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
  2660. // If we have input named node types, propagate their types to the named
  2661. // values here.
  2662. if (InNamedTypes) {
  2663. if (!InNamedTypes->count(Entry.getKey())) {
  2664. error("Node '" + std::string(Entry.getKey()) +
  2665. "' in output pattern but not input pattern");
  2666. return true;
  2667. }
  2668. const SmallVectorImpl<TreePatternNode*> &InNodes =
  2669. InNamedTypes->find(Entry.getKey())->second;
  2670. // The input types should be fully resolved by now.
  2671. for (TreePatternNode *Node : Nodes) {
  2672. // If this node is a register class, and it is the root of the pattern
  2673. // then we're mapping something onto an input register. We allow
  2674. // changing the type of the input register in this case. This allows
  2675. // us to match things like:
  2676. // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
  2677. if (Node == Trees[0].get() && Node->isLeaf()) {
  2678. DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
  2679. if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
  2680. DI->getDef()->isSubClassOf("RegisterOperand")))
  2681. continue;
  2682. }
  2683. assert(Node->getNumTypes() == 1 &&
  2684. InNodes[0]->getNumTypes() == 1 &&
  2685. "FIXME: cannot name multiple result nodes yet");
  2686. MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
  2687. *this);
  2688. }
  2689. }
  2690. // If there are multiple nodes with the same name, they must all have the
  2691. // same type.
  2692. if (Entry.second.size() > 1) {
  2693. for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
  2694. TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
  2695. assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
  2696. "FIXME: cannot name multiple result nodes yet");
  2697. MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
  2698. MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
  2699. }
  2700. }
  2701. }
  2702. }
  2703. bool HasUnresolvedTypes = false;
  2704. for (const TreePatternNodePtr &Tree : Trees)
  2705. HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
  2706. return !HasUnresolvedTypes;
  2707. }
  2708. void TreePattern::print(raw_ostream &OS) const {
  2709. OS << getRecord()->getName();
  2710. if (!Args.empty()) {
  2711. OS << "(";
  2712. ListSeparator LS;
  2713. for (const std::string &Arg : Args)
  2714. OS << LS << Arg;
  2715. OS << ")";
  2716. }
  2717. OS << ": ";
  2718. if (Trees.size() > 1)
  2719. OS << "[\n";
  2720. for (const TreePatternNodePtr &Tree : Trees) {
  2721. OS << "\t";
  2722. Tree->print(OS);
  2723. OS << "\n";
  2724. }
  2725. if (Trees.size() > 1)
  2726. OS << "]\n";
  2727. }
  2728. void TreePattern::dump() const { print(errs()); }
  2729. //===----------------------------------------------------------------------===//
  2730. // CodeGenDAGPatterns implementation
  2731. //
  2732. CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
  2733. PatternRewriterFn PatternRewriter)
  2734. : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
  2735. PatternRewriter(PatternRewriter) {
  2736. Intrinsics = CodeGenIntrinsicTable(Records);
  2737. ParseNodeInfo();
  2738. ParseNodeTransforms();
  2739. ParseComplexPatterns();
  2740. ParsePatternFragments();
  2741. ParseDefaultOperands();
  2742. ParseInstructions();
  2743. ParsePatternFragments(/*OutFrags*/true);
  2744. ParsePatterns();
  2745. // Generate variants. For example, commutative patterns can match
  2746. // multiple ways. Add them to PatternsToMatch as well.
  2747. GenerateVariants();
  2748. // Break patterns with parameterized types into a series of patterns,
  2749. // where each one has a fixed type and is predicated on the conditions
  2750. // of the associated HW mode.
  2751. ExpandHwModeBasedTypes();
  2752. // Infer instruction flags. For example, we can detect loads,
  2753. // stores, and side effects in many cases by examining an
  2754. // instruction's pattern.
  2755. InferInstructionFlags();
  2756. // Verify that instruction flags match the patterns.
  2757. VerifyInstructionFlags();
  2758. }
  2759. Record *CodeGenDAGPatterns::getSDNodeNamed(StringRef Name) const {
  2760. Record *N = Records.getDef(Name);
  2761. if (!N || !N->isSubClassOf("SDNode"))
  2762. PrintFatalError("Error getting SDNode '" + Name + "'!");
  2763. return N;
  2764. }
  2765. // Parse all of the SDNode definitions for the target, populating SDNodes.
  2766. void CodeGenDAGPatterns::ParseNodeInfo() {
  2767. std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
  2768. const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
  2769. while (!Nodes.empty()) {
  2770. Record *R = Nodes.back();
  2771. SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
  2772. Nodes.pop_back();
  2773. }
  2774. // Get the builtin intrinsic nodes.
  2775. intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
  2776. intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
  2777. intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
  2778. }
  2779. /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
  2780. /// map, and emit them to the file as functions.
  2781. void CodeGenDAGPatterns::ParseNodeTransforms() {
  2782. std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
  2783. while (!Xforms.empty()) {
  2784. Record *XFormNode = Xforms.back();
  2785. Record *SDNode = XFormNode->getValueAsDef("Opcode");
  2786. StringRef Code = XFormNode->getValueAsString("XFormFunction");
  2787. SDNodeXForms.insert(
  2788. std::make_pair(XFormNode, NodeXForm(SDNode, std::string(Code))));
  2789. Xforms.pop_back();
  2790. }
  2791. }
  2792. void CodeGenDAGPatterns::ParseComplexPatterns() {
  2793. std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
  2794. while (!AMs.empty()) {
  2795. ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
  2796. AMs.pop_back();
  2797. }
  2798. }
  2799. /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
  2800. /// file, building up the PatternFragments map. After we've collected them all,
  2801. /// inline fragments together as necessary, so that there are no references left
  2802. /// inside a pattern fragment to a pattern fragment.
  2803. ///
  2804. void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
  2805. std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrags");
  2806. // First step, parse all of the fragments.
  2807. for (Record *Frag : Fragments) {
  2808. if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
  2809. continue;
  2810. ListInit *LI = Frag->getValueAsListInit("Fragments");
  2811. TreePattern *P =
  2812. (PatternFragments[Frag] = std::make_unique<TreePattern>(
  2813. Frag, LI, !Frag->isSubClassOf("OutPatFrag"),
  2814. *this)).get();
  2815. // Validate the argument list, converting it to set, to discard duplicates.
  2816. std::vector<std::string> &Args = P->getArgList();
  2817. // Copy the args so we can take StringRefs to them.
  2818. auto ArgsCopy = Args;
  2819. SmallDenseSet<StringRef, 4> OperandsSet;
  2820. OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
  2821. if (OperandsSet.count(""))
  2822. P->error("Cannot have unnamed 'node' values in pattern fragment!");
  2823. // Parse the operands list.
  2824. DagInit *OpsList = Frag->getValueAsDag("Operands");
  2825. DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
  2826. // Special cases: ops == outs == ins. Different names are used to
  2827. // improve readability.
  2828. if (!OpsOp ||
  2829. (OpsOp->getDef()->getName() != "ops" &&
  2830. OpsOp->getDef()->getName() != "outs" &&
  2831. OpsOp->getDef()->getName() != "ins"))
  2832. P->error("Operands list should start with '(ops ... '!");
  2833. // Copy over the arguments.
  2834. Args.clear();
  2835. for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
  2836. if (!isa<DefInit>(OpsList->getArg(j)) ||
  2837. cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
  2838. P->error("Operands list should all be 'node' values.");
  2839. if (!OpsList->getArgName(j))
  2840. P->error("Operands list should have names for each operand!");
  2841. StringRef ArgNameStr = OpsList->getArgNameStr(j);
  2842. if (!OperandsSet.count(ArgNameStr))
  2843. P->error("'" + ArgNameStr +
  2844. "' does not occur in pattern or was multiply specified!");
  2845. OperandsSet.erase(ArgNameStr);
  2846. Args.push_back(std::string(ArgNameStr));
  2847. }
  2848. if (!OperandsSet.empty())
  2849. P->error("Operands list does not contain an entry for operand '" +
  2850. *OperandsSet.begin() + "'!");
  2851. // If there is a node transformation corresponding to this, keep track of
  2852. // it.
  2853. Record *Transform = Frag->getValueAsDef("OperandTransform");
  2854. if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
  2855. for (const auto &T : P->getTrees())
  2856. T->setTransformFn(Transform);
  2857. }
  2858. // Now that we've parsed all of the tree fragments, do a closure on them so
  2859. // that there are not references to PatFrags left inside of them.
  2860. for (Record *Frag : Fragments) {
  2861. if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
  2862. continue;
  2863. TreePattern &ThePat = *PatternFragments[Frag];
  2864. ThePat.InlinePatternFragments();
  2865. // Infer as many types as possible. Don't worry about it if we don't infer
  2866. // all of them, some may depend on the inputs of the pattern. Also, don't
  2867. // validate type sets; validation may cause spurious failures e.g. if a
  2868. // fragment needs floating-point types but the current target does not have
  2869. // any (this is only an error if that fragment is ever used!).
  2870. {
  2871. TypeInfer::SuppressValidation SV(ThePat.getInfer());
  2872. ThePat.InferAllTypes();
  2873. ThePat.resetError();
  2874. }
  2875. // If debugging, print out the pattern fragment result.
  2876. LLVM_DEBUG(ThePat.dump());
  2877. }
  2878. }
  2879. void CodeGenDAGPatterns::ParseDefaultOperands() {
  2880. std::vector<Record*> DefaultOps;
  2881. DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
  2882. // Find some SDNode.
  2883. assert(!SDNodes.empty() && "No SDNodes parsed?");
  2884. Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
  2885. for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
  2886. DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
  2887. // Clone the DefaultInfo dag node, changing the operator from 'ops' to
  2888. // SomeSDnode so that we can parse this.
  2889. std::vector<std::pair<Init*, StringInit*> > Ops;
  2890. for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
  2891. Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
  2892. DefaultInfo->getArgName(op)));
  2893. DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
  2894. // Create a TreePattern to parse this.
  2895. TreePattern P(DefaultOps[i], DI, false, *this);
  2896. assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
  2897. // Copy the operands over into a DAGDefaultOperand.
  2898. DAGDefaultOperand DefaultOpInfo;
  2899. const TreePatternNodePtr &T = P.getTree(0);
  2900. for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
  2901. TreePatternNodePtr TPN = T->getChildShared(op);
  2902. while (TPN->ApplyTypeConstraints(P, false))
  2903. /* Resolve all types */;
  2904. if (TPN->ContainsUnresolvedType(P)) {
  2905. PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
  2906. DefaultOps[i]->getName() +
  2907. "' doesn't have a concrete type!");
  2908. }
  2909. DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
  2910. }
  2911. // Insert it into the DefaultOperands map so we can find it later.
  2912. DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
  2913. }
  2914. }
  2915. /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
  2916. /// instruction input. Return true if this is a real use.
  2917. static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
  2918. std::map<std::string, TreePatternNodePtr> &InstInputs) {
  2919. // No name -> not interesting.
  2920. if (Pat->getName().empty()) {
  2921. if (Pat->isLeaf()) {
  2922. DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
  2923. if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
  2924. DI->getDef()->isSubClassOf("RegisterOperand")))
  2925. I.error("Input " + DI->getDef()->getName() + " must be named!");
  2926. }
  2927. return false;
  2928. }
  2929. Record *Rec;
  2930. if (Pat->isLeaf()) {
  2931. DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
  2932. if (!DI)
  2933. I.error("Input $" + Pat->getName() + " must be an identifier!");
  2934. Rec = DI->getDef();
  2935. } else {
  2936. Rec = Pat->getOperator();
  2937. }
  2938. // SRCVALUE nodes are ignored.
  2939. if (Rec->getName() == "srcvalue")
  2940. return false;
  2941. TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
  2942. if (!Slot) {
  2943. Slot = Pat;
  2944. return true;
  2945. }
  2946. Record *SlotRec;
  2947. if (Slot->isLeaf()) {
  2948. SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
  2949. } else {
  2950. assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
  2951. SlotRec = Slot->getOperator();
  2952. }
  2953. // Ensure that the inputs agree if we've already seen this input.
  2954. if (Rec != SlotRec)
  2955. I.error("All $" + Pat->getName() + " inputs must agree with each other");
  2956. // Ensure that the types can agree as well.
  2957. Slot->UpdateNodeType(0, Pat->getExtType(0), I);
  2958. Pat->UpdateNodeType(0, Slot->getExtType(0), I);
  2959. if (Slot->getExtTypes() != Pat->getExtTypes())
  2960. I.error("All $" + Pat->getName() + " inputs must agree with each other");
  2961. return true;
  2962. }
  2963. /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
  2964. /// part of "I", the instruction), computing the set of inputs and outputs of
  2965. /// the pattern. Report errors if we see anything naughty.
  2966. void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
  2967. TreePattern &I, TreePatternNodePtr Pat,
  2968. std::map<std::string, TreePatternNodePtr> &InstInputs,
  2969. MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
  2970. &InstResults,
  2971. std::vector<Record *> &InstImpResults) {
  2972. // The instruction pattern still has unresolved fragments. For *named*
  2973. // nodes we must resolve those here. This may not result in multiple
  2974. // alternatives.
  2975. if (!Pat->getName().empty()) {
  2976. TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
  2977. SrcPattern.InlinePatternFragments();
  2978. SrcPattern.InferAllTypes();
  2979. Pat = SrcPattern.getOnlyTree();
  2980. }
  2981. if (Pat->isLeaf()) {
  2982. bool isUse = HandleUse(I, Pat, InstInputs);
  2983. if (!isUse && Pat->getTransformFn())
  2984. I.error("Cannot specify a transform function for a non-input value!");
  2985. return;
  2986. }
  2987. if (Pat->getOperator()->getName() == "implicit") {
  2988. for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
  2989. TreePatternNode *Dest = Pat->getChild(i);
  2990. if (!Dest->isLeaf())
  2991. I.error("implicitly defined value should be a register!");
  2992. DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
  2993. if (!Val || !Val->getDef()->isSubClassOf("Register"))
  2994. I.error("implicitly defined value should be a register!");
  2995. InstImpResults.push_back(Val->getDef());
  2996. }
  2997. return;
  2998. }
  2999. if (Pat->getOperator()->getName() != "set") {
  3000. // If this is not a set, verify that the children nodes are not void typed,
  3001. // and recurse.
  3002. for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
  3003. if (Pat->getChild(i)->getNumTypes() == 0)
  3004. I.error("Cannot have void nodes inside of patterns!");
  3005. FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
  3006. InstResults, InstImpResults);
  3007. }
  3008. // If this is a non-leaf node with no children, treat it basically as if
  3009. // it were a leaf. This handles nodes like (imm).
  3010. bool isUse = HandleUse(I, Pat, InstInputs);
  3011. if (!isUse && Pat->getTransformFn())
  3012. I.error("Cannot specify a transform function for a non-input value!");
  3013. return;
  3014. }
  3015. // Otherwise, this is a set, validate and collect instruction results.
  3016. if (Pat->getNumChildren() == 0)
  3017. I.error("set requires operands!");
  3018. if (Pat->getTransformFn())
  3019. I.error("Cannot specify a transform function on a set node!");
  3020. // Check the set destinations.
  3021. unsigned NumDests = Pat->getNumChildren()-1;
  3022. for (unsigned i = 0; i != NumDests; ++i) {
  3023. TreePatternNodePtr Dest = Pat->getChildShared(i);
  3024. // For set destinations we also must resolve fragments here.
  3025. TreePattern DestPattern(I.getRecord(), Dest, false, *this);
  3026. DestPattern.InlinePatternFragments();
  3027. DestPattern.InferAllTypes();
  3028. Dest = DestPattern.getOnlyTree();
  3029. if (!Dest->isLeaf())
  3030. I.error("set destination should be a register!");
  3031. DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
  3032. if (!Val) {
  3033. I.error("set destination should be a register!");
  3034. continue;
  3035. }
  3036. if (Val->getDef()->isSubClassOf("RegisterClass") ||
  3037. Val->getDef()->isSubClassOf("ValueType") ||
  3038. Val->getDef()->isSubClassOf("RegisterOperand") ||
  3039. Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
  3040. if (Dest->getName().empty())
  3041. I.error("set destination must have a name!");
  3042. if (InstResults.count(Dest->getName()))
  3043. I.error("cannot set '" + Dest->getName() + "' multiple times");
  3044. InstResults[Dest->getName()] = Dest;
  3045. } else if (Val->getDef()->isSubClassOf("Register")) {
  3046. InstImpResults.push_back(Val->getDef());
  3047. } else {
  3048. I.error("set destination should be a register!");
  3049. }
  3050. }
  3051. // Verify and collect info from the computation.
  3052. FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
  3053. InstResults, InstImpResults);
  3054. }
  3055. //===----------------------------------------------------------------------===//
  3056. // Instruction Analysis
  3057. //===----------------------------------------------------------------------===//
  3058. class InstAnalyzer {
  3059. const CodeGenDAGPatterns &CDP;
  3060. public:
  3061. bool hasSideEffects;
  3062. bool mayStore;
  3063. bool mayLoad;
  3064. bool isBitcast;
  3065. bool isVariadic;
  3066. bool hasChain;
  3067. InstAnalyzer(const CodeGenDAGPatterns &cdp)
  3068. : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
  3069. isBitcast(false), isVariadic(false), hasChain(false) {}
  3070. void Analyze(const PatternToMatch &Pat) {
  3071. const TreePatternNode *N = Pat.getSrcPattern();
  3072. AnalyzeNode(N);
  3073. // These properties are detected only on the root node.
  3074. isBitcast = IsNodeBitcast(N);
  3075. }
  3076. private:
  3077. bool IsNodeBitcast(const TreePatternNode *N) const {
  3078. if (hasSideEffects || mayLoad || mayStore || isVariadic)
  3079. return false;
  3080. if (N->isLeaf())
  3081. return false;
  3082. if (N->getNumChildren() != 1 || !N->getChild(0)->isLeaf())
  3083. return false;
  3084. if (N->getOperator()->isSubClassOf("ComplexPattern"))
  3085. return false;
  3086. const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
  3087. if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
  3088. return false;
  3089. return OpInfo.getEnumName() == "ISD::BITCAST";
  3090. }
  3091. public:
  3092. void AnalyzeNode(const TreePatternNode *N) {
  3093. if (N->isLeaf()) {
  3094. if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
  3095. Record *LeafRec = DI->getDef();
  3096. // Handle ComplexPattern leaves.
  3097. if (LeafRec->isSubClassOf("ComplexPattern")) {
  3098. const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
  3099. if (CP.hasProperty(SDNPMayStore)) mayStore = true;
  3100. if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
  3101. if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
  3102. }
  3103. }
  3104. return;
  3105. }
  3106. // Analyze children.
  3107. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  3108. AnalyzeNode(N->getChild(i));
  3109. // Notice properties of the node.
  3110. if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
  3111. if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
  3112. if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
  3113. if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
  3114. if (N->NodeHasProperty(SDNPHasChain, CDP)) hasChain = true;
  3115. if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
  3116. // If this is an intrinsic, analyze it.
  3117. if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
  3118. mayLoad = true;// These may load memory.
  3119. if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
  3120. mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
  3121. if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
  3122. IntInfo->hasSideEffects)
  3123. // ReadWriteMem intrinsics can have other strange effects.
  3124. hasSideEffects = true;
  3125. }
  3126. }
  3127. };
  3128. static bool InferFromPattern(CodeGenInstruction &InstInfo,
  3129. const InstAnalyzer &PatInfo,
  3130. Record *PatDef) {
  3131. bool Error = false;
  3132. // Remember where InstInfo got its flags.
  3133. if (InstInfo.hasUndefFlags())
  3134. InstInfo.InferredFrom = PatDef;
  3135. // Check explicitly set flags for consistency.
  3136. if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
  3137. !InstInfo.hasSideEffects_Unset) {
  3138. // Allow explicitly setting hasSideEffects = 1 on instructions, even when
  3139. // the pattern has no side effects. That could be useful for div/rem
  3140. // instructions that may trap.
  3141. if (!InstInfo.hasSideEffects) {
  3142. Error = true;
  3143. PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
  3144. Twine(InstInfo.hasSideEffects));
  3145. }
  3146. }
  3147. if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
  3148. Error = true;
  3149. PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
  3150. Twine(InstInfo.mayStore));
  3151. }
  3152. if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
  3153. // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
  3154. // Some targets translate immediates to loads.
  3155. if (!InstInfo.mayLoad) {
  3156. Error = true;
  3157. PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
  3158. Twine(InstInfo.mayLoad));
  3159. }
  3160. }
  3161. // Transfer inferred flags.
  3162. InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
  3163. InstInfo.mayStore |= PatInfo.mayStore;
  3164. InstInfo.mayLoad |= PatInfo.mayLoad;
  3165. // These flags are silently added without any verification.
  3166. // FIXME: To match historical behavior of TableGen, for now add those flags
  3167. // only when we're inferring from the primary instruction pattern.
  3168. if (PatDef->isSubClassOf("Instruction")) {
  3169. InstInfo.isBitcast |= PatInfo.isBitcast;
  3170. InstInfo.hasChain |= PatInfo.hasChain;
  3171. InstInfo.hasChain_Inferred = true;
  3172. }
  3173. // Don't infer isVariadic. This flag means something different on SDNodes and
  3174. // instructions. For example, a CALL SDNode is variadic because it has the
  3175. // call arguments as operands, but a CALL instruction is not variadic - it
  3176. // has argument registers as implicit, not explicit uses.
  3177. return Error;
  3178. }
  3179. /// hasNullFragReference - Return true if the DAG has any reference to the
  3180. /// null_frag operator.
  3181. static bool hasNullFragReference(DagInit *DI) {
  3182. DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
  3183. if (!OpDef) return false;
  3184. Record *Operator = OpDef->getDef();
  3185. // If this is the null fragment, return true.
  3186. if (Operator->getName() == "null_frag") return true;
  3187. // If any of the arguments reference the null fragment, return true.
  3188. for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
  3189. if (auto Arg = dyn_cast<DefInit>(DI->getArg(i)))
  3190. if (Arg->getDef()->getName() == "null_frag")
  3191. return true;
  3192. DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
  3193. if (Arg && hasNullFragReference(Arg))
  3194. return true;
  3195. }
  3196. return false;
  3197. }
  3198. /// hasNullFragReference - Return true if any DAG in the list references
  3199. /// the null_frag operator.
  3200. static bool hasNullFragReference(ListInit *LI) {
  3201. for (Init *I : LI->getValues()) {
  3202. DagInit *DI = dyn_cast<DagInit>(I);
  3203. assert(DI && "non-dag in an instruction Pattern list?!");
  3204. if (hasNullFragReference(DI))
  3205. return true;
  3206. }
  3207. return false;
  3208. }
  3209. /// Get all the instructions in a tree.
  3210. static void
  3211. getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
  3212. if (Tree->isLeaf())
  3213. return;
  3214. if (Tree->getOperator()->isSubClassOf("Instruction"))
  3215. Instrs.push_back(Tree->getOperator());
  3216. for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
  3217. getInstructionsInTree(Tree->getChild(i), Instrs);
  3218. }
  3219. /// Check the class of a pattern leaf node against the instruction operand it
  3220. /// represents.
  3221. static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
  3222. Record *Leaf) {
  3223. if (OI.Rec == Leaf)
  3224. return true;
  3225. // Allow direct value types to be used in instruction set patterns.
  3226. // The type will be checked later.
  3227. if (Leaf->isSubClassOf("ValueType"))
  3228. return true;
  3229. // Patterns can also be ComplexPattern instances.
  3230. if (Leaf->isSubClassOf("ComplexPattern"))
  3231. return true;
  3232. return false;
  3233. }
  3234. void CodeGenDAGPatterns::parseInstructionPattern(
  3235. CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
  3236. assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
  3237. // Parse the instruction.
  3238. TreePattern I(CGI.TheDef, Pat, true, *this);
  3239. // InstInputs - Keep track of all of the inputs of the instruction, along
  3240. // with the record they are declared as.
  3241. std::map<std::string, TreePatternNodePtr> InstInputs;
  3242. // InstResults - Keep track of all the virtual registers that are 'set'
  3243. // in the instruction, including what reg class they are.
  3244. MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
  3245. InstResults;
  3246. std::vector<Record*> InstImpResults;
  3247. // Verify that the top-level forms in the instruction are of void type, and
  3248. // fill in the InstResults map.
  3249. SmallString<32> TypesString;
  3250. for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
  3251. TypesString.clear();
  3252. TreePatternNodePtr Pat = I.getTree(j);
  3253. if (Pat->getNumTypes() != 0) {
  3254. raw_svector_ostream OS(TypesString);
  3255. ListSeparator LS;
  3256. for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
  3257. OS << LS;
  3258. Pat->getExtType(k).writeToStream(OS);
  3259. }
  3260. I.error("Top-level forms in instruction pattern should have"
  3261. " void types, has types " +
  3262. OS.str());
  3263. }
  3264. // Find inputs and outputs, and verify the structure of the uses/defs.
  3265. FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
  3266. InstImpResults);
  3267. }
  3268. // Now that we have inputs and outputs of the pattern, inspect the operands
  3269. // list for the instruction. This determines the order that operands are
  3270. // added to the machine instruction the node corresponds to.
  3271. unsigned NumResults = InstResults.size();
  3272. // Parse the operands list from the (ops) list, validating it.
  3273. assert(I.getArgList().empty() && "Args list should still be empty here!");
  3274. // Check that all of the results occur first in the list.
  3275. std::vector<Record*> Results;
  3276. std::vector<unsigned> ResultIndices;
  3277. SmallVector<TreePatternNodePtr, 2> ResNodes;
  3278. for (unsigned i = 0; i != NumResults; ++i) {
  3279. if (i == CGI.Operands.size()) {
  3280. const std::string &OpName =
  3281. llvm::find_if(
  3282. InstResults,
  3283. [](const std::pair<std::string, TreePatternNodePtr> &P) {
  3284. return P.second;
  3285. })
  3286. ->first;
  3287. I.error("'" + OpName + "' set but does not appear in operand list!");
  3288. }
  3289. const std::string &OpName = CGI.Operands[i].Name;
  3290. // Check that it exists in InstResults.
  3291. auto InstResultIter = InstResults.find(OpName);
  3292. if (InstResultIter == InstResults.end() || !InstResultIter->second)
  3293. I.error("Operand $" + OpName + " does not exist in operand list!");
  3294. TreePatternNodePtr RNode = InstResultIter->second;
  3295. Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
  3296. ResNodes.push_back(std::move(RNode));
  3297. if (!R)
  3298. I.error("Operand $" + OpName + " should be a set destination: all "
  3299. "outputs must occur before inputs in operand list!");
  3300. if (!checkOperandClass(CGI.Operands[i], R))
  3301. I.error("Operand $" + OpName + " class mismatch!");
  3302. // Remember the return type.
  3303. Results.push_back(CGI.Operands[i].Rec);
  3304. // Remember the result index.
  3305. ResultIndices.push_back(std::distance(InstResults.begin(), InstResultIter));
  3306. // Okay, this one checks out.
  3307. InstResultIter->second = nullptr;
  3308. }
  3309. // Loop over the inputs next.
  3310. std::vector<TreePatternNodePtr> ResultNodeOperands;
  3311. std::vector<Record*> Operands;
  3312. for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
  3313. CGIOperandList::OperandInfo &Op = CGI.Operands[i];
  3314. const std::string &OpName = Op.Name;
  3315. if (OpName.empty())
  3316. I.error("Operand #" + Twine(i) + " in operands list has no name!");
  3317. if (!InstInputs.count(OpName)) {
  3318. // If this is an operand with a DefaultOps set filled in, we can ignore
  3319. // this. When we codegen it, we will do so as always executed.
  3320. if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
  3321. // Does it have a non-empty DefaultOps field? If so, ignore this
  3322. // operand.
  3323. if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
  3324. continue;
  3325. }
  3326. I.error("Operand $" + OpName +
  3327. " does not appear in the instruction pattern");
  3328. }
  3329. TreePatternNodePtr InVal = InstInputs[OpName];
  3330. InstInputs.erase(OpName); // It occurred, remove from map.
  3331. if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
  3332. Record *InRec = cast<DefInit>(InVal->getLeafValue())->getDef();
  3333. if (!checkOperandClass(Op, InRec))
  3334. I.error("Operand $" + OpName + "'s register class disagrees"
  3335. " between the operand and pattern");
  3336. }
  3337. Operands.push_back(Op.Rec);
  3338. // Construct the result for the dest-pattern operand list.
  3339. TreePatternNodePtr OpNode = InVal->clone();
  3340. // No predicate is useful on the result.
  3341. OpNode->clearPredicateCalls();
  3342. // Promote the xform function to be an explicit node if set.
  3343. if (Record *Xform = OpNode->getTransformFn()) {
  3344. OpNode->setTransformFn(nullptr);
  3345. std::vector<TreePatternNodePtr> Children;
  3346. Children.push_back(OpNode);
  3347. OpNode = std::make_shared<TreePatternNode>(Xform, std::move(Children),
  3348. OpNode->getNumTypes());
  3349. }
  3350. ResultNodeOperands.push_back(std::move(OpNode));
  3351. }
  3352. if (!InstInputs.empty())
  3353. I.error("Input operand $" + InstInputs.begin()->first +
  3354. " occurs in pattern but not in operands list!");
  3355. TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
  3356. I.getRecord(), std::move(ResultNodeOperands),
  3357. GetNumNodeResults(I.getRecord(), *this));
  3358. // Copy fully inferred output node types to instruction result pattern.
  3359. for (unsigned i = 0; i != NumResults; ++i) {
  3360. assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
  3361. ResultPattern->setType(i, ResNodes[i]->getExtType(0));
  3362. ResultPattern->setResultIndex(i, ResultIndices[i]);
  3363. }
  3364. // FIXME: Assume only the first tree is the pattern. The others are clobber
  3365. // nodes.
  3366. TreePatternNodePtr Pattern = I.getTree(0);
  3367. TreePatternNodePtr SrcPattern;
  3368. if (Pattern->getOperator()->getName() == "set") {
  3369. SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
  3370. } else{
  3371. // Not a set (store or something?)
  3372. SrcPattern = Pattern;
  3373. }
  3374. // Create and insert the instruction.
  3375. // FIXME: InstImpResults should not be part of DAGInstruction.
  3376. Record *R = I.getRecord();
  3377. DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
  3378. std::forward_as_tuple(Results, Operands, InstImpResults,
  3379. SrcPattern, ResultPattern));
  3380. LLVM_DEBUG(I.dump());
  3381. }
  3382. /// ParseInstructions - Parse all of the instructions, inlining and resolving
  3383. /// any fragments involved. This populates the Instructions list with fully
  3384. /// resolved instructions.
  3385. void CodeGenDAGPatterns::ParseInstructions() {
  3386. std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
  3387. for (Record *Instr : Instrs) {
  3388. ListInit *LI = nullptr;
  3389. if (isa<ListInit>(Instr->getValueInit("Pattern")))
  3390. LI = Instr->getValueAsListInit("Pattern");
  3391. // If there is no pattern, only collect minimal information about the
  3392. // instruction for its operand list. We have to assume that there is one
  3393. // result, as we have no detailed info. A pattern which references the
  3394. // null_frag operator is as-if no pattern were specified. Normally this
  3395. // is from a multiclass expansion w/ a SDPatternOperator passed in as
  3396. // null_frag.
  3397. if (!LI || LI->empty() || hasNullFragReference(LI)) {
  3398. std::vector<Record*> Results;
  3399. std::vector<Record*> Operands;
  3400. CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
  3401. if (InstInfo.Operands.size() != 0) {
  3402. for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
  3403. Results.push_back(InstInfo.Operands[j].Rec);
  3404. // The rest are inputs.
  3405. for (unsigned j = InstInfo.Operands.NumDefs,
  3406. e = InstInfo.Operands.size(); j < e; ++j)
  3407. Operands.push_back(InstInfo.Operands[j].Rec);
  3408. }
  3409. // Create and insert the instruction.
  3410. std::vector<Record*> ImpResults;
  3411. Instructions.insert(std::make_pair(Instr,
  3412. DAGInstruction(Results, Operands, ImpResults)));
  3413. continue; // no pattern.
  3414. }
  3415. CodeGenInstruction &CGI = Target.getInstruction(Instr);
  3416. parseInstructionPattern(CGI, LI, Instructions);
  3417. }
  3418. // If we can, convert the instructions to be patterns that are matched!
  3419. for (auto &Entry : Instructions) {
  3420. Record *Instr = Entry.first;
  3421. DAGInstruction &TheInst = Entry.second;
  3422. TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
  3423. TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
  3424. if (SrcPattern && ResultPattern) {
  3425. TreePattern Pattern(Instr, SrcPattern, true, *this);
  3426. TreePattern Result(Instr, ResultPattern, false, *this);
  3427. ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
  3428. }
  3429. }
  3430. }
  3431. typedef std::pair<TreePatternNode *, unsigned> NameRecord;
  3432. static void FindNames(TreePatternNode *P,
  3433. std::map<std::string, NameRecord> &Names,
  3434. TreePattern *PatternTop) {
  3435. if (!P->getName().empty()) {
  3436. NameRecord &Rec = Names[P->getName()];
  3437. // If this is the first instance of the name, remember the node.
  3438. if (Rec.second++ == 0)
  3439. Rec.first = P;
  3440. else if (Rec.first->getExtTypes() != P->getExtTypes())
  3441. PatternTop->error("repetition of value: $" + P->getName() +
  3442. " where different uses have different types!");
  3443. }
  3444. if (!P->isLeaf()) {
  3445. for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
  3446. FindNames(P->getChild(i), Names, PatternTop);
  3447. }
  3448. }
  3449. void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
  3450. PatternToMatch &&PTM) {
  3451. // Do some sanity checking on the pattern we're about to match.
  3452. std::string Reason;
  3453. if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
  3454. PrintWarning(Pattern->getRecord()->getLoc(),
  3455. Twine("Pattern can never match: ") + Reason);
  3456. return;
  3457. }
  3458. // If the source pattern's root is a complex pattern, that complex pattern
  3459. // must specify the nodes it can potentially match.
  3460. if (const ComplexPattern *CP =
  3461. PTM.getSrcPattern()->getComplexPatternInfo(*this))
  3462. if (CP->getRootNodes().empty())
  3463. Pattern->error("ComplexPattern at root must specify list of opcodes it"
  3464. " could match");
  3465. // Find all of the named values in the input and output, ensure they have the
  3466. // same type.
  3467. std::map<std::string, NameRecord> SrcNames, DstNames;
  3468. FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
  3469. FindNames(PTM.getDstPattern(), DstNames, Pattern);
  3470. // Scan all of the named values in the destination pattern, rejecting them if
  3471. // they don't exist in the input pattern.
  3472. for (const auto &Entry : DstNames) {
  3473. if (SrcNames[Entry.first].first == nullptr)
  3474. Pattern->error("Pattern has input without matching name in output: $" +
  3475. Entry.first);
  3476. }
  3477. // Scan all of the named values in the source pattern, rejecting them if the
  3478. // name isn't used in the dest, and isn't used to tie two values together.
  3479. for (const auto &Entry : SrcNames)
  3480. if (DstNames[Entry.first].first == nullptr &&
  3481. SrcNames[Entry.first].second == 1)
  3482. Pattern->error("Pattern has dead named input: $" + Entry.first);
  3483. PatternsToMatch.push_back(std::move(PTM));
  3484. }
  3485. void CodeGenDAGPatterns::InferInstructionFlags() {
  3486. ArrayRef<const CodeGenInstruction*> Instructions =
  3487. Target.getInstructionsByEnumValue();
  3488. unsigned Errors = 0;
  3489. // Try to infer flags from all patterns in PatternToMatch. These include
  3490. // both the primary instruction patterns (which always come first) and
  3491. // patterns defined outside the instruction.
  3492. for (const PatternToMatch &PTM : ptms()) {
  3493. // We can only infer from single-instruction patterns, otherwise we won't
  3494. // know which instruction should get the flags.
  3495. SmallVector<Record*, 8> PatInstrs;
  3496. getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
  3497. if (PatInstrs.size() != 1)
  3498. continue;
  3499. // Get the single instruction.
  3500. CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
  3501. // Only infer properties from the first pattern. We'll verify the others.
  3502. if (InstInfo.InferredFrom)
  3503. continue;
  3504. InstAnalyzer PatInfo(*this);
  3505. PatInfo.Analyze(PTM);
  3506. Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
  3507. }
  3508. if (Errors)
  3509. PrintFatalError("pattern conflicts");
  3510. // If requested by the target, guess any undefined properties.
  3511. if (Target.guessInstructionProperties()) {
  3512. for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
  3513. CodeGenInstruction *InstInfo =
  3514. const_cast<CodeGenInstruction *>(Instructions[i]);
  3515. if (InstInfo->InferredFrom)
  3516. continue;
  3517. // The mayLoad and mayStore flags default to false.
  3518. // Conservatively assume hasSideEffects if it wasn't explicit.
  3519. if (InstInfo->hasSideEffects_Unset)
  3520. InstInfo->hasSideEffects = true;
  3521. }
  3522. return;
  3523. }
  3524. // Complain about any flags that are still undefined.
  3525. for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
  3526. CodeGenInstruction *InstInfo =
  3527. const_cast<CodeGenInstruction *>(Instructions[i]);
  3528. if (InstInfo->InferredFrom)
  3529. continue;
  3530. if (InstInfo->hasSideEffects_Unset)
  3531. PrintError(InstInfo->TheDef->getLoc(),
  3532. "Can't infer hasSideEffects from patterns");
  3533. if (InstInfo->mayStore_Unset)
  3534. PrintError(InstInfo->TheDef->getLoc(),
  3535. "Can't infer mayStore from patterns");
  3536. if (InstInfo->mayLoad_Unset)
  3537. PrintError(InstInfo->TheDef->getLoc(),
  3538. "Can't infer mayLoad from patterns");
  3539. }
  3540. }
  3541. /// Verify instruction flags against pattern node properties.
  3542. void CodeGenDAGPatterns::VerifyInstructionFlags() {
  3543. unsigned Errors = 0;
  3544. for (const PatternToMatch &PTM : ptms()) {
  3545. SmallVector<Record*, 8> Instrs;
  3546. getInstructionsInTree(PTM.getDstPattern(), Instrs);
  3547. if (Instrs.empty())
  3548. continue;
  3549. // Count the number of instructions with each flag set.
  3550. unsigned NumSideEffects = 0;
  3551. unsigned NumStores = 0;
  3552. unsigned NumLoads = 0;
  3553. for (const Record *Instr : Instrs) {
  3554. const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
  3555. NumSideEffects += InstInfo.hasSideEffects;
  3556. NumStores += InstInfo.mayStore;
  3557. NumLoads += InstInfo.mayLoad;
  3558. }
  3559. // Analyze the source pattern.
  3560. InstAnalyzer PatInfo(*this);
  3561. PatInfo.Analyze(PTM);
  3562. // Collect error messages.
  3563. SmallVector<std::string, 4> Msgs;
  3564. // Check for missing flags in the output.
  3565. // Permit extra flags for now at least.
  3566. if (PatInfo.hasSideEffects && !NumSideEffects)
  3567. Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
  3568. // Don't verify store flags on instructions with side effects. At least for
  3569. // intrinsics, side effects implies mayStore.
  3570. if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
  3571. Msgs.push_back("pattern may store, but mayStore isn't set");
  3572. // Similarly, mayStore implies mayLoad on intrinsics.
  3573. if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
  3574. Msgs.push_back("pattern may load, but mayLoad isn't set");
  3575. // Print error messages.
  3576. if (Msgs.empty())
  3577. continue;
  3578. ++Errors;
  3579. for (const std::string &Msg : Msgs)
  3580. PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
  3581. (Instrs.size() == 1 ?
  3582. "instruction" : "output instructions"));
  3583. // Provide the location of the relevant instruction definitions.
  3584. for (const Record *Instr : Instrs) {
  3585. if (Instr != PTM.getSrcRecord())
  3586. PrintError(Instr->getLoc(), "defined here");
  3587. const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
  3588. if (InstInfo.InferredFrom &&
  3589. InstInfo.InferredFrom != InstInfo.TheDef &&
  3590. InstInfo.InferredFrom != PTM.getSrcRecord())
  3591. PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
  3592. }
  3593. }
  3594. if (Errors)
  3595. PrintFatalError("Errors in DAG patterns");
  3596. }
  3597. /// Given a pattern result with an unresolved type, see if we can find one
  3598. /// instruction with an unresolved result type. Force this result type to an
  3599. /// arbitrary element if it's possible types to converge results.
  3600. static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
  3601. if (N->isLeaf())
  3602. return false;
  3603. // Analyze children.
  3604. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  3605. if (ForceArbitraryInstResultType(N->getChild(i), TP))
  3606. return true;
  3607. if (!N->getOperator()->isSubClassOf("Instruction"))
  3608. return false;
  3609. // If this type is already concrete or completely unknown we can't do
  3610. // anything.
  3611. TypeInfer &TI = TP.getInfer();
  3612. for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
  3613. if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
  3614. continue;
  3615. // Otherwise, force its type to an arbitrary choice.
  3616. if (TI.forceArbitrary(N->getExtType(i)))
  3617. return true;
  3618. }
  3619. return false;
  3620. }
  3621. // Promote xform function to be an explicit node wherever set.
  3622. static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
  3623. if (Record *Xform = N->getTransformFn()) {
  3624. N->setTransformFn(nullptr);
  3625. std::vector<TreePatternNodePtr> Children;
  3626. Children.push_back(PromoteXForms(N));
  3627. return std::make_shared<TreePatternNode>(Xform, std::move(Children),
  3628. N->getNumTypes());
  3629. }
  3630. if (!N->isLeaf())
  3631. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
  3632. TreePatternNodePtr Child = N->getChildShared(i);
  3633. N->setChild(i, PromoteXForms(Child));
  3634. }
  3635. return N;
  3636. }
  3637. void CodeGenDAGPatterns::ParseOnePattern(Record *TheDef,
  3638. TreePattern &Pattern, TreePattern &Result,
  3639. const std::vector<Record *> &InstImpResults) {
  3640. // Inline pattern fragments and expand multiple alternatives.
  3641. Pattern.InlinePatternFragments();
  3642. Result.InlinePatternFragments();
  3643. if (Result.getNumTrees() != 1)
  3644. Result.error("Cannot use multi-alternative fragments in result pattern!");
  3645. // Infer types.
  3646. bool IterateInference;
  3647. bool InferredAllPatternTypes, InferredAllResultTypes;
  3648. do {
  3649. // Infer as many types as possible. If we cannot infer all of them, we
  3650. // can never do anything with this pattern: report it to the user.
  3651. InferredAllPatternTypes =
  3652. Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
  3653. // Infer as many types as possible. If we cannot infer all of them, we
  3654. // can never do anything with this pattern: report it to the user.
  3655. InferredAllResultTypes =
  3656. Result.InferAllTypes(&Pattern.getNamedNodesMap());
  3657. IterateInference = false;
  3658. // Apply the type of the result to the source pattern. This helps us
  3659. // resolve cases where the input type is known to be a pointer type (which
  3660. // is considered resolved), but the result knows it needs to be 32- or
  3661. // 64-bits. Infer the other way for good measure.
  3662. for (const auto &T : Pattern.getTrees())
  3663. for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
  3664. T->getNumTypes());
  3665. i != e; ++i) {
  3666. IterateInference |= T->UpdateNodeType(
  3667. i, Result.getOnlyTree()->getExtType(i), Result);
  3668. IterateInference |= Result.getOnlyTree()->UpdateNodeType(
  3669. i, T->getExtType(i), Result);
  3670. }
  3671. // If our iteration has converged and the input pattern's types are fully
  3672. // resolved but the result pattern is not fully resolved, we may have a
  3673. // situation where we have two instructions in the result pattern and
  3674. // the instructions require a common register class, but don't care about
  3675. // what actual MVT is used. This is actually a bug in our modelling:
  3676. // output patterns should have register classes, not MVTs.
  3677. //
  3678. // In any case, to handle this, we just go through and disambiguate some
  3679. // arbitrary types to the result pattern's nodes.
  3680. if (!IterateInference && InferredAllPatternTypes &&
  3681. !InferredAllResultTypes)
  3682. IterateInference =
  3683. ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
  3684. } while (IterateInference);
  3685. // Verify that we inferred enough types that we can do something with the
  3686. // pattern and result. If these fire the user has to add type casts.
  3687. if (!InferredAllPatternTypes)
  3688. Pattern.error("Could not infer all types in pattern!");
  3689. if (!InferredAllResultTypes) {
  3690. Pattern.dump();
  3691. Result.error("Could not infer all types in pattern result!");
  3692. }
  3693. // Promote xform function to be an explicit node wherever set.
  3694. TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
  3695. TreePattern Temp(Result.getRecord(), DstShared, false, *this);
  3696. Temp.InferAllTypes();
  3697. ListInit *Preds = TheDef->getValueAsListInit("Predicates");
  3698. int Complexity = TheDef->getValueAsInt("AddedComplexity");
  3699. if (PatternRewriter)
  3700. PatternRewriter(&Pattern);
  3701. // A pattern may end up with an "impossible" type, i.e. a situation
  3702. // where all types have been eliminated for some node in this pattern.
  3703. // This could occur for intrinsics that only make sense for a specific
  3704. // value type, and use a specific register class. If, for some mode,
  3705. // that register class does not accept that type, the type inference
  3706. // will lead to a contradiction, which is not an error however, but
  3707. // a sign that this pattern will simply never match.
  3708. if (Temp.getOnlyTree()->hasPossibleType())
  3709. for (const auto &T : Pattern.getTrees())
  3710. if (T->hasPossibleType())
  3711. AddPatternToMatch(&Pattern,
  3712. PatternToMatch(TheDef, Preds, T, Temp.getOnlyTree(),
  3713. InstImpResults, Complexity,
  3714. TheDef->getID()));
  3715. }
  3716. void CodeGenDAGPatterns::ParsePatterns() {
  3717. std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
  3718. for (Record *CurPattern : Patterns) {
  3719. DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
  3720. // If the pattern references the null_frag, there's nothing to do.
  3721. if (hasNullFragReference(Tree))
  3722. continue;
  3723. TreePattern Pattern(CurPattern, Tree, true, *this);
  3724. ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
  3725. if (LI->empty()) continue; // no pattern.
  3726. // Parse the instruction.
  3727. TreePattern Result(CurPattern, LI, false, *this);
  3728. if (Result.getNumTrees() != 1)
  3729. Result.error("Cannot handle instructions producing instructions "
  3730. "with temporaries yet!");
  3731. // Validate that the input pattern is correct.
  3732. std::map<std::string, TreePatternNodePtr> InstInputs;
  3733. MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
  3734. InstResults;
  3735. std::vector<Record*> InstImpResults;
  3736. for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
  3737. FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
  3738. InstResults, InstImpResults);
  3739. ParseOnePattern(CurPattern, Pattern, Result, InstImpResults);
  3740. }
  3741. }
  3742. static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
  3743. for (const TypeSetByHwMode &VTS : N->getExtTypes())
  3744. for (const auto &I : VTS)
  3745. Modes.insert(I.first);
  3746. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  3747. collectModes(Modes, N->getChild(i));
  3748. }
  3749. void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
  3750. const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
  3751. std::vector<PatternToMatch> Copy;
  3752. PatternsToMatch.swap(Copy);
  3753. auto AppendPattern = [this](PatternToMatch &P, unsigned Mode,
  3754. StringRef Check) {
  3755. TreePatternNodePtr NewSrc = P.getSrcPattern()->clone();
  3756. TreePatternNodePtr NewDst = P.getDstPattern()->clone();
  3757. if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
  3758. return;
  3759. }
  3760. PatternsToMatch.emplace_back(P.getSrcRecord(), P.getPredicates(),
  3761. std::move(NewSrc), std::move(NewDst),
  3762. P.getDstRegs(), P.getAddedComplexity(),
  3763. Record::getNewUID(), Mode, Check);
  3764. };
  3765. for (PatternToMatch &P : Copy) {
  3766. TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
  3767. if (P.getSrcPattern()->hasProperTypeByHwMode())
  3768. SrcP = P.getSrcPatternShared();
  3769. if (P.getDstPattern()->hasProperTypeByHwMode())
  3770. DstP = P.getDstPatternShared();
  3771. if (!SrcP && !DstP) {
  3772. PatternsToMatch.push_back(P);
  3773. continue;
  3774. }
  3775. std::set<unsigned> Modes;
  3776. if (SrcP)
  3777. collectModes(Modes, SrcP.get());
  3778. if (DstP)
  3779. collectModes(Modes, DstP.get());
  3780. // The predicate for the default mode needs to be constructed for each
  3781. // pattern separately.
  3782. // Since not all modes must be present in each pattern, if a mode m is
  3783. // absent, then there is no point in constructing a check for m. If such
  3784. // a check was created, it would be equivalent to checking the default
  3785. // mode, except not all modes' predicates would be a part of the checking
  3786. // code. The subsequently generated check for the default mode would then
  3787. // have the exact same patterns, but a different predicate code. To avoid
  3788. // duplicated patterns with different predicate checks, construct the
  3789. // default check as a negation of all predicates that are actually present
  3790. // in the source/destination patterns.
  3791. SmallString<128> DefaultCheck;
  3792. for (unsigned M : Modes) {
  3793. if (M == DefaultMode)
  3794. continue;
  3795. // Fill the map entry for this mode.
  3796. const HwMode &HM = CGH.getMode(M);
  3797. AppendPattern(P, M, "(MF->getSubtarget().checkFeatures(\"" + HM.Features + "\"))");
  3798. // Add negations of the HM's predicates to the default predicate.
  3799. if (!DefaultCheck.empty())
  3800. DefaultCheck += " && ";
  3801. DefaultCheck += "(!(MF->getSubtarget().checkFeatures(\"";
  3802. DefaultCheck += HM.Features;
  3803. DefaultCheck += "\")))";
  3804. }
  3805. bool HasDefault = Modes.count(DefaultMode);
  3806. if (HasDefault)
  3807. AppendPattern(P, DefaultMode, DefaultCheck);
  3808. }
  3809. }
  3810. /// Dependent variable map for CodeGenDAGPattern variant generation
  3811. typedef StringMap<int> DepVarMap;
  3812. static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
  3813. if (N->isLeaf()) {
  3814. if (N->hasName() && isa<DefInit>(N->getLeafValue()))
  3815. DepMap[N->getName()]++;
  3816. } else {
  3817. for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
  3818. FindDepVarsOf(N->getChild(i), DepMap);
  3819. }
  3820. }
  3821. /// Find dependent variables within child patterns
  3822. static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
  3823. DepVarMap depcounts;
  3824. FindDepVarsOf(N, depcounts);
  3825. for (const auto &Pair : depcounts) {
  3826. if (Pair.getValue() > 1)
  3827. DepVars.insert(Pair.getKey());
  3828. }
  3829. }
  3830. #ifndef NDEBUG
  3831. /// Dump the dependent variable set:
  3832. static void DumpDepVars(MultipleUseVarSet &DepVars) {
  3833. if (DepVars.empty()) {
  3834. LLVM_DEBUG(errs() << "<empty set>");
  3835. } else {
  3836. LLVM_DEBUG(errs() << "[ ");
  3837. for (const auto &DepVar : DepVars) {
  3838. LLVM_DEBUG(errs() << DepVar.getKey() << " ");
  3839. }
  3840. LLVM_DEBUG(errs() << "]");
  3841. }
  3842. }
  3843. #endif
  3844. /// CombineChildVariants - Given a bunch of permutations of each child of the
  3845. /// 'operator' node, put them together in all possible ways.
  3846. static void CombineChildVariants(
  3847. TreePatternNodePtr Orig,
  3848. const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
  3849. std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
  3850. const MultipleUseVarSet &DepVars) {
  3851. // Make sure that each operand has at least one variant to choose from.
  3852. for (const auto &Variants : ChildVariants)
  3853. if (Variants.empty())
  3854. return;
  3855. // The end result is an all-pairs construction of the resultant pattern.
  3856. std::vector<unsigned> Idxs;
  3857. Idxs.resize(ChildVariants.size());
  3858. bool NotDone;
  3859. do {
  3860. #ifndef NDEBUG
  3861. LLVM_DEBUG(if (!Idxs.empty()) {
  3862. errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
  3863. for (unsigned Idx : Idxs) {
  3864. errs() << Idx << " ";
  3865. }
  3866. errs() << "]\n";
  3867. });
  3868. #endif
  3869. // Create the variant and add it to the output list.
  3870. std::vector<TreePatternNodePtr> NewChildren;
  3871. for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
  3872. NewChildren.push_back(ChildVariants[i][Idxs[i]]);
  3873. TreePatternNodePtr R = std::make_shared<TreePatternNode>(
  3874. Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
  3875. // Copy over properties.
  3876. R->setName(Orig->getName());
  3877. R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());
  3878. R->setPredicateCalls(Orig->getPredicateCalls());
  3879. R->setTransformFn(Orig->getTransformFn());
  3880. for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
  3881. R->setType(i, Orig->getExtType(i));
  3882. // If this pattern cannot match, do not include it as a variant.
  3883. std::string ErrString;
  3884. // Scan to see if this pattern has already been emitted. We can get
  3885. // duplication due to things like commuting:
  3886. // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
  3887. // which are the same pattern. Ignore the dups.
  3888. if (R->canPatternMatch(ErrString, CDP) &&
  3889. none_of(OutVariants, [&](TreePatternNodePtr Variant) {
  3890. return R->isIsomorphicTo(Variant.get(), DepVars);
  3891. }))
  3892. OutVariants.push_back(R);
  3893. // Increment indices to the next permutation by incrementing the
  3894. // indices from last index backward, e.g., generate the sequence
  3895. // [0, 0], [0, 1], [1, 0], [1, 1].
  3896. int IdxsIdx;
  3897. for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
  3898. if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
  3899. Idxs[IdxsIdx] = 0;
  3900. else
  3901. break;
  3902. }
  3903. NotDone = (IdxsIdx >= 0);
  3904. } while (NotDone);
  3905. }
  3906. /// CombineChildVariants - A helper function for binary operators.
  3907. ///
  3908. static void CombineChildVariants(TreePatternNodePtr Orig,
  3909. const std::vector<TreePatternNodePtr> &LHS,
  3910. const std::vector<TreePatternNodePtr> &RHS,
  3911. std::vector<TreePatternNodePtr> &OutVariants,
  3912. CodeGenDAGPatterns &CDP,
  3913. const MultipleUseVarSet &DepVars) {
  3914. std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
  3915. ChildVariants.push_back(LHS);
  3916. ChildVariants.push_back(RHS);
  3917. CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
  3918. }
  3919. static void
  3920. GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
  3921. std::vector<TreePatternNodePtr> &Children) {
  3922. assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
  3923. Record *Operator = N->getOperator();
  3924. // Only permit raw nodes.
  3925. if (!N->getName().empty() || !N->getPredicateCalls().empty() ||
  3926. N->getTransformFn()) {
  3927. Children.push_back(N);
  3928. return;
  3929. }
  3930. if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
  3931. Children.push_back(N->getChildShared(0));
  3932. else
  3933. GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
  3934. if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
  3935. Children.push_back(N->getChildShared(1));
  3936. else
  3937. GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
  3938. }
  3939. /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
  3940. /// the (potentially recursive) pattern by using algebraic laws.
  3941. ///
  3942. static void GenerateVariantsOf(TreePatternNodePtr N,
  3943. std::vector<TreePatternNodePtr> &OutVariants,
  3944. CodeGenDAGPatterns &CDP,
  3945. const MultipleUseVarSet &DepVars) {
  3946. // We cannot permute leaves or ComplexPattern uses.
  3947. if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
  3948. OutVariants.push_back(N);
  3949. return;
  3950. }
  3951. // Look up interesting info about the node.
  3952. const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
  3953. // If this node is associative, re-associate.
  3954. if (NodeInfo.hasProperty(SDNPAssociative)) {
  3955. // Re-associate by pulling together all of the linked operators
  3956. std::vector<TreePatternNodePtr> MaximalChildren;
  3957. GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
  3958. // Only handle child sizes of 3. Otherwise we'll end up trying too many
  3959. // permutations.
  3960. if (MaximalChildren.size() == 3) {
  3961. // Find the variants of all of our maximal children.
  3962. std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
  3963. GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
  3964. GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
  3965. GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
  3966. // There are only two ways we can permute the tree:
  3967. // (A op B) op C and A op (B op C)
  3968. // Within these forms, we can also permute A/B/C.
  3969. // Generate legal pair permutations of A/B/C.
  3970. std::vector<TreePatternNodePtr> ABVariants;
  3971. std::vector<TreePatternNodePtr> BAVariants;
  3972. std::vector<TreePatternNodePtr> ACVariants;
  3973. std::vector<TreePatternNodePtr> CAVariants;
  3974. std::vector<TreePatternNodePtr> BCVariants;
  3975. std::vector<TreePatternNodePtr> CBVariants;
  3976. CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
  3977. CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
  3978. CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
  3979. CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
  3980. CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
  3981. CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
  3982. // Combine those into the result: (x op x) op x
  3983. CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
  3984. CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
  3985. CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
  3986. CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
  3987. CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
  3988. CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
  3989. // Combine those into the result: x op (x op x)
  3990. CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
  3991. CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
  3992. CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
  3993. CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
  3994. CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
  3995. CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
  3996. return;
  3997. }
  3998. }
  3999. // Compute permutations of all children.
  4000. std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
  4001. ChildVariants.resize(N->getNumChildren());
  4002. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  4003. GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
  4004. // Build all permutations based on how the children were formed.
  4005. CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
  4006. // If this node is commutative, consider the commuted order.
  4007. bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
  4008. if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
  4009. unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
  4010. assert(N->getNumChildren() >= (2 + Skip) &&
  4011. "Commutative but doesn't have 2 children!");
  4012. // Don't allow commuting children which are actually register references.
  4013. bool NoRegisters = true;
  4014. unsigned i = 0 + Skip;
  4015. unsigned e = 2 + Skip;
  4016. for (; i != e; ++i) {
  4017. TreePatternNode *Child = N->getChild(i);
  4018. if (Child->isLeaf())
  4019. if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
  4020. Record *RR = DI->getDef();
  4021. if (RR->isSubClassOf("Register"))
  4022. NoRegisters = false;
  4023. }
  4024. }
  4025. // Consider the commuted order.
  4026. if (NoRegisters) {
  4027. std::vector<std::vector<TreePatternNodePtr>> Variants;
  4028. unsigned i = 0;
  4029. if (isCommIntrinsic)
  4030. Variants.push_back(std::move(ChildVariants[i++])); // Intrinsic id.
  4031. Variants.push_back(std::move(ChildVariants[i + 1]));
  4032. Variants.push_back(std::move(ChildVariants[i]));
  4033. i += 2;
  4034. // Remaining operands are not commuted.
  4035. for (; i != N->getNumChildren(); ++i)
  4036. Variants.push_back(std::move(ChildVariants[i]));
  4037. CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
  4038. }
  4039. }
  4040. }
  4041. // GenerateVariants - Generate variants. For example, commutative patterns can
  4042. // match multiple ways. Add them to PatternsToMatch as well.
  4043. void CodeGenDAGPatterns::GenerateVariants() {
  4044. LLVM_DEBUG(errs() << "Generating instruction variants.\n");
  4045. // Loop over all of the patterns we've collected, checking to see if we can
  4046. // generate variants of the instruction, through the exploitation of
  4047. // identities. This permits the target to provide aggressive matching without
  4048. // the .td file having to contain tons of variants of instructions.
  4049. //
  4050. // Note that this loop adds new patterns to the PatternsToMatch list, but we
  4051. // intentionally do not reconsider these. Any variants of added patterns have
  4052. // already been added.
  4053. //
  4054. for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
  4055. MultipleUseVarSet DepVars;
  4056. std::vector<TreePatternNodePtr> Variants;
  4057. FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
  4058. LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
  4059. LLVM_DEBUG(DumpDepVars(DepVars));
  4060. LLVM_DEBUG(errs() << "\n");
  4061. GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
  4062. *this, DepVars);
  4063. assert(PatternsToMatch[i].getHwModeFeatures().empty() &&
  4064. "HwModes should not have been expanded yet!");
  4065. assert(!Variants.empty() && "Must create at least original variant!");
  4066. if (Variants.size() == 1) // No additional variants for this pattern.
  4067. continue;
  4068. LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
  4069. PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
  4070. for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
  4071. TreePatternNodePtr Variant = Variants[v];
  4072. LLVM_DEBUG(errs() << " VAR#" << v << ": "; Variant->dump();
  4073. errs() << "\n");
  4074. // Scan to see if an instruction or explicit pattern already matches this.
  4075. bool AlreadyExists = false;
  4076. for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
  4077. // Skip if the top level predicates do not match.
  4078. if ((i != p) && (PatternsToMatch[i].getPredicates() !=
  4079. PatternsToMatch[p].getPredicates()))
  4080. continue;
  4081. // Check to see if this variant already exists.
  4082. if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
  4083. DepVars)) {
  4084. LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
  4085. AlreadyExists = true;
  4086. break;
  4087. }
  4088. }
  4089. // If we already have it, ignore the variant.
  4090. if (AlreadyExists) continue;
  4091. // Otherwise, add it to the list of patterns we have.
  4092. PatternsToMatch.emplace_back(
  4093. PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
  4094. Variant, PatternsToMatch[i].getDstPatternShared(),
  4095. PatternsToMatch[i].getDstRegs(),
  4096. PatternsToMatch[i].getAddedComplexity(), Record::getNewUID(),
  4097. PatternsToMatch[i].getForceMode(),
  4098. PatternsToMatch[i].getHwModeFeatures());
  4099. }
  4100. LLVM_DEBUG(errs() << "\n");
  4101. }
  4102. }