CodeGenDAGPatterns.cpp 172 KB

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